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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3