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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3