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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3