[Bio] / Sprout / Sprout.pm Repository:
ViewVC logotype

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.99 - (view) (download) (as text)

1 : parrello 1.1 package Sprout;
2 :    
3 : parrello 1.58 require Exporter;
4 :     use ERDB;
5 :     @ISA = qw(Exporter ERDB);
6 : parrello 1.15 use Data::Dumper;
7 :     use strict;
8 :     use DBKernel;
9 :     use XML::Simple;
10 :     use DBQuery;
11 : parrello 1.98 use ERDBObject;
12 : parrello 1.15 use Tracer;
13 :     use FIGRules;
14 : parrello 1.71 use FidCheck;
15 : parrello 1.15 use Stats;
16 : parrello 1.3 use POSIX qw(strftime);
17 : parrello 1.76 use BasicLocation;
18 : parrello 1.99 use CustomAttributes;
19 :     use RemoteCustomAttributes;
20 : parrello 1.1
21 :     =head1 Sprout Database Manipulation Object
22 :    
23 :     =head2 Introduction
24 :    
25 :     This object enables the user to load and query the Sprout genome database using a few simple methods.
26 :     To construct the object, specify the name of the database. By default, the database is assumed to be a
27 :     MySQL database accessed via the user ID I<root> with no password and the database definition will
28 :     be in a file called F<SproutDBD.xml>. All of these defaults can be overridden
29 :     on the constructor. For example, the following invocation specifies a PostgreSQL database named I<GenDB>
30 :     whose definition and data files are in a co-directory named F<Data>.
31 :    
32 :     C<< my $sprout = Sprout->new('GenDB', { dbType => 'pg', dataDir => '../Data', xmlFileName => '../Data/SproutDBD.xml' }); >>
33 :    
34 :     Once you have a sprout object, you may use it to re-create the database, load the tables from
35 :     tab-delimited flat files and perform queries. Several special methods are provided for common
36 :     query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and
37 :     L</dna_seq> returns the DNA sequence for a specified genome location.
38 :    
39 : parrello 1.58 The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.
40 :    
41 : parrello 1.1 =cut
42 :    
43 : parrello 1.3 #: Constructor SFXlate->new_sprout_only();
44 :    
45 : parrello 1.1 =head2 Public Methods
46 :    
47 :     =head3 new
48 :    
49 :     C<< my $sprout = Sprout->new($dbName, \%options); >>
50 :    
51 :     This is the constructor for a sprout object. It connects to the database and loads the
52 :     database definition into memory. The positional first parameter specifies the name of the
53 :     database.
54 :    
55 :     =over 4
56 :    
57 :     =item dbName
58 :    
59 :     Name of the database.
60 :    
61 :     =item options
62 :    
63 :     Table of options.
64 :    
65 :     * B<dbType> type of database (currently C<mysql> for MySQL and C<pg> for PostgreSQL) (default C<mysql>)
66 :    
67 :     * B<dataDir> directory containing the database definition file and the flat files used to load the data (default C<Data>)
68 :    
69 :     * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)
70 :    
71 : parrello 1.57 * B<userData> user name and password, delimited by a slash (default same as SEED)
72 : parrello 1.1
73 :     * B<port> connection port (default C<0>)
74 :    
75 : parrello 1.57 * B<sock> connection socket (default same as SEED)
76 :    
77 : parrello 1.1 * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
78 :    
79 :     * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
80 :    
81 : parrello 1.25 * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
82 :    
83 : parrello 1.1 =back
84 :    
85 :     For example, the following constructor call specifies a database named I<Sprout> and a user name of
86 :     I<fig> with a password of I<admin>. The database load files are in the directory
87 :     F</usr/fig/SproutData>.
88 :    
89 :     C<< my $sprout = Sprout->new('Sprout', { userData =>; 'fig/admin', dataDir => '/usr/fig/SproutData' }); >>
90 :    
91 :     =cut
92 :    
93 :     sub new {
94 : parrello 1.15 # Get the parameters.
95 :     my ($class, $dbName, $options) = @_;
96 : parrello 1.78 # Compute the DBD directory.
97 :     my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
98 :     $FIG_Config::fig );
99 : parrello 1.15 # Compute the options. We do this by starting with a table of defaults and overwriting with
100 :     # the incoming data.
101 :     my $optionTable = Tracer::GetOptions({
102 : parrello 1.18 dbType => $FIG_Config::dbms,
103 :     # database type
104 :     dataDir => $FIG_Config::sproutData,
105 :     # data file directory
106 : parrello 1.78 xmlFileName => "$dbd_dir/SproutDBD.xml",
107 : parrello 1.18 # database definition file name
108 :     userData => "$FIG_Config::dbuser/$FIG_Config::dbpass",
109 :     # user name and password
110 :     port => $FIG_Config::dbport,
111 :     # database connection port
112 : parrello 1.69 sock => $FIG_Config::dbsock,
113 : olson 1.79 host => $FIG_Config::dbhost,
114 : parrello 1.15 maxSegmentLength => 4500, # maximum feature segment length
115 :     maxSequenceLength => 8000, # maximum contig sequence length
116 : parrello 1.25 noDBOpen => 0, # 1 to suppress the database open
117 : parrello 1.15 }, $options);
118 :     # Get the data directory.
119 :     my $dataDir = $optionTable->{dataDir};
120 :     # Extract the user ID and password.
121 :     $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
122 :     my ($userName, $password) = ($1, $2);
123 :     # Connect to the database.
124 : parrello 1.25 my $dbh;
125 :     if (! $optionTable->{noDBOpen}) {
126 :     $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
127 : olson 1.79 $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
128 : parrello 1.25 }
129 : parrello 1.15 # Create the ERDB object.
130 :     my $xmlFileName = "$optionTable->{xmlFileName}";
131 : parrello 1.58 my $retVal = ERDB::new($class, $dbh, $xmlFileName);
132 :     # Add the option table and XML file name.
133 :     $retVal->{_options} = $optionTable;
134 :     $retVal->{_xmlName} = $xmlFileName;
135 : parrello 1.85 # Set up space for the group file data.
136 :     $retVal->{groupHash} = undef;
137 : parrello 1.99 # Connect to the attributes.
138 :     if ($FIG_Config::attrURL) {
139 :     Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);
140 :     $retVal->{_ca} = RemoteCustomAttributes->new($FIG_Config::attrURL);
141 :     } elsif ($FIG_Config::attrDbName) {
142 :     Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);
143 :     my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));
144 :     $retVal->{_ca} = CustomAttributes->new(user => $user);
145 :     }
146 : parrello 1.58 # Return it.
147 :     return $retVal;
148 : parrello 1.1 }
149 :    
150 :     =head3 MaxSegment
151 :    
152 :     C<< my $length = $sprout->MaxSegment(); >>
153 :    
154 :     This method returns the maximum permissible length of a feature segment. The length is important
155 :     because it enables us to make reasonable guesses at how to find features inside a particular
156 :     contig region. For example, if the maximum length is 4000 and we're looking for a feature that
157 :     overlaps the region from 6000 to 7000 we know that the starting position must be between 2001
158 :     and 10999.
159 :    
160 :     =cut
161 : parrello 1.3 #: Return Type $;
162 : parrello 1.1 sub MaxSegment {
163 : parrello 1.15 my ($self) = @_;
164 :     return $self->{_options}->{maxSegmentLength};
165 : parrello 1.1 }
166 :    
167 :     =head3 MaxSequence
168 :    
169 :     C<< my $length = $sprout->MaxSequence(); >>
170 :    
171 :     This method returns the maximum permissible length of a contig sequence. A contig is broken
172 :     into sequences in order to save memory resources. In particular, when manipulating features,
173 :     we generally only need a few sequences in memory rather than the entire contig.
174 :    
175 :     =cut
176 : parrello 1.3 #: Return Type $;
177 : parrello 1.1 sub MaxSequence {
178 : parrello 1.15 my ($self) = @_;
179 :     return $self->{_options}->{maxSequenceLength};
180 : parrello 1.1 }
181 :    
182 :     =head3 Load
183 :    
184 :     C<< $sprout->Load($rebuild); >>;
185 :    
186 :     Load the database from files in the data directory, optionally re-creating the tables.
187 :    
188 :     This method always deletes the data from the database before loading, even if the tables are not
189 :     re-created. The data is loaded into the relations from files in the data directory either having the
190 :     same name as the target relation with no extension or with an extension of C<.dtx>. Files without an
191 :     extension are used in preference to the files with an extension.
192 :    
193 :     The files are loaded based on the presumption that each line of the file is a record in the
194 :     relation, and the individual fields are delimited by tabs. Tab and new-line characters inside
195 :     fields must be represented by the escape sequences C<\t> and C<\n>, respectively. The fields must
196 :     be presented in the order given in the relation tables produced by the L</ShowMetaData> method.
197 :    
198 :     =over 4
199 :    
200 :     =item rebuild
201 :    
202 :     TRUE if the data tables need to be created or re-created, else FALSE
203 :    
204 :     =item RETURN
205 :    
206 :     Returns a statistical object containing the number of records read, the number of duplicates found,
207 :     the number of errors, and a list of the error messages.
208 :    
209 :     =back
210 :    
211 :     =cut
212 : parrello 1.3 #: Return Type %;
213 : parrello 1.1 sub Load {
214 : parrello 1.15 # Get the parameters.
215 :     my ($self, $rebuild) = @_;
216 :     # Load the tables from the data directory.
217 : parrello 1.58 my $retVal = $self->LoadTables($self->{_options}->{dataDir}, $rebuild);
218 : parrello 1.15 # Return the statistics.
219 :     return $retVal;
220 : parrello 1.1 }
221 :    
222 :     =head3 LoadUpdate
223 :    
224 : parrello 1.44 C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
225 : parrello 1.1
226 :     Load updates to one or more database tables. This method enables the client to make changes to one
227 :     or two tables without reloading the whole database. For each table, there must be a corresponding
228 :     file in the data directory, either with the same name as the table, or with a C<.dtx> suffix. So,
229 :     for example, to make updates to the B<FeatureTranslation> relation, there must be a
230 :     C<FeatureTranslation.dtx> file in the data directory. Unlike a full load, files without an extension
231 :     are not examined. This allows update files to co-exist with files from an original load.
232 :    
233 :     =over 4
234 :    
235 :     =item truncateFlag
236 :    
237 :     TRUE if the tables should be rebuilt before loading, else FALSE. A value of TRUE therefore causes
238 :     current data and schema of the tables to be replaced, while a value of FALSE means the new data
239 :     is added to the existing data in the various relations.
240 :    
241 :     =item tableList
242 :    
243 :     List of the tables to be updated.
244 :    
245 :     =item RETURN
246 :    
247 :     Returns a statistical object containing the number of records read, the number of duplicates found,
248 :     the number of errors encountered, and a list of error messages.
249 :    
250 :     =back
251 :    
252 :     =cut
253 : parrello 1.7 #: Return Type $%;
254 : parrello 1.1 sub LoadUpdate {
255 : parrello 1.15 # Get the parameters.
256 :     my ($self, $truncateFlag, $tableList) = @_;
257 :     # Declare the return value.
258 :     my $retVal = Stats->new();
259 :     # Get the data directory.
260 :     my $optionTable = $self->{_options};
261 :     my $dataDir = $optionTable->{dataDir};
262 :     # Loop through the incoming table names.
263 :     for my $tableName (@{$tableList}) {
264 :     # Find the table's file.
265 : parrello 1.18 my $fileName = LoadFileName($dataDir, $tableName);
266 :     if (! $fileName) {
267 :     Trace("No load file found for $tableName in $dataDir.") if T(0);
268 :     } else {
269 :     # Attempt to load this table.
270 : parrello 1.58 my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);
271 : parrello 1.18 # Accumulate the resulting statistics.
272 :     $retVal->Accumulate($result);
273 : parrello 1.15 }
274 :     }
275 :     # Return the statistics.
276 :     return $retVal;
277 : parrello 1.1 }
278 :    
279 : parrello 1.58 =head3 GenomeCounts
280 :    
281 :     C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>
282 :    
283 :     Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
284 :     genomes will be included in the counts.
285 :    
286 :     =over 4
287 :    
288 :     =item complete
289 :    
290 :     TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
291 :     counted
292 :    
293 :     =item RETURN
294 :    
295 :     A six-element list containing the number of genomes in each of six categories--
296 :     Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
297 :    
298 :     =back
299 :    
300 :     =cut
301 :    
302 :     sub GenomeCounts {
303 :     # Get the parameters.
304 :     my ($self, $complete) = @_;
305 :     # Set the filter based on the completeness flag.
306 :     my $filter = ($complete ? "Genome(complete) = 1" : "");
307 :     # Get all the genomes and the related taxonomy information.
308 :     my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
309 :     # Clear the counters.
310 :     my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
311 :     # Loop through, counting the domains.
312 :     for my $genome (@genomes) {
313 :     if ($genome->[1] =~ /^archaea/i) { ++$arch }
314 :     elsif ($genome->[1] =~ /^bacter/i) { ++$bact }
315 :     elsif ($genome->[1] =~ /^eukar/i) { ++$euk }
316 :     elsif ($genome->[1] =~ /^vir/i) { ++$vir }
317 :     elsif ($genome->[1] =~ /^env/i) { ++$env }
318 :     else { ++$unk }
319 :     }
320 :     # Return the counts.
321 :     return ($arch, $bact, $euk, $vir, $env, $unk);
322 :     }
323 :    
324 : parrello 1.59 =head3 ContigCount
325 :    
326 :     C<< my $count = $sprout->ContigCount($genomeID); >>
327 :    
328 :     Return the number of contigs for the specified genome ID.
329 :    
330 :     =over 4
331 :    
332 :     =item genomeID
333 :    
334 :     ID of the genome whose contig count is desired.
335 :    
336 :     =item RETURN
337 :    
338 :     Returns the number of contigs for the specified genome.
339 :    
340 :     =back
341 :    
342 :     =cut
343 :    
344 :     sub ContigCount {
345 :     # Get the parameters.
346 :     my ($self, $genomeID) = @_;
347 :     # Get the contig count.
348 :     my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
349 :     # Return the result.
350 :     return $retVal;
351 :     }
352 :    
353 :     =head3 GeneMenu
354 :    
355 : parrello 1.85 C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected); >>
356 : parrello 1.59
357 :     Return an HTML select menu of genomes. Each genome will be an option in the menu,
358 :     and will be displayed by name with the ID and a contig count attached. The selection
359 :     value will be the genome ID. The genomes will be sorted by genus/species name.
360 :    
361 :     =over 4
362 :    
363 :     =item attributes
364 :    
365 :     Reference to a hash mapping attributes to values for the SELECT tag generated.
366 :    
367 :     =item filterString
368 :    
369 :     A filter string for use in selecting the genomes. The filter string must conform
370 :     to the rules for the C<< ERDB->Get >> method.
371 :    
372 :     =item params
373 :    
374 :     Reference to a list of values to be substituted in for the parameter marks in
375 :     the filter string.
376 :    
377 : parrello 1.85 =item selected (optional)
378 :    
379 :     ID of the genome to be initially selected.
380 :    
381 :     =item fast (optional)
382 :    
383 :     If specified and TRUE, the contig counts will be omitted to improve performance.
384 :    
385 : parrello 1.59 =item RETURN
386 :    
387 :     Returns an HTML select menu with the specified genomes as selectable options.
388 :    
389 :     =back
390 :    
391 :     =cut
392 :    
393 :     sub GeneMenu {
394 :     # Get the parameters.
395 : parrello 1.85 my ($self, $attributes, $filterString, $params, $selected, $fast) = @_;
396 :     my $slowMode = ! $fast;
397 :     # Default to nothing selected. This prevents an execution warning if "$selected"
398 :     # is undefined.
399 :     $selected = "" unless defined $selected;
400 :     Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3);
401 : parrello 1.59 # Start the menu.
402 :     my $retVal = "<select " .
403 :     join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
404 :     ">\n";
405 :     # Get the genomes.
406 :     my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
407 :     'Genome(genus)',
408 : parrello 1.69 'Genome(species)',
409 :     'Genome(unique-characterization)']);
410 : parrello 1.59 # Sort them by name.
411 :     my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
412 :     # Loop through the genomes, creating the option tags.
413 :     for my $genomeData (@sorted) {
414 :     # Get the data for this genome.
415 : parrello 1.69 my ($genomeID, $genus, $species, $strain) = @{$genomeData};
416 : parrello 1.59 # Get the contig count.
417 : parrello 1.85 my $contigInfo = "";
418 :     if ($slowMode) {
419 :     my $count = $self->ContigCount($genomeID);
420 :     my $counting = ($count == 1 ? "contig" : "contigs");
421 :     $contigInfo = "[$count $counting]";
422 :     }
423 :     # Find out if we're selected.
424 :     my $selectOption = ($selected eq $genomeID ? " selected" : "");
425 : parrello 1.59 # Build the option tag.
426 : parrello 1.85 $retVal .= "<option value=\"$genomeID\"$selectOption>$genus $species $strain ($genomeID)$contigInfo</option>\n";
427 : parrello 1.59 }
428 :     # Close the SELECT tag.
429 :     $retVal .= "</select>\n";
430 :     # Return the result.
431 :     return $retVal;
432 :     }
433 : parrello 1.85
434 : parrello 1.1 =head3 Build
435 :    
436 :     C<< $sprout->Build(); >>
437 :    
438 :     Build the database. The database will be cleared and the tables re-created from the metadata.
439 :     This method is useful when a database is brand new or when the database definition has
440 :     changed.
441 :    
442 :     =cut
443 : parrello 1.3 #: Return Type ;
444 : parrello 1.1 sub Build {
445 : parrello 1.15 # Get the parameters.
446 :     my ($self) = @_;
447 :     # Create the tables.
448 : parrello 1.58 $self->CreateTables();
449 : parrello 1.1 }
450 :    
451 :     =head3 Genomes
452 :    
453 :     C<< my @genomes = $sprout->Genomes(); >>
454 :    
455 :     Return a list of all the genome IDs.
456 :    
457 :     =cut
458 : parrello 1.3 #: Return Type @;
459 : parrello 1.1 sub Genomes {
460 : parrello 1.15 # Get the parameters.
461 :     my ($self) = @_;
462 :     # Get all the genomes.
463 :     my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');
464 :     # Return the list of IDs.
465 :     return @retVal;
466 : parrello 1.1 }
467 :    
468 :     =head3 GenusSpecies
469 :    
470 :     C<< my $infoString = $sprout->GenusSpecies($genomeID); >>
471 :    
472 :     Return the genus, species, and unique characterization for a genome.
473 :    
474 :     =over 4
475 :    
476 :     =item genomeID
477 :    
478 :     ID of the genome whose genus and species is desired
479 :    
480 :     =item RETURN
481 :    
482 :     Returns the genus and species of the genome, with the unique characterization (if any). If the genome
483 :     does not exist, returns an undefined value.
484 :    
485 :     =back
486 :    
487 :     =cut
488 : parrello 1.3 #: Return Type $;
489 : parrello 1.1 sub GenusSpecies {
490 : parrello 1.15 # Get the parameters.
491 :     my ($self, $genomeID) = @_;
492 :     # Get the data for the specified genome.
493 :     my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',
494 :     'Genome(unique-characterization)']);
495 :     # Format the result and return it.
496 :     my $retVal = join(' ', @values);
497 :     return $retVal;
498 : parrello 1.1 }
499 :    
500 :     =head3 FeaturesOf
501 :    
502 :     C<< my @features = $sprout->FeaturesOf($genomeID, $ftype); >>
503 :    
504 :     Return a list of the features relevant to a specified genome.
505 :    
506 :     =over 4
507 :    
508 :     =item genomeID
509 :    
510 :     Genome whose features are desired.
511 :    
512 :     =item ftype
513 :    
514 :     Type of feature desired. If omitted, all features will be returned.
515 :    
516 :     =item RETURN
517 :    
518 :     Returns a list of the feature IDs for features relevant to the genome. If the genome does not exist,
519 :     will return an empty list.
520 :    
521 :     =back
522 :    
523 :     =cut
524 : parrello 1.3 #: Return Type @;
525 : parrello 1.1 sub FeaturesOf {
526 : parrello 1.15 # Get the parameters.
527 :     my ($self, $genomeID,$ftype) = @_;
528 :     # Get the features we want.
529 :     my @features;
530 :     if (!$ftype) {
531 :     @features = $self->GetFlat(['HasContig', 'IsLocatedIn'], "HasContig(from-link) = ?",
532 :     [$genomeID], 'IsLocatedIn(from-link)');
533 :     } else {
534 :     @features = $self->GetFlat(['HasContig', 'IsLocatedIn', 'Feature'],
535 :     "HasContig(from-link) = ? AND Feature(feature-type) = ?",
536 :     [$genomeID, $ftype], 'IsLocatedIn(from-link)');
537 :     }
538 :     # Return the list with duplicates merged out. We need to merge out duplicates because
539 :     # a feature will appear twice if it spans more than one contig.
540 :     my @retVal = Tracer::Merge(@features);
541 :     # Return the list of feature IDs.
542 :     return @retVal;
543 : parrello 1.1 }
544 :    
545 :     =head3 FeatureLocation
546 :    
547 :     C<< my @locations = $sprout->FeatureLocation($featureID); >>
548 :    
549 :     Return the location of a feature in its genome's contig segments. In a list context, this method
550 :     will return a list of the locations. In a scalar context, it will return the locations as a space-
551 :     delimited string. Each location will be of the form I<contigID>C<_>I<begin>I<dir>I<len> where
552 :     I<begin> is the starting position, I<dir> is C<+> for a forward transcription or C<-> for a backward
553 :     transcription, and I<len> is the length. So, for example, C<1999.1_NC123_4000+200> describes a location
554 :     beginning at position 4000 of contig C<1999.1_NC123> and ending at position 4199. Similarly,
555 :     C<1999.1_NC123_2000-400> describes a location in the same contig starting at position 2000 and ending
556 :     at position 1601.
557 :    
558 :     This process is complicated by the fact that we automatically split up feature segments longer than
559 :     the maximum segment length. When we find two segments that are adjacent to each other, we must
560 :     put them back together.
561 :    
562 :     =over 4
563 :    
564 :     =item featureID
565 :    
566 :     FIG ID of the desired feature
567 :    
568 :     =item RETURN
569 :    
570 :     Returns a list of the feature's contig segments. The locations are returned as a list in a list
571 : parrello 1.20 context and as a comma-delimited string in a scalar context.
572 : parrello 1.1
573 :     =back
574 :    
575 :     =cut
576 : parrello 1.3 #: Return Type @;
577 :     #: Return Type $;
578 : parrello 1.1 sub FeatureLocation {
579 : parrello 1.15 # Get the parameters.
580 :     my ($self, $featureID) = @_;
581 :     # Create a query for the feature locations.
582 :     my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",
583 :     [$featureID]);
584 :     # Create the return list.
585 :     my @retVal = ();
586 :     # Set up the variables used to determine if we have adjacent segments. This initial setup will
587 :     # not match anything.
588 :     my ($prevContig, $prevBeg, $prevDir, $prevLen) = ("", 0, "0", 0);
589 :     # Loop through the query results, creating location specifiers.
590 :     while (my $location = $query->Fetch()) {
591 :     # Get the location parameters.
592 :     my ($contigID, $beg, $dir, $len) = $location->Values(['IsLocatedIn(to-link)',
593 :     'IsLocatedIn(beg)', 'IsLocatedIn(dir)', 'IsLocatedIn(len)']);
594 :     # Check to see if we are adjacent to the previous segment.
595 :     if ($prevContig eq $contigID && $dir eq $prevDir) {
596 :     # Here the new segment is in the same direction on the same contig. Insure the
597 :     # new segment's beginning is next to the old segment's end.
598 : parrello 1.41 if ($dir eq "-" && $beg + $len == $prevBeg) {
599 :     # Here we're merging two backward blocks, so we keep the new begin point
600 :     # and adjust the length.
601 :     $len += $prevLen;
602 :     # Pop the old segment off. The new one will replace it later.
603 :     pop @retVal;
604 :     } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
605 :     # Here we need to merge two forward blocks. Adjust the beginning and
606 :     # length values to include both segments.
607 : parrello 1.15 $beg = $prevBeg;
608 :     $len += $prevLen;
609 :     # Pop the old segment off. The new one will replace it later.
610 :     pop @retVal;
611 :     }
612 :     }
613 :     # Remember this specifier for the adjacent-segment test the next time through.
614 :     ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
615 : parrello 1.32 # Compute the initial base pair.
616 :     my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
617 : parrello 1.15 # Add the specifier to the list.
618 : parrello 1.33 push @retVal, "${contigID}_$start$dir$len";
619 : parrello 1.15 }
620 :     # Return the list in the format indicated by the context.
621 : parrello 1.20 return (wantarray ? @retVal : join(',', @retVal));
622 : parrello 1.1 }
623 :    
624 :     =head3 ParseLocation
625 :    
626 :     C<< my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location); >>
627 :    
628 :     Split a location specifier into the contig ID, the starting point, the direction, and the
629 :     length.
630 :    
631 :     =over 4
632 :    
633 :     =item location
634 :    
635 :     A location specifier (see L</FeatureLocation> for a description).
636 :    
637 :     =item RETURN
638 :    
639 :     Returns a list containing the contig ID, the start position, the direction (C<+> or C<->),
640 :     and the length indicated by the incoming location specifier.
641 :    
642 :     =back
643 :    
644 :     =cut
645 : parrello 1.3 #: Return Type @;
646 : parrello 1.1 sub ParseLocation {
647 : parrello 1.15 # Get the parameter. Note that if we're called as an instance method, we ignore
648 : parrello 1.10 # the first parameter.
649 :     shift if UNIVERSAL::isa($_[0],__PACKAGE__);
650 : parrello 1.15 my ($location) = @_;
651 :     # Parse it into segments.
652 : parrello 1.40 $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
653 : parrello 1.15 my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
654 :     # If the direction is an underscore, convert it to a + or -.
655 :     if ($dir eq "_") {
656 :     if ($start < $len) {
657 :     $dir = "+";
658 :     $len = $len - $start + 1;
659 :     } else {
660 :     $dir = "-";
661 :     $len = $start - $len + 1;
662 :     }
663 :     }
664 :     # Return the result.
665 :     return ($contigID, $start, $dir, $len);
666 : parrello 1.1 }
667 :    
668 : parrello 1.85
669 :    
670 : parrello 1.10 =head3 PointLocation
671 :    
672 :     C<< my $found = Sprout::PointLocation($location, $point); >>
673 :    
674 :     Return the offset into the specified location of the specified point on the contig. If
675 :     the specified point is before the location, a negative value will be returned. If it is
676 : parrello 1.19 beyond the location, an undefined value will be returned. It is assumed that the offset
677 :     is for the location's contig. The location can either be new-style (using a C<+> or C<->
678 : parrello 1.10 and a length) or old-style (using C<_> and start and end positions.
679 :    
680 :     =over 4
681 :    
682 :     =item location
683 :    
684 :     A location specifier (see L</FeatureLocation> for a description).
685 :    
686 :     =item point
687 :    
688 :     The offset into the contig of the point in which we're interested.
689 :    
690 :     =item RETURN
691 :    
692 :     Returns the offset inside the specified location of the specified point, a negative
693 :     number if the point is before the location, or an undefined value if the point is past
694 :     the location. If the length of the location is 0, this method will B<always> denote
695 :     that it is outside the location. The offset will always be relative to the left-most
696 :     position in the location.
697 :    
698 :     =back
699 :    
700 :     =cut
701 :     #: Return Type $;
702 :     sub PointLocation {
703 : parrello 1.15 # Get the parameter. Note that if we're called as an instance method, we ignore
704 : parrello 1.10 # the first parameter.
705 :     shift if UNIVERSAL::isa($_[0],__PACKAGE__);
706 : parrello 1.15 my ($location, $point) = @_;
707 : parrello 1.10 # Parse out the location elements. Note that this works on both old-style and new-style
708 :     # locations.
709 :     my ($contigID, $start, $dir, $len) = ParseLocation($location);
710 :     # Declare the return variable.
711 :     my $retVal;
712 :     # Compute the offset. The computation is dependent on the direction of the location.
713 :     my $offset = (($dir == '+') ? $point - $start : $point - ($start - $len + 1));
714 :     # Return the offset if it's valid.
715 :     if ($offset < $len) {
716 :     $retVal = $offset;
717 :     }
718 :     # Return the offset found.
719 :     return $retVal;
720 :     }
721 :    
722 : parrello 1.1 =head3 DNASeq
723 :    
724 :     C<< my $sequence = $sprout->DNASeq(\@locationList); >>
725 :    
726 :     This method returns the DNA sequence represented by a list of locations. The list of locations
727 : parrello 1.2 should be of the form returned by L</featureLocation> when in a list context. In other words,
728 : parrello 1.1 each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.
729 :    
730 : parrello 1.55 For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
731 :     between positions 1401 and 1532, inclusive.
732 :    
733 :     my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
734 :    
735 : parrello 1.1 =over 4
736 :    
737 :     =item locationList
738 :    
739 : parrello 1.55 List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<len> or
740 :     I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
741 : parrello 1.1
742 :     =item RETURN
743 :    
744 :     Returns a string of nucleotides corresponding to the DNA segments in the location list.
745 :    
746 :     =back
747 :    
748 :     =cut
749 : parrello 1.3 #: Return Type $;
750 : parrello 1.1 sub DNASeq {
751 : parrello 1.15 # Get the parameters.
752 :     my ($self, $locationList) = @_;
753 :     # Create the return string.
754 :     my $retVal = "";
755 :     # Loop through the locations.
756 :     for my $location (@{$locationList}) {
757 :     # Set up a variable to contain the DNA at this location.
758 :     my $locationDNA = "";
759 :     # Parse out the contig ID, the beginning point, the direction, and the end point.
760 :     my ($contigID, $beg, $dir, $len) = ParseLocation($location);
761 :     # Now we must create a query to return all the sequences in the contig relevant to the region
762 :     # specified. First, we compute the start and stop points when reading through the sequences.
763 :     # For a forward transcription, the start point is the beginning; for a backward transcription,
764 :     # the start point is the ending. Note that in the latter case we must reverse the DNA string
765 :     # before putting it in the return value.
766 :     my ($start, $stop);
767 : parrello 1.34 Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
768 : parrello 1.15 if ($dir eq "+") {
769 :     $start = $beg;
770 : parrello 1.38 $stop = $beg + $len - 1;
771 : parrello 1.15 } else {
772 : parrello 1.38 $start = $beg - $len + 1;
773 :     $stop = $beg;
774 : parrello 1.15 }
775 : parrello 1.38 Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
776 : parrello 1.15 my $query = $self->Get(['IsMadeUpOf','Sequence'],
777 :     "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
778 : parrello 1.38 " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
779 : parrello 1.15 [$contigID, $start, $stop]);
780 :     # Loop through the sequences.
781 :     while (my $sequence = $query->Fetch()) {
782 :     # Determine whether the location starts, stops, or continues through this sequence.
783 :     my ($startPosition, $sequenceData, $sequenceLength) =
784 :     $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
785 :     'IsMadeUpOf(len)']);
786 :     my $stopPosition = $startPosition + $sequenceLength;
787 : parrello 1.29 Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
788 : parrello 1.15 # Figure out the start point and length of the relevant section.
789 :     my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
790 : parrello 1.39 my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
791 : parrello 1.29 Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
792 : parrello 1.15 # Add the relevant data to the location data.
793 : parrello 1.29 $locationDNA .= substr($sequenceData, $pos1, $len1);
794 : parrello 1.15 }
795 :     # Add this location's data to the return string. Note that we may need to reverse it.
796 :     if ($dir eq '+') {
797 :     $retVal .= $locationDNA;
798 :     } else {
799 : parrello 1.27 $retVal .= FIG::reverse_comp($locationDNA);
800 : parrello 1.15 }
801 :     }
802 :     # Return the result.
803 :     return $retVal;
804 : parrello 1.1 }
805 :    
806 :     =head3 AllContigs
807 :    
808 :     C<< my @idList = $sprout->AllContigs($genomeID); >>
809 :    
810 :     Return a list of all the contigs for a genome.
811 :    
812 :     =over 4
813 :    
814 :     =item genomeID
815 :    
816 :     Genome whose contigs are desired.
817 :    
818 :     =item RETURN
819 :    
820 :     Returns a list of the IDs for the genome's contigs.
821 :    
822 :     =back
823 :    
824 :     =cut
825 : parrello 1.3 #: Return Type @;
826 : parrello 1.1 sub AllContigs {
827 : parrello 1.15 # Get the parameters.
828 :     my ($self, $genomeID) = @_;
829 :     # Ask for the genome's Contigs.
830 :     my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],
831 :     'HasContig(to-link)');
832 :     # Return the list of Contigs.
833 :     return @retVal;
834 : parrello 1.1 }
835 :    
836 : parrello 1.62 =head3 GenomeLength
837 :    
838 :     C<< my $length = $sprout->GenomeLength($genomeID); >>
839 :    
840 :     Return the length of the specified genome in base pairs.
841 :    
842 :     =over 4
843 :    
844 :     =item genomeID
845 :    
846 :     ID of the genome whose base pair count is desired.
847 :    
848 :     =item RETURN
849 :    
850 :     Returns the number of base pairs in all the contigs of the specified
851 :     genome.
852 :    
853 :     =back
854 :    
855 :     =cut
856 :    
857 :     sub GenomeLength {
858 :     # Get the parameters.
859 :     my ($self, $genomeID) = @_;
860 :     # Declare the return variable.
861 :     my $retVal = 0;
862 :     # Get the genome's contig sequence lengths.
863 : parrello 1.63 my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
864 : parrello 1.62 [$genomeID], 'IsMadeUpOf(len)');
865 :     # Sum the lengths.
866 :     map { $retVal += $_ } @lens;
867 :     # Return the result.
868 :     return $retVal;
869 :     }
870 :    
871 :     =head3 FeatureCount
872 :    
873 :     C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
874 :    
875 :     Return the number of features of the specified type in the specified genome.
876 :    
877 :     =over 4
878 :    
879 : parrello 1.68 =item genomeID
880 : parrello 1.62
881 :     ID of the genome whose feature count is desired.
882 :    
883 :     =item type
884 :    
885 :     Type of feature to count (eg. C<peg>, C<rna>, etc.).
886 :    
887 :     =item RETURN
888 :    
889 :     Returns the number of features of the specified type for the specified genome.
890 :    
891 :     =back
892 :    
893 :     =cut
894 :    
895 :     sub FeatureCount {
896 :     # Get the parameters.
897 :     my ($self, $genomeID, $type) = @_;
898 :     # Compute the count.
899 :     my $retVal = $self->GetCount(['HasFeature', 'Feature'],
900 : parrello 1.64 "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
901 : parrello 1.62 [$genomeID, $type]);
902 :     # Return the result.
903 :     return $retVal;
904 :     }
905 :    
906 :     =head3 GenomeAssignments
907 :    
908 :     C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
909 :    
910 :     Return a list of a genome's assigned features. The return hash will contain each
911 :     assigned feature of the genome mapped to the text of its most recent functional
912 :     assignment.
913 :    
914 :     =over 4
915 :    
916 :     =item genomeID
917 :    
918 :     ID of the genome whose functional assignments are desired.
919 :    
920 :     =item RETURN
921 :    
922 :     Returns a reference to a hash which maps each feature to its most recent
923 :     functional assignment.
924 :    
925 :     =back
926 :    
927 :     =cut
928 :    
929 :     sub GenomeAssignments {
930 :     # Get the parameters.
931 :     my ($self, $genomeID) = @_;
932 :     # Declare the return variable.
933 :     my $retVal = {};
934 : parrello 1.93 # Query the genome's features.
935 :     my $query = $self->Get(['HasFeature', 'Feature'], "HasFeature(from-link) = ?",
936 : parrello 1.62 [$genomeID]);
937 : parrello 1.93 # Loop through the features.
938 : parrello 1.62 while (my $data = $query->Fetch) {
939 : parrello 1.93 # Get the feature ID and assignment.
940 :     my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']);
941 :     if ($assignment) {
942 : parrello 1.62 $retVal->{$fid} = $assignment;
943 :     }
944 :     }
945 :     # Return the result.
946 :     return $retVal;
947 :     }
948 :    
949 : parrello 1.1 =head3 ContigLength
950 :    
951 :     C<< my $length = $sprout->ContigLength($contigID); >>
952 :    
953 :     Compute the length of a contig.
954 :    
955 :     =over 4
956 :    
957 :     =item contigID
958 :    
959 :     ID of the contig whose length is desired.
960 :    
961 : parrello 1.3 =item RETURN
962 :    
963 :     Returns the number of positions in the contig.
964 :    
965 : parrello 1.1 =back
966 :    
967 :     =cut
968 : parrello 1.3 #: Return Type $;
969 : parrello 1.1 sub ContigLength {
970 : parrello 1.15 # Get the parameters.
971 :     my ($self, $contigID) = @_;
972 :     # Get the contig's last sequence.
973 :     my $query = $self->Get(['IsMadeUpOf'],
974 :     "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
975 :     [$contigID]);
976 :     my $sequence = $query->Fetch();
977 :     # Declare the return value.
978 :     my $retVal = 0;
979 :     # Set it from the sequence data, if any.
980 :     if ($sequence) {
981 :     my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
982 : parrello 1.40 $retVal = $start + $len - 1;
983 :     }
984 :     # Return the result.
985 :     return $retVal;
986 :     }
987 :    
988 :     =head3 ClusterPEGs
989 :    
990 :     C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
991 :    
992 :     Cluster the PEGs in a list according to the cluster coding scheme of the specified
993 :     subsystem. In order for this to work properly, the subsystem object must have
994 :     been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
995 :     This causes the cluster numbers to be pulled into the subsystem's color hash.
996 :     If a PEG is not found in the color hash, it will not appear in the output
997 :     sequence.
998 :    
999 :     =over 4
1000 :    
1001 :     =item sub
1002 :    
1003 :     Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
1004 :     method.
1005 :    
1006 :     =item pegs
1007 :    
1008 :     Reference to the list of PEGs to be clustered.
1009 :    
1010 :     =item RETURN
1011 :    
1012 :     Returns a list of the PEGs, grouped into smaller lists by cluster number.
1013 :    
1014 :     =back
1015 :    
1016 :     =cut
1017 :     #: Return Type $@@;
1018 :     sub ClusterPEGs {
1019 :     # Get the parameters.
1020 :     my ($self, $sub, $pegs) = @_;
1021 :     # Declare the return variable.
1022 :     my $retVal = [];
1023 :     # Loop through the PEGs, creating arrays for each cluster.
1024 :     for my $pegID (@{$pegs}) {
1025 :     my $clusterNumber = $sub->get_cluster_number($pegID);
1026 :     # Only proceed if the PEG is in a cluster.
1027 :     if ($clusterNumber >= 0) {
1028 :     # Push this PEG onto the sub-list for the specified cluster number.
1029 :     push @{$retVal->[$clusterNumber]}, $pegID;
1030 :     }
1031 : parrello 1.15 }
1032 :     # Return the result.
1033 :     return $retVal;
1034 : parrello 1.1 }
1035 :    
1036 :     =head3 GenesInRegion
1037 :    
1038 :     C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>
1039 :    
1040 :     List the features which overlap a specified region in a contig.
1041 :    
1042 :     =over 4
1043 :    
1044 :     =item contigID
1045 :    
1046 :     ID of the contig containing the region of interest.
1047 :    
1048 :     =item start
1049 :    
1050 :     Offset of the first residue in the region of interest.
1051 :    
1052 :     =item stop
1053 :    
1054 :     Offset of the last residue in the region of interest.
1055 :    
1056 :     =item RETURN
1057 :    
1058 :     Returns a three-element list. The first element is a list of feature IDs for the features that
1059 :     overlap the region of interest. The second and third elements are the minimum and maximum
1060 :     locations of the features provided on the specified contig. These may extend outside
1061 : parrello 1.9 the start and stop values. The first element (that is, the list of features) is sorted
1062 :     roughly by location.
1063 : parrello 1.1
1064 :     =back
1065 :    
1066 :     =cut
1067 : parrello 1.9 #: Return Type @@;
1068 : parrello 1.1 sub GenesInRegion {
1069 : parrello 1.15 # Get the parameters.
1070 :     my ($self, $contigID, $start, $stop) = @_;
1071 :     # Get the maximum segment length.
1072 :     my $maximumSegmentLength = $self->MaxSegment;
1073 :     # Create a hash to receive the feature list. We use a hash so that we can eliminate
1074 :     # duplicates easily. The hash key will be the feature ID. The value will be a two-element
1075 : parrello 1.19 # containing the minimum and maximum offsets. We will use the offsets to sort the results
1076 : parrello 1.15 # when we're building the result set.
1077 :     my %featuresFound = ();
1078 :     # Prime the values we'll use for the returned beginning and end.
1079 :     my @initialMinMax = ($self->ContigLength($contigID), 0);
1080 :     my ($min, $max) = @initialMinMax;
1081 :     # Create a table of parameters for each query. Each query looks for features travelling in
1082 :     # a particular direction. The query parameters include the contig ID, the feature direction,
1083 :     # the lowest possible start position, and the highest possible start position. This works
1084 :     # because each feature segment length must be no greater than the maximum segment length.
1085 :     my %queryParms = (forward => [$contigID, '+', $start - $maximumSegmentLength + 1, $stop],
1086 :     reverse => [$contigID, '-', $start, $stop + $maximumSegmentLength - 1]);
1087 :     # Loop through the query parameters.
1088 :     for my $parms (values %queryParms) {
1089 :     # Create the query.
1090 :     my $query = $self->Get(['IsLocatedIn'],
1091 :     "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
1092 :     $parms);
1093 :     # Loop through the feature segments found.
1094 :     while (my $segment = $query->Fetch) {
1095 :     # Get the data about this segment.
1096 :     my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',
1097 :     'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);
1098 :     # Determine if this feature actually overlaps the region. The query insures that
1099 :     # this will be the case if the segment is the maximum length, so to fine-tune
1100 :     # the results we insure that the inequality from the query holds using the actual
1101 :     # length.
1102 :     my ($found, $end) = (0, 0);
1103 :     if ($dir eq '+') {
1104 :     $end = $beg + $len;
1105 :     if ($end >= $start) {
1106 :     # Denote we found a useful feature.
1107 :     $found = 1;
1108 :     }
1109 :     } elsif ($dir eq '-') {
1110 :     # Note we switch things around so that the beginning is to the left of the
1111 :     # ending.
1112 :     ($beg, $end) = ($beg - $len, $beg);
1113 :     if ($beg <= $stop) {
1114 :     # Denote we found a useful feature.
1115 :     $found = 1;
1116 :     }
1117 :     }
1118 :     if ($found) {
1119 :     # Here we need to record the feature and update the minima and maxima. First,
1120 :     # get the current entry for the specified feature.
1121 :     my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :
1122 :     @initialMinMax);
1123 :     # Merge the current segment's begin and end into the feature begin and end and the
1124 :     # global min and max.
1125 :     if ($beg < $loc1) {
1126 :     $loc1 = $beg;
1127 :     $min = $beg if $beg < $min;
1128 :     }
1129 :     if ($end > $loc2) {
1130 :     $loc2 = $end;
1131 :     $max = $end if $end > $max;
1132 :     }
1133 :     # Store the entry back into the hash table.
1134 :     $featuresFound{$featureID} = [$loc1, $loc2];
1135 :     }
1136 :     }
1137 :     }
1138 :     # Now we must compute the list of the IDs for the features found. We start with a list
1139 :     # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1140 :     # but the result of the sort will be the same.)
1141 :     my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;
1142 :     # Now we sort by midpoint and yank out the feature IDs.
1143 :     my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1144 :     # Return it along with the min and max.
1145 :     return (\@retVal, $min, $max);
1146 : parrello 1.1 }
1147 :    
1148 :     =head3 FType
1149 :    
1150 :     C<< my $ftype = $sprout->FType($featureID); >>
1151 :    
1152 :     Return the type of a feature.
1153 :    
1154 :     =over 4
1155 :    
1156 :     =item featureID
1157 :    
1158 :     ID of the feature whose type is desired.
1159 :    
1160 :     =item RETURN
1161 :    
1162 :     A string indicating the type of feature (e.g. peg, rna). If the feature does not exist, returns an
1163 :     undefined value.
1164 :    
1165 :     =back
1166 :    
1167 :     =cut
1168 : parrello 1.3 #: Return Type $;
1169 : parrello 1.1 sub FType {
1170 : parrello 1.15 # Get the parameters.
1171 :     my ($self, $featureID) = @_;
1172 :     # Get the specified feature's type.
1173 :     my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
1174 :     # Return the result.
1175 :     return $retVal;
1176 : parrello 1.1 }
1177 :    
1178 :     =head3 FeatureAnnotations
1179 :    
1180 : parrello 1.40 C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1181 : parrello 1.1
1182 :     Return the annotations of a feature.
1183 :    
1184 :     =over 4
1185 :    
1186 :     =item featureID
1187 :    
1188 :     ID of the feature whose annotations are desired.
1189 :    
1190 : parrello 1.40 =item rawFlag
1191 :    
1192 :     If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1193 :     will be returned in human-readable form.
1194 :    
1195 : parrello 1.1 =item RETURN
1196 :    
1197 :     Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.
1198 :    
1199 :     * B<featureID> ID of the relevant feature.
1200 :    
1201 : parrello 1.40 * B<timeStamp> time the annotation was made.
1202 : parrello 1.1
1203 :     * B<user> ID of the user who made the annotation
1204 :    
1205 :     * B<text> text of the annotation.
1206 :    
1207 :     =back
1208 :    
1209 :     =cut
1210 : parrello 1.3 #: Return Type @%;
1211 : parrello 1.1 sub FeatureAnnotations {
1212 : parrello 1.15 # Get the parameters.
1213 : parrello 1.40 my ($self, $featureID, $rawFlag) = @_;
1214 : parrello 1.15 # Create a query to get the feature's annotations and the associated users.
1215 :     my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1216 :     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
1217 :     # Create the return list.
1218 :     my @retVal = ();
1219 :     # Loop through the annotations.
1220 :     while (my $annotation = $query->Fetch) {
1221 :     # Get the fields to return.
1222 :     my ($featureID, $timeStamp, $user, $text) =
1223 :     $annotation->Values(['IsTargetOfAnnotation(from-link)',
1224 :     'Annotation(time)', 'MadeAnnotation(from-link)',
1225 :     'Annotation(annotation)']);
1226 : parrello 1.40 # Convert the time, if necessary.
1227 :     if (! $rawFlag) {
1228 :     $timeStamp = FriendlyTimestamp($timeStamp);
1229 :     }
1230 : parrello 1.15 # Assemble them into a hash.
1231 : parrello 1.3 my $annotationHash = { featureID => $featureID,
1232 : parrello 1.40 timeStamp => $timeStamp,
1233 : parrello 1.15 user => $user, text => $text };
1234 :     # Add it to the return list.
1235 :     push @retVal, $annotationHash;
1236 :     }
1237 :     # Return the result list.
1238 :     return @retVal;
1239 : parrello 1.1 }
1240 :    
1241 :     =head3 AllFunctionsOf
1242 :    
1243 :     C<< my %functions = $sprout->AllFunctionsOf($featureID); >>
1244 :    
1245 :     Return all of the functional assignments for a particular feature. The data is returned as a
1246 : parrello 1.11 hash of functional assignments to user IDs. A functional assignment is a type of annotation,
1247 : parrello 1.19 Functional assignments are described in the L</ParseAssignment> function. Its worth noting that
1248 :     we cannot filter on the content of the annotation itself because it's a text field; however,
1249 :     this is not a big problem because most features only have a small number of annotations.
1250 :     Finally, if a single user has multiple functional assignments, we will only keep the most
1251 : parrello 1.11 recent one.
1252 : parrello 1.1
1253 :     =over 4
1254 :    
1255 :     =item featureID
1256 :    
1257 :     ID of the feature whose functional assignments are desired.
1258 :    
1259 : parrello 1.3 =item RETURN
1260 :    
1261 : parrello 1.46 Returns a hash mapping the user IDs to functional assignment IDs.
1262 : parrello 1.3
1263 : parrello 1.1 =back
1264 :    
1265 :     =cut
1266 : parrello 1.3 #: Return Type %;
1267 : parrello 1.1 sub AllFunctionsOf {
1268 : parrello 1.15 # Get the parameters.
1269 :     my ($self, $featureID) = @_;
1270 :     # Get all of the feature's annotations.
1271 : parrello 1.47 my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1272 : parrello 1.15 "IsTargetOfAnnotation(from-link) = ?",
1273 : parrello 1.47 [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1274 :     'MadeAnnotation(from-link)']);
1275 : parrello 1.15 # Declare the return hash.
1276 :     my %retVal;
1277 : parrello 1.5 # Now we sort the assignments by timestamp in reverse.
1278 :     my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1279 : parrello 1.15 # Loop until we run out of annotations.
1280 : parrello 1.5 for my $annotation (@sortedQuery) {
1281 :     # Get the annotation fields.
1282 : parrello 1.47 my ($timeStamp, $text, $user) = @{$annotation};
1283 : parrello 1.15 # Check to see if this is a functional assignment.
1284 : parrello 1.48 my ($actualUser, $function) = _ParseAssignment($user, $text);
1285 :     if ($actualUser && ! exists $retVal{$actualUser}) {
1286 : parrello 1.5 # Here it is a functional assignment and there has been no
1287 :     # previous assignment for this user, so we stuff it in the
1288 :     # return hash.
1289 : parrello 1.48 $retVal{$actualUser} = $function;
1290 : parrello 1.15 }
1291 :     }
1292 :     # Return the hash of assignments found.
1293 :     return %retVal;
1294 : parrello 1.1 }
1295 :    
1296 :     =head3 FunctionOf
1297 :    
1298 :     C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>
1299 :    
1300 : parrello 1.3 Return the most recently-determined functional assignment of a particular feature.
1301 :    
1302 :     The functional assignment is handled differently depending on the type of feature. If
1303 : parrello 1.93 the feature is identified by a FIG ID (begins with the string C<fig|>), then the functional
1304 :     assignment is taken from the B<Feature> or C<Annotation> table, depending.
1305 : parrello 1.1
1306 : parrello 1.3 Each user has an associated list of trusted users. The assignment returned will be the most
1307 :     recent one by at least one of the trusted users. If no trusted user list is available, then
1308 :     the specified user and FIG are considered trusted. If the user ID is omitted, only FIG
1309 :     is trusted.
1310 :    
1311 :     If the feature is B<not> identified by a FIG ID, then the functional assignment
1312 :     information is taken from the B<ExternalAliasFunc> table. If the table does
1313 :     not contain an entry for the feature, an undefined value is returned.
1314 :    
1315 : parrello 1.1 =over 4
1316 :    
1317 :     =item featureID
1318 :    
1319 :     ID of the feature whose functional assignment is desired.
1320 :    
1321 :     =item userID (optional)
1322 :    
1323 : parrello 1.93 ID of the user whose function determination is desired. If omitted, the primary
1324 :     functional assignment in the B<Feature> table will be returned.
1325 : parrello 1.1
1326 :     =item RETURN
1327 :    
1328 :     Returns the text of the assigned function.
1329 :    
1330 :     =back
1331 :    
1332 :     =cut
1333 : parrello 1.3 #: Return Type $;
1334 : parrello 1.1 sub FunctionOf {
1335 : parrello 1.15 # Get the parameters.
1336 :     my ($self, $featureID, $userID) = @_;
1337 : parrello 1.3 # Declare the return value.
1338 :     my $retVal;
1339 :     # Determine the ID type.
1340 :     if ($featureID =~ m/^fig\|/) {
1341 : parrello 1.93 # Here we have a FIG feature ID.
1342 : parrello 1.3 if (!$userID) {
1343 : parrello 1.93 # Use the primary assignment.
1344 :     ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']);
1345 : parrello 1.3 } else {
1346 : parrello 1.93 # We must build the list of trusted users.
1347 :     my %trusteeTable = ();
1348 :     # Check the user ID.
1349 :     if (!$userID) {
1350 :     # No user ID, so only FIG is trusted.
1351 : parrello 1.3 $trusteeTable{FIG} = 1;
1352 :     } else {
1353 : parrello 1.93 # Add this user's ID.
1354 :     $trusteeTable{$userID} = 1;
1355 :     # Look for the trusted users in the database.
1356 :     my @trustees = $self->GetFlat(['IsTrustedBy'], 'IsTrustedBy(from-link) = ?', [$userID], 'IsTrustedBy(to-link)');
1357 :     if (! @trustees) {
1358 :     # None were found, so build a default list.
1359 :     $trusteeTable{FIG} = 1;
1360 :     } else {
1361 :     # Otherwise, put all the trustees in.
1362 :     for my $trustee (@trustees) {
1363 :     $trusteeTable{$trustee} = 1;
1364 :     }
1365 : parrello 1.3 }
1366 :     }
1367 : parrello 1.93 # Build a query for all of the feature's annotations, sorted by date.
1368 :     my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1369 :     "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1370 :     [$featureID]);
1371 :     my $timeSelected = 0;
1372 :     # Loop until we run out of annotations.
1373 :     while (my $annotation = $query->Fetch()) {
1374 :     # Get the annotation text.
1375 :     my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1376 :     'Annotation(time)', 'MadeAnnotation(from-link)']);
1377 :     # Check to see if this is a functional assignment for a trusted user.
1378 :     my ($actualUser, $function) = _ParseAssignment($user, $text);
1379 :     Trace("Assignment user is $actualUser, text is $function.") if T(4);
1380 :     if ($actualUser) {
1381 :     # Here it is a functional assignment. Check the time and the user
1382 :     # name. The time must be recent and the user must be trusted.
1383 :     if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1384 :     $retVal = $function;
1385 :     $timeSelected = $time;
1386 :     }
1387 : parrello 1.3 }
1388 :     }
1389 :     }
1390 :     } else {
1391 :     # Here we have a non-FIG feature ID. In this case the user ID does not
1392 :     # matter. We simply get the information from the External Alias Function
1393 :     # table.
1394 : parrello 1.4 ($retVal) = $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']);
1395 : parrello 1.3 }
1396 : parrello 1.15 # Return the assignment found.
1397 :     return $retVal;
1398 : parrello 1.1 }
1399 :    
1400 : parrello 1.45 =head3 FunctionsOf
1401 :    
1402 :     C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1403 :    
1404 :     Return the functional assignments of a particular feature.
1405 :    
1406 :     The functional assignment is handled differently depending on the type of feature. If
1407 :     the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1408 :     assignment is a type of annotation. The format of an assignment is described in
1409 :     L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1410 :     annotation itself because it's a text field; however, this is not a big problem because
1411 :     most features only have a small number of annotations.
1412 :    
1413 :     If the feature is B<not> identified by a FIG ID, then the functional assignment
1414 :     information is taken from the B<ExternalAliasFunc> table. If the table does
1415 :     not contain an entry for the feature, an empty list is returned.
1416 :    
1417 :     =over 4
1418 :    
1419 :     =item featureID
1420 :    
1421 :     ID of the feature whose functional assignments are desired.
1422 :    
1423 :     =item RETURN
1424 :    
1425 :     Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1426 :     that user.
1427 :    
1428 :     =back
1429 :    
1430 :     =cut
1431 :     #: Return Type @@;
1432 :     sub FunctionsOf {
1433 :     # Get the parameters.
1434 :     my ($self, $featureID) = @_;
1435 :     # Declare the return value.
1436 :     my @retVal = ();
1437 :     # Determine the ID type.
1438 :     if ($featureID =~ m/^fig\|/) {
1439 :     # Here we have a FIG feature ID. We must build the list of trusted
1440 :     # users.
1441 :     my %trusteeTable = ();
1442 :     # Build a query for all of the feature's annotations, sorted by date.
1443 : parrello 1.48 my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1444 : parrello 1.45 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1445 :     [$featureID]);
1446 :     my $timeSelected = 0;
1447 :     # Loop until we run out of annotations.
1448 :     while (my $annotation = $query->Fetch()) {
1449 :     # Get the annotation text.
1450 : parrello 1.48 my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1451 :     'Annotation(time)',
1452 :     'MadeAnnotation(user)']);
1453 : parrello 1.45 # Check to see if this is a functional assignment for a trusted user.
1454 : parrello 1.48 my ($actualUser, $function) = _ParseAssignment($user, $text);
1455 :     if ($actualUser) {
1456 : parrello 1.45 # Here it is a functional assignment.
1457 : parrello 1.48 push @retVal, [$actualUser, $function];
1458 : parrello 1.45 }
1459 :     }
1460 :     } else {
1461 :     # Here we have a non-FIG feature ID. In this case the user ID does not
1462 :     # matter. We simply get the information from the External Alias Function
1463 :     # table.
1464 : parrello 1.48 my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1465 :     ['ExternalAliasFunc(func)']);
1466 :     push @retVal, map { ['master', $_] } @assignments;
1467 : parrello 1.45 }
1468 :     # Return the assignments found.
1469 :     return @retVal;
1470 :     }
1471 :    
1472 : parrello 1.1 =head3 BBHList
1473 :    
1474 :     C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
1475 :    
1476 :     Return a hash mapping the features in a specified list to their bidirectional best hits
1477 :     on a specified target genome.
1478 :    
1479 :     =over 4
1480 :    
1481 :     =item genomeID
1482 :    
1483 :     ID of the genome from which the best hits should be taken.
1484 :    
1485 :     =item featureList
1486 :    
1487 :     List of the features whose best hits are desired.
1488 :    
1489 :     =item RETURN
1490 :    
1491 : parrello 1.15 Returns a reference to a hash that maps the IDs of the incoming features to the best hits
1492 :     on the target genome.
1493 : parrello 1.1
1494 :     =back
1495 :    
1496 :     =cut
1497 : parrello 1.3 #: Return Type %;
1498 : parrello 1.1 sub BBHList {
1499 : parrello 1.15 # Get the parameters.
1500 :     my ($self, $genomeID, $featureList) = @_;
1501 :     # Create the return structure.
1502 :     my %retVal = ();
1503 :     # Loop through the incoming features.
1504 :     for my $featureID (@{$featureList}) {
1505 : parrello 1.84 # Ask the server for the feature's best hit.
1506 :     my @bbhData = FIGRules::BBHData($featureID);
1507 : parrello 1.40 # Peel off the BBHs found.
1508 :     my @found = ();
1509 : parrello 1.84 for my $bbh (@bbhData) {
1510 : parrello 1.94 my $fid = $bbh->[0];
1511 :     my $bbGenome = $self->GenomeOf($fid);
1512 :     if ($bbGenome eq $genomeID) {
1513 :     push @found, $fid;
1514 :     }
1515 : parrello 1.15 }
1516 : parrello 1.40 $retVal{$featureID} = \@found;
1517 : parrello 1.15 }
1518 :     # Return the mapping.
1519 :     return \%retVal;
1520 :     }
1521 :    
1522 :     =head3 SimList
1523 :    
1524 :     C<< my %similarities = $sprout->SimList($featureID, $count); >>
1525 :    
1526 :     Return a list of the similarities to the specified feature.
1527 :    
1528 : parrello 1.84 This method just returns the bidirectional best hits for performance reasons.
1529 : parrello 1.15
1530 :     =over 4
1531 :    
1532 :     =item featureID
1533 :    
1534 :     ID of the feature whose similarities are desired.
1535 :    
1536 :     =item count
1537 :    
1538 :     Maximum number of similar features to be returned, or C<0> to return them all.
1539 :    
1540 :     =back
1541 :    
1542 :     =cut
1543 :     #: Return Type %;
1544 :     sub SimList {
1545 :     # Get the parameters.
1546 :     my ($self, $featureID, $count) = @_;
1547 :     # Ask for the best hits.
1548 : parrello 1.84 my @lists = FIGRules::BBHData($featureID);
1549 : parrello 1.15 # Create the return value.
1550 :     my %retVal = ();
1551 :     for my $tuple (@lists) {
1552 :     $retVal{$tuple->[0]} = $tuple->[1];
1553 :     }
1554 :     # Return the result.
1555 :     return %retVal;
1556 :     }
1557 :    
1558 :     =head3 IsComplete
1559 :    
1560 :     C<< my $flag = $sprout->IsComplete($genomeID); >>
1561 :    
1562 :     Return TRUE if the specified genome is complete, else FALSE.
1563 :    
1564 :     =over 4
1565 :    
1566 :     =item genomeID
1567 :    
1568 :     ID of the genome whose completeness status is desired.
1569 :    
1570 :     =item RETURN
1571 :    
1572 :     Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1573 :     not found.
1574 :    
1575 :     =back
1576 :    
1577 :     =cut
1578 :     #: Return Type $;
1579 :     sub IsComplete {
1580 :     # Get the parameters.
1581 :     my ($self, $genomeID) = @_;
1582 :     # Declare the return variable.
1583 :     my $retVal;
1584 :     # Get the genome's data.
1585 :     my $genomeData = $self->GetEntity('Genome', $genomeID);
1586 :     if ($genomeData) {
1587 :     # The genome exists, so get the completeness flag.
1588 : parrello 1.51 ($retVal) = $genomeData->Value('Genome(complete)');
1589 : parrello 1.15 }
1590 :     # Return the result.
1591 :     return $retVal;
1592 : parrello 1.1 }
1593 :    
1594 :     =head3 FeatureAliases
1595 :    
1596 :     C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
1597 :    
1598 :     Return a list of the aliases for a specified feature.
1599 :    
1600 :     =over 4
1601 :    
1602 :     =item featureID
1603 :    
1604 :     ID of the feature whose aliases are desired.
1605 :    
1606 :     =item RETURN
1607 :    
1608 :     Returns a list of the feature's aliases. If the feature is not found or has no aliases, it will
1609 :     return an empty list.
1610 :    
1611 :     =back
1612 :    
1613 :     =cut
1614 : parrello 1.3 #: Return Type @;
1615 : parrello 1.1 sub FeatureAliases {
1616 : parrello 1.15 # Get the parameters.
1617 :     my ($self, $featureID) = @_;
1618 :     # Get the desired feature's aliases
1619 :     my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);
1620 :     # Return the result.
1621 :     return @retVal;
1622 : parrello 1.1 }
1623 :    
1624 :     =head3 GenomeOf
1625 :    
1626 :     C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1627 :    
1628 : parrello 1.56 Return the genome that contains a specified feature or contig.
1629 : parrello 1.1
1630 :     =over 4
1631 :    
1632 :     =item featureID
1633 :    
1634 : parrello 1.56 ID of the feature or contig whose genome is desired.
1635 : parrello 1.1
1636 :     =item RETURN
1637 :    
1638 : parrello 1.56 Returns the ID of the genome for the specified feature or contig. If the feature or contig is not
1639 :     found, returns an undefined value.
1640 : parrello 1.1
1641 :     =back
1642 :    
1643 :     =cut
1644 : parrello 1.3 #: Return Type $;
1645 : parrello 1.1 sub GenomeOf {
1646 : parrello 1.15 # Get the parameters.
1647 :     my ($self, $featureID) = @_;
1648 : parrello 1.56 # Create a query to find the genome associated with the incoming ID.
1649 :     my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1650 :     [$featureID, $featureID]);
1651 : parrello 1.15 # Declare the return value.
1652 :     my $retVal;
1653 :     # Get the genome ID.
1654 :     if (my $relationship = $query->Fetch()) {
1655 :     ($retVal) = $relationship->Value('HasContig(from-link)');
1656 :     }
1657 :     # Return the value found.
1658 :     return $retVal;
1659 : parrello 1.1 }
1660 :    
1661 :     =head3 CoupledFeatures
1662 :    
1663 :     C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >>
1664 :    
1665 :     Return the features functionally coupled with a specified feature. Features are considered
1666 :     functionally coupled if they tend to be clustered on the same chromosome.
1667 :    
1668 :     =over 4
1669 :    
1670 :     =item featureID
1671 :    
1672 :     ID of the feature whose functionally-coupled brethren are desired.
1673 :    
1674 :     =item RETURN
1675 :    
1676 :     A hash mapping the functionally-coupled feature IDs to the coupling score.
1677 :    
1678 :     =back
1679 :    
1680 :     =cut
1681 : parrello 1.3 #: Return Type %;
1682 : parrello 1.1 sub CoupledFeatures {
1683 : parrello 1.15 # Get the parameters.
1684 :     my ($self, $featureID) = @_;
1685 : parrello 1.77 Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1686 : parrello 1.15 # Create a query to retrieve the functionally-coupled features.
1687 :     my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1688 :     "ParticipatesInCoupling(from-link) = ?", [$featureID]);
1689 :     # This value will be set to TRUE if we find at least one coupled feature.
1690 :     my $found = 0;
1691 :     # Create the return hash.
1692 :     my %retVal = ();
1693 :     # Retrieve the relationship records and store them in the hash.
1694 :     while (my $clustering = $query->Fetch()) {
1695 :     # Get the ID and score of the coupling.
1696 :     my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1697 :     'Coupling(score)']);
1698 : parrello 1.77 Trace("$featureID coupled with score $score to ID $couplingID.") if T(coupling => 4);
1699 : parrello 1.60 # Get the other feature that participates in the coupling.
1700 :     my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],
1701 :     "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",
1702 : parrello 1.61 [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');
1703 : parrello 1.77 Trace("$couplingID target feature is $otherFeatureID.") if T(coupling => 4);
1704 : parrello 1.15 # Attach the other feature's score to its ID.
1705 :     $retVal{$otherFeatureID} = $score;
1706 :     $found = 1;
1707 :     }
1708 :     # Functional coupling is reflexive. If we found at least one coupled feature, we must add
1709 :     # the incoming feature as well.
1710 :     if ($found) {
1711 :     $retVal{$featureID} = 9999;
1712 :     }
1713 :     # Return the hash.
1714 :     return %retVal;
1715 :     }
1716 :    
1717 :     =head3 CouplingEvidence
1718 :    
1719 :     C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1720 :    
1721 :     Return the evidence for a functional coupling.
1722 :    
1723 :     A pair of features is considered evidence of a coupling between two other
1724 :     features if they occur close together on a contig and both are similar to
1725 :     the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1726 :     B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1727 :     B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1728 :     similar to B<A2>.
1729 :    
1730 :     The score of a coupling is determined by the number of pieces of evidence
1731 :     that are considered I<representative>. If several evidence items belong to
1732 :     a group of genomes that are close to each other, only one of those items
1733 :     is considered representative. The other evidence items are presumed to be
1734 :     there because of the relationship between the genomes rather than because
1735 :     the two proteins generated by the features have a related functionality.
1736 :    
1737 :     Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1738 :     I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1739 :     is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1740 :     and FALSE otherwise.
1741 :    
1742 :     =over 4
1743 :    
1744 :     =item peg1
1745 :    
1746 :     ID of the feature of interest.
1747 :    
1748 :     =item peg2
1749 :    
1750 :     ID of a feature functionally coupled to the feature of interest.
1751 :    
1752 :     =item RETURN
1753 :    
1754 :     Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1755 :     of interest, a feature similar to the functionally coupled feature, and a flag
1756 :     that is TRUE for a representative piece of evidence and FALSE otherwise.
1757 :    
1758 :     =back
1759 :    
1760 :     =cut
1761 :     #: Return Type @@;
1762 :     sub CouplingEvidence {
1763 :     # Get the parameters.
1764 :     my ($self, $peg1, $peg2) = @_;
1765 :     # Declare the return variable.
1766 :     my @retVal = ();
1767 : parrello 1.18 # Our first task is to find out the nature of the coupling: whether or not
1768 :     # it exists, its score, and whether the features are stored in the same
1769 :     # order as the ones coming in.
1770 : parrello 1.15 my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1771 :     # Only proceed if a coupling exists.
1772 :     if ($couplingID) {
1773 :     # Determine the ordering to place on the evidence items. If we're
1774 : parrello 1.18 # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1775 :     # we want feature 1 before feature 2 (normal).
1776 : parrello 1.21 Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);
1777 : parrello 1.15 my $ordering = ($inverted ? "DESC" : "");
1778 :     # Get the coupling evidence.
1779 :     my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
1780 :     "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",
1781 :     [$couplingID],
1782 : overbeek 1.17 ['PCH(used)', 'UsesAsEvidence(to-link)']);
1783 : parrello 1.15 # Loop through the evidence items. Each piece of evidence is represented by two
1784 :     # positions in the evidence list, one for each feature on the other side of the
1785 :     # evidence link. If at some point we want to generalize to couplings with
1786 :     # more than two positions, this section of code will need to be re-done.
1787 :     while (@evidenceList > 0) {
1788 :     my $peg1Data = shift @evidenceList;
1789 :     my $peg2Data = shift @evidenceList;
1790 : parrello 1.21 Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1791 : parrello 1.15 push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1792 :     }
1793 : parrello 1.22 Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1794 : parrello 1.1 }
1795 : parrello 1.15 # Return the result.
1796 :     return @retVal;
1797 :     }
1798 :    
1799 :     =head3 GetCoupling
1800 :    
1801 :     C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>
1802 :    
1803 :     Return the coupling (if any) for the specified pair of PEGs. If a coupling
1804 :     exists, we return the coupling ID along with an indicator of whether the
1805 :     coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.
1806 :     In the second case, we say the coupling is I<inverted>. The importance of an
1807 :     inverted coupling is that the PEGs in the evidence will appear in reverse order.
1808 :    
1809 :     =over 4
1810 :    
1811 :     =item peg1
1812 :    
1813 :     ID of the feature of interest.
1814 :    
1815 :     =item peg2
1816 :    
1817 :     ID of the potentially coupled feature.
1818 :    
1819 :     =item RETURN
1820 :    
1821 :     Returns a three-element list. The first element contains the database ID of
1822 :     the coupling. The second element is FALSE if the coupling is stored in the
1823 :     database in the caller specified order and TRUE if it is stored in the
1824 :     inverted order. The third element is the coupling's score. If the coupling
1825 :     does not exist, all three list elements will be C<undef>.
1826 :    
1827 :     =back
1828 :    
1829 :     =cut
1830 :     #: Return Type $%@;
1831 :     sub GetCoupling {
1832 :     # Get the parameters.
1833 :     my ($self, $peg1, $peg2) = @_;
1834 :     # Declare the return values. We'll start with the coupling ID and undefine the
1835 :     # flag and score until we have more information.
1836 : parrello 1.73 my ($retVal, $inverted, $score) = ($self->CouplingID($peg1, $peg2), undef, undef);
1837 : parrello 1.15 # Find the coupling data.
1838 :     my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1839 :     "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1840 : overbeek 1.17 [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1841 : parrello 1.15 # Check to see if we found anything.
1842 :     if (!@pegs) {
1843 : parrello 1.23 Trace("No coupling found.") if T(Coupling => 4);
1844 : parrello 1.15 # No coupling, so undefine the return value.
1845 :     $retVal = undef;
1846 :     } else {
1847 :     # We have a coupling! Get the score and check for inversion.
1848 :     $score = $pegs[0]->[1];
1849 : parrello 1.23 my $firstFound = $pegs[0]->[0];
1850 :     $inverted = ($firstFound ne $peg1);
1851 :     Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1852 : parrello 1.15 }
1853 :     # Return the result.
1854 :     return ($retVal, $inverted, $score);
1855 :     }
1856 :    
1857 : parrello 1.74 =head3 GetSynonymGroup
1858 :    
1859 :     C<< my $id = $sprout->GetSynonymGroup($fid); >>
1860 :    
1861 :     Return the synonym group name for the specified feature.
1862 :    
1863 :     =over 4
1864 :    
1865 :     =item fid
1866 :    
1867 :     ID of the feature whose synonym group is desired.
1868 :    
1869 :     =item RETURN
1870 :    
1871 :     The name of the synonym group to which the feature belongs. If the feature does
1872 :     not belong to a synonym group, the feature ID itself is returned.
1873 :    
1874 :     =back
1875 :    
1876 :     =cut
1877 :    
1878 :     sub GetSynonymGroup {
1879 :     # Get the parameters.
1880 :     my ($self, $fid) = @_;
1881 :     # Declare the return variable.
1882 :     my $retVal;
1883 :     # Find the synonym group.
1884 :     my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1885 :     [$fid], 'IsSynonymGroupFor(from-link)');
1886 :     # Check to see if we found anything.
1887 :     if (@groups) {
1888 :     $retVal = $groups[0];
1889 :     } else {
1890 :     $retVal = $fid;
1891 :     }
1892 :     # Return the result.
1893 :     return $retVal;
1894 :     }
1895 :    
1896 : parrello 1.75 =head3 GetBoundaries
1897 :    
1898 :     C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>
1899 :    
1900 :     Determine the begin and end boundaries for the locations in a list. All of the
1901 :     locations must belong to the same contig and have mostly the same direction in
1902 :     order for this method to produce a meaningful result. The resulting
1903 :     begin/end pair will contain all of the bases in any of the locations.
1904 :    
1905 :     =over 4
1906 :    
1907 :     =item locList
1908 :    
1909 :     List of locations to process.
1910 :    
1911 :     =item RETURN
1912 :    
1913 :     Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1914 :     and the ending boundary. The beginning boundary will be left of the
1915 :     end for mostly-forward locations and right of the end for mostly-backward
1916 :     locations.
1917 :    
1918 :     =back
1919 :    
1920 :     =cut
1921 :    
1922 :     sub GetBoundaries {
1923 :     # Get the parameters.
1924 :     my ($self, @locList) = @_;
1925 :     # Set up the counters used to determine the most popular direction.
1926 :     my %counts = ( '+' => 0, '-' => 0 );
1927 :     # Get the last location and parse it.
1928 :     my $locObject = BasicLocation->new(pop @locList);
1929 :     # Prime the loop with its data.
1930 :     my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
1931 :     # Count its direction.
1932 :     $counts{$locObject->Dir}++;
1933 :     # Loop through the remaining locations. Note that in most situations, this loop
1934 :     # will not iterate at all, because most of the time we will be dealing with a
1935 :     # singleton list.
1936 :     for my $loc (@locList) {
1937 :     # Create a location object.
1938 :     my $locObject = BasicLocation->new($loc);
1939 :     # Count the direction.
1940 :     $counts{$locObject->Dir}++;
1941 :     # Get the left end and the right end.
1942 :     my $left = $locObject->Left;
1943 :     my $right = $locObject->Right;
1944 :     # Merge them into the return variables.
1945 :     if ($left < $beg) {
1946 :     $beg = $left;
1947 :     }
1948 :     if ($right > $end) {
1949 :     $end = $right;
1950 :     }
1951 :     }
1952 :     # If the most common direction is reverse, flip the begin and end markers.
1953 :     if ($counts{'-'} > $counts{'+'}) {
1954 :     ($beg, $end) = ($end, $beg);
1955 :     }
1956 :     # Return the result.
1957 :     return ($contig, $beg, $end);
1958 :     }
1959 :    
1960 : parrello 1.15 =head3 CouplingID
1961 :    
1962 : parrello 1.73 C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >>
1963 : parrello 1.15
1964 :     Return the coupling ID for a pair of feature IDs.
1965 :    
1966 :     The coupling ID is currently computed by joining the feature IDs in
1967 :     sorted order with a space. Client modules (that is, modules which
1968 :     use Sprout) should not, however, count on this always being the
1969 :     case. This method provides a way for abstracting the concept of a
1970 :     coupling ID. All that we know for sure about it is that it can be
1971 :     generated easily from the feature IDs and the order of the IDs
1972 :     in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>
1973 :     will have the same value as C<CouplingID("b1", "a1")>.
1974 :    
1975 :     =over 4
1976 :    
1977 :     =item peg1
1978 :    
1979 :     First feature of interest.
1980 :    
1981 :     =item peg2
1982 :    
1983 :     Second feature of interest.
1984 :    
1985 :     =item RETURN
1986 :    
1987 :     Returns the ID that would be used to represent a functional coupling of
1988 :     the two specified PEGs.
1989 :    
1990 :     =back
1991 :    
1992 :     =cut
1993 :     #: Return Type $;
1994 :     sub CouplingID {
1995 : parrello 1.73 my ($self, @pegs) = @_;
1996 :     return $self->DigestKey(join " ", sort @pegs);
1997 : parrello 1.1 }
1998 :    
1999 :     =head3 ReadFasta
2000 :    
2001 :     C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>
2002 :    
2003 :     Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by
2004 :     one or more lines of data. The first line begins with a > character and contains an ID.
2005 :     The remaining lines contain the sequence data in order.
2006 :    
2007 :     =over 4
2008 :    
2009 :     =item fileName
2010 :    
2011 :     Name of the FASTA file.
2012 :    
2013 :     =item prefix (optional)
2014 :    
2015 :     Prefix to be put in front of each ID found.
2016 :    
2017 :     =item RETURN
2018 :    
2019 :     Returns a hash that maps each ID to its sequence.
2020 :    
2021 :     =back
2022 :    
2023 :     =cut
2024 : parrello 1.3 #: Return Type %;
2025 : parrello 1.1 sub ReadFasta {
2026 : parrello 1.15 # Get the parameters.
2027 :     my ($fileName, $prefix) = @_;
2028 :     # Create the return hash.
2029 :     my %retVal = ();
2030 :     # Open the file for input.
2031 :     open FASTAFILE, '<', $fileName;
2032 :     # Declare the ID variable and clear the sequence accumulator.
2033 :     my $sequence = "";
2034 :     my $id = "";
2035 :     # Loop through the file.
2036 :     while (<FASTAFILE>) {
2037 :     # Get the current line.
2038 :     my $line = $_;
2039 :     # Check for a header line.
2040 :     if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
2041 :     # Here we have a new header. Store the current sequence if we have one.
2042 :     if ($id) {
2043 : parrello 1.24 $retVal{$id} = lc $sequence;
2044 : parrello 1.15 }
2045 :     # Clear the sequence accumulator and save the new ID.
2046 :     ($id, $sequence) = ("$prefix$1", "");
2047 :     } else {
2048 :     # Here we have a data line, so we add it to the sequence accumulator.
2049 : parrello 1.24 # First, we get the actual data out. Note that we normalize to lower
2050 : parrello 1.15 # case.
2051 :     $line =~ /^\s*(.*?)(\s|\n)/;
2052 :     $sequence .= $1;
2053 :     }
2054 :     }
2055 :     # Flush out the last sequence (if any).
2056 :     if ($sequence) {
2057 : parrello 1.24 $retVal{$id} = lc $sequence;
2058 : parrello 1.15 }
2059 :     # Close the file.
2060 :     close FASTAFILE;
2061 :     # Return the hash constructed from the file.
2062 :     return %retVal;
2063 : parrello 1.1 }
2064 :    
2065 :     =head3 FormatLocations
2066 :    
2067 :     C<< my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat); >>
2068 :    
2069 :     Insure that a list of feature locations is in the Sprout format. The Sprout feature location
2070 :     format is I<contig>_I<beg*len> where I<*> is C<+> for a forward gene and C<-> for a backward
2071 : parrello 1.10 gene. The old format is I<contig>_I<beg>_I<end>. If a feature is in the new format already,
2072 : parrello 1.19 it will not be changed; otherwise, it will be converted. This method can also be used to
2073 : parrello 1.10 perform the reverse task-- insuring that all the locations are in the old format.
2074 : parrello 1.1
2075 :     =over 4
2076 :    
2077 :     =item prefix
2078 :    
2079 :     Prefix to be put in front of each contig ID (or an empty string if the contig ID should not
2080 :     be changed.
2081 :    
2082 :     =item locations
2083 :    
2084 :     List of locations to be normalized.
2085 :    
2086 :     =item oldFormat
2087 :    
2088 :     TRUE to convert the locations to the old format, else FALSE
2089 :    
2090 :     =item RETURN
2091 :    
2092 :     Returns a list of updated location descriptors.
2093 :    
2094 :     =back
2095 :    
2096 :     =cut
2097 : parrello 1.3 #: Return Type @;
2098 : parrello 1.1 sub FormatLocations {
2099 : parrello 1.15 # Get the parameters.
2100 :     my ($self, $prefix, $locations, $oldFormat) = @_;
2101 :     # Create the return list.
2102 :     my @retVal = ();
2103 :     # Check to see if any locations were passed in.
2104 :     if ($locations eq '') {
2105 :     Confess("No locations specified.");
2106 :     } else {
2107 :     # Loop through the locations, converting them to the new format.
2108 :     for my $location (@{$locations}) {
2109 :     # Parse the location elements.
2110 :     my ($contig, $beg, $dir, $len) = ParseLocation($location);
2111 :     # Process according to the desired output format.
2112 :     if (!$oldFormat) {
2113 :     # Here we're producing the new format. Add the location to the return list.
2114 :     push @retVal, "$prefix${contig}_$beg$dir$len";
2115 :     } elsif ($dir eq '+') {
2116 :     # Here we're producing the old format and it's a forward gene.
2117 :     my $end = $beg + $len - 1;
2118 :     push @retVal, "$prefix${contig}_${beg}_$end";
2119 :     } else {
2120 :     # Here we're producting the old format and it's a backward gene.
2121 :     my $end = $beg - $len + 1;
2122 :     push @retVal, "$prefix${contig}_${beg}_$end";
2123 :     }
2124 :     }
2125 :     }
2126 :     # Return the normalized list.
2127 :     return @retVal;
2128 : parrello 1.1 }
2129 :    
2130 :     =head3 DumpData
2131 :    
2132 :     C<< $sprout->DumpData(); >>
2133 :    
2134 :     Dump all the tables to tab-delimited DTX files. The files will be stored in the data directory.
2135 :    
2136 :     =cut
2137 :    
2138 :     sub DumpData {
2139 : parrello 1.15 # Get the parameters.
2140 :     my ($self) = @_;
2141 :     # Get the data directory name.
2142 :     my $outputDirectory = $self->{_options}->{dataDir};
2143 :     # Dump the relations.
2144 : parrello 1.58 $self->DumpRelations($outputDirectory);
2145 : parrello 1.1 }
2146 :    
2147 :     =head3 XMLFileName
2148 :    
2149 :     C<< my $fileName = $sprout->XMLFileName(); >>
2150 :    
2151 :     Return the name of this database's XML definition file.
2152 :    
2153 :     =cut
2154 : parrello 1.3 #: Return Type $;
2155 : parrello 1.1 sub XMLFileName {
2156 : parrello 1.15 my ($self) = @_;
2157 :     return $self->{_xmlName};
2158 : parrello 1.1 }
2159 :    
2160 :     =head3 Insert
2161 :    
2162 :     C<< $sprout->Insert($objectType, \%fieldHash); >>
2163 :    
2164 :     Insert an entity or relationship instance into the database. The entity or relationship of interest
2165 :     is defined by a type name and then a hash of field names to values. Field values in the primary
2166 :     relation are represented by scalars. (Note that for relationships, the primary relation is
2167 :     the B<only> relation.) Field values for the other relations comprising the entity are always
2168 :     list references. For example, the following line inserts an inactive PEG feature named
2169 :     C<fig|188.1.peg.1> with aliases C<ZP_00210270.1> and C<gi|46206278>.
2170 :    
2171 :     C<< $sprout->Insert('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >>
2172 :    
2173 :     The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
2174 :     property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
2175 :    
2176 : parrello 1.15 C<< $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>
2177 : parrello 1.1
2178 :     =over 4
2179 :    
2180 :     =item newObjectType
2181 :    
2182 :     Type name of the entity or relationship to insert.
2183 :    
2184 :     =item fieldHash
2185 :    
2186 :     Hash of field names to values.
2187 :    
2188 :     =back
2189 :    
2190 :     =cut
2191 : parrello 1.3 #: Return Type ;
2192 : parrello 1.1 sub Insert {
2193 : parrello 1.15 # Get the parameters.
2194 :     my ($self, $objectType, $fieldHash) = @_;
2195 :     # Call the underlying method.
2196 : parrello 1.58 $self->InsertObject($objectType, $fieldHash);
2197 : parrello 1.1 }
2198 :    
2199 :     =head3 Annotate
2200 :    
2201 :     C<< my $ok = $sprout->Annotate($fid, $timestamp, $user, $text); >>
2202 :    
2203 :     Annotate a feature. This inserts an Annotation record into the database and links it to the
2204 :     specified feature and user.
2205 :    
2206 :     =over 4
2207 :    
2208 :     =item fid
2209 :    
2210 :     ID of the feature to be annotated.
2211 :    
2212 :     =item timestamp
2213 :    
2214 :     Numeric timestamp to apply to the annotation. This is concatenated to the feature ID to create the
2215 :     key.
2216 :    
2217 :     =item user
2218 :    
2219 :     ID of the user who is making the annotation.
2220 :    
2221 :     =item text
2222 :    
2223 :     Text of the annotation.
2224 :    
2225 :     =item RETURN
2226 :    
2227 :     Returns 1 if successful, 2 if an error occurred.
2228 :    
2229 :     =back
2230 :    
2231 :     =cut
2232 : parrello 1.3 #: Return Type $;
2233 : parrello 1.1 sub Annotate {
2234 : parrello 1.15 # Get the parameters.
2235 :     my ($self, $fid, $timestamp, $user, $text) = @_;
2236 :     # Create the annotation ID.
2237 :     my $aid = "$fid:$timestamp";
2238 :     # Insert the Annotation object.
2239 :     my $retVal = $self->Insert('Annotation', { id => $aid, time => $timestamp, annotation => $text });
2240 :     if ($retVal) {
2241 :     # Connect it to the user.
2242 :     $retVal = $self->Insert('MadeAnnotation', { 'from-link' => $user, 'to-link' => $aid });
2243 :     if ($retVal) {
2244 :     # Connect it to the feature.
2245 :     $retVal = $self->Insert('IsTargetOfAnnotation', { 'from-link' => $fid,
2246 :     'to-link' => $aid });
2247 :     }
2248 :     }
2249 :     # Return the success indicator.
2250 :     return $retVal;
2251 : parrello 1.1 }
2252 :    
2253 :     =head3 AssignFunction
2254 :    
2255 : parrello 1.11 C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>
2256 : parrello 1.1
2257 :     This method assigns a function to a feature. Functions are a special type of annotation. The general
2258 : parrello 1.11 format is described in L</ParseAssignment>.
2259 : parrello 1.1
2260 :     =over 4
2261 :    
2262 :     =item featureID
2263 :    
2264 :     ID of the feature to which the assignment is being made.
2265 :    
2266 :     =item user
2267 :    
2268 : parrello 1.11 Name of the user group making the assignment, such as C<kegg> or C<fig>.
2269 : parrello 1.1
2270 :     =item function
2271 :    
2272 :     Text of the function being assigned.
2273 :    
2274 : parrello 1.11 =item assigningUser (optional)
2275 :    
2276 :     Name of the individual user making the assignment. If omitted, defaults to the user group.
2277 :    
2278 : parrello 1.1 =item RETURN
2279 :    
2280 :     Returns 1 if successful, 0 if an error occurred.
2281 :    
2282 :     =back
2283 :    
2284 :     =cut
2285 : parrello 1.3 #: Return Type $;
2286 : parrello 1.1 sub AssignFunction {
2287 : parrello 1.15 # Get the parameters.
2288 :     my ($self, $featureID, $user, $function, $assigningUser) = @_;
2289 : parrello 1.11 # Default the assigning user.
2290 :     if (! $assigningUser) {
2291 :     $assigningUser = $user;
2292 :     }
2293 : parrello 1.15 # Create an annotation string from the parameters.
2294 :     my $annotationText = "$assigningUser\nset $user function to\n$function";
2295 :     # Get the current time.
2296 :     my $now = time;
2297 :     # Declare the return variable.
2298 :     my $retVal = 1;
2299 :     # Locate the genome containing the feature.
2300 :     my $genome = $self->GenomeOf($featureID);
2301 :     if (!$genome) {
2302 :     # Here the genome was not found. This probably means the feature ID is invalid.
2303 :     Trace("No genome found for feature $featureID.") if T(0);
2304 :     $retVal = 0;
2305 :     } else {
2306 :     # Here we know we have a feature with a genome. Store the annotation.
2307 : parrello 1.5 $retVal = $self->Annotate($featureID, $now, $user, $annotationText);
2308 : parrello 1.15 }
2309 :     # Return the success indicator.
2310 :     return $retVal;
2311 : parrello 1.1 }
2312 :    
2313 :     =head3 FeaturesByAlias
2314 :    
2315 :     C<< my @features = $sprout->FeaturesByAlias($alias); >>
2316 :    
2317 :     Returns a list of features with the specified alias. The alias is parsed to determine
2318 :     the type of the alias. A string of digits is a GenBack ID and a string of exactly 6
2319 :     alphanumerics is a UniProt ID. A built-in FIG.pm method is used to analyze the alias
2320 :     string and attach the necessary prefix. If the result is a FIG ID then it is returned
2321 :     unmodified; otherwise, we look for an alias.
2322 :    
2323 :     =over 4
2324 :    
2325 :     =item alias
2326 :    
2327 :     Alias whose features are desired.
2328 :    
2329 :     =item RETURN
2330 :    
2331 :     Returns a list of the features with the given alias.
2332 :    
2333 :     =back
2334 :    
2335 :     =cut
2336 : parrello 1.3 #: Return Type @;
2337 : parrello 1.1 sub FeaturesByAlias {
2338 : parrello 1.15 # Get the parameters.
2339 :     my ($self, $alias) = @_;
2340 :     # Declare the return variable.
2341 :     my @retVal = ();
2342 :     # Parse the alias.
2343 :     my ($mappedAlias, $flag) = FIGRules::NormalizeAlias($alias);
2344 :     # If it's a FIG alias, we're done.
2345 :     if ($flag) {
2346 :     push @retVal, $mappedAlias;
2347 :     } else {
2348 :     # Here we have a non-FIG alias. Get the features with the normalized alias.
2349 :     @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');
2350 :     }
2351 :     # Return the result.
2352 :     return @retVal;
2353 : parrello 1.1 }
2354 :    
2355 :     =head3 FeatureTranslation
2356 :    
2357 :     C<< my $translation = $sprout->FeatureTranslation($featureID); >>
2358 :    
2359 :     Return the translation of a feature.
2360 :    
2361 :     =over 4
2362 :    
2363 :     =item featureID
2364 :    
2365 :     ID of the feature whose translation is desired
2366 :    
2367 :     =item RETURN
2368 :    
2369 :     Returns the translation of the specified feature.
2370 :    
2371 :     =back
2372 :    
2373 :     =cut
2374 : parrello 1.3 #: Return Type $;
2375 : parrello 1.1 sub FeatureTranslation {
2376 : parrello 1.15 # Get the parameters.
2377 :     my ($self, $featureID) = @_;
2378 :     # Get the specified feature's translation.
2379 :     my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
2380 :     return $retVal;
2381 : parrello 1.1 }
2382 :    
2383 :     =head3 Taxonomy
2384 :    
2385 :     C<< my @taxonomyList = $sprout->Taxonomy($genome); >>
2386 :    
2387 :     Return the taxonomy of the specified genome. This will be in the form of a list
2388 :     containing the various classifications in order from domain (eg. C<Bacteria>, C<Archaea>,
2389 :     or C<Eukaryote>) to sub-species. For example,
2390 :    
2391 :     C<< (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12) >>
2392 :    
2393 :     =over 4
2394 :    
2395 :     =item genome
2396 :    
2397 :     ID of the genome whose taxonomy is desired.
2398 :    
2399 :     =item RETURN
2400 :    
2401 :     Returns a list containing all the taxonomy classifications for the specified genome's organism.
2402 :    
2403 :     =back
2404 :    
2405 :     =cut
2406 : parrello 1.3 #: Return Type @;
2407 : parrello 1.1 sub Taxonomy {
2408 : parrello 1.15 # Get the parameters.
2409 :     my ($self, $genome) = @_;
2410 :     # Find the specified genome's taxonomy string.
2411 :     my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);
2412 :     # Declare the return variable.
2413 :     my @retVal = ();
2414 :     # If we found the genome, return its taxonomy string.
2415 :     if ($list) {
2416 :     @retVal = split /\s*;\s*/, $list;
2417 :     } else {
2418 :     Trace("Genome \"$genome\" does not have a taxonomy in the database.\n") if T(0);
2419 :     }
2420 :     # Return the value found.
2421 :     return @retVal;
2422 : parrello 1.1 }
2423 :    
2424 :     =head3 CrudeDistance
2425 :    
2426 :     C<< my $distance = $sprout->CrudeDistance($genome1, $genome2); >>
2427 :    
2428 :     Returns a crude estimate of the distance between two genomes. The distance is construed so
2429 :     that it will be 0 for genomes with identical taxonomies and 1 for genomes from different domains.
2430 :    
2431 :     =over 4
2432 :    
2433 :     =item genome1
2434 :    
2435 :     ID of the first genome to compare.
2436 :    
2437 :     =item genome2
2438 :    
2439 :     ID of the second genome to compare.
2440 :    
2441 :     =item RETURN
2442 :    
2443 :     Returns a value from 0 to 1, with 0 meaning identical organisms, and 1 meaning organisms from
2444 :     different domains.
2445 :    
2446 :     =back
2447 :    
2448 :     =cut
2449 : parrello 1.3 #: Return Type $;
2450 : parrello 1.1 sub CrudeDistance {
2451 : parrello 1.15 # Get the parameters.
2452 :     my ($self, $genome1, $genome2) = @_;
2453 :     # Insure that the distance is commutative by sorting the genome IDs.
2454 :     my ($genomeA, $genomeB);
2455 :     if ($genome2 < $genome2) {
2456 :     ($genomeA, $genomeB) = ($genome1, $genome2);
2457 :     } else {
2458 :     ($genomeA, $genomeB) = ($genome2, $genome1);
2459 :     }
2460 :     my @taxA = $self->Taxonomy($genomeA);
2461 :     my @taxB = $self->Taxonomy($genomeB);
2462 :     # Initialize the distance to 1. We'll reduce it each time we find a match between the
2463 :     # taxonomies.
2464 :     my $retVal = 1.0;
2465 :     # Initialize the subtraction amount. This amount determines the distance reduction caused
2466 :     # by a mismatch at the current level.
2467 :     my $v = 0.5;
2468 :     # Loop through the taxonomies.
2469 :     for (my $i = 0; ($i < @taxA) && ($i < @taxB) && ($taxA[$i] eq $taxB[$i]); $i++) {
2470 :     $retVal -= $v;
2471 :     $v /= 2;
2472 :     }
2473 : parrello 1.1 return $retVal;
2474 :     }
2475 :    
2476 :     =head3 RoleName
2477 :    
2478 :     C<< my $roleName = $sprout->RoleName($roleID); >>
2479 :    
2480 :     Return the descriptive name of the role with the specified ID. In general, a role
2481 :     will only have a descriptive name if it is coded as an EC number.
2482 :    
2483 :     =over 4
2484 :    
2485 :     =item roleID
2486 :    
2487 :     ID of the role whose description is desired.
2488 :    
2489 :     =item RETURN
2490 :    
2491 :     Returns the descriptive name of the desired role.
2492 :    
2493 :     =back
2494 :    
2495 :     =cut
2496 : parrello 1.3 #: Return Type $;
2497 : parrello 1.1 sub RoleName {
2498 : parrello 1.15 # Get the parameters.
2499 :     my ($self, $roleID) = @_;
2500 :     # Get the specified role's name.
2501 :     my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);
2502 :     # Use the ID if the role has no name.
2503 :     if (!$retVal) {
2504 :     $retVal = $roleID;
2505 :     }
2506 :     # Return the name.
2507 :     return $retVal;
2508 : parrello 1.1 }
2509 :    
2510 :     =head3 RoleDiagrams
2511 :    
2512 :     C<< my @diagrams = $sprout->RoleDiagrams($roleID); >>
2513 :    
2514 :     Return a list of the diagrams containing a specified functional role.
2515 :    
2516 :     =over 4
2517 :    
2518 :     =item roleID
2519 :    
2520 :     ID of the role whose diagrams are desired.
2521 :    
2522 :     =item RETURN
2523 :    
2524 :     Returns a list of the IDs for the diagrams that contain the specified functional role.
2525 :    
2526 :     =back
2527 :    
2528 :     =cut
2529 : parrello 1.3 #: Return Type @;
2530 : parrello 1.1 sub RoleDiagrams {
2531 : parrello 1.15 # Get the parameters.
2532 :     my ($self, $roleID) = @_;
2533 :     # Query for the diagrams.
2534 :     my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2535 :     'RoleOccursIn(to-link)');
2536 :     # Return the result.
2537 :     return @retVal;
2538 : parrello 1.1 }
2539 :    
2540 : parrello 1.19 =head3 GetProperties
2541 :    
2542 :     C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2543 :    
2544 :     Return a list of the properties with the specified characteristics.
2545 :    
2546 : parrello 1.99 Properties are the Sprout analog of the FIG attributes. The call is
2547 :     passed directly to the CustomAttributes or RemoteCustomAttributes object
2548 :     contained in this object.
2549 :    
2550 :     This method returns a series of tuples that match the specified criteria. Each tuple
2551 :     will contain an object ID, a key, and one or more values. The parameters to this
2552 :     method therefore correspond structurally to the values expected in each tuple. In
2553 :     addition, you can ask for a generic search by suffixing a percent sign (C<%>) to any
2554 :     of the parameters. So, for example,
2555 :    
2556 :     my @attributeList = $sprout->GetProperties('fig|100226.1.peg.1004', 'structure%', 1, 2);
2557 : parrello 1.19
2558 : parrello 1.99 would return something like
2559 :    
2560 :     ['fig}100226.1.peg.1004', 'structure', 1, 2]
2561 :     ['fig}100226.1.peg.1004', 'structure1', 1, 2]
2562 :     ['fig}100226.1.peg.1004', 'structure2', 1, 2]
2563 :     ['fig}100226.1.peg.1004', 'structureA', 1, 2]
2564 : parrello 1.19
2565 : parrello 1.99 Use of C<undef> in any position acts as a wild card (all values). You can also specify
2566 :     a list reference in the ID column. Thus,
2567 : parrello 1.19
2568 : parrello 1.99 my @attributeList = $sprout->GetProperties(['100226.1', 'fig|100226.1.%'], 'PUBMED');
2569 : parrello 1.19
2570 : parrello 1.99 would get the PUBMED attribute data for Streptomyces coelicolor A3(2) and all its
2571 :     features.
2572 : parrello 1.19
2573 : parrello 1.99 In addition to values in multiple sections, a single attribute key can have multiple
2574 :     values, so even
2575 : parrello 1.19
2576 : parrello 1.99 my @attributeList = $sprout->GetProperties($peg, 'virulent');
2577 : parrello 1.19
2578 : parrello 1.99 which has no wildcard in the key or the object ID, may return multiple tuples.
2579 : parrello 1.19
2580 : parrello 1.99 =over 4
2581 : parrello 1.19
2582 : parrello 1.99 =item objectID
2583 : parrello 1.19
2584 : parrello 1.99 ID of object whose attributes are desired. If the attributes are desired for multiple
2585 :     objects, this parameter can be specified as a list reference. If the attributes are
2586 :     desired for all objects, specify C<undef> or an empty string. Finally, you can specify
2587 :     attributes for a range of object IDs by putting a percent sign (C<%>) at the end.
2588 : parrello 1.19
2589 : parrello 1.99 =item key
2590 : parrello 1.19
2591 : parrello 1.99 Attribute key name. A value of C<undef> or an empty string will match all
2592 :     attribute keys. If the values are desired for multiple keys, this parameter can be
2593 :     specified as a list reference. Finally, you can specify attributes for a range of
2594 :     keys by putting a percent sign (C<%>) at the end.
2595 :    
2596 :     =item values
2597 :    
2598 :     List of the desired attribute values, section by section. If C<undef>
2599 :     or an empty string is specified, all values in that section will match. A
2600 :     generic match can be requested by placing a percent sign (C<%>) at the end.
2601 :     In that case, all values that match up to and not including the percent sign
2602 :     will match. You may also specify a regular expression enclosed
2603 :     in slashes. All values that match the regular expression will be returned. For
2604 :     performance reasons, only values have this extra capability.
2605 : parrello 1.19
2606 : parrello 1.99 =item RETURN
2607 : parrello 1.19
2608 : parrello 1.99 Returns a list of tuples. The first element in the tuple is an object ID, the
2609 :     second is an attribute key, and the remaining elements are the sections of
2610 :     the attribute value. All of the tuples will match the criteria set forth in
2611 :     the parameter list.
2612 : parrello 1.19
2613 : parrello 1.99 =back
2614 : parrello 1.19
2615 :     =cut
2616 : parrello 1.99
2617 : parrello 1.19 sub GetProperties {
2618 :     # Get the parameters.
2619 :     my ($self, @parms) = @_;
2620 :     # Declare the return variable.
2621 : parrello 1.99 my @retVal = $self->{_ca}->GetAttributes(@parms);
2622 : parrello 1.19 # Return the result.
2623 :     return @retVal;
2624 :     }
2625 :    
2626 : parrello 1.1 =head3 FeatureProperties
2627 :    
2628 :     C<< my @properties = $sprout->FeatureProperties($featureID); >>
2629 :    
2630 :     Return a list of the properties for the specified feature. Properties are key-value pairs
2631 :     that specify special characteristics of the feature. For example, a property could indicate
2632 :     that a feature is essential to the survival of the organism or that it has benign influence
2633 :     on the activities of a pathogen. Each property is returned as a triple of the form
2634 : parrello 1.99 C<($key,@values)>, where C<$key> is the property name and C<@values> are its values.
2635 : parrello 1.1
2636 :     =over 4
2637 :    
2638 :     =item featureID
2639 :    
2640 :     ID of the feature whose properties are desired.
2641 :    
2642 :     =item RETURN
2643 :    
2644 : parrello 1.99 Returns a list of tuples, each tuple containing the property name and its values.
2645 : parrello 1.1
2646 :     =back
2647 :    
2648 :     =cut
2649 : parrello 1.3 #: Return Type @@;
2650 : parrello 1.1 sub FeatureProperties {
2651 : parrello 1.15 # Get the parameters.
2652 :     my ($self, $featureID) = @_;
2653 :     # Get the properties.
2654 : parrello 1.99 my @attributes = $self->{_ca}->GetAttributes($featureID);
2655 :     # Strip the feature ID off each tuple.
2656 :     my @retVal = ();
2657 :     for my $attributeRow (@attributes) {
2658 :     shift @{$attributeRow};
2659 :     push @retVal, $attributeRow;
2660 :     }
2661 : parrello 1.15 # Return the resulting list.
2662 :     return @retVal;
2663 : parrello 1.1 }
2664 :    
2665 :     =head3 DiagramName
2666 :    
2667 :     C<< my $diagramName = $sprout->DiagramName($diagramID); >>
2668 :    
2669 :     Return the descriptive name of a diagram.
2670 :    
2671 :     =over 4
2672 :    
2673 :     =item diagramID
2674 :    
2675 :     ID of the diagram whose description is desired.
2676 :    
2677 :     =item RETURN
2678 :    
2679 :     Returns the descripive name of the specified diagram.
2680 :    
2681 :     =back
2682 :    
2683 :     =cut
2684 : parrello 1.3 #: Return Type $;
2685 : parrello 1.1 sub DiagramName {
2686 : parrello 1.15 # Get the parameters.
2687 :     my ($self, $diagramID) = @_;
2688 :     # Get the specified diagram's name and return it.
2689 :     my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);
2690 :     return $retVal;
2691 : parrello 1.1 }
2692 :    
2693 : parrello 1.88 =head3 PropertyID
2694 :    
2695 :     C<< my $id = $sprout->PropertyID($propName, $propValue); >>
2696 :    
2697 :     Return the ID of the specified property name and value pair, if the
2698 : parrello 1.99 pair exists. Only a small subset of the FIG attributes are stored as
2699 :     Sprout properties, mostly for use in search optimization.
2700 : parrello 1.88
2701 :     =over 4
2702 :    
2703 :     =item propName
2704 :    
2705 :     Name of the desired property.
2706 :    
2707 :     =item propValue
2708 :    
2709 :     Value expected for the desired property.
2710 :    
2711 :     =item RETURN
2712 :    
2713 :     Returns the ID of the name/value pair, or C<undef> if the pair does not exist.
2714 :    
2715 :     =back
2716 :    
2717 :     =cut
2718 :    
2719 :     sub PropertyID {
2720 :     # Get the parameters.
2721 :     my ($self, $propName, $propValue) = @_;
2722 :     # Try to find the ID.
2723 :     my ($retVal) = $self->GetFlat(['Property'],
2724 :     "Property(property-name) = ? AND Property(property-value) = ?",
2725 : parrello 1.89 [$propName, $propValue], 'Property(id)');
2726 : parrello 1.88 # Return the result.
2727 :     return $retVal;
2728 :     }
2729 :    
2730 : parrello 1.1 =head3 MergedAnnotations
2731 :    
2732 :     C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>
2733 :    
2734 :     Returns a merged list of the annotations for the features in a list. Each annotation is
2735 :     represented by a 4-tuple of the form C<($fid, $timestamp, $userID, $annotation)>, where
2736 :     C<$fid> is the ID of a feature, C<$timestamp> is the time at which the annotation was made,
2737 :     C<$userID> is the ID of the user who made the annotation, and C<$annotation> is the annotation
2738 :     text. The list is sorted by timestamp.
2739 :    
2740 :     =over 4
2741 :    
2742 :     =item list
2743 :    
2744 :     List of the IDs for the features whose annotations are desired.
2745 :    
2746 :     =item RETURN
2747 :    
2748 :     Returns a list of annotation descriptions sorted by the annotation time.
2749 :    
2750 :     =back
2751 :    
2752 :     =cut
2753 : parrello 1.3 #: Return Type @;
2754 : parrello 1.1 sub MergedAnnotations {
2755 : parrello 1.15 # Get the parameters.
2756 :     my ($self, $list) = @_;
2757 :     # Create a list to hold the annotation tuples found.
2758 :     my @tuples = ();
2759 :     # Loop through the features in the input list.
2760 :     for my $fid (@{$list}) {
2761 :     # Create a list of this feature's annotation tuples.
2762 :     my @newTuples = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
2763 :     "IsTargetOfAnnotation(from-link) = ?", [$fid],
2764 :     ['IsTargetOfAnnotation(from-link)', 'Annotation(time)',
2765 :     'MadeAnnotation(from-link)', 'Annotation(annotation)']);
2766 :     # Put it in the result list.
2767 :     push @tuples, @newTuples;
2768 :     }
2769 :     # Sort the result list by timestamp.
2770 :     my @retVal = sort { $a->[1] <=> $b->[1] } @tuples;
2771 : parrello 1.3 # Loop through and make the time stamps friendly.
2772 :     for my $tuple (@retVal) {
2773 :     $tuple->[1] = FriendlyTimestamp($tuple->[1]);
2774 :     }
2775 : parrello 1.15 # Return the sorted list.
2776 :     return @retVal;
2777 : parrello 1.1 }
2778 :    
2779 :     =head3 RoleNeighbors
2780 :    
2781 :     C<< my @roleList = $sprout->RoleNeighbors($roleID); >>
2782 :    
2783 :     Returns a list of the roles that occur in the same diagram as the specified role. Because
2784 :     diagrams and roles are in a many-to-many relationship with each other, the list is
2785 :     essentially the set of roles from all of the maps that contain the incoming role. Such
2786 :     roles are considered neighbors because they are used together in cellular subsystems.
2787 :    
2788 :     =over 4
2789 :    
2790 :     =item roleID
2791 :    
2792 :     ID of the role whose neighbors are desired.
2793 :    
2794 :     =item RETURN
2795 :    
2796 :     Returns a list containing the IDs of the roles that are related to the incoming role.
2797 :    
2798 :     =back
2799 :    
2800 :     =cut
2801 : parrello 1.3 #: Return Type @;
2802 : parrello 1.1 sub RoleNeighbors {
2803 : parrello 1.15 # Get the parameters.
2804 :     my ($self, $roleID) = @_;
2805 :     # Get all the diagrams containing this role.
2806 :     my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2807 :     'RoleOccursIn(to-link)');
2808 :     # Create the return list.
2809 :     my @retVal = ();
2810 :     # Loop through the diagrams.
2811 :     for my $diagramID (@diagrams) {
2812 :     # Get all the roles in this diagram.
2813 :     my @roles = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(to-link) = ?", [$diagramID],
2814 :     'RoleOccursIn(from-link)');
2815 :     # Add them to the return list.
2816 :     push @retVal, @roles;
2817 :     }
2818 :     # Merge the duplicates from the list.
2819 :     return Tracer::Merge(@retVal);
2820 : parrello 1.1 }
2821 :    
2822 :     =head3 FeatureLinks
2823 :    
2824 :     C<< my @links = $sprout->FeatureLinks($featureID); >>
2825 :    
2826 :     Return a list of the web hyperlinks associated with a feature. The web hyperlinks are
2827 :     to external websites describing either the feature itself or the organism containing it
2828 :     and are represented in raw HTML.
2829 :    
2830 :     =over 4
2831 :    
2832 :     =item featureID
2833 :    
2834 :     ID of the feature whose links are desired.
2835 :    
2836 :     =item RETURN
2837 :    
2838 :     Returns a list of the web links for this feature.
2839 :    
2840 :     =back
2841 :    
2842 :     =cut
2843 : parrello 1.3 #: Return Type @;
2844 : parrello 1.1 sub FeatureLinks {
2845 : parrello 1.15 # Get the parameters.
2846 :     my ($self, $featureID) = @_;
2847 :     # Get the feature's links.
2848 :     my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);
2849 :     # Return the feature's links.
2850 :     return @retVal;
2851 : parrello 1.1 }
2852 :    
2853 :     =head3 SubsystemsOf
2854 :    
2855 :     C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2856 :    
2857 :     Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped
2858 : parrello 1.20 to the roles the feature performs.
2859 : parrello 1.1
2860 :     =over 4
2861 :    
2862 :     =item featureID
2863 :    
2864 :     ID of the feature whose subsystems are desired.
2865 :    
2866 :     =item RETURN
2867 :    
2868 : parrello 1.20 Returns a hash mapping all the feature's subsystems to a list of the feature's roles.
2869 : parrello 1.1
2870 :     =back
2871 :    
2872 :     =cut
2873 : parrello 1.20 #: Return Type %@;
2874 : parrello 1.1 sub SubsystemsOf {
2875 : parrello 1.15 # Get the parameters.
2876 :     my ($self, $featureID) = @_;
2877 : parrello 1.16 # Get the subsystem list.
2878 : parrello 1.15 my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2879 :     "ContainsFeature(to-link) = ?", [$featureID],
2880 :     ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2881 :     # Create the return value.
2882 :     my %retVal = ();
2883 : parrello 1.42 # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2884 :     # in two spreadsheet cells.
2885 :     my %dupHash = ();
2886 : parrello 1.15 # Loop through the results, adding them to the hash.
2887 :     for my $record (@subsystems) {
2888 : parrello 1.42 # Get this subsystem and role.
2889 : parrello 1.20 my ($subsys, $role) = @{$record};
2890 : parrello 1.42 # Insure it's the first time for both.
2891 :     my $dupKey = "$subsys\n$role";
2892 :     if (! exists $dupHash{"$subsys\n$role"}) {
2893 :     $dupHash{$dupKey} = 1;
2894 : parrello 1.20 push @{$retVal{$subsys}}, $role;
2895 :     }
2896 : parrello 1.15 }
2897 :     # Return the hash.
2898 :     return %retVal;
2899 : parrello 1.1 }
2900 :    
2901 : parrello 1.16 =head3 SubsystemList
2902 :    
2903 :     C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2904 :    
2905 :     Return a list containing the names of the subsystems in which the specified
2906 :     feature participates. Unlike L</SubsystemsOf>, this method only returns the
2907 :     subsystem names, not the roles.
2908 :    
2909 :     =over 4
2910 :    
2911 :     =item featureID
2912 :    
2913 :     ID of the feature whose subsystem names are desired.
2914 :    
2915 :     =item RETURN
2916 :    
2917 :     Returns a list of the names of the subsystems in which the feature participates.
2918 :    
2919 :     =back
2920 :    
2921 :     =cut
2922 :     #: Return Type @;
2923 :     sub SubsystemList {
2924 :     # Get the parameters.
2925 :     my ($self, $featureID) = @_;
2926 :     # Get the list of names.
2927 : parrello 1.88 my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?",
2928 :     [$featureID], 'HasRoleInSubsystem(to-link)');
2929 :     # Return the result, sorted.
2930 :     return sort @retVal;
2931 : parrello 1.16 }
2932 :    
2933 : parrello 1.80 =head3 GenomeSubsystemData
2934 :    
2935 :     C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>
2936 :    
2937 :     Return a hash mapping genome features to their subsystem roles.
2938 :    
2939 :     =over 4
2940 :    
2941 :     =item genomeID
2942 :    
2943 :     ID of the genome whose subsystem feature map is desired.
2944 :    
2945 :     =item RETURN
2946 :    
2947 :     Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb
2948 :     2-tuple contains a subsystem name followed by a role ID.
2949 :    
2950 :     =back
2951 :    
2952 :     =cut
2953 :    
2954 :     sub GenomeSubsystemData {
2955 :     # Get the parameters.
2956 :     my ($self, $genomeID) = @_;
2957 :     # Declare the return variable.
2958 :     my %retVal = ();
2959 :     # Get a list of the genome features that participate in subsystems. For each
2960 :     # feature we get its spreadsheet cells and the corresponding roles.
2961 :     my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],
2962 :     "HasFeature(from-link) = ?", [$genomeID],
2963 :     ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);
2964 :     # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems
2965 :     # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the
2966 :     # list. We use it at the beginning to get all the spreadsheet cells for the genome and
2967 :     # again at the end to filter out participation in subsystems with a negative variant code.
2968 :     my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],
2969 :     "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?",
2970 :     [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']);
2971 :     # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features.
2972 :     # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We
2973 :     # link these two lists together to create the result. First, we want a hash mapping
2974 :     # spreadsheet cells to subsystem names.
2975 :     my %subHash = map { $_->[0] => $_->[1] } @cellData;
2976 :     # We loop through @cellData to build the hash.
2977 :     for my $roleEntry (@roleData) {
2978 :     # Get the data for this feature and cell.
2979 :     my ($fid, $cellID, $role) = @{$roleEntry};
2980 :     # Check for a subsystem name.
2981 :     my $subsys = $subHash{$cellID};
2982 :     if ($subsys) {
2983 :     # Insure this feature has an entry in the return hash.
2984 :     if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
2985 :     # Merge in this new data.
2986 :     push @{$retVal{$fid}}, [$subsys, $role];
2987 :     }
2988 :     }
2989 :     # Return the result.
2990 :     return %retVal;
2991 :     }
2992 :    
2993 : parrello 1.1 =head3 RelatedFeatures
2994 :    
2995 :     C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
2996 :    
2997 :     Return a list of the features which are bi-directional best hits of the specified feature and
2998 :     have been assigned the specified function by the specified user. If no such features exists,
2999 :     an empty list will be returned.
3000 :    
3001 :     =over 4
3002 :    
3003 :     =item featureID
3004 :    
3005 :     ID of the feature to whom the desired features are related.
3006 :    
3007 :     =item function
3008 :    
3009 :     Functional assignment (as returned by C</FunctionOf>) that is used to determine which related
3010 :     features should be selected.
3011 :    
3012 :     =item userID
3013 :    
3014 :     ID of the user whose functional assignments are to be used. If omitted, C<FIG> is assumed.
3015 :    
3016 :     =item RETURN
3017 :    
3018 :     Returns a list of the related features with the specified function.
3019 :    
3020 :     =back
3021 :    
3022 :     =cut
3023 : parrello 1.3 #: Return Type @;
3024 : parrello 1.1 sub RelatedFeatures {
3025 : parrello 1.15 # Get the parameters.
3026 :     my ($self, $featureID, $function, $userID) = @_;
3027 :     # Get a list of the features that are BBHs of the incoming feature.
3028 : parrello 1.84 my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
3029 : parrello 1.15 # Now we loop through the features, pulling out the ones that have the correct
3030 :     # functional assignment.
3031 :     my @retVal = ();
3032 :     for my $bbhFeature (@bbhFeatures) {
3033 :     # Get this feature's functional assignment.
3034 :     my $newFunction = $self->FunctionOf($bbhFeature, $userID);
3035 :     # If it matches, add it to the result list.
3036 :     if ($newFunction eq $function) {
3037 :     push @retVal, $bbhFeature;
3038 :     }
3039 :     }
3040 :     # Return the result list.
3041 :     return @retVal;
3042 : parrello 1.1 }
3043 :    
3044 :     =head3 TaxonomySort
3045 :    
3046 :     C<< my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs); >>
3047 :    
3048 :     Return a list formed by sorting the specified features by the taxonomy of the containing
3049 :     genome. This will cause genomes from similar organisms to float close to each other.
3050 :    
3051 :     This task could almost be handled by the database; however, the taxonomy string in the
3052 :     database is a text field and can't be indexed. Instead, we create a hash table that maps
3053 :     taxonomy strings to lists of features. We then process the hash table using a key sort
3054 :     and merge the feature lists together to create the output.
3055 :    
3056 :     =over 4
3057 :    
3058 :     =item $featureIDs
3059 :    
3060 :     List of features to be taxonomically sorted.
3061 :    
3062 :     =item RETURN
3063 :    
3064 :     Returns the list of features sorted by the taxonomies of the containing genomes.
3065 :    
3066 :     =back
3067 :    
3068 :     =cut
3069 : parrello 1.3 #: Return Type @;
3070 : parrello 1.1 sub TaxonomySort {
3071 : parrello 1.15 # Get the parameters.
3072 :     my ($self, $featureIDs) = @_;
3073 :     # Create the working hash table.
3074 :     my %hashBuffer = ();
3075 :     # Loop through the features.
3076 :     for my $fid (@{$featureIDs}) {
3077 :     # Get the taxonomy of the feature's genome.
3078 :     my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
3079 :     [$fid], 'Genome(taxonomy)');
3080 :     # Add this feature to the hash buffer.
3081 : parrello 1.10 Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);
3082 : parrello 1.15 }
3083 :     # Sort the keys and get the elements.
3084 :     my @retVal = ();
3085 :     for my $taxon (sort keys %hashBuffer) {
3086 :     push @retVal, @{$hashBuffer{$taxon}};
3087 :     }
3088 :     # Return the result.
3089 :     return @retVal;
3090 : parrello 1.1 }
3091 :    
3092 :     =head3 Protein
3093 :    
3094 :     C<< my $protein = Sprout::Protein($sequence, $table); >>
3095 :    
3096 :     Translate a DNA sequence into a protein sequence.
3097 :    
3098 :     =over 4
3099 :    
3100 :     =item sequence
3101 :    
3102 :     DNA sequence to translate.
3103 :    
3104 :     =item table (optional)
3105 :    
3106 :     Reference to a Hash that translates DNA triples to proteins. A triple that does not
3107 :     appear in the hash will be translated automatically to C<X>.
3108 :    
3109 :     =item RETURN
3110 :    
3111 :     Returns the protein sequence that would be created by the DNA sequence.
3112 :    
3113 :     =back
3114 :    
3115 :     =cut
3116 :    
3117 :     # This is the translation table for protein synthesis.
3118 :     my $ProteinTable = { AAA => 'K', AAG => 'K', AAT => 'N', AAC => 'N',
3119 : parrello 1.15 AGA => 'R', AGG => 'R', AGT => 'S', AGC => 'S',
3120 :     ATA => 'I', ATG => 'M', ATT => 'I', ATC => 'I',
3121 :     ACA => 'T', ACG => 'T', ACT => 'T', ACC => 'T',
3122 :     GAA => 'E', GAG => 'E', GAT => 'D', GAC => 'D',
3123 :     GTA => 'V', GTG => 'V', GTT => 'V', GTC => 'V',
3124 :     GGA => 'G', GGG => 'G', GGT => 'G', GGC => 'G',
3125 :     GCA => 'A', GCG => 'A', GCT => 'A', GCC => 'A',
3126 :     CAA => 'Q', CAG => 'Q', CAT => 'H', CAC => 'H',
3127 :     CTA => 'L', CTG => 'L', CTT => 'L', CTC => 'L',
3128 :     CGA => 'R', CGG => 'R', CGT => 'R', CGC => 'R',
3129 :     CCA => 'P', CCG => 'P', CCT => 'P', CCC => 'P',
3130 :     TAA => '*', TAG => '*', TAT => 'Y', TAC => 'Y',
3131 :     TGA => '*', TGG => 'W', TGT => 'C', TGC => 'C',
3132 :     TTA => 'L', TTG => 'L', TTT => 'F', TTC => 'F',
3133 :     TCA => 'S', TCG => 'S', TCT => 'S', TCC => 'S',
3134 :     AAR => 'K', AAY => 'N',
3135 :     AGR => 'R', AGY => 'S',
3136 :     ATY => 'I',
3137 :     ACR => 'T', ACY => 'T', 'ACX' => 'T',
3138 :     GAR => 'E', GAY => 'D',
3139 :     GTR => 'V', GTY => 'V', GTX => 'V',
3140 :     GGR => 'G', GGY => 'G', GGX => 'G',
3141 :     GCR => 'A', GCY => 'A', GCX => 'A',
3142 :     CAR => 'Q', CAY => 'H',
3143 :     CTR => 'L', CTY => 'L', CTX => 'L',
3144 :     CGR => 'R', CGY => 'R', CGX => 'R',
3145 :     CCR => 'P', CCY => 'P', CCX => 'P',
3146 :     TAR => '*', TAY => 'Y',
3147 :     TGY => 'C',
3148 :     TTR => 'L', TTY => 'F',
3149 :     TCR => 'S', TCY => 'S', TCX => 'S'
3150 :     };
3151 : parrello 1.1
3152 :     sub Protein {
3153 : parrello 1.15 # Get the paraeters.
3154 :     my ($sequence, $table) = @_;
3155 :     # If no table was specified, use the default.
3156 :     if (!$table) {
3157 :     $table = $ProteinTable;
3158 :     }
3159 :     # Create the return value.
3160 :     my $retVal = "";
3161 :     # Loop through the input triples.
3162 :     my $n = length $sequence;
3163 :     for (my $i = 0; $i < $n; $i += 3) {
3164 : parrello 1.92 # Get the current triple from the sequence. Note we convert to
3165 :     # upper case to insure a match.
3166 :     my $triple = uc substr($sequence, $i, 3);
3167 : parrello 1.15 # Translate it using the table.
3168 :     my $protein = "X";
3169 :     if (exists $table->{$triple}) { $protein = $table->{$triple}; }
3170 :     $retVal .= $protein;
3171 :     }
3172 :     # Remove the stop codon (if any).
3173 :     $retVal =~ s/\*$//;
3174 :     # Return the result.
3175 :     return $retVal;
3176 : parrello 1.1 }
3177 :    
3178 :     =head3 LoadInfo
3179 :    
3180 :     C<< my ($dirName, @relNames) = $sprout->LoadInfo(); >>
3181 :    
3182 :     Return the name of the directory from which data is to be loaded and a list of the relation
3183 :     names. This information is useful when trying to analyze what needs to be put where in order
3184 :     to load the entire database.
3185 :    
3186 :     =cut
3187 : parrello 1.3 #: Return Type @;
3188 : parrello 1.1 sub LoadInfo {
3189 : parrello 1.15 # Get the parameters.
3190 :     my ($self) = @_;
3191 :     # Create the return list, priming it with the name of the data directory.
3192 :     my @retVal = ($self->{_options}->{dataDir});
3193 :     # Concatenate the table names.
3194 : parrello 1.58 push @retVal, $self->GetTableNames();
3195 : parrello 1.15 # Return the result.
3196 :     return @retVal;
3197 : parrello 1.1 }
3198 :    
3199 : parrello 1.96 =head3 BBHMatrix
3200 :    
3201 :     C<< my %bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets); >>
3202 :    
3203 :     Find all the bidirectional best hits for the features of a genome in a
3204 :     specified list of target genomes. The return value will be a hash mapping
3205 :     features in the original genome to their bidirectional best hits in the
3206 :     target genomes.
3207 :    
3208 :     =over 4
3209 :    
3210 :     =item genomeID
3211 :    
3212 :     ID of the genome whose features are to be examined for bidirectional best hits.
3213 :    
3214 :     =item cutoff
3215 :    
3216 :     A cutoff value. Only hits with a score lower than the cutoff will be returned.
3217 :    
3218 :     =item targets
3219 :    
3220 :     List of target genomes. Only pairs originating in the original
3221 :     genome and landing in one of the target genomes will be returned.
3222 :    
3223 :     =item RETURN
3224 :    
3225 :     Returns a hash mapping each feature in the original genome to a hash mapping its
3226 :     BBH pegs in the target genomes to their scores.
3227 :    
3228 :     =back
3229 :    
3230 :     =cut
3231 :    
3232 :     sub BBHMatrix {
3233 :     # Get the parameters.
3234 :     my ($self, $genomeID, $cutoff, @targets) = @_;
3235 :     # Declare the return variable.
3236 :     my %retVal = ();
3237 :     # Ask for the BBHs.
3238 :     my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets);
3239 :     # We now have a set of 4-tuples that we need to convert into a hash of hashes.
3240 :     for my $bbhData (@bbhList) {
3241 :     my ($peg1, $peg2, $score) = @{$bbhData};
3242 :     if (! exists $retVal{$peg1}) {
3243 :     $retVal{$peg1} = { $peg2 => $score };
3244 :     } else {
3245 :     $retVal{$peg1}->{$peg2} = $score;
3246 :     }
3247 :     }
3248 :     # Return the result.
3249 :     return %retVal;
3250 :     }
3251 :    
3252 : parrello 1.98
3253 :     =head3 SimMatrix
3254 :    
3255 :     C<< my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets); >>
3256 :    
3257 :     Find all the similarities for the features of a genome in a
3258 :     specified list of target genomes. The return value will be a hash mapping
3259 :     features in the original genome to their similarites in the
3260 :     target genomes.
3261 :    
3262 :     =over 4
3263 :    
3264 :     =item genomeID
3265 :    
3266 :     ID of the genome whose features are to be examined for similarities.
3267 :    
3268 :     =item cutoff
3269 :    
3270 :     A cutoff value. Only hits with a score lower than the cutoff will be returned.
3271 :    
3272 :     =item targets
3273 :    
3274 :     List of target genomes. Only pairs originating in the original
3275 :     genome and landing in one of the target genomes will be returned.
3276 :    
3277 :     =item RETURN
3278 :    
3279 :     Returns a hash mapping each feature in the original genome to a hash mapping its
3280 :     similar pegs in the target genomes to their scores.
3281 :    
3282 :     =back
3283 :    
3284 :     =cut
3285 :    
3286 :     sub SimMatrix {
3287 :     # Get the parameters.
3288 :     my ($self, $genomeID, $cutoff, @targets) = @_;
3289 :     # Declare the return variable.
3290 :     my %retVal = ();
3291 :     # Get the list of features in the source organism.
3292 :     my @fids = $self->FeaturesOf($genomeID);
3293 :     # Ask for the sims. We only want similarities to fig features.
3294 :     my $simList = FIGRules::GetNetworkSims($self, \@fids, {}, 1000, $cutoff, "fig");
3295 :     if (! defined $simList) {
3296 :     Confess("Unable to retrieve similarities from server.");
3297 :     } else {
3298 :     Trace("Processing sims.") if T(3);
3299 :     # We now have a set of sims that we need to convert into a hash of hashes. First, we
3300 :     # Create a hash for the target genomes.
3301 :     my %targetHash = map { $_ => 1 } @targets;
3302 :     for my $simData (@{$simList}) {
3303 :     # Get the PEGs and the score.
3304 :     my ($peg1, $peg2, $score) = ($simData->id1, $simData->id2, $simData->psc);
3305 :     # Insure the second ID is in the target list.
3306 :     my ($genome2) = FIGRules::ParseFeatureID($peg2);
3307 :     if (exists $targetHash{$genome2}) {
3308 :     # Here it is. Now we need to add it to the return hash. How we do that depends
3309 :     # on whether or not $peg1 is new to us.
3310 :     if (! exists $retVal{$peg1}) {
3311 :     $retVal{$peg1} = { $peg2 => $score };
3312 :     } else {
3313 :     $retVal{$peg1}->{$peg2} = $score;
3314 :     }
3315 :     }
3316 :     }
3317 :     }
3318 :     # Return the result.
3319 :     return %retVal;
3320 :     }
3321 :    
3322 :    
3323 : parrello 1.1 =head3 LowBBHs
3324 :    
3325 : parrello 1.58 C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
3326 : parrello 1.1
3327 :     Return the bidirectional best hits of a feature whose score is no greater than a
3328 :     specified cutoff value. A higher cutoff value will allow inclusion of hits with
3329 :     a greater score. The value returned is a map of feature IDs to scores.
3330 :    
3331 :     =over 4
3332 :    
3333 :     =item featureID
3334 :    
3335 :     ID of the feature whose best hits are desired.
3336 :    
3337 :     =item cutoff
3338 :    
3339 :     Maximum permissible score for inclusion in the results.
3340 :    
3341 :     =item RETURN
3342 :    
3343 :     Returns a hash mapping feature IDs to scores.
3344 :    
3345 :     =back
3346 :    
3347 :     =cut
3348 : parrello 1.3 #: Return Type %;
3349 : parrello 1.1 sub LowBBHs {
3350 : parrello 1.15 # Get the parsameters.
3351 :     my ($self, $featureID, $cutoff) = @_;
3352 :     # Create the return hash.
3353 :     my %retVal = ();
3354 : parrello 1.84 # Query for the desired BBHs.
3355 :     my @bbhList = FIGRules::BBHData($featureID, $cutoff);
3356 : parrello 1.15 # Form the results into the return hash.
3357 :     for my $pair (@bbhList) {
3358 : parrello 1.94 my $fid = $pair->[0];
3359 :     if ($self->Exists('Feature', $fid)) {
3360 :     $retVal{$fid} = $pair->[1];
3361 :     }
3362 : parrello 1.15 }
3363 :     # Return the result.
3364 :     return %retVal;
3365 : parrello 1.1 }
3366 :    
3367 : parrello 1.71 =head3 Sims
3368 :    
3369 :     C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>
3370 :    
3371 :     Get a list of similarities for a specified feature. Similarity information is not kept in the
3372 :     Sprout database; rather, they are retrieved from a network server. The similarities are
3373 :     returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3374 :     so that its elements can be accessed by name.
3375 :    
3376 :     Similarities can be either raw or expanded. The raw similarities are basic
3377 :     hits between features with similar DNA. Expanding a raw similarity drags in any
3378 :     features considered substantially identical. So, for example, if features B<A1>,
3379 : parrello 1.98 B<A2>, and B<A3> are all substantially identical to B<A>, then a raw similarity
3380 : parrello 1.71 B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3381 :    
3382 :     =over 4
3383 :    
3384 :     =item fid
3385 :    
3386 :     ID of the feature whose similarities are desired.
3387 :    
3388 :     =item maxN
3389 :    
3390 :     Maximum number of similarities to return.
3391 :    
3392 :     =item maxP
3393 :    
3394 :     Minumum allowable similarity score.
3395 :    
3396 :     =item select
3397 :    
3398 :     Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3399 :     means only similarities to FIG features are returned; C<all> means all expanded
3400 :     similarities are returned; and C<figx> means similarities are expanded until the
3401 :     number of FIG features equals the maximum.
3402 :    
3403 :     =item max_expand
3404 :    
3405 :     The maximum number of features to expand.
3406 :    
3407 :     =item filters
3408 :    
3409 :     Reference to a hash containing filter information, or a subroutine that can be
3410 :     used to filter the sims.
3411 :    
3412 :     =item RETURN
3413 :    
3414 :     Returns a reference to a list of similarity objects, or C<undef> if an error
3415 :     occurred.
3416 :    
3417 :     =back
3418 :    
3419 :     =cut
3420 :    
3421 :     sub Sims {
3422 :     # Get the parameters.
3423 :     my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3424 :     # Create the shim object to test for deleted FIDs.
3425 :     my $shim = FidCheck->new($self);
3426 :     # Ask the network for sims.
3427 :     my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3428 :     # Return the result.
3429 :     return $retVal;
3430 :     }
3431 :    
3432 : parrello 1.90 =head3 IsAllGenomes
3433 :    
3434 :     C<< my $flag = $sprout->IsAllGenomes(\@list, \@checkList); >>
3435 :    
3436 :     Return TRUE if all genomes in the second list are represented in the first list at
3437 :     least one. Otherwise, return FALSE. If the second list is omitted, the first list is
3438 :     compared to a list of all the genomes.
3439 :    
3440 :     =over 4
3441 :    
3442 :     =item list
3443 :    
3444 :     Reference to the list to be compared to the second list.
3445 :    
3446 :     =item checkList (optional)
3447 :    
3448 :     Reference to the comparison target list. Every genome ID in this list must occur at
3449 :     least once in the first list. If this parameter is omitted, a list of all the genomes
3450 :     is used.
3451 :    
3452 :     =item RETURN
3453 :    
3454 :     Returns TRUE if every item in the second list appears at least once in the
3455 :     first list, else FALSE.
3456 :    
3457 :     =back
3458 :    
3459 :     =cut
3460 :    
3461 :     sub IsAllGenomes {
3462 :     # Get the parameters.
3463 :     my ($self, $list, $checkList) = @_;
3464 :     # Supply the checklist if it was omitted.
3465 :     $checkList = [$self->Genomes()] if ! defined($checkList);
3466 :     # Create a hash of the original list.
3467 :     my %testList = map { $_ => 1 } @{$list};
3468 :     # Declare the return variable. We assume that the representation
3469 :     # is complete and stop at the first failure.
3470 :     my $retVal = 1;
3471 :     my $n = scalar @{$checkList};
3472 :     for (my $i = 0; $retVal && $i < $n; $i++) {
3473 :     if (! $testList{$checkList->[$i]}) {
3474 :     $retVal = 0;
3475 :     }
3476 :     }
3477 :     # Return the result.
3478 :     return $retVal;
3479 :     }
3480 :    
3481 : parrello 1.7 =head3 GetGroups
3482 :    
3483 : parrello 1.8 C<< my %groups = $sprout->GetGroups(\@groupList); >>
3484 :    
3485 :     Return a hash mapping each group to the IDs of the genomes in the group.
3486 :     A list of groups may be specified, in which case only those groups will be
3487 :     shown. Alternatively, if no parameter is supplied, all groups will be
3488 :     included. Genomes that are not in any group are omitted.
3489 :    
3490 : parrello 1.7 =cut
3491 :     #: Return Type %@;
3492 :     sub GetGroups {
3493 : parrello 1.8 # Get the parameters.
3494 : parrello 1.10 my ($self, $groupList) = @_;
3495 : parrello 1.8 # Declare the return value.
3496 :     my %retVal = ();
3497 :     # Determine whether we are getting all the groups or just some.
3498 :     if (defined $groupList) {
3499 :     # Here we have a group list. Loop through them individually,
3500 :     # getting a list of the relevant genomes.
3501 :     for my $group (@{$groupList}) {
3502 : parrello 1.86 my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3503 : parrello 1.8 [$group], "Genome(id)");
3504 :     $retVal{$group} = \@genomeIDs;
3505 :     }
3506 :     } else {
3507 :     # Here we need all of the groups. In this case, we run through all
3508 :     # of the genome records, putting each one found into the appropriate
3509 :     # group. Note that we use a filter clause to insure that only genomes
3510 : parrello 1.86 # in real NMPDR groups are included in the return set.
3511 :     my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3512 :     [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3513 : parrello 1.8 # Loop through the genomes found.
3514 :     for my $genome (@genomes) {
3515 :     # Pop this genome's ID off the current list.
3516 :     my @groups = @{$genome};
3517 :     my $genomeID = shift @groups;
3518 :     # Loop through the groups, adding the genome ID to each group's
3519 :     # list.
3520 :     for my $group (@groups) {
3521 : parrello 1.10 Tracer::AddToListMap(\%retVal, $group, $genomeID);
3522 : parrello 1.8 }
3523 :     }
3524 :     }
3525 :     # Return the hash we just built.
3526 :     return %retVal;
3527 : parrello 1.7 }
3528 :    
3529 : parrello 1.18 =head3 MyGenomes
3530 :    
3531 :     C<< my @genomes = Sprout::MyGenomes($dataDir); >>
3532 :    
3533 :     Return a list of the genomes to be included in the Sprout.
3534 :    
3535 :     This method is provided for use during the Sprout load. It presumes the Genome load file has
3536 :     already been created. (It will be in the Sprout data directory and called either C<Genome>
3537 :     or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3538 :     IDs.
3539 :    
3540 :     =over 4
3541 :    
3542 :     =item dataDir
3543 :    
3544 :     Directory containing the Sprout load files.
3545 :    
3546 :     =back
3547 :    
3548 :     =cut
3549 :     #: Return Type @;
3550 :     sub MyGenomes {
3551 :     # Get the parameters.
3552 :     my ($dataDir) = @_;
3553 :     # Compute the genome file name.
3554 :     my $genomeFileName = LoadFileName($dataDir, "Genome");
3555 :     # Extract the genome IDs from the files.
3556 :     my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3557 :     # Return the result.
3558 :     return @retVal;
3559 :     }
3560 :    
3561 :     =head3 LoadFileName
3562 :    
3563 :     C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3564 :    
3565 :     Return the name of the load file for the specified table in the specified data
3566 :     directory.
3567 :    
3568 :     =over 4
3569 :    
3570 :     =item dataDir
3571 :    
3572 :     Directory containing the Sprout load files.
3573 :    
3574 :     =item tableName
3575 :    
3576 :     Name of the table whose load file is desired.
3577 :    
3578 :     =item RETURN
3579 :    
3580 :     Returns the name of the file containing the load data for the specified table, or
3581 :     C<undef> if no load file is present.
3582 :    
3583 :     =back
3584 :    
3585 :     =cut
3586 :     #: Return Type $;
3587 :     sub LoadFileName {
3588 :     # Get the parameters.
3589 :     my ($dataDir, $tableName) = @_;
3590 :     # Declare the return variable.
3591 :     my $retVal;
3592 :     # Check for the various file names.
3593 :     if (-e "$dataDir/$tableName") {
3594 :     $retVal = "$dataDir/$tableName";
3595 :     } elsif (-e "$dataDir/$tableName.dtx") {
3596 :     $retVal = "$dataDir/$tableName.dtx";
3597 :     }
3598 :     # Return the result.
3599 :     return $retVal;
3600 :     }
3601 :    
3602 : parrello 1.53 =head3 DeleteGenome
3603 :    
3604 :     C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3605 :    
3606 :     Delete a genome from the database.
3607 :    
3608 :     =over 4
3609 :    
3610 :     =item genomeID
3611 :    
3612 :     ID of the genome to delete
3613 :    
3614 :     =item testFlag
3615 :    
3616 :     If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3617 :    
3618 :     =item RETURN
3619 :    
3620 :     Returns a statistics object describing the rows deleted.
3621 :    
3622 :     =back
3623 :    
3624 :     =cut
3625 :     #: Return Type $%;
3626 :     sub DeleteGenome {
3627 :     # Get the parameters.
3628 :     my ($self, $genomeID, $testFlag) = @_;
3629 :     # Perform the delete for the genome's features.
3630 : parrello 1.95 my $retVal = $self->Delete('Feature', "fig|$genomeID.%", testMode => $testFlag);
3631 : parrello 1.53 # Perform the delete for the primary genome data.
3632 : parrello 1.95 my $stats = $self->Delete('Genome', $genomeID, testMode => $testFlag);
3633 : parrello 1.53 $retVal->Accumulate($stats);
3634 :     # Return the result.
3635 :     return $retVal;
3636 :     }
3637 :    
3638 : parrello 1.82 =head3 Fix
3639 :    
3640 :     C<< my %fixedHash = Sprout::Fix(%groupHash); >>
3641 :    
3642 :     Prepare a genome group hash (like that returned by L</GetGroups> for processing.
3643 :     Groups with the same primary name will be combined. The primary name is the
3644 :     first capitalized word in the group name.
3645 :    
3646 :     =over 4
3647 :    
3648 :     =item groupHash
3649 :    
3650 :     Hash to be fixed up.
3651 :    
3652 :     =item RETURN
3653 :    
3654 :     Returns a fixed-up version of the hash.
3655 :    
3656 :     =back
3657 :    
3658 :     =cut
3659 :    
3660 :     sub Fix {
3661 :     # Get the parameters.
3662 :     my (%groupHash) = @_;
3663 :     # Create the result hash.
3664 :     my %retVal = ();
3665 :     # Copy over the genomes.
3666 :     for my $groupID (keys %groupHash) {
3667 :     # Make a safety copy of the group ID.
3668 :     my $realGroupID = $groupID;
3669 :     # Yank the primary name.
3670 :     if ($groupID =~ /([A-Z]\w+)/) {
3671 :     $realGroupID = $1;
3672 :     }
3673 :     # Append this group's genomes into the result hash.
3674 :     Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}});
3675 :     }
3676 :     # Return the result hash.
3677 :     return %retVal;
3678 :     }
3679 :    
3680 : parrello 1.85 =head3 GroupPageName
3681 :    
3682 :     C<< my $name = $sprout->GroupPageName($group); >>
3683 :    
3684 :     Return the name of the page for the specified NMPDR group.
3685 :    
3686 :     =over 4
3687 :    
3688 :     =item group
3689 :    
3690 :     Name of the relevant group.
3691 :    
3692 :     =item RETURN
3693 :    
3694 :     Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3695 :     memory it will be read in.
3696 :    
3697 :     =back
3698 :    
3699 :     =cut
3700 :    
3701 :     sub GroupPageName {
3702 :     # Get the parameters.
3703 :     my ($self, $group) = @_;
3704 :     # Declare the return variable.
3705 :     my $retVal;
3706 :     # Check for the group file data.
3707 :     if (! defined $self->{groupHash}) {
3708 :     # Read the group file.
3709 :     my %groupData = Sprout::ReadGroupFile($self->{_options}->{dataDir} . "/groups.tbl");
3710 :     # Store it in our object.
3711 :     $self->{groupHash} = \%groupData;
3712 :     }
3713 :     # Compute the real group name.
3714 :     my $realGroup = $group;
3715 :     if ($group =~ /([A-Z]\w+)/) {
3716 :     $realGroup = $1;
3717 :     }
3718 :     # Return the page name.
3719 :     $retVal = "../content/" . $self->{groupHash}->{$realGroup}->[1];
3720 :     # Return the result.
3721 :     return $retVal;
3722 :     }
3723 :    
3724 : parrello 1.83 =head3 ReadGroupFile
3725 :    
3726 :     C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >>
3727 :    
3728 :     Read in the data from the specified group file. The group file contains information
3729 :     about each of the NMPDR groups.
3730 :    
3731 :     =over 4
3732 :    
3733 :     =item name
3734 :    
3735 :     Name of the group.
3736 :    
3737 :     =item page
3738 :    
3739 :     Name of the group's page on the web site (e.g. C<campy.php> for
3740 :     Campylobacter)
3741 :    
3742 :     =item genus
3743 :    
3744 :     Genus of the group
3745 :    
3746 :     =item species
3747 :    
3748 :     Species of the group, or an empty string if the group is for an entire
3749 :     genus. If the group contains more than one species, the species names
3750 :     should be separated by commas.
3751 :    
3752 :     =back
3753 :    
3754 :     The parameters to this method are as follows
3755 :    
3756 :     =over 4
3757 :    
3758 :     =item groupFile
3759 :    
3760 :     Name of the file containing the group data.
3761 :    
3762 :     =item RETURN
3763 :    
3764 :     Returns a hash keyed on group name. The value of each hash
3765 :    
3766 :     =back
3767 :    
3768 :     =cut
3769 :    
3770 :     sub ReadGroupFile {
3771 :     # Get the parameters.
3772 :     my ($groupFileName) = @_;
3773 :     # Declare the return variable.
3774 :     my %retVal;
3775 :     # Read the group file.
3776 :     my @groupLines = Tracer::GetFile($groupFileName);
3777 :     for my $groupLine (@groupLines) {
3778 :     my ($name, $page, $genus, $species) = split(/\t/, $groupLine);
3779 :     $retVal{$name} = [$page, $genus, $species];
3780 :     }
3781 :     # Return the result.
3782 :     return %retVal;
3783 :     }
3784 :    
3785 : parrello 1.90 =head3 AddProperty
3786 :    
3787 : parrello 1.99 C<< my = $sprout->AddProperty($featureID, $key, @values); >>
3788 : parrello 1.90
3789 : parrello 1.99 Add a new attribute value (Property) to a feature.
3790 : parrello 1.90
3791 :     =over 4
3792 :    
3793 :     =item peg
3794 :    
3795 : parrello 1.99 ID of the feature to which the attribute is to be added.
3796 : parrello 1.90
3797 :     =item key
3798 :    
3799 :     Name of the attribute (key).
3800 :    
3801 : parrello 1.99 =item values
3802 : parrello 1.90
3803 : parrello 1.99 Values of the attribute.
3804 : parrello 1.90
3805 :     =back
3806 :    
3807 :     =cut
3808 :     #: Return Type ;
3809 :     sub AddProperty {
3810 :     # Get the parameters.
3811 : parrello 1.99 my ($self, $featureID, $key, @values) = @_;
3812 :     # Add the property using the attached attributes object.
3813 :     $self->{_ca}->AddAttribute($featureID, $key, @values);
3814 : parrello 1.90 }
3815 :    
3816 : parrello 1.91 =head2 Virtual Methods
3817 :    
3818 :     =head3 CleanKeywords
3819 :    
3820 :     C<< my $cleanedString = $sprout->CleanKeywords($searchExpression); >>
3821 :    
3822 :     Clean up a search expression or keyword list. This involves converting the periods
3823 :     in EC numbers to underscores, converting non-leading minus signs to underscores,
3824 :     a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
3825 :     characters. In addition, any extra spaces are removed.
3826 :    
3827 :     =over 4
3828 :    
3829 :     =item searchExpression
3830 :    
3831 :     Search expression or keyword list to clean. Note that a search expression may
3832 :     contain boolean operators which need to be preserved. This includes leading
3833 :     minus signs.
3834 :    
3835 :     =item RETURN
3836 :    
3837 :     Cleaned expression or keyword list.
3838 :    
3839 :     =back
3840 :    
3841 :     =cut
3842 :    
3843 :     sub CleanKeywords {
3844 :     # Get the parameters.
3845 :     my ($self, $searchExpression) = @_;
3846 :     # Perform the standard cleanup.
3847 :     my $retVal = $self->ERDB::CleanKeywords($searchExpression);
3848 :     # Fix the periods in EC and TC numbers.
3849 :     $retVal =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g;
3850 :     # Fix non-trailing periods.
3851 :     $retVal =~ s/\.(\w)/_$1/g;
3852 :     # Fix non-leading minus signs.
3853 :     $retVal =~ s/(\w)[\-]/$1_/g;
3854 :     # Fix the vertical bars and colons
3855 :     $retVal =~ s/(\w)[|:](\w)/$1'$2/g;
3856 :     # Return the result.
3857 :     return $retVal;
3858 :     }
3859 :    
3860 : parrello 1.1 =head2 Internal Utility Methods
3861 :    
3862 :     =head3 ParseAssignment
3863 :    
3864 :     Parse annotation text to determine whether or not it is a functional assignment. If it is,
3865 : parrello 1.19 the user, function text, and assigning user will be returned as a 3-element list. If it
3866 : parrello 1.11 isn't, an empty list will be returned.
3867 :    
3868 :     A functional assignment is always of the form
3869 :    
3870 : parrello 1.48 C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3871 : parrello 1.19
3872 : parrello 1.48 where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3873 :     the user and the assigning user (from MadeAnnotation) will be the same, but that is
3874 :     not always the case.
3875 : parrello 1.1
3876 : parrello 1.52 In addition, the functional role may contain extra data that is stripped, such as
3877 :     terminating spaces or a comment separated from the rest of the text by a tab.
3878 :    
3879 : parrello 1.1 This is a static method.
3880 :    
3881 :     =over 4
3882 :    
3883 : parrello 1.48 =item user
3884 :    
3885 :     Name of the assigning user.
3886 :    
3887 : parrello 1.1 =item text
3888 :    
3889 :     Text of the annotation.
3890 :    
3891 :     =item RETURN
3892 :    
3893 :     Returns an empty list if the annotation is not a functional assignment; otherwise, returns
3894 :     a two-element list containing the user name and the function text.
3895 :    
3896 :     =back
3897 :    
3898 :     =cut
3899 :    
3900 : parrello 1.11 sub _ParseAssignment {
3901 : parrello 1.15 # Get the parameters.
3902 : parrello 1.48 my ($user, $text) = @_;
3903 : parrello 1.15 # Declare the return value.
3904 :     my @retVal = ();
3905 :     # Check to see if this is a functional assignment.
3906 : parrello 1.43 my ($type, $function) = split(/\n/, $text);
3907 : parrello 1.48 if ($type =~ m/^set function to$/i) {
3908 :     # Here we have an assignment without a user, so we use the incoming user ID.
3909 :     @retVal = ($user, $function);
3910 :     } elsif ($type =~ m/^set (\S+) function to$/i) {
3911 : parrello 1.52 # Here we have an assignment with a user that is passed back to the caller.
3912 : parrello 1.43 @retVal = ($1, $function);
3913 : parrello 1.15 }
3914 : parrello 1.52 # If we have an assignment, we need to clean the function text. There may be
3915 :     # extra junk at the end added as a note from the user.
3916 : parrello 1.81 if (defined( $retVal[1] )) {
3917 : parrello 1.52 $retVal[1] =~ s/(\t\S)?\s*$//;
3918 :     }
3919 : parrello 1.15 # Return the result list.
3920 :     return @retVal;
3921 : parrello 1.1 }
3922 :    
3923 : parrello 1.3 =head3 FriendlyTimestamp
3924 :    
3925 :     Convert a time number to a user-friendly time stamp for display.
3926 :    
3927 :     This is a static method.
3928 :    
3929 :     =over 4
3930 :    
3931 :     =item timeValue
3932 :    
3933 :     Numeric time value.
3934 :    
3935 :     =item RETURN
3936 :    
3937 :     Returns a string containing the same time in user-readable format.
3938 :    
3939 :     =back
3940 :    
3941 :     =cut
3942 :    
3943 :     sub FriendlyTimestamp {
3944 :     my ($timeValue) = @_;
3945 : parrello 1.40 my $retVal = localtime($timeValue);
3946 : parrello 1.3 return $retVal;
3947 :     }
3948 :    
3949 : parrello 1.51
3950 : olson 1.79 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3