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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3