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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3