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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3