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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3