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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.59 - (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 :     =head3 ContigLength
797 :    
798 :     C<< my $length = $sprout->ContigLength($contigID); >>
799 :    
800 :     Compute the length of a contig.
801 :    
802 :     =over 4
803 :    
804 :     =item contigID
805 :    
806 :     ID of the contig whose length is desired.
807 :    
808 : parrello 1.3 =item RETURN
809 :    
810 :     Returns the number of positions in the contig.
811 :    
812 : parrello 1.1 =back
813 :    
814 :     =cut
815 : parrello 1.3 #: Return Type $;
816 : parrello 1.1 sub ContigLength {
817 : parrello 1.15 # Get the parameters.
818 :     my ($self, $contigID) = @_;
819 :     # Get the contig's last sequence.
820 :     my $query = $self->Get(['IsMadeUpOf'],
821 :     "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
822 :     [$contigID]);
823 :     my $sequence = $query->Fetch();
824 :     # Declare the return value.
825 :     my $retVal = 0;
826 :     # Set it from the sequence data, if any.
827 :     if ($sequence) {
828 :     my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
829 : parrello 1.40 $retVal = $start + $len - 1;
830 :     }
831 :     # Return the result.
832 :     return $retVal;
833 :     }
834 :    
835 :     =head3 ClusterPEGs
836 :    
837 :     C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
838 :    
839 :     Cluster the PEGs in a list according to the cluster coding scheme of the specified
840 :     subsystem. In order for this to work properly, the subsystem object must have
841 :     been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
842 :     This causes the cluster numbers to be pulled into the subsystem's color hash.
843 :     If a PEG is not found in the color hash, it will not appear in the output
844 :     sequence.
845 :    
846 :     =over 4
847 :    
848 :     =item sub
849 :    
850 :     Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
851 :     method.
852 :    
853 :     =item pegs
854 :    
855 :     Reference to the list of PEGs to be clustered.
856 :    
857 :     =item RETURN
858 :    
859 :     Returns a list of the PEGs, grouped into smaller lists by cluster number.
860 :    
861 :     =back
862 :    
863 :     =cut
864 :     #: Return Type $@@;
865 :     sub ClusterPEGs {
866 :     # Get the parameters.
867 :     my ($self, $sub, $pegs) = @_;
868 :     # Declare the return variable.
869 :     my $retVal = [];
870 :     # Loop through the PEGs, creating arrays for each cluster.
871 :     for my $pegID (@{$pegs}) {
872 :     my $clusterNumber = $sub->get_cluster_number($pegID);
873 :     # Only proceed if the PEG is in a cluster.
874 :     if ($clusterNumber >= 0) {
875 :     # Push this PEG onto the sub-list for the specified cluster number.
876 :     push @{$retVal->[$clusterNumber]}, $pegID;
877 :     }
878 : parrello 1.15 }
879 :     # Return the result.
880 :     return $retVal;
881 : parrello 1.1 }
882 :    
883 :     =head3 GenesInRegion
884 :    
885 :     C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>
886 :    
887 :     List the features which overlap a specified region in a contig.
888 :    
889 :     =over 4
890 :    
891 :     =item contigID
892 :    
893 :     ID of the contig containing the region of interest.
894 :    
895 :     =item start
896 :    
897 :     Offset of the first residue in the region of interest.
898 :    
899 :     =item stop
900 :    
901 :     Offset of the last residue in the region of interest.
902 :    
903 :     =item RETURN
904 :    
905 :     Returns a three-element list. The first element is a list of feature IDs for the features that
906 :     overlap the region of interest. The second and third elements are the minimum and maximum
907 :     locations of the features provided on the specified contig. These may extend outside
908 : parrello 1.9 the start and stop values. The first element (that is, the list of features) is sorted
909 :     roughly by location.
910 : parrello 1.1
911 :     =back
912 :    
913 :     =cut
914 : parrello 1.9 #: Return Type @@;
915 : parrello 1.1 sub GenesInRegion {
916 : parrello 1.15 # Get the parameters.
917 :     my ($self, $contigID, $start, $stop) = @_;
918 :     # Get the maximum segment length.
919 :     my $maximumSegmentLength = $self->MaxSegment;
920 :     # Create a hash to receive the feature list. We use a hash so that we can eliminate
921 :     # duplicates easily. The hash key will be the feature ID. The value will be a two-element
922 : parrello 1.19 # containing the minimum and maximum offsets. We will use the offsets to sort the results
923 : parrello 1.15 # when we're building the result set.
924 :     my %featuresFound = ();
925 :     # Prime the values we'll use for the returned beginning and end.
926 :     my @initialMinMax = ($self->ContigLength($contigID), 0);
927 :     my ($min, $max) = @initialMinMax;
928 :     # Create a table of parameters for each query. Each query looks for features travelling in
929 :     # a particular direction. The query parameters include the contig ID, the feature direction,
930 :     # the lowest possible start position, and the highest possible start position. This works
931 :     # because each feature segment length must be no greater than the maximum segment length.
932 :     my %queryParms = (forward => [$contigID, '+', $start - $maximumSegmentLength + 1, $stop],
933 :     reverse => [$contigID, '-', $start, $stop + $maximumSegmentLength - 1]);
934 :     # Loop through the query parameters.
935 :     for my $parms (values %queryParms) {
936 :     # Create the query.
937 :     my $query = $self->Get(['IsLocatedIn'],
938 :     "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
939 :     $parms);
940 :     # Loop through the feature segments found.
941 :     while (my $segment = $query->Fetch) {
942 :     # Get the data about this segment.
943 :     my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',
944 :     'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);
945 :     # Determine if this feature actually overlaps the region. The query insures that
946 :     # this will be the case if the segment is the maximum length, so to fine-tune
947 :     # the results we insure that the inequality from the query holds using the actual
948 :     # length.
949 :     my ($found, $end) = (0, 0);
950 :     if ($dir eq '+') {
951 :     $end = $beg + $len;
952 :     if ($end >= $start) {
953 :     # Denote we found a useful feature.
954 :     $found = 1;
955 :     }
956 :     } elsif ($dir eq '-') {
957 :     # Note we switch things around so that the beginning is to the left of the
958 :     # ending.
959 :     ($beg, $end) = ($beg - $len, $beg);
960 :     if ($beg <= $stop) {
961 :     # Denote we found a useful feature.
962 :     $found = 1;
963 :     }
964 :     }
965 :     if ($found) {
966 :     # Here we need to record the feature and update the minima and maxima. First,
967 :     # get the current entry for the specified feature.
968 :     my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :
969 :     @initialMinMax);
970 :     # Merge the current segment's begin and end into the feature begin and end and the
971 :     # global min and max.
972 :     if ($beg < $loc1) {
973 :     $loc1 = $beg;
974 :     $min = $beg if $beg < $min;
975 :     }
976 :     if ($end > $loc2) {
977 :     $loc2 = $end;
978 :     $max = $end if $end > $max;
979 :     }
980 :     # Store the entry back into the hash table.
981 :     $featuresFound{$featureID} = [$loc1, $loc2];
982 :     }
983 :     }
984 :     }
985 :     # Now we must compute the list of the IDs for the features found. We start with a list
986 :     # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
987 :     # but the result of the sort will be the same.)
988 :     my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;
989 :     # Now we sort by midpoint and yank out the feature IDs.
990 :     my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
991 :     # Return it along with the min and max.
992 :     return (\@retVal, $min, $max);
993 : parrello 1.1 }
994 :    
995 :     =head3 FType
996 :    
997 :     C<< my $ftype = $sprout->FType($featureID); >>
998 :    
999 :     Return the type of a feature.
1000 :    
1001 :     =over 4
1002 :    
1003 :     =item featureID
1004 :    
1005 :     ID of the feature whose type is desired.
1006 :    
1007 :     =item RETURN
1008 :    
1009 :     A string indicating the type of feature (e.g. peg, rna). If the feature does not exist, returns an
1010 :     undefined value.
1011 :    
1012 :     =back
1013 :    
1014 :     =cut
1015 : parrello 1.3 #: Return Type $;
1016 : parrello 1.1 sub FType {
1017 : parrello 1.15 # Get the parameters.
1018 :     my ($self, $featureID) = @_;
1019 :     # Get the specified feature's type.
1020 :     my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
1021 :     # Return the result.
1022 :     return $retVal;
1023 : parrello 1.1 }
1024 :    
1025 :     =head3 FeatureAnnotations
1026 :    
1027 : parrello 1.40 C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1028 : parrello 1.1
1029 :     Return the annotations of a feature.
1030 :    
1031 :     =over 4
1032 :    
1033 :     =item featureID
1034 :    
1035 :     ID of the feature whose annotations are desired.
1036 :    
1037 : parrello 1.40 =item rawFlag
1038 :    
1039 :     If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1040 :     will be returned in human-readable form.
1041 :    
1042 : parrello 1.1 =item RETURN
1043 :    
1044 :     Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.
1045 :    
1046 :     * B<featureID> ID of the relevant feature.
1047 :    
1048 : parrello 1.40 * B<timeStamp> time the annotation was made.
1049 : parrello 1.1
1050 :     * B<user> ID of the user who made the annotation
1051 :    
1052 :     * B<text> text of the annotation.
1053 :    
1054 :     =back
1055 :    
1056 :     =cut
1057 : parrello 1.3 #: Return Type @%;
1058 : parrello 1.1 sub FeatureAnnotations {
1059 : parrello 1.15 # Get the parameters.
1060 : parrello 1.40 my ($self, $featureID, $rawFlag) = @_;
1061 : parrello 1.15 # Create a query to get the feature's annotations and the associated users.
1062 :     my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1063 :     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
1064 :     # Create the return list.
1065 :     my @retVal = ();
1066 :     # Loop through the annotations.
1067 :     while (my $annotation = $query->Fetch) {
1068 :     # Get the fields to return.
1069 :     my ($featureID, $timeStamp, $user, $text) =
1070 :     $annotation->Values(['IsTargetOfAnnotation(from-link)',
1071 :     'Annotation(time)', 'MadeAnnotation(from-link)',
1072 :     'Annotation(annotation)']);
1073 : parrello 1.40 # Convert the time, if necessary.
1074 :     if (! $rawFlag) {
1075 :     $timeStamp = FriendlyTimestamp($timeStamp);
1076 :     }
1077 : parrello 1.15 # Assemble them into a hash.
1078 : parrello 1.3 my $annotationHash = { featureID => $featureID,
1079 : parrello 1.40 timeStamp => $timeStamp,
1080 : parrello 1.15 user => $user, text => $text };
1081 :     # Add it to the return list.
1082 :     push @retVal, $annotationHash;
1083 :     }
1084 :     # Return the result list.
1085 :     return @retVal;
1086 : parrello 1.1 }
1087 :    
1088 :     =head3 AllFunctionsOf
1089 :    
1090 :     C<< my %functions = $sprout->AllFunctionsOf($featureID); >>
1091 :    
1092 :     Return all of the functional assignments for a particular feature. The data is returned as a
1093 : parrello 1.11 hash of functional assignments to user IDs. A functional assignment is a type of annotation,
1094 : parrello 1.19 Functional assignments are described in the L</ParseAssignment> function. Its worth noting that
1095 :     we cannot filter on the content of the annotation itself because it's a text field; however,
1096 :     this is not a big problem because most features only have a small number of annotations.
1097 :     Finally, if a single user has multiple functional assignments, we will only keep the most
1098 : parrello 1.11 recent one.
1099 : parrello 1.1
1100 :     =over 4
1101 :    
1102 :     =item featureID
1103 :    
1104 :     ID of the feature whose functional assignments are desired.
1105 :    
1106 : parrello 1.3 =item RETURN
1107 :    
1108 : parrello 1.46 Returns a hash mapping the user IDs to functional assignment IDs.
1109 : parrello 1.3
1110 : parrello 1.1 =back
1111 :    
1112 :     =cut
1113 : parrello 1.3 #: Return Type %;
1114 : parrello 1.1 sub AllFunctionsOf {
1115 : parrello 1.15 # Get the parameters.
1116 :     my ($self, $featureID) = @_;
1117 :     # Get all of the feature's annotations.
1118 : parrello 1.47 my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1119 : parrello 1.15 "IsTargetOfAnnotation(from-link) = ?",
1120 : parrello 1.47 [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1121 :     'MadeAnnotation(from-link)']);
1122 : parrello 1.15 # Declare the return hash.
1123 :     my %retVal;
1124 : parrello 1.5 # Now we sort the assignments by timestamp in reverse.
1125 :     my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1126 : parrello 1.15 # Loop until we run out of annotations.
1127 : parrello 1.5 for my $annotation (@sortedQuery) {
1128 :     # Get the annotation fields.
1129 : parrello 1.47 my ($timeStamp, $text, $user) = @{$annotation};
1130 : parrello 1.15 # Check to see if this is a functional assignment.
1131 : parrello 1.48 my ($actualUser, $function) = _ParseAssignment($user, $text);
1132 :     if ($actualUser && ! exists $retVal{$actualUser}) {
1133 : parrello 1.5 # Here it is a functional assignment and there has been no
1134 :     # previous assignment for this user, so we stuff it in the
1135 :     # return hash.
1136 : parrello 1.48 $retVal{$actualUser} = $function;
1137 : parrello 1.15 }
1138 :     }
1139 :     # Return the hash of assignments found.
1140 :     return %retVal;
1141 : parrello 1.1 }
1142 :    
1143 :     =head3 FunctionOf
1144 :    
1145 :     C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>
1146 :    
1147 : parrello 1.3 Return the most recently-determined functional assignment of a particular feature.
1148 :    
1149 :     The functional assignment is handled differently depending on the type of feature. If
1150 :     the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1151 : parrello 1.11 assignment is a type of annotation. The format of an assignment is described in
1152 : parrello 1.45 L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1153 : parrello 1.19 annotation itself because it's a text field; however, this is not a big problem because
1154 : parrello 1.11 most features only have a small number of annotations.
1155 : parrello 1.1
1156 : parrello 1.3 Each user has an associated list of trusted users. The assignment returned will be the most
1157 :     recent one by at least one of the trusted users. If no trusted user list is available, then
1158 :     the specified user and FIG are considered trusted. If the user ID is omitted, only FIG
1159 :     is trusted.
1160 :    
1161 :     If the feature is B<not> identified by a FIG ID, then the functional assignment
1162 :     information is taken from the B<ExternalAliasFunc> table. If the table does
1163 :     not contain an entry for the feature, an undefined value is returned.
1164 :    
1165 : parrello 1.1 =over 4
1166 :    
1167 :     =item featureID
1168 :    
1169 :     ID of the feature whose functional assignment is desired.
1170 :    
1171 :     =item userID (optional)
1172 :    
1173 : parrello 1.3 ID of the user whose function determination is desired. If omitted, only the latest
1174 :     C<FIG> assignment will be returned.
1175 : parrello 1.1
1176 :     =item RETURN
1177 :    
1178 :     Returns the text of the assigned function.
1179 :    
1180 :     =back
1181 :    
1182 :     =cut
1183 : parrello 1.3 #: Return Type $;
1184 : parrello 1.1 sub FunctionOf {
1185 : parrello 1.15 # Get the parameters.
1186 :     my ($self, $featureID, $userID) = @_;
1187 : parrello 1.3 # Declare the return value.
1188 :     my $retVal;
1189 :     # Determine the ID type.
1190 :     if ($featureID =~ m/^fig\|/) {
1191 :     # Here we have a FIG feature ID. We must build the list of trusted
1192 :     # users.
1193 :     my %trusteeTable = ();
1194 :     # Check the user ID.
1195 :     if (!$userID) {
1196 :     # No user ID, so only FIG is trusted.
1197 :     $trusteeTable{FIG} = 1;
1198 :     } else {
1199 :     # Add this user's ID.
1200 :     $trusteeTable{$userID} = 1;
1201 :     # Look for the trusted users in the database.
1202 :     my @trustees = $self->GetFlat(['IsTrustedBy'], 'IsTrustedBy(from-link) = ?', [$userID], 'IsTrustedBy(to-link)');
1203 :     if (! @trustees) {
1204 :     # None were found, so build a default list.
1205 :     $trusteeTable{FIG} = 1;
1206 :     } else {
1207 :     # Otherwise, put all the trustees in.
1208 :     for my $trustee (@trustees) {
1209 :     $trusteeTable{$trustee} = 1;
1210 :     }
1211 :     }
1212 :     }
1213 :     # Build a query for all of the feature's annotations, sorted by date.
1214 : parrello 1.48 my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1215 : parrello 1.3 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1216 :     [$featureID]);
1217 :     my $timeSelected = 0;
1218 :     # Loop until we run out of annotations.
1219 :     while (my $annotation = $query->Fetch()) {
1220 :     # Get the annotation text.
1221 : parrello 1.48 my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1222 :     'Annotation(time)', 'MadeAnnotation(from-link)']);
1223 : parrello 1.3 # Check to see if this is a functional assignment for a trusted user.
1224 : parrello 1.48 my ($actualUser, $function) = _ParseAssignment($user, $text);
1225 : parrello 1.49 Trace("Assignment user is $actualUser, text is $function.") if T(4);
1226 : parrello 1.48 if ($actualUser) {
1227 : parrello 1.3 # Here it is a functional assignment. Check the time and the user
1228 :     # name. The time must be recent and the user must be trusted.
1229 : parrello 1.50 if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1230 : parrello 1.3 $retVal = $function;
1231 :     $timeSelected = $time;
1232 :     }
1233 :     }
1234 :     }
1235 :     } else {
1236 :     # Here we have a non-FIG feature ID. In this case the user ID does not
1237 :     # matter. We simply get the information from the External Alias Function
1238 :     # table.
1239 : parrello 1.4 ($retVal) = $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']);
1240 : parrello 1.3 }
1241 : parrello 1.15 # Return the assignment found.
1242 :     return $retVal;
1243 : parrello 1.1 }
1244 :    
1245 : parrello 1.45 =head3 FunctionsOf
1246 :    
1247 :     C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1248 :    
1249 :     Return the functional assignments of a particular feature.
1250 :    
1251 :     The functional assignment is handled differently depending on the type of feature. If
1252 :     the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1253 :     assignment is a type of annotation. The format of an assignment is described in
1254 :     L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1255 :     annotation itself because it's a text field; however, this is not a big problem because
1256 :     most features only have a small number of annotations.
1257 :    
1258 :     If the feature is B<not> identified by a FIG ID, then the functional assignment
1259 :     information is taken from the B<ExternalAliasFunc> table. If the table does
1260 :     not contain an entry for the feature, an empty list is returned.
1261 :    
1262 :     =over 4
1263 :    
1264 :     =item featureID
1265 :    
1266 :     ID of the feature whose functional assignments are desired.
1267 :    
1268 :     =item RETURN
1269 :    
1270 :     Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1271 :     that user.
1272 :    
1273 :     =back
1274 :    
1275 :     =cut
1276 :     #: Return Type @@;
1277 :     sub FunctionsOf {
1278 :     # Get the parameters.
1279 :     my ($self, $featureID) = @_;
1280 :     # Declare the return value.
1281 :     my @retVal = ();
1282 :     # Determine the ID type.
1283 :     if ($featureID =~ m/^fig\|/) {
1284 :     # Here we have a FIG feature ID. We must build the list of trusted
1285 :     # users.
1286 :     my %trusteeTable = ();
1287 :     # Build a query for all of the feature's annotations, sorted by date.
1288 : parrello 1.48 my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1289 : parrello 1.45 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1290 :     [$featureID]);
1291 :     my $timeSelected = 0;
1292 :     # Loop until we run out of annotations.
1293 :     while (my $annotation = $query->Fetch()) {
1294 :     # Get the annotation text.
1295 : parrello 1.48 my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1296 :     'Annotation(time)',
1297 :     'MadeAnnotation(user)']);
1298 : parrello 1.45 # Check to see if this is a functional assignment for a trusted user.
1299 : parrello 1.48 my ($actualUser, $function) = _ParseAssignment($user, $text);
1300 :     if ($actualUser) {
1301 : parrello 1.45 # Here it is a functional assignment.
1302 : parrello 1.48 push @retVal, [$actualUser, $function];
1303 : parrello 1.45 }
1304 :     }
1305 :     } else {
1306 :     # Here we have a non-FIG feature ID. In this case the user ID does not
1307 :     # matter. We simply get the information from the External Alias Function
1308 :     # table.
1309 : parrello 1.48 my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1310 :     ['ExternalAliasFunc(func)']);
1311 :     push @retVal, map { ['master', $_] } @assignments;
1312 : parrello 1.45 }
1313 :     # Return the assignments found.
1314 :     return @retVal;
1315 :     }
1316 :    
1317 : parrello 1.1 =head3 BBHList
1318 :    
1319 :     C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
1320 :    
1321 :     Return a hash mapping the features in a specified list to their bidirectional best hits
1322 :     on a specified target genome.
1323 :    
1324 :     =over 4
1325 :    
1326 :     =item genomeID
1327 :    
1328 :     ID of the genome from which the best hits should be taken.
1329 :    
1330 :     =item featureList
1331 :    
1332 :     List of the features whose best hits are desired.
1333 :    
1334 :     =item RETURN
1335 :    
1336 : parrello 1.15 Returns a reference to a hash that maps the IDs of the incoming features to the best hits
1337 :     on the target genome.
1338 : parrello 1.1
1339 :     =back
1340 :    
1341 :     =cut
1342 : parrello 1.3 #: Return Type %;
1343 : parrello 1.1 sub BBHList {
1344 : parrello 1.15 # Get the parameters.
1345 :     my ($self, $genomeID, $featureList) = @_;
1346 :     # Create the return structure.
1347 :     my %retVal = ();
1348 :     # Loop through the incoming features.
1349 :     for my $featureID (@{$featureList}) {
1350 :     # Create a query to get the feature's best hit.
1351 :     my $query = $self->Get(['IsBidirectionalBestHitOf'],
1352 :     "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",
1353 :     [$featureID, $genomeID]);
1354 : parrello 1.40 # Peel off the BBHs found.
1355 :     my @found = ();
1356 :     while (my $bbh = $query->Fetch) {
1357 :     push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');
1358 : parrello 1.15 }
1359 : parrello 1.40 $retVal{$featureID} = \@found;
1360 : parrello 1.15 }
1361 :     # Return the mapping.
1362 :     return \%retVal;
1363 :     }
1364 :    
1365 :     =head3 SimList
1366 :    
1367 :     C<< my %similarities = $sprout->SimList($featureID, $count); >>
1368 :    
1369 :     Return a list of the similarities to the specified feature.
1370 :    
1371 :     Sprout does not support real similarities, so this method just returns the bidirectional
1372 :     best hits.
1373 :    
1374 :     =over 4
1375 :    
1376 :     =item featureID
1377 :    
1378 :     ID of the feature whose similarities are desired.
1379 :    
1380 :     =item count
1381 :    
1382 :     Maximum number of similar features to be returned, or C<0> to return them all.
1383 :    
1384 :     =back
1385 :    
1386 :     =cut
1387 :     #: Return Type %;
1388 :     sub SimList {
1389 :     # Get the parameters.
1390 :     my ($self, $featureID, $count) = @_;
1391 :     # Ask for the best hits.
1392 :     my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],
1393 :     "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",
1394 :     [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],
1395 :     $count);
1396 :     # Create the return value.
1397 :     my %retVal = ();
1398 :     for my $tuple (@lists) {
1399 :     $retVal{$tuple->[0]} = $tuple->[1];
1400 :     }
1401 :     # Return the result.
1402 :     return %retVal;
1403 :     }
1404 :    
1405 :    
1406 :    
1407 :     =head3 IsComplete
1408 :    
1409 :     C<< my $flag = $sprout->IsComplete($genomeID); >>
1410 :    
1411 :     Return TRUE if the specified genome is complete, else FALSE.
1412 :    
1413 :     =over 4
1414 :    
1415 :     =item genomeID
1416 :    
1417 :     ID of the genome whose completeness status is desired.
1418 :    
1419 :     =item RETURN
1420 :    
1421 :     Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1422 :     not found.
1423 :    
1424 :     =back
1425 :    
1426 :     =cut
1427 :     #: Return Type $;
1428 :     sub IsComplete {
1429 :     # Get the parameters.
1430 :     my ($self, $genomeID) = @_;
1431 :     # Declare the return variable.
1432 :     my $retVal;
1433 :     # Get the genome's data.
1434 :     my $genomeData = $self->GetEntity('Genome', $genomeID);
1435 :     if ($genomeData) {
1436 :     # The genome exists, so get the completeness flag.
1437 : parrello 1.51 ($retVal) = $genomeData->Value('Genome(complete)');
1438 : parrello 1.15 }
1439 :     # Return the result.
1440 :     return $retVal;
1441 : parrello 1.1 }
1442 :    
1443 :     =head3 FeatureAliases
1444 :    
1445 :     C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
1446 :    
1447 :     Return a list of the aliases for a specified feature.
1448 :    
1449 :     =over 4
1450 :    
1451 :     =item featureID
1452 :    
1453 :     ID of the feature whose aliases are desired.
1454 :    
1455 :     =item RETURN
1456 :    
1457 :     Returns a list of the feature's aliases. If the feature is not found or has no aliases, it will
1458 :     return an empty list.
1459 :    
1460 :     =back
1461 :    
1462 :     =cut
1463 : parrello 1.3 #: Return Type @;
1464 : parrello 1.1 sub FeatureAliases {
1465 : parrello 1.15 # Get the parameters.
1466 :     my ($self, $featureID) = @_;
1467 :     # Get the desired feature's aliases
1468 :     my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);
1469 :     # Return the result.
1470 :     return @retVal;
1471 : parrello 1.1 }
1472 :    
1473 :     =head3 GenomeOf
1474 :    
1475 :     C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1476 :    
1477 : parrello 1.56 Return the genome that contains a specified feature or contig.
1478 : parrello 1.1
1479 :     =over 4
1480 :    
1481 :     =item featureID
1482 :    
1483 : parrello 1.56 ID of the feature or contig whose genome is desired.
1484 : parrello 1.1
1485 :     =item RETURN
1486 :    
1487 : parrello 1.56 Returns the ID of the genome for the specified feature or contig. If the feature or contig is not
1488 :     found, returns an undefined value.
1489 : parrello 1.1
1490 :     =back
1491 :    
1492 :     =cut
1493 : parrello 1.3 #: Return Type $;
1494 : parrello 1.1 sub GenomeOf {
1495 : parrello 1.15 # Get the parameters.
1496 :     my ($self, $featureID) = @_;
1497 : parrello 1.56 # Create a query to find the genome associated with the incoming ID.
1498 :     my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1499 :     [$featureID, $featureID]);
1500 : parrello 1.15 # Declare the return value.
1501 :     my $retVal;
1502 :     # Get the genome ID.
1503 :     if (my $relationship = $query->Fetch()) {
1504 :     ($retVal) = $relationship->Value('HasContig(from-link)');
1505 :     }
1506 :     # Return the value found.
1507 :     return $retVal;
1508 : parrello 1.1 }
1509 :    
1510 :     =head3 CoupledFeatures
1511 :    
1512 :     C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >>
1513 :    
1514 :     Return the features functionally coupled with a specified feature. Features are considered
1515 :     functionally coupled if they tend to be clustered on the same chromosome.
1516 :    
1517 :     =over 4
1518 :    
1519 :     =item featureID
1520 :    
1521 :     ID of the feature whose functionally-coupled brethren are desired.
1522 :    
1523 :     =item RETURN
1524 :    
1525 :     A hash mapping the functionally-coupled feature IDs to the coupling score.
1526 :    
1527 :     =back
1528 :    
1529 :     =cut
1530 : parrello 1.3 #: Return Type %;
1531 : parrello 1.1 sub CoupledFeatures {
1532 : parrello 1.15 # Get the parameters.
1533 :     my ($self, $featureID) = @_;
1534 :     # Create a query to retrieve the functionally-coupled features.
1535 :     my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1536 :     "ParticipatesInCoupling(from-link) = ?", [$featureID]);
1537 :     # This value will be set to TRUE if we find at least one coupled feature.
1538 :     my $found = 0;
1539 :     # Create the return hash.
1540 :     my %retVal = ();
1541 :     # Retrieve the relationship records and store them in the hash.
1542 :     while (my $clustering = $query->Fetch()) {
1543 :     # Get the ID and score of the coupling.
1544 :     my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1545 :     'Coupling(score)']);
1546 :     # The coupling ID contains the two feature IDs separated by a space. We use
1547 :     # this information to find the ID of the other feature.
1548 :     my ($fid1, $fid2) = split / /, $couplingID;
1549 :     my $otherFeatureID = ($featureID eq $fid1 ? $fid2 : $fid1);
1550 :     # Attach the other feature's score to its ID.
1551 :     $retVal{$otherFeatureID} = $score;
1552 :     $found = 1;
1553 :     }
1554 :     # Functional coupling is reflexive. If we found at least one coupled feature, we must add
1555 :     # the incoming feature as well.
1556 :     if ($found) {
1557 :     $retVal{$featureID} = 9999;
1558 :     }
1559 :     # Return the hash.
1560 :     return %retVal;
1561 :     }
1562 :    
1563 :     =head3 CouplingEvidence
1564 :    
1565 :     C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1566 :    
1567 :     Return the evidence for a functional coupling.
1568 :    
1569 :     A pair of features is considered evidence of a coupling between two other
1570 :     features if they occur close together on a contig and both are similar to
1571 :     the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1572 :     B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1573 :     B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1574 :     similar to B<A2>.
1575 :    
1576 :     The score of a coupling is determined by the number of pieces of evidence
1577 :     that are considered I<representative>. If several evidence items belong to
1578 :     a group of genomes that are close to each other, only one of those items
1579 :     is considered representative. The other evidence items are presumed to be
1580 :     there because of the relationship between the genomes rather than because
1581 :     the two proteins generated by the features have a related functionality.
1582 :    
1583 :     Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1584 :     I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1585 :     is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1586 :     and FALSE otherwise.
1587 :    
1588 :     =over 4
1589 :    
1590 :     =item peg1
1591 :    
1592 :     ID of the feature of interest.
1593 :    
1594 :     =item peg2
1595 :    
1596 :     ID of a feature functionally coupled to the feature of interest.
1597 :    
1598 :     =item RETURN
1599 :    
1600 :     Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1601 :     of interest, a feature similar to the functionally coupled feature, and a flag
1602 :     that is TRUE for a representative piece of evidence and FALSE otherwise.
1603 :    
1604 :     =back
1605 :    
1606 :     =cut
1607 :     #: Return Type @@;
1608 :     sub CouplingEvidence {
1609 :     # Get the parameters.
1610 :     my ($self, $peg1, $peg2) = @_;
1611 :     # Declare the return variable.
1612 :     my @retVal = ();
1613 : parrello 1.18 # Our first task is to find out the nature of the coupling: whether or not
1614 :     # it exists, its score, and whether the features are stored in the same
1615 :     # order as the ones coming in.
1616 : parrello 1.15 my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1617 :     # Only proceed if a coupling exists.
1618 :     if ($couplingID) {
1619 :     # Determine the ordering to place on the evidence items. If we're
1620 : parrello 1.18 # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1621 :     # we want feature 1 before feature 2 (normal).
1622 : parrello 1.21 Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);
1623 : parrello 1.15 my $ordering = ($inverted ? "DESC" : "");
1624 :     # Get the coupling evidence.
1625 :     my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
1626 :     "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",
1627 :     [$couplingID],
1628 : overbeek 1.17 ['PCH(used)', 'UsesAsEvidence(to-link)']);
1629 : parrello 1.15 # Loop through the evidence items. Each piece of evidence is represented by two
1630 :     # positions in the evidence list, one for each feature on the other side of the
1631 :     # evidence link. If at some point we want to generalize to couplings with
1632 :     # more than two positions, this section of code will need to be re-done.
1633 :     while (@evidenceList > 0) {
1634 :     my $peg1Data = shift @evidenceList;
1635 :     my $peg2Data = shift @evidenceList;
1636 : parrello 1.21 Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1637 : parrello 1.15 push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1638 :     }
1639 : parrello 1.22 Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1640 : parrello 1.1 }
1641 : parrello 1.15 # Return the result.
1642 :     return @retVal;
1643 :     }
1644 :    
1645 :     =head3 GetCoupling
1646 :    
1647 :     C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>
1648 :    
1649 :     Return the coupling (if any) for the specified pair of PEGs. If a coupling
1650 :     exists, we return the coupling ID along with an indicator of whether the
1651 :     coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.
1652 :     In the second case, we say the coupling is I<inverted>. The importance of an
1653 :     inverted coupling is that the PEGs in the evidence will appear in reverse order.
1654 :    
1655 :     =over 4
1656 :    
1657 :     =item peg1
1658 :    
1659 :     ID of the feature of interest.
1660 :    
1661 :     =item peg2
1662 :    
1663 :     ID of the potentially coupled feature.
1664 :    
1665 :     =item RETURN
1666 :    
1667 :     Returns a three-element list. The first element contains the database ID of
1668 :     the coupling. The second element is FALSE if the coupling is stored in the
1669 :     database in the caller specified order and TRUE if it is stored in the
1670 :     inverted order. The third element is the coupling's score. If the coupling
1671 :     does not exist, all three list elements will be C<undef>.
1672 :    
1673 :     =back
1674 :    
1675 :     =cut
1676 :     #: Return Type $%@;
1677 :     sub GetCoupling {
1678 :     # Get the parameters.
1679 :     my ($self, $peg1, $peg2) = @_;
1680 :     # Declare the return values. We'll start with the coupling ID and undefine the
1681 :     # flag and score until we have more information.
1682 :     my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);
1683 :     # Find the coupling data.
1684 :     my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1685 :     "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1686 : overbeek 1.17 [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1687 : parrello 1.15 # Check to see if we found anything.
1688 :     if (!@pegs) {
1689 : parrello 1.23 Trace("No coupling found.") if T(Coupling => 4);
1690 : parrello 1.15 # No coupling, so undefine the return value.
1691 :     $retVal = undef;
1692 :     } else {
1693 :     # We have a coupling! Get the score and check for inversion.
1694 :     $score = $pegs[0]->[1];
1695 : parrello 1.23 my $firstFound = $pegs[0]->[0];
1696 :     $inverted = ($firstFound ne $peg1);
1697 :     Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1698 : parrello 1.15 }
1699 :     # Return the result.
1700 :     return ($retVal, $inverted, $score);
1701 :     }
1702 :    
1703 :     =head3 CouplingID
1704 :    
1705 :     C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>
1706 :    
1707 :     Return the coupling ID for a pair of feature IDs.
1708 :    
1709 :     The coupling ID is currently computed by joining the feature IDs in
1710 :     sorted order with a space. Client modules (that is, modules which
1711 :     use Sprout) should not, however, count on this always being the
1712 :     case. This method provides a way for abstracting the concept of a
1713 :     coupling ID. All that we know for sure about it is that it can be
1714 :     generated easily from the feature IDs and the order of the IDs
1715 :     in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>
1716 :     will have the same value as C<CouplingID("b1", "a1")>.
1717 :    
1718 :     =over 4
1719 :    
1720 :     =item peg1
1721 :    
1722 :     First feature of interest.
1723 :    
1724 :     =item peg2
1725 :    
1726 :     Second feature of interest.
1727 :    
1728 :     =item RETURN
1729 :    
1730 :     Returns the ID that would be used to represent a functional coupling of
1731 :     the two specified PEGs.
1732 :    
1733 :     =back
1734 :    
1735 :     =cut
1736 :     #: Return Type $;
1737 :     sub CouplingID {
1738 :     return join " ", sort @_;
1739 : parrello 1.1 }
1740 :    
1741 :     =head3 ReadFasta
1742 :    
1743 :     C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>
1744 :    
1745 :     Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by
1746 :     one or more lines of data. The first line begins with a > character and contains an ID.
1747 :     The remaining lines contain the sequence data in order.
1748 :    
1749 :     =over 4
1750 :    
1751 :     =item fileName
1752 :    
1753 :     Name of the FASTA file.
1754 :    
1755 :     =item prefix (optional)
1756 :    
1757 :     Prefix to be put in front of each ID found.
1758 :    
1759 :     =item RETURN
1760 :    
1761 :     Returns a hash that maps each ID to its sequence.
1762 :    
1763 :     =back
1764 :    
1765 :     =cut
1766 : parrello 1.3 #: Return Type %;
1767 : parrello 1.1 sub ReadFasta {
1768 : parrello 1.15 # Get the parameters.
1769 :     my ($fileName, $prefix) = @_;
1770 :     # Create the return hash.
1771 :     my %retVal = ();
1772 :     # Open the file for input.
1773 :     open FASTAFILE, '<', $fileName;
1774 :     # Declare the ID variable and clear the sequence accumulator.
1775 :     my $sequence = "";
1776 :     my $id = "";
1777 :     # Loop through the file.
1778 :     while (<FASTAFILE>) {
1779 :     # Get the current line.
1780 :     my $line = $_;
1781 :     # Check for a header line.
1782 :     if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1783 :     # Here we have a new header. Store the current sequence if we have one.
1784 :     if ($id) {
1785 : parrello 1.24 $retVal{$id} = lc $sequence;
1786 : parrello 1.15 }
1787 :     # Clear the sequence accumulator and save the new ID.
1788 :     ($id, $sequence) = ("$prefix$1", "");
1789 :     } else {
1790 :     # Here we have a data line, so we add it to the sequence accumulator.
1791 : parrello 1.24 # First, we get the actual data out. Note that we normalize to lower
1792 : parrello 1.15 # case.
1793 :     $line =~ /^\s*(.*?)(\s|\n)/;
1794 :     $sequence .= $1;
1795 :     }
1796 :     }
1797 :     # Flush out the last sequence (if any).
1798 :     if ($sequence) {
1799 : parrello 1.24 $retVal{$id} = lc $sequence;
1800 : parrello 1.15 }
1801 :     # Close the file.
1802 :     close FASTAFILE;
1803 :     # Return the hash constructed from the file.
1804 :     return %retVal;
1805 : parrello 1.1 }
1806 :    
1807 :     =head3 FormatLocations
1808 :    
1809 :     C<< my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat); >>
1810 :    
1811 :     Insure that a list of feature locations is in the Sprout format. The Sprout feature location
1812 :     format is I<contig>_I<beg*len> where I<*> is C<+> for a forward gene and C<-> for a backward
1813 : parrello 1.10 gene. The old format is I<contig>_I<beg>_I<end>. If a feature is in the new format already,
1814 : parrello 1.19 it will not be changed; otherwise, it will be converted. This method can also be used to
1815 : parrello 1.10 perform the reverse task-- insuring that all the locations are in the old format.
1816 : parrello 1.1
1817 :     =over 4
1818 :    
1819 :     =item prefix
1820 :    
1821 :     Prefix to be put in front of each contig ID (or an empty string if the contig ID should not
1822 :     be changed.
1823 :    
1824 :     =item locations
1825 :    
1826 :     List of locations to be normalized.
1827 :    
1828 :     =item oldFormat
1829 :    
1830 :     TRUE to convert the locations to the old format, else FALSE
1831 :    
1832 :     =item RETURN
1833 :    
1834 :     Returns a list of updated location descriptors.
1835 :    
1836 :     =back
1837 :    
1838 :     =cut
1839 : parrello 1.3 #: Return Type @;
1840 : parrello 1.1 sub FormatLocations {
1841 : parrello 1.15 # Get the parameters.
1842 :     my ($self, $prefix, $locations, $oldFormat) = @_;
1843 :     # Create the return list.
1844 :     my @retVal = ();
1845 :     # Check to see if any locations were passed in.
1846 :     if ($locations eq '') {
1847 :     Confess("No locations specified.");
1848 :     } else {
1849 :     # Loop through the locations, converting them to the new format.
1850 :     for my $location (@{$locations}) {
1851 :     # Parse the location elements.
1852 :     my ($contig, $beg, $dir, $len) = ParseLocation($location);
1853 :     # Process according to the desired output format.
1854 :     if (!$oldFormat) {
1855 :     # Here we're producing the new format. Add the location to the return list.
1856 :     push @retVal, "$prefix${contig}_$beg$dir$len";
1857 :     } elsif ($dir eq '+') {
1858 :     # Here we're producing the old format and it's a forward gene.
1859 :     my $end = $beg + $len - 1;
1860 :     push @retVal, "$prefix${contig}_${beg}_$end";
1861 :     } else {
1862 :     # Here we're producting the old format and it's a backward gene.
1863 :     my $end = $beg - $len + 1;
1864 :     push @retVal, "$prefix${contig}_${beg}_$end";
1865 :     }
1866 :     }
1867 :     }
1868 :     # Return the normalized list.
1869 :     return @retVal;
1870 : parrello 1.1 }
1871 :    
1872 :     =head3 DumpData
1873 :    
1874 :     C<< $sprout->DumpData(); >>
1875 :    
1876 :     Dump all the tables to tab-delimited DTX files. The files will be stored in the data directory.
1877 :    
1878 :     =cut
1879 :    
1880 :     sub DumpData {
1881 : parrello 1.15 # Get the parameters.
1882 :     my ($self) = @_;
1883 :     # Get the data directory name.
1884 :     my $outputDirectory = $self->{_options}->{dataDir};
1885 :     # Dump the relations.
1886 : parrello 1.58 $self->DumpRelations($outputDirectory);
1887 : parrello 1.1 }
1888 :    
1889 :     =head3 XMLFileName
1890 :    
1891 :     C<< my $fileName = $sprout->XMLFileName(); >>
1892 :    
1893 :     Return the name of this database's XML definition file.
1894 :    
1895 :     =cut
1896 : parrello 1.3 #: Return Type $;
1897 : parrello 1.1 sub XMLFileName {
1898 : parrello 1.15 my ($self) = @_;
1899 :     return $self->{_xmlName};
1900 : parrello 1.1 }
1901 :    
1902 :     =head3 Insert
1903 :    
1904 :     C<< $sprout->Insert($objectType, \%fieldHash); >>
1905 :    
1906 :     Insert an entity or relationship instance into the database. The entity or relationship of interest
1907 :     is defined by a type name and then a hash of field names to values. Field values in the primary
1908 :     relation are represented by scalars. (Note that for relationships, the primary relation is
1909 :     the B<only> relation.) Field values for the other relations comprising the entity are always
1910 :     list references. For example, the following line inserts an inactive PEG feature named
1911 :     C<fig|188.1.peg.1> with aliases C<ZP_00210270.1> and C<gi|46206278>.
1912 :    
1913 :     C<< $sprout->Insert('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >>
1914 :    
1915 :     The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
1916 :     property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
1917 :    
1918 : 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'}); >>
1919 : parrello 1.1
1920 :     =over 4
1921 :    
1922 :     =item newObjectType
1923 :    
1924 :     Type name of the entity or relationship to insert.
1925 :    
1926 :     =item fieldHash
1927 :    
1928 :     Hash of field names to values.
1929 :    
1930 :     =back
1931 :    
1932 :     =cut
1933 : parrello 1.3 #: Return Type ;
1934 : parrello 1.1 sub Insert {
1935 : parrello 1.15 # Get the parameters.
1936 :     my ($self, $objectType, $fieldHash) = @_;
1937 :     # Call the underlying method.
1938 : parrello 1.58 $self->InsertObject($objectType, $fieldHash);
1939 : parrello 1.1 }
1940 :    
1941 :     =head3 Annotate
1942 :    
1943 :     C<< my $ok = $sprout->Annotate($fid, $timestamp, $user, $text); >>
1944 :    
1945 :     Annotate a feature. This inserts an Annotation record into the database and links it to the
1946 :     specified feature and user.
1947 :    
1948 :     =over 4
1949 :    
1950 :     =item fid
1951 :    
1952 :     ID of the feature to be annotated.
1953 :    
1954 :     =item timestamp
1955 :    
1956 :     Numeric timestamp to apply to the annotation. This is concatenated to the feature ID to create the
1957 :     key.
1958 :    
1959 :     =item user
1960 :    
1961 :     ID of the user who is making the annotation.
1962 :    
1963 :     =item text
1964 :    
1965 :     Text of the annotation.
1966 :    
1967 :     =item RETURN
1968 :    
1969 :     Returns 1 if successful, 2 if an error occurred.
1970 :    
1971 :     =back
1972 :    
1973 :     =cut
1974 : parrello 1.3 #: Return Type $;
1975 : parrello 1.1 sub Annotate {
1976 : parrello 1.15 # Get the parameters.
1977 :     my ($self, $fid, $timestamp, $user, $text) = @_;
1978 :     # Create the annotation ID.
1979 :     my $aid = "$fid:$timestamp";
1980 :     # Insert the Annotation object.
1981 :     my $retVal = $self->Insert('Annotation', { id => $aid, time => $timestamp, annotation => $text });
1982 :     if ($retVal) {
1983 :     # Connect it to the user.
1984 :     $retVal = $self->Insert('MadeAnnotation', { 'from-link' => $user, 'to-link' => $aid });
1985 :     if ($retVal) {
1986 :     # Connect it to the feature.
1987 :     $retVal = $self->Insert('IsTargetOfAnnotation', { 'from-link' => $fid,
1988 :     'to-link' => $aid });
1989 :     }
1990 :     }
1991 :     # Return the success indicator.
1992 :     return $retVal;
1993 : parrello 1.1 }
1994 :    
1995 :     =head3 AssignFunction
1996 :    
1997 : parrello 1.11 C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>
1998 : parrello 1.1
1999 :     This method assigns a function to a feature. Functions are a special type of annotation. The general
2000 : parrello 1.11 format is described in L</ParseAssignment>.
2001 : parrello 1.1
2002 :     =over 4
2003 :    
2004 :     =item featureID
2005 :    
2006 :     ID of the feature to which the assignment is being made.
2007 :    
2008 :     =item user
2009 :    
2010 : parrello 1.11 Name of the user group making the assignment, such as C<kegg> or C<fig>.
2011 : parrello 1.1
2012 :     =item function
2013 :    
2014 :     Text of the function being assigned.
2015 :    
2016 : parrello 1.11 =item assigningUser (optional)
2017 :    
2018 :     Name of the individual user making the assignment. If omitted, defaults to the user group.
2019 :    
2020 : parrello 1.1 =item RETURN
2021 :    
2022 :     Returns 1 if successful, 0 if an error occurred.
2023 :    
2024 :     =back
2025 :    
2026 :     =cut
2027 : parrello 1.3 #: Return Type $;
2028 : parrello 1.1 sub AssignFunction {
2029 : parrello 1.15 # Get the parameters.
2030 :     my ($self, $featureID, $user, $function, $assigningUser) = @_;
2031 : parrello 1.11 # Default the assigning user.
2032 :     if (! $assigningUser) {
2033 :     $assigningUser = $user;
2034 :     }
2035 : parrello 1.15 # Create an annotation string from the parameters.
2036 :     my $annotationText = "$assigningUser\nset $user function to\n$function";
2037 :     # Get the current time.
2038 :     my $now = time;
2039 :     # Declare the return variable.
2040 :     my $retVal = 1;
2041 :     # Locate the genome containing the feature.
2042 :     my $genome = $self->GenomeOf($featureID);
2043 :     if (!$genome) {
2044 :     # Here the genome was not found. This probably means the feature ID is invalid.
2045 :     Trace("No genome found for feature $featureID.") if T(0);
2046 :     $retVal = 0;
2047 :     } else {
2048 :     # Here we know we have a feature with a genome. Store the annotation.
2049 : parrello 1.5 $retVal = $self->Annotate($featureID, $now, $user, $annotationText);
2050 : parrello 1.15 }
2051 :     # Return the success indicator.
2052 :     return $retVal;
2053 : parrello 1.1 }
2054 :    
2055 :     =head3 FeaturesByAlias
2056 :    
2057 :     C<< my @features = $sprout->FeaturesByAlias($alias); >>
2058 :    
2059 :     Returns a list of features with the specified alias. The alias is parsed to determine
2060 :     the type of the alias. A string of digits is a GenBack ID and a string of exactly 6
2061 :     alphanumerics is a UniProt ID. A built-in FIG.pm method is used to analyze the alias
2062 :     string and attach the necessary prefix. If the result is a FIG ID then it is returned
2063 :     unmodified; otherwise, we look for an alias.
2064 :    
2065 :     =over 4
2066 :    
2067 :     =item alias
2068 :    
2069 :     Alias whose features are desired.
2070 :    
2071 :     =item RETURN
2072 :    
2073 :     Returns a list of the features with the given alias.
2074 :    
2075 :     =back
2076 :    
2077 :     =cut
2078 : parrello 1.3 #: Return Type @;
2079 : parrello 1.1 sub FeaturesByAlias {
2080 : parrello 1.15 # Get the parameters.
2081 :     my ($self, $alias) = @_;
2082 :     # Declare the return variable.
2083 :     my @retVal = ();
2084 :     # Parse the alias.
2085 :     my ($mappedAlias, $flag) = FIGRules::NormalizeAlias($alias);
2086 :     # If it's a FIG alias, we're done.
2087 :     if ($flag) {
2088 :     push @retVal, $mappedAlias;
2089 :     } else {
2090 :     # Here we have a non-FIG alias. Get the features with the normalized alias.
2091 :     @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');
2092 :     }
2093 :     # Return the result.
2094 :     return @retVal;
2095 : parrello 1.1 }
2096 :    
2097 :     =head3 Exists
2098 :    
2099 :     C<< my $found = $sprout->Exists($entityName, $entityID); >>
2100 :    
2101 :     Return TRUE if an entity exists, else FALSE.
2102 :    
2103 :     =over 4
2104 :    
2105 :     =item entityName
2106 :    
2107 :     Name of the entity type (e.g. C<Feature>) relevant to the existence check.
2108 :    
2109 :     =item entityID
2110 :    
2111 :     ID of the entity instance whose existence is to be checked.
2112 :    
2113 :     =item RETURN
2114 :    
2115 :     Returns TRUE if the entity instance exists, else FALSE.
2116 :    
2117 :     =back
2118 :    
2119 :     =cut
2120 : parrello 1.3 #: Return Type $;
2121 : parrello 1.1 sub Exists {
2122 : parrello 1.15 # Get the parameters.
2123 :     my ($self, $entityName, $entityID) = @_;
2124 :     # Check for the entity instance.
2125 : parrello 1.26 Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
2126 : parrello 1.15 my $testInstance = $self->GetEntity($entityName, $entityID);
2127 :     # Return an existence indicator.
2128 :     my $retVal = ($testInstance ? 1 : 0);
2129 :     return $retVal;
2130 : parrello 1.1 }
2131 :    
2132 :     =head3 FeatureTranslation
2133 :    
2134 :     C<< my $translation = $sprout->FeatureTranslation($featureID); >>
2135 :    
2136 :     Return the translation of a feature.
2137 :    
2138 :     =over 4
2139 :    
2140 :     =item featureID
2141 :    
2142 :     ID of the feature whose translation is desired
2143 :    
2144 :     =item RETURN
2145 :    
2146 :     Returns the translation of the specified feature.
2147 :    
2148 :     =back
2149 :    
2150 :     =cut
2151 : parrello 1.3 #: Return Type $;
2152 : parrello 1.1 sub FeatureTranslation {
2153 : parrello 1.15 # Get the parameters.
2154 :     my ($self, $featureID) = @_;
2155 :     # Get the specified feature's translation.
2156 :     my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
2157 :     return $retVal;
2158 : parrello 1.1 }
2159 :    
2160 :     =head3 Taxonomy
2161 :    
2162 :     C<< my @taxonomyList = $sprout->Taxonomy($genome); >>
2163 :    
2164 :     Return the taxonomy of the specified genome. This will be in the form of a list
2165 :     containing the various classifications in order from domain (eg. C<Bacteria>, C<Archaea>,
2166 :     or C<Eukaryote>) to sub-species. For example,
2167 :    
2168 :     C<< (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12) >>
2169 :    
2170 :     =over 4
2171 :    
2172 :     =item genome
2173 :    
2174 :     ID of the genome whose taxonomy is desired.
2175 :    
2176 :     =item RETURN
2177 :    
2178 :     Returns a list containing all the taxonomy classifications for the specified genome's organism.
2179 :    
2180 :     =back
2181 :    
2182 :     =cut
2183 : parrello 1.3 #: Return Type @;
2184 : parrello 1.1 sub Taxonomy {
2185 : parrello 1.15 # Get the parameters.
2186 :     my ($self, $genome) = @_;
2187 :     # Find the specified genome's taxonomy string.
2188 :     my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);
2189 :     # Declare the return variable.
2190 :     my @retVal = ();
2191 :     # If we found the genome, return its taxonomy string.
2192 :     if ($list) {
2193 :     @retVal = split /\s*;\s*/, $list;
2194 :     } else {
2195 :     Trace("Genome \"$genome\" does not have a taxonomy in the database.\n") if T(0);
2196 :     }
2197 :     # Return the value found.
2198 :     return @retVal;
2199 : parrello 1.1 }
2200 :    
2201 :     =head3 CrudeDistance
2202 :    
2203 :     C<< my $distance = $sprout->CrudeDistance($genome1, $genome2); >>
2204 :    
2205 :     Returns a crude estimate of the distance between two genomes. The distance is construed so
2206 :     that it will be 0 for genomes with identical taxonomies and 1 for genomes from different domains.
2207 :    
2208 :     =over 4
2209 :    
2210 :     =item genome1
2211 :    
2212 :     ID of the first genome to compare.
2213 :    
2214 :     =item genome2
2215 :    
2216 :     ID of the second genome to compare.
2217 :    
2218 :     =item RETURN
2219 :    
2220 :     Returns a value from 0 to 1, with 0 meaning identical organisms, and 1 meaning organisms from
2221 :     different domains.
2222 :    
2223 :     =back
2224 :    
2225 :     =cut
2226 : parrello 1.3 #: Return Type $;
2227 : parrello 1.1 sub CrudeDistance {
2228 : parrello 1.15 # Get the parameters.
2229 :     my ($self, $genome1, $genome2) = @_;
2230 :     # Insure that the distance is commutative by sorting the genome IDs.
2231 :     my ($genomeA, $genomeB);
2232 :     if ($genome2 < $genome2) {
2233 :     ($genomeA, $genomeB) = ($genome1, $genome2);
2234 :     } else {
2235 :     ($genomeA, $genomeB) = ($genome2, $genome1);
2236 :     }
2237 :     my @taxA = $self->Taxonomy($genomeA);
2238 :     my @taxB = $self->Taxonomy($genomeB);
2239 :     # Initialize the distance to 1. We'll reduce it each time we find a match between the
2240 :     # taxonomies.
2241 :     my $retVal = 1.0;
2242 :     # Initialize the subtraction amount. This amount determines the distance reduction caused
2243 :     # by a mismatch at the current level.
2244 :     my $v = 0.5;
2245 :     # Loop through the taxonomies.
2246 :     for (my $i = 0; ($i < @taxA) && ($i < @taxB) && ($taxA[$i] eq $taxB[$i]); $i++) {
2247 :     $retVal -= $v;
2248 :     $v /= 2;
2249 :     }
2250 : parrello 1.1 return $retVal;
2251 :     }
2252 :    
2253 :     =head3 RoleName
2254 :    
2255 :     C<< my $roleName = $sprout->RoleName($roleID); >>
2256 :    
2257 :     Return the descriptive name of the role with the specified ID. In general, a role
2258 :     will only have a descriptive name if it is coded as an EC number.
2259 :    
2260 :     =over 4
2261 :    
2262 :     =item roleID
2263 :    
2264 :     ID of the role whose description is desired.
2265 :    
2266 :     =item RETURN
2267 :    
2268 :     Returns the descriptive name of the desired role.
2269 :    
2270 :     =back
2271 :    
2272 :     =cut
2273 : parrello 1.3 #: Return Type $;
2274 : parrello 1.1 sub RoleName {
2275 : parrello 1.15 # Get the parameters.
2276 :     my ($self, $roleID) = @_;
2277 :     # Get the specified role's name.
2278 :     my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);
2279 :     # Use the ID if the role has no name.
2280 :     if (!$retVal) {
2281 :     $retVal = $roleID;
2282 :     }
2283 :     # Return the name.
2284 :     return $retVal;
2285 : parrello 1.1 }
2286 :    
2287 :     =head3 RoleDiagrams
2288 :    
2289 :     C<< my @diagrams = $sprout->RoleDiagrams($roleID); >>
2290 :    
2291 :     Return a list of the diagrams containing a specified functional role.
2292 :    
2293 :     =over 4
2294 :    
2295 :     =item roleID
2296 :    
2297 :     ID of the role whose diagrams are desired.
2298 :    
2299 :     =item RETURN
2300 :    
2301 :     Returns a list of the IDs for the diagrams that contain the specified functional role.
2302 :    
2303 :     =back
2304 :    
2305 :     =cut
2306 : parrello 1.3 #: Return Type @;
2307 : parrello 1.1 sub RoleDiagrams {
2308 : parrello 1.15 # Get the parameters.
2309 :     my ($self, $roleID) = @_;
2310 :     # Query for the diagrams.
2311 :     my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2312 :     'RoleOccursIn(to-link)');
2313 :     # Return the result.
2314 :     return @retVal;
2315 : parrello 1.1 }
2316 :    
2317 : parrello 1.19 =head3 GetProperties
2318 :    
2319 :     C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2320 :    
2321 :     Return a list of the properties with the specified characteristics.
2322 :    
2323 :     Properties are arbitrary key-value pairs associated with a feature. (At some point they
2324 :     will also be associated with genomes.) A property value is represented by a 4-tuple of
2325 :     the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2326 :    
2327 :     =over 4
2328 :    
2329 :     =item fid
2330 :    
2331 :     ID of the feature possessing the property.
2332 :    
2333 :     =item key
2334 :    
2335 :     Name or key of the property.
2336 :    
2337 :     =item value
2338 :    
2339 :     Value of the property.
2340 :    
2341 :     =item url
2342 :    
2343 :     URL of the document that indicated the property should have this particular value, or an
2344 :     empty string if no such document exists.
2345 :    
2346 :     =back
2347 :    
2348 :     The parameters act as a filter for the desired data. Any non-null parameter will
2349 :     automatically match all the tuples returned. So, specifying just the I<$fid> will
2350 :     return all the properties of the specified feature; similarly, specifying the I<$key>
2351 :     and I<$value> parameters will return all the features having the specified property
2352 :     value.
2353 :    
2354 :     A single property key can have many values, representing different ideas about the
2355 :     feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2356 :     virulent, and another may declare that it is not virulent. A query about the virulence of
2357 :     C<fig|83333.1.peg.10> would be coded as
2358 :    
2359 :     my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2360 :    
2361 :     Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2362 :     not to be filtered. The tuples returned would be
2363 :    
2364 :     ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2365 :     ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2366 :    
2367 :     =cut
2368 :     #: Return Type @@;
2369 :     sub GetProperties {
2370 :     # Get the parameters.
2371 :     my ($self, @parms) = @_;
2372 :     # Declare the return variable.
2373 :     my @retVal = ();
2374 :     # Now we need to create a WHERE clause that will get us the data we want. First,
2375 :     # we create a list of the columns containing the data for each parameter.
2376 :     my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2377 :     'Property(property-value)', 'HasProperty(evidence)');
2378 :     # Now we build the WHERE clause and the list of parameter values.
2379 :     my @where = ();
2380 :     my @values = ();
2381 :     for (my $i = 0; $i <= $#colNames; $i++) {
2382 :     my $parm = $parms[$i];
2383 :     if (defined $parm && ($parm ne '')) {
2384 :     push @where, "$colNames[$i] = ?";
2385 :     push @values, $parm;
2386 :     }
2387 :     }
2388 :     # Format the WHERE clause.
2389 :     my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2390 :     # Ask for all the propertie values with the desired characteristics.
2391 :     my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2392 :     while (my $valueObject = $query->Fetch()) {
2393 :     my @tuple = $valueObject->Values(\@colNames);
2394 :     push @retVal, \@tuple;
2395 :     }
2396 :     # Return the result.
2397 :     return @retVal;
2398 :     }
2399 :    
2400 : parrello 1.1 =head3 FeatureProperties
2401 :    
2402 :     C<< my @properties = $sprout->FeatureProperties($featureID); >>
2403 :    
2404 :     Return a list of the properties for the specified feature. Properties are key-value pairs
2405 :     that specify special characteristics of the feature. For example, a property could indicate
2406 :     that a feature is essential to the survival of the organism or that it has benign influence
2407 :     on the activities of a pathogen. Each property is returned as a triple of the form
2408 :     C<($key,$value,$url)>, where C<$key> is the property name, C<$value> is its value (commonly
2409 :     a 1 or a 0, but possibly a string or a floating-point value), and C<$url> is a string describing
2410 :     the web address or citation in which the property's value for the feature was identified.
2411 :    
2412 :     =over 4
2413 :    
2414 :     =item featureID
2415 :    
2416 :     ID of the feature whose properties are desired.
2417 :    
2418 :     =item RETURN
2419 :    
2420 :     Returns a list of triples, each triple containing the property name, its value, and a URL or
2421 :     citation.
2422 :    
2423 :     =back
2424 :    
2425 :     =cut
2426 : parrello 1.3 #: Return Type @@;
2427 : parrello 1.1 sub FeatureProperties {
2428 : parrello 1.15 # Get the parameters.
2429 :     my ($self, $featureID) = @_;
2430 :     # Get the properties.
2431 :     my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],
2432 :     ['Property(property-name)', 'Property(property-value)',
2433 :     'HasProperty(evidence)']);
2434 :     # Return the resulting list.
2435 :     return @retVal;
2436 : parrello 1.1 }
2437 :    
2438 :     =head3 DiagramName
2439 :    
2440 :     C<< my $diagramName = $sprout->DiagramName($diagramID); >>
2441 :    
2442 :     Return the descriptive name of a diagram.
2443 :    
2444 :     =over 4
2445 :    
2446 :     =item diagramID
2447 :    
2448 :     ID of the diagram whose description is desired.
2449 :    
2450 :     =item RETURN
2451 :    
2452 :     Returns the descripive name of the specified diagram.
2453 :    
2454 :     =back
2455 :    
2456 :     =cut
2457 : parrello 1.3 #: Return Type $;
2458 : parrello 1.1 sub DiagramName {
2459 : parrello 1.15 # Get the parameters.
2460 :     my ($self, $diagramID) = @_;
2461 :     # Get the specified diagram's name and return it.
2462 :     my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);
2463 :     return $retVal;
2464 : parrello 1.1 }
2465 :    
2466 :     =head3 MergedAnnotations
2467 :    
2468 :     C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>
2469 :    
2470 :     Returns a merged list of the annotations for the features in a list. Each annotation is
2471 :     represented by a 4-tuple of the form C<($fid, $timestamp, $userID, $annotation)>, where
2472 :     C<$fid> is the ID of a feature, C<$timestamp> is the time at which the annotation was made,
2473 :     C<$userID> is the ID of the user who made the annotation, and C<$annotation> is the annotation
2474 :     text. The list is sorted by timestamp.
2475 :    
2476 :     =over 4
2477 :    
2478 :     =item list
2479 :    
2480 :     List of the IDs for the features whose annotations are desired.
2481 :    
2482 :     =item RETURN
2483 :    
2484 :     Returns a list of annotation descriptions sorted by the annotation time.
2485 :    
2486 :     =back
2487 :    
2488 :     =cut
2489 : parrello 1.3 #: Return Type @;
2490 : parrello 1.1 sub MergedAnnotations {
2491 : parrello 1.15 # Get the parameters.
2492 :     my ($self, $list) = @_;
2493 :     # Create a list to hold the annotation tuples found.
2494 :     my @tuples = ();
2495 :     # Loop through the features in the input list.
2496 :     for my $fid (@{$list}) {
2497 :     # Create a list of this feature's annotation tuples.
2498 :     my @newTuples = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
2499 :     "IsTargetOfAnnotation(from-link) = ?", [$fid],
2500 :     ['IsTargetOfAnnotation(from-link)', 'Annotation(time)',
2501 :     'MadeAnnotation(from-link)', 'Annotation(annotation)']);
2502 :     # Put it in the result list.
2503 :     push @tuples, @newTuples;
2504 :     }
2505 :     # Sort the result list by timestamp.
2506 :     my @retVal = sort { $a->[1] <=> $b->[1] } @tuples;
2507 : parrello 1.3 # Loop through and make the time stamps friendly.
2508 :     for my $tuple (@retVal) {
2509 :     $tuple->[1] = FriendlyTimestamp($tuple->[1]);
2510 :     }
2511 : parrello 1.15 # Return the sorted list.
2512 :     return @retVal;
2513 : parrello 1.1 }
2514 :    
2515 :     =head3 RoleNeighbors
2516 :    
2517 :     C<< my @roleList = $sprout->RoleNeighbors($roleID); >>
2518 :    
2519 :     Returns a list of the roles that occur in the same diagram as the specified role. Because
2520 :     diagrams and roles are in a many-to-many relationship with each other, the list is
2521 :     essentially the set of roles from all of the maps that contain the incoming role. Such
2522 :     roles are considered neighbors because they are used together in cellular subsystems.
2523 :    
2524 :     =over 4
2525 :    
2526 :     =item roleID
2527 :    
2528 :     ID of the role whose neighbors are desired.
2529 :    
2530 :     =item RETURN
2531 :    
2532 :     Returns a list containing the IDs of the roles that are related to the incoming role.
2533 :    
2534 :     =back
2535 :    
2536 :     =cut
2537 : parrello 1.3 #: Return Type @;
2538 : parrello 1.1 sub RoleNeighbors {
2539 : parrello 1.15 # Get the parameters.
2540 :     my ($self, $roleID) = @_;
2541 :     # Get all the diagrams containing this role.
2542 :     my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2543 :     'RoleOccursIn(to-link)');
2544 :     # Create the return list.
2545 :     my @retVal = ();
2546 :     # Loop through the diagrams.
2547 :     for my $diagramID (@diagrams) {
2548 :     # Get all the roles in this diagram.
2549 :     my @roles = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(to-link) = ?", [$diagramID],
2550 :     'RoleOccursIn(from-link)');
2551 :     # Add them to the return list.
2552 :     push @retVal, @roles;
2553 :     }
2554 :     # Merge the duplicates from the list.
2555 :     return Tracer::Merge(@retVal);
2556 : parrello 1.1 }
2557 :    
2558 :     =head3 FeatureLinks
2559 :    
2560 :     C<< my @links = $sprout->FeatureLinks($featureID); >>
2561 :    
2562 :     Return a list of the web hyperlinks associated with a feature. The web hyperlinks are
2563 :     to external websites describing either the feature itself or the organism containing it
2564 :     and are represented in raw HTML.
2565 :    
2566 :     =over 4
2567 :    
2568 :     =item featureID
2569 :    
2570 :     ID of the feature whose links are desired.
2571 :    
2572 :     =item RETURN
2573 :    
2574 :     Returns a list of the web links for this feature.
2575 :    
2576 :     =back
2577 :    
2578 :     =cut
2579 : parrello 1.3 #: Return Type @;
2580 : parrello 1.1 sub FeatureLinks {
2581 : parrello 1.15 # Get the parameters.
2582 :     my ($self, $featureID) = @_;
2583 :     # Get the feature's links.
2584 :     my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);
2585 :     # Return the feature's links.
2586 :     return @retVal;
2587 : parrello 1.1 }
2588 :    
2589 :     =head3 SubsystemsOf
2590 :    
2591 :     C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2592 :    
2593 :     Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped
2594 : parrello 1.20 to the roles the feature performs.
2595 : parrello 1.1
2596 :     =over 4
2597 :    
2598 :     =item featureID
2599 :    
2600 :     ID of the feature whose subsystems are desired.
2601 :    
2602 :     =item RETURN
2603 :    
2604 : parrello 1.20 Returns a hash mapping all the feature's subsystems to a list of the feature's roles.
2605 : parrello 1.1
2606 :     =back
2607 :    
2608 :     =cut
2609 : parrello 1.20 #: Return Type %@;
2610 : parrello 1.1 sub SubsystemsOf {
2611 : parrello 1.15 # Get the parameters.
2612 :     my ($self, $featureID) = @_;
2613 : parrello 1.16 # Get the subsystem list.
2614 : parrello 1.15 my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2615 :     "ContainsFeature(to-link) = ?", [$featureID],
2616 :     ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2617 :     # Create the return value.
2618 :     my %retVal = ();
2619 : parrello 1.42 # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2620 :     # in two spreadsheet cells.
2621 :     my %dupHash = ();
2622 : parrello 1.15 # Loop through the results, adding them to the hash.
2623 :     for my $record (@subsystems) {
2624 : parrello 1.42 # Get this subsystem and role.
2625 : parrello 1.20 my ($subsys, $role) = @{$record};
2626 : parrello 1.42 # Insure it's the first time for both.
2627 :     my $dupKey = "$subsys\n$role";
2628 :     if (! exists $dupHash{"$subsys\n$role"}) {
2629 :     $dupHash{$dupKey} = 1;
2630 : parrello 1.20 push @{$retVal{$subsys}}, $role;
2631 :     }
2632 : parrello 1.15 }
2633 :     # Return the hash.
2634 :     return %retVal;
2635 : parrello 1.1 }
2636 :    
2637 : parrello 1.16 =head3 SubsystemList
2638 :    
2639 :     C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2640 :    
2641 :     Return a list containing the names of the subsystems in which the specified
2642 :     feature participates. Unlike L</SubsystemsOf>, this method only returns the
2643 :     subsystem names, not the roles.
2644 :    
2645 :     =over 4
2646 :    
2647 :     =item featureID
2648 :    
2649 :     ID of the feature whose subsystem names are desired.
2650 :    
2651 :     =item RETURN
2652 :    
2653 :     Returns a list of the names of the subsystems in which the feature participates.
2654 :    
2655 :     =back
2656 :    
2657 :     =cut
2658 :     #: Return Type @;
2659 :     sub SubsystemList {
2660 :     # Get the parameters.
2661 :     my ($self, $featureID) = @_;
2662 :     # Get the list of names.
2663 :     my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",
2664 :     [$featureID], 'HasSSCell(from-link)');
2665 :     # Return the result.
2666 :     return @retVal;
2667 :     }
2668 :    
2669 : parrello 1.56
2670 :    
2671 : parrello 1.1 =head3 RelatedFeatures
2672 :    
2673 :     C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
2674 :    
2675 :     Return a list of the features which are bi-directional best hits of the specified feature and
2676 :     have been assigned the specified function by the specified user. If no such features exists,
2677 :     an empty list will be returned.
2678 :    
2679 :     =over 4
2680 :    
2681 :     =item featureID
2682 :    
2683 :     ID of the feature to whom the desired features are related.
2684 :    
2685 :     =item function
2686 :    
2687 :     Functional assignment (as returned by C</FunctionOf>) that is used to determine which related
2688 :     features should be selected.
2689 :    
2690 :     =item userID
2691 :    
2692 :     ID of the user whose functional assignments are to be used. If omitted, C<FIG> is assumed.
2693 :    
2694 :     =item RETURN
2695 :    
2696 :     Returns a list of the related features with the specified function.
2697 :    
2698 :     =back
2699 :    
2700 :     =cut
2701 : parrello 1.3 #: Return Type @;
2702 : parrello 1.1 sub RelatedFeatures {
2703 : parrello 1.15 # Get the parameters.
2704 :     my ($self, $featureID, $function, $userID) = @_;
2705 :     # Get a list of the features that are BBHs of the incoming feature.
2706 :     my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],
2707 :     "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],
2708 :     'IsBidirectionalBestHitOf(to-link)');
2709 :     # Now we loop through the features, pulling out the ones that have the correct
2710 :     # functional assignment.
2711 :     my @retVal = ();
2712 :     for my $bbhFeature (@bbhFeatures) {
2713 :     # Get this feature's functional assignment.
2714 :     my $newFunction = $self->FunctionOf($bbhFeature, $userID);
2715 :     # If it matches, add it to the result list.
2716 :     if ($newFunction eq $function) {
2717 :     push @retVal, $bbhFeature;
2718 :     }
2719 :     }
2720 :     # Return the result list.
2721 :     return @retVal;
2722 : parrello 1.1 }
2723 :    
2724 :     =head3 TaxonomySort
2725 :    
2726 :     C<< my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs); >>
2727 :    
2728 :     Return a list formed by sorting the specified features by the taxonomy of the containing
2729 :     genome. This will cause genomes from similar organisms to float close to each other.
2730 :    
2731 :     This task could almost be handled by the database; however, the taxonomy string in the
2732 :     database is a text field and can't be indexed. Instead, we create a hash table that maps
2733 :     taxonomy strings to lists of features. We then process the hash table using a key sort
2734 :     and merge the feature lists together to create the output.
2735 :    
2736 :     =over 4
2737 :    
2738 :     =item $featureIDs
2739 :    
2740 :     List of features to be taxonomically sorted.
2741 :    
2742 :     =item RETURN
2743 :    
2744 :     Returns the list of features sorted by the taxonomies of the containing genomes.
2745 :    
2746 :     =back
2747 :    
2748 :     =cut
2749 : parrello 1.3 #: Return Type @;
2750 : parrello 1.1 sub TaxonomySort {
2751 : parrello 1.15 # Get the parameters.
2752 :     my ($self, $featureIDs) = @_;
2753 :     # Create the working hash table.
2754 :     my %hashBuffer = ();
2755 :     # Loop through the features.
2756 :     for my $fid (@{$featureIDs}) {
2757 :     # Get the taxonomy of the feature's genome.
2758 :     my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
2759 :     [$fid], 'Genome(taxonomy)');
2760 :     # Add this feature to the hash buffer.
2761 : parrello 1.10 Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);
2762 : parrello 1.15 }
2763 :     # Sort the keys and get the elements.
2764 :     my @retVal = ();
2765 :     for my $taxon (sort keys %hashBuffer) {
2766 :     push @retVal, @{$hashBuffer{$taxon}};
2767 :     }
2768 :     # Return the result.
2769 :     return @retVal;
2770 : parrello 1.1 }
2771 :    
2772 :     =head3 Protein
2773 :    
2774 :     C<< my $protein = Sprout::Protein($sequence, $table); >>
2775 :    
2776 :     Translate a DNA sequence into a protein sequence.
2777 :    
2778 :     =over 4
2779 :    
2780 :     =item sequence
2781 :    
2782 :     DNA sequence to translate.
2783 :    
2784 :     =item table (optional)
2785 :    
2786 :     Reference to a Hash that translates DNA triples to proteins. A triple that does not
2787 :     appear in the hash will be translated automatically to C<X>.
2788 :    
2789 :     =item RETURN
2790 :    
2791 :     Returns the protein sequence that would be created by the DNA sequence.
2792 :    
2793 :     =back
2794 :    
2795 :     =cut
2796 :    
2797 :     # This is the translation table for protein synthesis.
2798 :     my $ProteinTable = { AAA => 'K', AAG => 'K', AAT => 'N', AAC => 'N',
2799 : parrello 1.15 AGA => 'R', AGG => 'R', AGT => 'S', AGC => 'S',
2800 :     ATA => 'I', ATG => 'M', ATT => 'I', ATC => 'I',
2801 :     ACA => 'T', ACG => 'T', ACT => 'T', ACC => 'T',
2802 :     GAA => 'E', GAG => 'E', GAT => 'D', GAC => 'D',
2803 :     GTA => 'V', GTG => 'V', GTT => 'V', GTC => 'V',
2804 :     GGA => 'G', GGG => 'G', GGT => 'G', GGC => 'G',
2805 :     GCA => 'A', GCG => 'A', GCT => 'A', GCC => 'A',
2806 :     CAA => 'Q', CAG => 'Q', CAT => 'H', CAC => 'H',
2807 :     CTA => 'L', CTG => 'L', CTT => 'L', CTC => 'L',
2808 :     CGA => 'R', CGG => 'R', CGT => 'R', CGC => 'R',
2809 :     CCA => 'P', CCG => 'P', CCT => 'P', CCC => 'P',
2810 :     TAA => '*', TAG => '*', TAT => 'Y', TAC => 'Y',
2811 :     TGA => '*', TGG => 'W', TGT => 'C', TGC => 'C',
2812 :     TTA => 'L', TTG => 'L', TTT => 'F', TTC => 'F',
2813 :     TCA => 'S', TCG => 'S', TCT => 'S', TCC => 'S',
2814 :     AAR => 'K', AAY => 'N',
2815 :     AGR => 'R', AGY => 'S',
2816 :     ATY => 'I',
2817 :     ACR => 'T', ACY => 'T', 'ACX' => 'T',
2818 :     GAR => 'E', GAY => 'D',
2819 :     GTR => 'V', GTY => 'V', GTX => 'V',
2820 :     GGR => 'G', GGY => 'G', GGX => 'G',
2821 :     GCR => 'A', GCY => 'A', GCX => 'A',
2822 :     CAR => 'Q', CAY => 'H',
2823 :     CTR => 'L', CTY => 'L', CTX => 'L',
2824 :     CGR => 'R', CGY => 'R', CGX => 'R',
2825 :     CCR => 'P', CCY => 'P', CCX => 'P',
2826 :     TAR => '*', TAY => 'Y',
2827 :     TGY => 'C',
2828 :     TTR => 'L', TTY => 'F',
2829 :     TCR => 'S', TCY => 'S', TCX => 'S'
2830 :     };
2831 : parrello 1.1
2832 :     sub Protein {
2833 : parrello 1.15 # Get the paraeters.
2834 :     my ($sequence, $table) = @_;
2835 :     # If no table was specified, use the default.
2836 :     if (!$table) {
2837 :     $table = $ProteinTable;
2838 :     }
2839 :     # Create the return value.
2840 :     my $retVal = "";
2841 :     # Loop through the input triples.
2842 :     my $n = length $sequence;
2843 :     for (my $i = 0; $i < $n; $i += 3) {
2844 :     # Get the current triple from the sequence.
2845 :     my $triple = substr($sequence, $i, 3);
2846 :     # Translate it using the table.
2847 :     my $protein = "X";
2848 :     if (exists $table->{$triple}) { $protein = $table->{$triple}; }
2849 :     $retVal .= $protein;
2850 :     }
2851 :     # Remove the stop codon (if any).
2852 :     $retVal =~ s/\*$//;
2853 :     # Return the result.
2854 :     return $retVal;
2855 : parrello 1.1 }
2856 :    
2857 :     =head3 LoadInfo
2858 :    
2859 :     C<< my ($dirName, @relNames) = $sprout->LoadInfo(); >>
2860 :    
2861 :     Return the name of the directory from which data is to be loaded and a list of the relation
2862 :     names. This information is useful when trying to analyze what needs to be put where in order
2863 :     to load the entire database.
2864 :    
2865 :     =cut
2866 : parrello 1.3 #: Return Type @;
2867 : parrello 1.1 sub LoadInfo {
2868 : parrello 1.15 # Get the parameters.
2869 :     my ($self) = @_;
2870 :     # Create the return list, priming it with the name of the data directory.
2871 :     my @retVal = ($self->{_options}->{dataDir});
2872 :     # Concatenate the table names.
2873 : parrello 1.58 push @retVal, $self->GetTableNames();
2874 : parrello 1.15 # Return the result.
2875 :     return @retVal;
2876 : parrello 1.1 }
2877 :    
2878 :     =head3 LowBBHs
2879 :    
2880 : parrello 1.58 C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
2881 : parrello 1.1
2882 :     Return the bidirectional best hits of a feature whose score is no greater than a
2883 :     specified cutoff value. A higher cutoff value will allow inclusion of hits with
2884 :     a greater score. The value returned is a map of feature IDs to scores.
2885 :    
2886 :     =over 4
2887 :    
2888 :     =item featureID
2889 :    
2890 :     ID of the feature whose best hits are desired.
2891 :    
2892 :     =item cutoff
2893 :    
2894 :     Maximum permissible score for inclusion in the results.
2895 :    
2896 :     =item RETURN
2897 :    
2898 :     Returns a hash mapping feature IDs to scores.
2899 :    
2900 :     =back
2901 :    
2902 :     =cut
2903 : parrello 1.3 #: Return Type %;
2904 : parrello 1.1 sub LowBBHs {
2905 : parrello 1.15 # Get the parsameters.
2906 :     my ($self, $featureID, $cutoff) = @_;
2907 :     # Create the return hash.
2908 :     my %retVal = ();
2909 :     # Create a query to get the desired BBHs.
2910 :     my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],
2911 :     'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',
2912 :     [$cutoff, $featureID],
2913 :     ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);
2914 :     # Form the results into the return hash.
2915 :     for my $pair (@bbhList) {
2916 :     $retVal{$pair->[0]} = $pair->[1];
2917 :     }
2918 :     # Return the result.
2919 :     return %retVal;
2920 : parrello 1.1 }
2921 :    
2922 : parrello 1.7 =head3 GetGroups
2923 :    
2924 : parrello 1.8 C<< my %groups = $sprout->GetGroups(\@groupList); >>
2925 :    
2926 :     Return a hash mapping each group to the IDs of the genomes in the group.
2927 :     A list of groups may be specified, in which case only those groups will be
2928 :     shown. Alternatively, if no parameter is supplied, all groups will be
2929 :     included. Genomes that are not in any group are omitted.
2930 :    
2931 : parrello 1.7 =cut
2932 :     #: Return Type %@;
2933 :     sub GetGroups {
2934 : parrello 1.8 # Get the parameters.
2935 : parrello 1.10 my ($self, $groupList) = @_;
2936 : parrello 1.8 # Declare the return value.
2937 :     my %retVal = ();
2938 :     # Determine whether we are getting all the groups or just some.
2939 :     if (defined $groupList) {
2940 :     # Here we have a group list. Loop through them individually,
2941 :     # getting a list of the relevant genomes.
2942 :     for my $group (@{$groupList}) {
2943 :     my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",
2944 :     [$group], "Genome(id)");
2945 :     $retVal{$group} = \@genomeIDs;
2946 :     }
2947 :     } else {
2948 :     # Here we need all of the groups. In this case, we run through all
2949 :     # of the genome records, putting each one found into the appropriate
2950 :     # group. Note that we use a filter clause to insure that only genomes
2951 :     # in groups are included in the return set.
2952 :     my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],
2953 :     ['Genome(id)', 'Genome(group-name)']);
2954 :     # Loop through the genomes found.
2955 :     for my $genome (@genomes) {
2956 :     # Pop this genome's ID off the current list.
2957 :     my @groups = @{$genome};
2958 :     my $genomeID = shift @groups;
2959 :     # Loop through the groups, adding the genome ID to each group's
2960 :     # list.
2961 :     for my $group (@groups) {
2962 : parrello 1.10 Tracer::AddToListMap(\%retVal, $group, $genomeID);
2963 : parrello 1.8 }
2964 :     }
2965 :     }
2966 :     # Return the hash we just built.
2967 :     return %retVal;
2968 : parrello 1.7 }
2969 :    
2970 : parrello 1.18 =head3 MyGenomes
2971 :    
2972 :     C<< my @genomes = Sprout::MyGenomes($dataDir); >>
2973 :    
2974 :     Return a list of the genomes to be included in the Sprout.
2975 :    
2976 :     This method is provided for use during the Sprout load. It presumes the Genome load file has
2977 :     already been created. (It will be in the Sprout data directory and called either C<Genome>
2978 :     or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
2979 :     IDs.
2980 :    
2981 :     =over 4
2982 :    
2983 :     =item dataDir
2984 :    
2985 :     Directory containing the Sprout load files.
2986 :    
2987 :     =back
2988 :    
2989 :     =cut
2990 :     #: Return Type @;
2991 :     sub MyGenomes {
2992 :     # Get the parameters.
2993 :     my ($dataDir) = @_;
2994 :     # Compute the genome file name.
2995 :     my $genomeFileName = LoadFileName($dataDir, "Genome");
2996 :     # Extract the genome IDs from the files.
2997 :     my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
2998 :     # Return the result.
2999 :     return @retVal;
3000 :     }
3001 :    
3002 :     =head3 LoadFileName
3003 :    
3004 :     C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3005 :    
3006 :     Return the name of the load file for the specified table in the specified data
3007 :     directory.
3008 :    
3009 :     =over 4
3010 :    
3011 :     =item dataDir
3012 :    
3013 :     Directory containing the Sprout load files.
3014 :    
3015 :     =item tableName
3016 :    
3017 :     Name of the table whose load file is desired.
3018 :    
3019 :     =item RETURN
3020 :    
3021 :     Returns the name of the file containing the load data for the specified table, or
3022 :     C<undef> if no load file is present.
3023 :    
3024 :     =back
3025 :    
3026 :     =cut
3027 :     #: Return Type $;
3028 :     sub LoadFileName {
3029 :     # Get the parameters.
3030 :     my ($dataDir, $tableName) = @_;
3031 :     # Declare the return variable.
3032 :     my $retVal;
3033 :     # Check for the various file names.
3034 :     if (-e "$dataDir/$tableName") {
3035 :     $retVal = "$dataDir/$tableName";
3036 :     } elsif (-e "$dataDir/$tableName.dtx") {
3037 :     $retVal = "$dataDir/$tableName.dtx";
3038 :     }
3039 :     # Return the result.
3040 :     return $retVal;
3041 :     }
3042 :    
3043 : parrello 1.53 =head3 DeleteGenome
3044 :    
3045 :     C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3046 :    
3047 :     Delete a genome from the database.
3048 :    
3049 :     =over 4
3050 :    
3051 :     =item genomeID
3052 :    
3053 :     ID of the genome to delete
3054 :    
3055 :     =item testFlag
3056 :    
3057 :     If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3058 :    
3059 :     =item RETURN
3060 :    
3061 :     Returns a statistics object describing the rows deleted.
3062 :    
3063 :     =back
3064 :    
3065 :     =cut
3066 :     #: Return Type $%;
3067 :     sub DeleteGenome {
3068 :     # Get the parameters.
3069 :     my ($self, $genomeID, $testFlag) = @_;
3070 :     # Perform the delete for the genome's features.
3071 : parrello 1.58 my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);
3072 : parrello 1.53 # Perform the delete for the primary genome data.
3073 : parrello 1.58 my $stats = $self->Delete('Genome', $genomeID, $testFlag);
3074 : parrello 1.53 $retVal->Accumulate($stats);
3075 :     # Return the result.
3076 :     return $retVal;
3077 :     }
3078 :    
3079 : parrello 1.1 =head2 Internal Utility Methods
3080 :    
3081 :     =head3 ParseAssignment
3082 :    
3083 :     Parse annotation text to determine whether or not it is a functional assignment. If it is,
3084 : parrello 1.19 the user, function text, and assigning user will be returned as a 3-element list. If it
3085 : parrello 1.11 isn't, an empty list will be returned.
3086 :    
3087 :     A functional assignment is always of the form
3088 :    
3089 : parrello 1.48 C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3090 : parrello 1.19
3091 : parrello 1.48 where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3092 :     the user and the assigning user (from MadeAnnotation) will be the same, but that is
3093 :     not always the case.
3094 : parrello 1.1
3095 : parrello 1.52 In addition, the functional role may contain extra data that is stripped, such as
3096 :     terminating spaces or a comment separated from the rest of the text by a tab.
3097 :    
3098 : parrello 1.1 This is a static method.
3099 :    
3100 :     =over 4
3101 :    
3102 : parrello 1.48 =item user
3103 :    
3104 :     Name of the assigning user.
3105 :    
3106 : parrello 1.1 =item text
3107 :    
3108 :     Text of the annotation.
3109 :    
3110 :     =item RETURN
3111 :    
3112 :     Returns an empty list if the annotation is not a functional assignment; otherwise, returns
3113 :     a two-element list containing the user name and the function text.
3114 :    
3115 :     =back
3116 :    
3117 :     =cut
3118 :    
3119 : parrello 1.11 sub _ParseAssignment {
3120 : parrello 1.15 # Get the parameters.
3121 : parrello 1.48 my ($user, $text) = @_;
3122 : parrello 1.15 # Declare the return value.
3123 :     my @retVal = ();
3124 :     # Check to see if this is a functional assignment.
3125 : parrello 1.43 my ($type, $function) = split(/\n/, $text);
3126 : parrello 1.48 if ($type =~ m/^set function to$/i) {
3127 :     # Here we have an assignment without a user, so we use the incoming user ID.
3128 :     @retVal = ($user, $function);
3129 :     } elsif ($type =~ m/^set (\S+) function to$/i) {
3130 : parrello 1.52 # Here we have an assignment with a user that is passed back to the caller.
3131 : parrello 1.43 @retVal = ($1, $function);
3132 : parrello 1.15 }
3133 : parrello 1.52 # If we have an assignment, we need to clean the function text. There may be
3134 :     # extra junk at the end added as a note from the user.
3135 :     if (@retVal) {
3136 :     $retVal[1] =~ s/(\t\S)?\s*$//;
3137 :     }
3138 : parrello 1.15 # Return the result list.
3139 :     return @retVal;
3140 : parrello 1.1 }
3141 :    
3142 : parrello 1.3 =head3 FriendlyTimestamp
3143 :    
3144 :     Convert a time number to a user-friendly time stamp for display.
3145 :    
3146 :     This is a static method.
3147 :    
3148 :     =over 4
3149 :    
3150 :     =item timeValue
3151 :    
3152 :     Numeric time value.
3153 :    
3154 :     =item RETURN
3155 :    
3156 :     Returns a string containing the same time in user-readable format.
3157 :    
3158 :     =back
3159 :    
3160 :     =cut
3161 :    
3162 :     sub FriendlyTimestamp {
3163 :     my ($timeValue) = @_;
3164 : parrello 1.40 my $retVal = localtime($timeValue);
3165 : parrello 1.3 return $retVal;
3166 :     }
3167 :    
3168 : parrello 1.15 =head3 AddProperty
3169 :    
3170 :     C<< my = $sprout->AddProperty($featureID, $key, $value, $url); >>
3171 :    
3172 :     Add a new attribute value (Property) to a feature. In the SEED system, attributes can
3173 :     be added to almost any object. In Sprout, they can only be added to features. In
3174 :     Sprout, attributes are implemented using I<properties>. A property represents a key/value
3175 :     pair. If the particular key/value pair coming in is not already in the database, a new
3176 :     B<Property> record is created to hold it.
3177 :    
3178 :     =over 4
3179 :    
3180 :     =item peg
3181 :    
3182 :     ID of the feature to which the attribute is to be replied.
3183 :    
3184 :     =item key
3185 :    
3186 :     Name of the attribute (key).
3187 :    
3188 :     =item value
3189 :    
3190 :     Value of the attribute.
3191 :    
3192 :     =item url
3193 :    
3194 :     URL or text citation from which the property was obtained.
3195 :    
3196 :     =back
3197 :    
3198 :     =cut
3199 :     #: Return Type ;
3200 :     sub AddProperty {
3201 :     # Get the parameters.
3202 :     my ($self, $featureID, $key, $value, $url) = @_;
3203 :     # Declare the variable to hold the desired property ID.
3204 :     my $propID;
3205 :     # Attempt to find a property record for this key/value pair.
3206 :     my @properties = $self->GetFlat(['Property'],
3207 :     "Property(property-name) = ? AND Property(property-value) = ?",
3208 :     [$key, $value], 'Property(id)');
3209 :     if (@properties) {
3210 :     # Here the property is already in the database. We save its ID.
3211 :     $propID = $properties[0];
3212 :     # Here the property value does not exist. We need to generate an ID. It will be set
3213 :     # to a number one greater than the maximum value in the database. This call to
3214 :     # GetAll will stop after one record.
3215 :     my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],
3216 :     1);
3217 :     $propID = $maxProperty[0]->[0] + 1;
3218 :     # Insert the new property value.
3219 :     $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });
3220 :     }
3221 :     # Now we connect the incoming feature to the property.
3222 :     $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3223 :     }
3224 :    
3225 : parrello 1.51
3226 : parrello 1.48 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3