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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

1 : parrello 1.1 package Sprout;
2 :    
3 :     use Data::Dumper;
4 :     use strict;
5 :     use Carp;
6 :     use DBKernel;
7 :     use XML::Simple;
8 :     use DBQuery;
9 :     use DBObject;
10 :     use ERDB;
11 :     use Tracer;
12 :     use FIGRules;
13 :     use Stats;
14 : parrello 1.3 use POSIX qw(strftime);
15 : parrello 1.1
16 :    
17 :     =head1 Sprout Database Manipulation Object
18 :    
19 :     =head2 Introduction
20 :    
21 :     This object enables the user to load and query the Sprout genome database using a few simple methods.
22 :     To construct the object, specify the name of the database. By default, the database is assumed to be a
23 :     MySQL database accessed via the user ID I<root> with no password and the database definition will
24 :     be in a file called F<SproutDBD.xml>. All of these defaults can be overridden
25 :     on the constructor. For example, the following invocation specifies a PostgreSQL database named I<GenDB>
26 :     whose definition and data files are in a co-directory named F<Data>.
27 :    
28 :     C<< my $sprout = Sprout->new('GenDB', { dbType => 'pg', dataDir => '../Data', xmlFileName => '../Data/SproutDBD.xml' }); >>
29 :    
30 :     Once you have a sprout object, you may use it to re-create the database, load the tables from
31 :     tab-delimited flat files and perform queries. Several special methods are provided for common
32 :     query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and
33 :     L</dna_seq> returns the DNA sequence for a specified genome location.
34 :    
35 :     =cut
36 :    
37 : parrello 1.3 #: Constructor SFXlate->new_sprout_only();
38 :    
39 : parrello 1.1 =head2 Public Methods
40 :    
41 :     =head3 new
42 :    
43 :     C<< my $sprout = Sprout->new($dbName, \%options); >>
44 :    
45 :     This is the constructor for a sprout object. It connects to the database and loads the
46 :     database definition into memory. The positional first parameter specifies the name of the
47 :     database.
48 :    
49 :     =over 4
50 :    
51 :     =item dbName
52 :    
53 :     Name of the database.
54 :    
55 :     =item options
56 :    
57 :     Table of options.
58 :    
59 :     * B<dbType> type of database (currently C<mysql> for MySQL and C<pg> for PostgreSQL) (default C<mysql>)
60 :    
61 :     * B<dataDir> directory containing the database definition file and the flat files used to load the data (default C<Data>)
62 :    
63 :     * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)
64 :    
65 :     * B<userData> user name and password, delimited by a slash (default C<root/>)
66 :    
67 :     * B<port> connection port (default C<0>)
68 :    
69 :     * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
70 :    
71 :     * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
72 :    
73 :     =back
74 :    
75 :     For example, the following constructor call specifies a database named I<Sprout> and a user name of
76 :     I<fig> with a password of I<admin>. The database load files are in the directory
77 :     F</usr/fig/SproutData>.
78 :    
79 :     C<< my $sprout = Sprout->new('Sprout', { userData =>; 'fig/admin', dataDir => '/usr/fig/SproutData' }); >>
80 :    
81 :     =cut
82 :    
83 :     sub new {
84 :     # Get the parameters.
85 :     my ($class, $dbName, $options) = @_;
86 :     # Compute the options. We do this by starting with a table of defaults and overwriting with
87 :     # the incoming data.
88 :     my $optionTable = Tracer::GetOptions({
89 :     dbType => 'mysql', # database type
90 :     dataDir => 'Data', # data file directory
91 :     xmlFileName => 'SproutDBD.xml', # database definition file name
92 :     userData => 'root/', # user name and password
93 :     port => 0, # database connection port
94 :     maxSegmentLength => 4500, # maximum feature segment length
95 :     maxSequenceLength => 8000, # maximum contig sequence length
96 :     }, $options);
97 :     # Get the data directory.
98 :     my $dataDir = $optionTable->{dataDir};
99 :     # Extract the user ID and password.
100 :     $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
101 :     my ($userName, $password) = ($1, $2);
102 :     # Connect to the database.
103 :     my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});
104 :     # Create the ERDB object.
105 :     my $xmlFileName = "$optionTable->{xmlFileName}";
106 :     my $erdb = ERDB->new($dbh, $xmlFileName);
107 :     # Create this object.
108 :     my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };
109 :     # Bless and return it.
110 :     bless $self;
111 :     return $self;
112 :     }
113 :    
114 :     =head3 MaxSegment
115 :    
116 :     C<< my $length = $sprout->MaxSegment(); >>
117 :    
118 :     This method returns the maximum permissible length of a feature segment. The length is important
119 :     because it enables us to make reasonable guesses at how to find features inside a particular
120 :     contig region. For example, if the maximum length is 4000 and we're looking for a feature that
121 :     overlaps the region from 6000 to 7000 we know that the starting position must be between 2001
122 :     and 10999.
123 :    
124 :     =cut
125 : parrello 1.3 #: Return Type $;
126 : parrello 1.1 sub MaxSegment {
127 :     my $self = shift @_;
128 :     return $self->{_options}->{maxSegmentLength};
129 :     }
130 :    
131 :     =head3 MaxSequence
132 :    
133 :     C<< my $length = $sprout->MaxSequence(); >>
134 :    
135 :     This method returns the maximum permissible length of a contig sequence. A contig is broken
136 :     into sequences in order to save memory resources. In particular, when manipulating features,
137 :     we generally only need a few sequences in memory rather than the entire contig.
138 :    
139 :     =cut
140 : parrello 1.3 #: Return Type $;
141 : parrello 1.1 sub MaxSequence {
142 :     my $self = shift @_;
143 :     return $self->{_options}->{maxSequenceLength};
144 :     }
145 :    
146 :     =head3 Get
147 :    
148 :     C<< my $query = $sprout->Get(\@objectNames, $filterClause, \@parameterList); >>
149 :    
150 :     This method allows a general query against the Sprout data using a specified filter clause.
151 :    
152 :     The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each
153 :     field name represented in the form B<I<objectName>(I<fieldName>)>. For example, the
154 :     following call requests all B<Genome> objects for the genus specified in the variable
155 :     $genus.
156 :    
157 :     C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>
158 :    
159 :     The WHERE clause contains a single question mark, so there is a single additional
160 :     parameter representing the parameter value. It would also be possible to code
161 :    
162 :     C<< $query = $sprout->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>
163 :    
164 :     however, this version of the call would generate a syntax error if there were any quote
165 :     characters inside the variable C<$genus>.
166 :    
167 :     The use of the strange parenthesized notation for field names enables us to distinguish
168 :     hyphens contained within field names from minus signs that participate in the computation
169 :     of the WHERE clause. All of the methods that manipulate fields will use this same notation.
170 :    
171 :     It is possible to specify multiple entity and relationship names in order to retrieve more than
172 :     one object's data at the same time, which allows highly complex joined queries. For example,
173 :    
174 :     C<< $query = $sprout->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>
175 :    
176 :     This query returns all the genomes for a particular genus and allows access to the
177 :     sources from which they came. The join clauses to go from Genome to Source are generated
178 :     automatically.
179 :    
180 :     Finally, the filter clause can contain sort information. To do this, simply put an C<ORDER BY>
181 :     clause at the end of the filter. Field references in the ORDER BY section follow the same rules
182 :     as they do in the filter itself; in other words, each one must be of the form B<I<objectName>(I<fieldName>)>.
183 :     For example, the following filter string gets all genomes for a particular genus and sorts
184 :     them by species name.
185 :    
186 :     C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ? ORDER BY Genome(species)", [$genus]); >>
187 :    
188 :     It is also permissible to specify I<only> an ORDER BY clause. For example, the following invocation gets
189 :     all genomes ordered by genus and species.
190 :    
191 :     C<< $query = $sprout->Get(['Genome'], "ORDER BY Genome(genus), Genome(species)"); >>
192 :    
193 :     Odd things may happen if one of the ORDER BY fields is in a secondary relation. So, for example, an
194 :     attempt to order B<Feature>s by alias may (depending on the underlying database engine used) cause
195 :     a single feature to appear more than once.
196 :    
197 :     If multiple names are specified, then the query processor will automatically determine a
198 :     join path between the entities and relationships. The algorithm used is very simplistic.
199 :     In particular, you can't specify any entity or relationship more than once, and if a
200 :     relationship is recursive, the path is determined by the order in which the entity
201 :     and the relationship appear. For example, consider a recursive relationship B<IsParentOf>
202 :     which relates B<People> objects to other B<People> objects. If the join path is
203 :     coded as C<['People', 'IsParentOf']>, then the people returned will be parents. If, however,
204 :     the join path is C<['IsParentOf', 'People']>, then the people returned will be children.
205 :    
206 :     =over 4
207 :    
208 :     =item objectNames
209 :    
210 :     List containing the names of the entity and relationship objects to be retrieved.
211 :    
212 :     =item filterClause
213 :    
214 :     WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
215 :     be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
216 :     B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
217 :     parameter list as additional parameters. The fields in a filter clause can come from primary
218 :     entity relations, relationship relations, or secondary entity relations; however, all of the
219 :     entities and relationships involved must be included in the list of object names.
220 :    
221 :     =item parameterList
222 :    
223 :     List of the parameters to be substituted in for the parameters marks in the filter clause.
224 :    
225 :     =item RETURN
226 :    
227 :     Returns a B<DBQuery> that can be used to iterate through all of the results.
228 :    
229 :     =back
230 :    
231 :     =cut
232 :    
233 :     sub Get {
234 :     # Get the parameters.
235 :     my $self = shift @_;
236 :     my ($objectNames, $filterClause, $parameterList) = @_;
237 :     # We differ from the ERDB Get method in that the parameter list is passed in as a list reference
238 :     # rather than a list of parameters. The next step is to convert the parameters from a reference
239 :     # to a real list. We can only do this if the parameters have been specified.
240 :     my @parameters;
241 :     if ($parameterList) { @parameters = @{$parameterList}; }
242 :     return $self->{_erdb}->Get($objectNames, $filterClause, @parameters);
243 :     }
244 :    
245 :     =head3 GetEntity
246 :    
247 :     C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>
248 :    
249 :     Return an object describing the entity instance with a specified ID.
250 :    
251 :     =over 4
252 :    
253 :     =item entityType
254 :    
255 :     Entity type name.
256 :    
257 :     =item ID
258 :    
259 :     ID of the desired entity.
260 :    
261 :     =item RETURN
262 :    
263 :     Returns a B<DBObject> representing the desired entity instance, or an undefined value if no
264 :     instance is found with the specified key.
265 :    
266 :     =back
267 :    
268 :     =cut
269 :    
270 :     sub GetEntity {
271 :     # Get the parameters.
272 :     my $self = shift @_;
273 :     my ($entityType, $ID) = @_;
274 :     # Create a query.
275 :     my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
276 :     # Get the first (and only) object.
277 :     my $retVal = $query->Fetch();
278 :     # Return the result.
279 :     return $retVal;
280 :     }
281 :    
282 :     =head3 GetEntityValues
283 :    
284 :     C<< my @values = GetEntityValues($entityType, $ID, \@fields); >>
285 :    
286 :     Return a list of values from a specified entity instance.
287 :    
288 :     =over 4
289 :    
290 :     =item entityType
291 :    
292 :     Entity type name.
293 :    
294 :     =item ID
295 :    
296 :     ID of the desired entity.
297 :    
298 :     =item fields
299 :    
300 :     List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.
301 :    
302 :     =item RETURN
303 :    
304 :     Returns a flattened list of the values of the specified fields for the specified entity.
305 :    
306 :     =back
307 :    
308 :     =cut
309 : parrello 1.3 #: Return Type @;
310 : parrello 1.1 sub GetEntityValues {
311 :     # Get the parameters.
312 :     my $self = shift @_;
313 :     my ($entityType, $ID, $fields) = @_;
314 :     # Get the specified entity.
315 :     my $entity = $self->GetEntity($entityType, $ID);
316 :     # Declare the return list.
317 :     my @retVal = ();
318 :     # If we found the entity, push the values into the return list.
319 :     if ($entity) {
320 :     push @retVal, $entity->Values($fields);
321 :     }
322 :     # Return the result.
323 :     return @retVal;
324 :     }
325 :    
326 :     =head3 ShowMetaData
327 :    
328 :     C<< $sprout->ShowMetaData($fileName); >>
329 :    
330 :     This method outputs a description of the database to an HTML file in the data directory.
331 :    
332 :     =over 4
333 :    
334 :     =item fileName
335 :    
336 :     Fully-qualified name to give to the output file.
337 :    
338 :     =back
339 :    
340 :     =cut
341 :    
342 :     sub ShowMetaData {
343 :     # Get the parameters.
344 :     my $self = shift @_;
345 :     my ($fileName) = @_;
346 :     # Compute the file name.
347 :     my $options = $self->{_options};
348 :     # Call the show method on the underlying ERDB object.
349 :     $self->{_erdb}->ShowMetaData($fileName);
350 :     }
351 :    
352 :     =head3 Load
353 :    
354 :     C<< $sprout->Load($rebuild); >>;
355 :    
356 :     Load the database from files in the data directory, optionally re-creating the tables.
357 :    
358 :     This method always deletes the data from the database before loading, even if the tables are not
359 :     re-created. The data is loaded into the relations from files in the data directory either having the
360 :     same name as the target relation with no extension or with an extension of C<.dtx>. Files without an
361 :     extension are used in preference to the files with an extension.
362 :    
363 :     The files are loaded based on the presumption that each line of the file is a record in the
364 :     relation, and the individual fields are delimited by tabs. Tab and new-line characters inside
365 :     fields must be represented by the escape sequences C<\t> and C<\n>, respectively. The fields must
366 :     be presented in the order given in the relation tables produced by the L</ShowMetaData> method.
367 :    
368 :     =over 4
369 :    
370 :     =item rebuild
371 :    
372 :     TRUE if the data tables need to be created or re-created, else FALSE
373 :    
374 :     =item RETURN
375 :    
376 :     Returns a statistical object containing the number of records read, the number of duplicates found,
377 :     the number of errors, and a list of the error messages.
378 :    
379 :     =back
380 :    
381 :     =cut
382 : parrello 1.3 #: Return Type %;
383 : parrello 1.1 sub Load {
384 :     # Get the parameters.
385 :     my $self = shift @_;
386 :     my ($rebuild) = @_;
387 :     # Get the database object.
388 :     my $erdb = $self->{_erdb};
389 :     # Load the tables from the data directory.
390 :     my $retVal = $erdb->LoadTables($self->{_options}->{dataDir}, $rebuild);
391 :     # Return the statistics.
392 :     return $retVal;
393 :     }
394 :    
395 :     =head3 LoadUpdate
396 :    
397 :     C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
398 :    
399 :     Load updates to one or more database tables. This method enables the client to make changes to one
400 :     or two tables without reloading the whole database. For each table, there must be a corresponding
401 :     file in the data directory, either with the same name as the table, or with a C<.dtx> suffix. So,
402 :     for example, to make updates to the B<FeatureTranslation> relation, there must be a
403 :     C<FeatureTranslation.dtx> file in the data directory. Unlike a full load, files without an extension
404 :     are not examined. This allows update files to co-exist with files from an original load.
405 :    
406 :     =over 4
407 :    
408 :     =item truncateFlag
409 :    
410 :     TRUE if the tables should be rebuilt before loading, else FALSE. A value of TRUE therefore causes
411 :     current data and schema of the tables to be replaced, while a value of FALSE means the new data
412 :     is added to the existing data in the various relations.
413 :    
414 :     =item tableList
415 :    
416 :     List of the tables to be updated.
417 :    
418 :     =item RETURN
419 :    
420 :     Returns a statistical object containing the number of records read, the number of duplicates found,
421 :     the number of errors encountered, and a list of error messages.
422 :    
423 :     =back
424 :    
425 :     =cut
426 : parrello 1.3 #: Return Type %;
427 : parrello 1.1 sub LoadUpdate {
428 :     # Get the parameters.
429 :     my $self = shift @_;
430 :     my ($truncateFlag, $tableList) = @_;
431 :     # Get the database object.
432 :     my $erdb = $self->{_erdb};
433 :     # Declare the return value.
434 :     my $retVal = Stats->new();
435 :     # Get the data directory.
436 :     my $optionTable = $self->{_options};
437 :     my $dataDir = $optionTable->{dataDir};
438 :     # Loop through the incoming table names.
439 :     for my $tableName (@{$tableList}) {
440 :     # Find the table's file.
441 :     my $fileName = "$dataDir/$tableName";
442 :     if (! -e $fileName) {
443 :     $fileName = "$fileName.dtx";
444 :     }
445 :     # Attempt to load this table.
446 :     my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);
447 :     # Accumulate the resulting statistics.
448 :     $retVal->Accumulate($result);
449 :     }
450 :     # Return the statistics.
451 :     return $retVal;
452 :     }
453 :    
454 :     =head3 Build
455 :    
456 :     C<< $sprout->Build(); >>
457 :    
458 :     Build the database. The database will be cleared and the tables re-created from the metadata.
459 :     This method is useful when a database is brand new or when the database definition has
460 :     changed.
461 :    
462 :     =cut
463 : parrello 1.3 #: Return Type ;
464 : parrello 1.1 sub Build {
465 :     # Get the parameters.
466 :     my $self = shift @_;
467 :     # Create the tables.
468 :     $self->{_erdb}->CreateTables;
469 :     }
470 :    
471 :     =head3 Genomes
472 :    
473 :     C<< my @genomes = $sprout->Genomes(); >>
474 :    
475 :     Return a list of all the genome IDs.
476 :    
477 :     =cut
478 : parrello 1.3 #: Return Type @;
479 : parrello 1.1 sub Genomes {
480 :     # Get the parameters.
481 :     my $self = shift @_;
482 :     # Get all the genomes.
483 :     my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');
484 :     # Return the list of IDs.
485 :     return @retVal;
486 :     }
487 :    
488 :     =head3 GenusSpecies
489 :    
490 :     C<< my $infoString = $sprout->GenusSpecies($genomeID); >>
491 :    
492 :     Return the genus, species, and unique characterization for a genome.
493 :    
494 :     =over 4
495 :    
496 :     =item genomeID
497 :    
498 :     ID of the genome whose genus and species is desired
499 :    
500 :     =item RETURN
501 :    
502 :     Returns the genus and species of the genome, with the unique characterization (if any). If the genome
503 :     does not exist, returns an undefined value.
504 :    
505 :     =back
506 :    
507 :     =cut
508 : parrello 1.3 #: Return Type $;
509 : parrello 1.1 sub GenusSpecies {
510 :     # Get the parameters.
511 :     my $self = shift @_;
512 :     my ($genomeID) = @_;
513 :     # Get the data for the specified genome.
514 :     my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',
515 :     'Genome(unique-characterization)']);
516 :     # Format the result and return it.
517 :     my $retVal = join(' ', @values);
518 :     return $retVal;
519 :     }
520 :    
521 :     =head3 FeaturesOf
522 :    
523 :     C<< my @features = $sprout->FeaturesOf($genomeID, $ftype); >>
524 :    
525 :     Return a list of the features relevant to a specified genome.
526 :    
527 :     =over 4
528 :    
529 :     =item genomeID
530 :    
531 :     Genome whose features are desired.
532 :    
533 :     =item ftype
534 :    
535 :     Type of feature desired. If omitted, all features will be returned.
536 :    
537 :     =item RETURN
538 :    
539 :     Returns a list of the feature IDs for features relevant to the genome. If the genome does not exist,
540 :     will return an empty list.
541 :    
542 :     =back
543 :    
544 :     =cut
545 : parrello 1.3 #: Return Type @;
546 : parrello 1.1 sub FeaturesOf {
547 :     # Get the parameters.
548 :     my $self = shift @_;
549 :     my ($genomeID,$ftype) = @_;
550 :     # Get the features we want.
551 :     my @features;
552 :     if (!$ftype) {
553 :     @features = $self->GetFlat(['HasContig', 'IsLocatedIn'], "HasContig(from-link) = ?",
554 :     [$genomeID], 'IsLocatedIn(from-link)');
555 :     } else {
556 :     @features = $self->GetFlat(['HasContig', 'IsLocatedIn', 'Feature'],
557 :     "HasContig(from-link) = ? AND Feature(feature-type) = ?",
558 :     [$genomeID, $ftype], 'IsLocatedIn(from-link)');
559 :     }
560 :     # Return the list with duplicates merged out. We need to merge out duplicates because
561 :     # a feature will appear twice if it spans more than one contig.
562 :     my @retVal = Tracer::Merge(@features);
563 :     # Return the list of feature IDs.
564 :     return @retVal;
565 :     }
566 :    
567 :     =head3 FeatureLocation
568 :    
569 :     C<< my @locations = $sprout->FeatureLocation($featureID); >>
570 :    
571 :     Return the location of a feature in its genome's contig segments. In a list context, this method
572 :     will return a list of the locations. In a scalar context, it will return the locations as a space-
573 :     delimited string. Each location will be of the form I<contigID>C<_>I<begin>I<dir>I<len> where
574 :     I<begin> is the starting position, I<dir> is C<+> for a forward transcription or C<-> for a backward
575 :     transcription, and I<len> is the length. So, for example, C<1999.1_NC123_4000+200> describes a location
576 :     beginning at position 4000 of contig C<1999.1_NC123> and ending at position 4199. Similarly,
577 :     C<1999.1_NC123_2000-400> describes a location in the same contig starting at position 2000 and ending
578 :     at position 1601.
579 :    
580 :     This process is complicated by the fact that we automatically split up feature segments longer than
581 :     the maximum segment length. When we find two segments that are adjacent to each other, we must
582 :     put them back together.
583 :    
584 :     =over 4
585 :    
586 :     =item featureID
587 :    
588 :     FIG ID of the desired feature
589 :    
590 :     =item RETURN
591 :    
592 :     Returns a list of the feature's contig segments. The locations are returned as a list in a list
593 :     context and as a space-delimited string in a scalar context.
594 :    
595 :     =back
596 :    
597 :     =cut
598 : parrello 1.3 #: Return Type @;
599 :     #: Return Type $;
600 : parrello 1.1 sub FeatureLocation {
601 :     # Get the parameters.
602 :     my $self = shift @_;
603 :     my ($featureID) = @_;
604 :     # Create a query for the feature locations.
605 :     my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",
606 :     [$featureID]);
607 :     # Create the return list.
608 :     my @retVal = ();
609 :     # Set up the variables used to determine if we have adjacent segments. This initial setup will
610 :     # not match anything.
611 :     my ($prevContig, $prevBeg, $prevDir, $prevLen) = ("", 0, "0", 0);
612 :     # Loop through the query results, creating location specifiers.
613 :     while (my $location = $query->Fetch()) {
614 :     # Get the location parameters.
615 :     my ($contigID, $beg, $dir, $len) = $location->Values(['IsLocatedIn(to-link)',
616 :     'IsLocatedIn(beg)', 'IsLocatedIn(dir)', 'IsLocatedIn(len)']);
617 :     # Check to see if we are adjacent to the previous segment.
618 :     if ($prevContig eq $contigID && $dir eq $prevDir) {
619 :     # Here the new segment is in the same direction on the same contig. Insure the
620 :     # new segment's beginning is next to the old segment's end.
621 :     if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||
622 :     ($dir eq "+" && $beg == $prevBeg + $prevLen)) {
623 :     # Here we need to merge two segments. Adjust the beginning and length values
624 :     # to include both segments.
625 :     $beg = $prevBeg;
626 :     $len += $prevLen;
627 :     # Pop the old segment off. The new one will replace it later.
628 :     pop @retVal;
629 :     }
630 :     }
631 :     # Remember this specifier for the adjacent-segment test the next time through.
632 :     ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
633 :     # Add the specifier to the list.
634 :     push @retVal, "${contigID}_$beg$dir$len";
635 :     }
636 :     # Return the list in the format indicated by the context.
637 :     return (wantarray ? @retVal : join(' ', @retVal));
638 :     }
639 :    
640 :     =head3 ParseLocation
641 :    
642 :     C<< my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location); >>
643 :    
644 :     Split a location specifier into the contig ID, the starting point, the direction, and the
645 :     length.
646 :    
647 :     =over 4
648 :    
649 :     =item location
650 :    
651 :     A location specifier (see L</FeatureLocation> for a description).
652 :    
653 :     =item RETURN
654 :    
655 :     Returns a list containing the contig ID, the start position, the direction (C<+> or C<->),
656 :     and the length indicated by the incoming location specifier.
657 :    
658 :     =back
659 :    
660 :     =cut
661 : parrello 1.3 #: Return Type @;
662 : parrello 1.1 sub ParseLocation {
663 :     # Get the parameter.
664 :     my ($location) = @_;
665 :     # Parse it into segments.
666 :     $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;
667 :     my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
668 :     # If the direction is an underscore, convert it to a + or -.
669 :     if ($dir eq "_") {
670 :     if ($start < $len) {
671 :     $dir = "+";
672 :     $len = $len - $start + 1;
673 :     } else {
674 :     $dir = "-";
675 :     $len = $start - $len + 1;
676 :     }
677 :     }
678 :     # Return the result.
679 :     return ($contigID, $start, $dir, $len);
680 :     }
681 :    
682 :     =head3 DNASeq
683 :    
684 :     C<< my $sequence = $sprout->DNASeq(\@locationList); >>
685 :    
686 :     This method returns the DNA sequence represented by a list of locations. The list of locations
687 : parrello 1.2 should be of the form returned by L</featureLocation> when in a list context. In other words,
688 : parrello 1.1 each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.
689 :    
690 :     =over 4
691 :    
692 :     =item locationList
693 :    
694 :     List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<end> (see
695 :     L</FeatureLocation> for more about this format).
696 :    
697 :     =item RETURN
698 :    
699 :     Returns a string of nucleotides corresponding to the DNA segments in the location list.
700 :    
701 :     =back
702 :    
703 :     =cut
704 : parrello 1.3 #: Return Type $;
705 : parrello 1.1 sub DNASeq {
706 :     # Get the parameters.
707 :     my $self = shift @_;
708 :     my ($locationList) = @_;
709 :     # Create the return string.
710 :     my $retVal = "";
711 :     # Loop through the locations.
712 :     for my $location (@{$locationList}) {
713 :     # Set up a variable to contain the DNA at this location.
714 :     my $locationDNA = "";
715 :     # Parse out the contig ID, the beginning point, the direction, and the end point.
716 :     my ($contigID, $beg, $dir, $len) = ParseLocation($location);
717 :     # Now we must create a query to return all the sequences in the contig relevant to the region
718 :     # specified. First, we compute the start and stop points when reading through the sequences.
719 :     # For a forward transcription, the start point is the beginning; for a backward transcription,
720 :     # the start point is the ending. Note that in the latter case we must reverse the DNA string
721 :     # before putting it in the return value.
722 :     my ($start, $stop);
723 :     if ($dir eq "+") {
724 :     $start = $beg;
725 :     $stop = $beg + $len - 1;
726 :     } else {
727 :     $start = $beg + $len + 1;
728 :     $stop = $beg;
729 :     }
730 :     my $query = $self->Get(['IsMadeUpOf','Sequence'],
731 :     "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
732 :     " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
733 :     [$contigID, $start, $stop]);
734 :     # Loop through the sequences.
735 :     while (my $sequence = $query->Fetch()) {
736 :     # Determine whether the location starts, stops, or continues through this sequence.
737 :     my ($startPosition, $sequenceData, $sequenceLength) =
738 :     $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
739 :     'IsMadeUpOf(len)']);
740 :     my $stopPosition = $startPosition + $sequenceLength;
741 :     # Figure out the start point and length of the relevant section.
742 :     my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
743 :     my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;
744 :     # Add the relevant data to the location data.
745 :     $locationDNA .= substr($sequenceData, $pos1, $len);
746 :     }
747 :     # Add this location's data to the return string. Note that we may need to reverse it.
748 :     if ($dir eq '+') {
749 :     $retVal .= $locationDNA;
750 :     } else {
751 :     $locationDNA = join('', reverse split //, $locationDNA);
752 :     $retVal .= $locationDNA;
753 :     }
754 :     }
755 :     # Return the result.
756 :     return $retVal;
757 :     }
758 :    
759 :     =head3 AllContigs
760 :    
761 :     C<< my @idList = $sprout->AllContigs($genomeID); >>
762 :    
763 :     Return a list of all the contigs for a genome.
764 :    
765 :     =over 4
766 :    
767 :     =item genomeID
768 :    
769 :     Genome whose contigs are desired.
770 :    
771 :     =item RETURN
772 :    
773 :     Returns a list of the IDs for the genome's contigs.
774 :    
775 :     =back
776 :    
777 :     =cut
778 : parrello 1.3 #: Return Type @;
779 : parrello 1.1 sub AllContigs {
780 :     # Get the parameters.
781 :     my $self = shift @_;
782 :     my ($genomeID) = @_;
783 :     # Ask for the genome's Contigs.
784 :     my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],
785 :     'HasContig(to-link)');
786 :     # Return the list of Contigs.
787 :     return @retVal;
788 :     }
789 :    
790 :     =head3 ContigLength
791 :    
792 :     C<< my $length = $sprout->ContigLength($contigID); >>
793 :    
794 :     Compute the length of a contig.
795 :    
796 :     =over 4
797 :    
798 :     =item contigID
799 :    
800 :     ID of the contig whose length is desired.
801 :    
802 : parrello 1.3 =item RETURN
803 :    
804 :     Returns the number of positions in the contig.
805 :    
806 : parrello 1.1 =back
807 :    
808 :     =cut
809 : parrello 1.3 #: Return Type $;
810 : parrello 1.1 sub ContigLength {
811 :     # Get the parameters.
812 :     my $self = shift @_;
813 :     my ($contigID) = @_;
814 :     # Get the contig's last sequence.
815 :     my $query = $self->Get(['IsMadeUpOf'],
816 :     "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
817 :     [$contigID]);
818 :     my $sequence = $query->Fetch();
819 :     # Declare the return value.
820 :     my $retVal = 0;
821 :     # Set it from the sequence data, if any.
822 :     if ($sequence) {
823 :     my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
824 :     $retVal = $start + $len;
825 :     }
826 :     # Return the result.
827 :     return $retVal;
828 :     }
829 :    
830 :     =head3 GenesInRegion
831 :    
832 :     C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>
833 :    
834 :     List the features which overlap a specified region in a contig.
835 :    
836 :     =over 4
837 :    
838 :     =item contigID
839 :    
840 :     ID of the contig containing the region of interest.
841 :    
842 :     =item start
843 :    
844 :     Offset of the first residue in the region of interest.
845 :    
846 :     =item stop
847 :    
848 :     Offset of the last residue in the region of interest.
849 :    
850 :     =item RETURN
851 :    
852 :     Returns a three-element list. The first element is a list of feature IDs for the features that
853 :     overlap the region of interest. The second and third elements are the minimum and maximum
854 :     locations of the features provided on the specified contig. These may extend outside
855 :     the start and stop values.
856 :    
857 :     =back
858 :    
859 :     =cut
860 : parrello 1.3 #: Return Type @;
861 : parrello 1.1 sub GenesInRegion {
862 :     # Get the parameters.
863 :     my $self = shift @_;
864 :     my ($contigID, $start, $stop) = @_;
865 :     # Get the maximum segment length.
866 :     my $maximumSegmentLength = $self->MaxSegment;
867 :     # Create a hash to receive the feature list. We use a hash so that we can eliminate
868 :     # duplicates easily.
869 :     my %featuresFound = ();
870 :     # Prime the values we'll use for the returned beginning and end.
871 :     my ($min, $max) = ($self->ContigLength($contigID), 0);
872 :     # Create a table of parameters for each query. Each query looks for features travelling in
873 :     # a particular direction. The query parameters include the contig ID, the feature direction,
874 :     # the lowest possible start position, and the highest possible start position. This works
875 :     # because each feature segment length must be no greater than the maximum segment length.
876 :     my %queryParms = (forward => [$contigID, '+', $start - $maximumSegmentLength + 1, $stop],
877 :     reverse => [$contigID, '-', $start, $stop + $maximumSegmentLength - 1]);
878 :     # Loop through the query parameters.
879 :     for my $parms (values %queryParms) {
880 :     # Create the query.
881 :     my $query = $self->Get(['IsLocatedIn'],
882 :     "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
883 :     $parms);
884 :     # Loop through the feature segments found.
885 :     while (my $segment = $query->Fetch) {
886 :     # Get the data about this segment.
887 :     my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',
888 :     'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);
889 :     # Determine if this feature actually overlaps the region. The query insures that
890 :     # this will be the case if the segment is the maximum length, so to fine-tune
891 :     # the results we insure that the inequality from the query holds using the actual
892 :     # length.
893 :     my ($found, $end) = (0, 0);
894 :     if ($dir eq '+') {
895 :     $end = $beg + $len;
896 :     if ($end >= $start) {
897 :     # Denote we found a useful feature.
898 :     $found = 1;
899 :     }
900 :     } elsif ($dir eq '-') {
901 :     $end = $beg - $len;
902 :     if ($end <= $stop) {
903 :     # Denote we found a useful feature.
904 :     $found = 1;
905 :     }
906 :     }
907 :     if ($found) {
908 :     # Here we need to record the feature and update the minimum and maximum.
909 :     $featuresFound{$featureID} = 1;
910 :     if ($beg < $min) { $min = $beg; }
911 :     if ($end < $min) { $min = $end; }
912 :     if ($beg > $max) { $max = $beg; }
913 :     if ($end > $max) { $max = $end; }
914 :     }
915 :     }
916 :     }
917 :     # Compute a list of the IDs for the features found.
918 :     my @list = (sort (keys %featuresFound));
919 :     # Return it along with the min and max.
920 :     return (\@list, $min, $max);
921 :     }
922 :    
923 :     =head3 FType
924 :    
925 :     C<< my $ftype = $sprout->FType($featureID); >>
926 :    
927 :     Return the type of a feature.
928 :    
929 :     =over 4
930 :    
931 :     =item featureID
932 :    
933 :     ID of the feature whose type is desired.
934 :    
935 :     =item RETURN
936 :    
937 :     A string indicating the type of feature (e.g. peg, rna). If the feature does not exist, returns an
938 :     undefined value.
939 :    
940 :     =back
941 :    
942 :     =cut
943 : parrello 1.3 #: Return Type $;
944 : parrello 1.1 sub FType {
945 :     # Get the parameters.
946 :     my $self = shift @_;
947 :     my ($featureID) = @_;
948 :     # Get the specified feature's type.
949 :     my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
950 :     # Return the result.
951 :     return $retVal;
952 :     }
953 :    
954 :     =head3 FeatureAnnotations
955 :    
956 :     C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>
957 :    
958 :     Return the annotations of a feature.
959 :    
960 :     =over 4
961 :    
962 :     =item featureID
963 :    
964 :     ID of the feature whose annotations are desired.
965 :    
966 :     =item RETURN
967 :    
968 :     Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.
969 :    
970 :     * B<featureID> ID of the relevant feature.
971 :    
972 : parrello 1.3 * B<timeStamp> time the annotation was made, in user-friendly format.
973 : parrello 1.1
974 :     * B<user> ID of the user who made the annotation
975 :    
976 :     * B<text> text of the annotation.
977 :    
978 :     =back
979 :    
980 :     =cut
981 : parrello 1.3 #: Return Type @%;
982 : parrello 1.1 sub FeatureAnnotations {
983 :     # Get the parameters.
984 :     my $self = shift @_;
985 :     my ($featureID) = @_;
986 :     # Create a query to get the feature's annotations and the associated users.
987 :     my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
988 :     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
989 :     # Create the return list.
990 :     my @retVal = ();
991 :     # Loop through the annotations.
992 :     while (my $annotation = $query->Fetch) {
993 :     # Get the fields to return.
994 :     my ($featureID, $timeStamp, $user, $text) =
995 :     $annotation->Values(['IsTargetOfAnnotation(from-link)',
996 :     'Annotation(time)', 'MadeAnnotation(from-link)',
997 :     'Annotation(annotation)']);
998 :     # Assemble them into a hash.
999 : parrello 1.3 my $annotationHash = { featureID => $featureID,
1000 :     timeStamp => FriendlyTimestamp($timeStamp),
1001 : parrello 1.1 user => $user, text => $text };
1002 :     # Add it to the return list.
1003 :     push @retVal, $annotationHash;
1004 :     }
1005 :     # Return the result list.
1006 :     return @retVal;
1007 :     }
1008 :    
1009 :     =head3 AllFunctionsOf
1010 :    
1011 :     C<< my %functions = $sprout->AllFunctionsOf($featureID); >>
1012 :    
1013 :     Return all of the functional assignments for a particular feature. The data is returned as a
1014 :     hash of functional assignments to user IDs. A functional assignment is a type of annotation.
1015 :     It has the format "XXXX\nset XXXX function to\nYYYYY". In this instance, XXXX is the user ID
1016 :     and YYYYY is the functional assignment text. Its worth noting that we cannot filter on the content
1017 :     of the annotation itself because it's a text field; however, this is not a big problem because most
1018 : parrello 1.5 features only have a small number of annotations. Finally, if a single user has multiple
1019 :     functional assignments, we will only keep the most recent one.
1020 : parrello 1.1
1021 :     =over 4
1022 :    
1023 :     =item featureID
1024 :    
1025 :     ID of the feature whose functional assignments are desired.
1026 :    
1027 : parrello 1.3 =item RETURN
1028 :    
1029 :     Returns a hash mapping the functional assignment IDs to user IDs.
1030 :    
1031 : parrello 1.1 =back
1032 :    
1033 :     =cut
1034 : parrello 1.3 #: Return Type %;
1035 : parrello 1.1 sub AllFunctionsOf {
1036 :     # Get the parameters.
1037 :     my $self = shift @_;
1038 :     my ($featureID) = @_;
1039 :     # Get all of the feature's annotations.
1040 : parrello 1.5 my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],
1041 : parrello 1.1 "IsTargetOfAnnotation(from-link) = ?",
1042 : parrello 1.5 [$featureID], ['Annotation(time)', 'Annotation(annotation)']);
1043 : parrello 1.1 # Declare the return hash.
1044 :     my %retVal;
1045 : parrello 1.5 # Declare a hash for insuring we only make one assignment per user.
1046 :     my %timeHash = ();
1047 :     # Now we sort the assignments by timestamp in reverse.
1048 :     my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1049 : parrello 1.1 # Loop until we run out of annotations.
1050 : parrello 1.5 for my $annotation (@sortedQuery) {
1051 :     # Get the annotation fields.
1052 :     my ($timeStamp, $text) = @{$annotation};
1053 : parrello 1.1 # Check to see if this is a functional assignment.
1054 :     my ($user, $function) = ParseAssignment($text);
1055 : parrello 1.5 if ($user && ! exists $timeHash{$user}) {
1056 :     # Here it is a functional assignment and there has been no
1057 :     # previous assignment for this user, so we stuff it in the
1058 :     # return hash.
1059 : parrello 1.1 $retVal{$function} = $user;
1060 : parrello 1.5 # Insure we don't assign to this user again.
1061 :     $timeHash{$user} = 1;
1062 : parrello 1.1 }
1063 :     }
1064 :     # Return the hash of assignments found.
1065 :     return %retVal;
1066 :     }
1067 :    
1068 :     =head3 FunctionOf
1069 :    
1070 :     C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>
1071 :    
1072 : parrello 1.3 Return the most recently-determined functional assignment of a particular feature.
1073 :    
1074 :     The functional assignment is handled differently depending on the type of feature. If
1075 :     the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1076 : parrello 1.1 assignment is a type of annotation. It has the format "XXXX\nset XXXX function to\nYYYYY". In this
1077 :     instance, XXXX is the user ID and YYYYY is the functional assignment text. Its worth noting that
1078 :     we cannot filter on the content of the annotation itself because it's a text field; however, this
1079 :     is not a big problem because most features only have a small number of annotations.
1080 :    
1081 : parrello 1.3 Each user has an associated list of trusted users. The assignment returned will be the most
1082 :     recent one by at least one of the trusted users. If no trusted user list is available, then
1083 :     the specified user and FIG are considered trusted. If the user ID is omitted, only FIG
1084 :     is trusted.
1085 :    
1086 :     If the feature is B<not> identified by a FIG ID, then the functional assignment
1087 :     information is taken from the B<ExternalAliasFunc> table. If the table does
1088 :     not contain an entry for the feature, an undefined value is returned.
1089 :    
1090 : parrello 1.1 =over 4
1091 :    
1092 :     =item featureID
1093 :    
1094 :     ID of the feature whose functional assignment is desired.
1095 :    
1096 :     =item userID (optional)
1097 :    
1098 : parrello 1.3 ID of the user whose function determination is desired. If omitted, only the latest
1099 :     C<FIG> assignment will be returned.
1100 : parrello 1.1
1101 :     =item RETURN
1102 :    
1103 :     Returns the text of the assigned function.
1104 :    
1105 :     =back
1106 :    
1107 :     =cut
1108 : parrello 1.3 #: Return Type $;
1109 : parrello 1.1 sub FunctionOf {
1110 :     # Get the parameters.
1111 :     my $self = shift @_;
1112 :     my ($featureID, $userID) = @_;
1113 : parrello 1.3 # Declare the return value.
1114 :     my $retVal;
1115 :     # Determine the ID type.
1116 :     if ($featureID =~ m/^fig\|/) {
1117 :     # Here we have a FIG feature ID. We must build the list of trusted
1118 :     # users.
1119 :     my %trusteeTable = ();
1120 :     # Check the user ID.
1121 :     if (!$userID) {
1122 :     # No user ID, so only FIG is trusted.
1123 :     $trusteeTable{FIG} = 1;
1124 :     } else {
1125 :     # Add this user's ID.
1126 :     $trusteeTable{$userID} = 1;
1127 :     # Look for the trusted users in the database.
1128 :     my @trustees = $self->GetFlat(['IsTrustedBy'], 'IsTrustedBy(from-link) = ?', [$userID], 'IsTrustedBy(to-link)');
1129 :     if (! @trustees) {
1130 :     # None were found, so build a default list.
1131 :     $trusteeTable{FIG} = 1;
1132 :     } else {
1133 :     # Otherwise, put all the trustees in.
1134 :     for my $trustee (@trustees) {
1135 :     $trusteeTable{$trustee} = 1;
1136 :     }
1137 :     }
1138 :     }
1139 :     # Build a query for all of the feature's annotations, sorted by date.
1140 :     my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],
1141 :     "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1142 :     [$featureID]);
1143 :     my $timeSelected = 0;
1144 :     # Loop until we run out of annotations.
1145 :     while (my $annotation = $query->Fetch()) {
1146 :     # Get the annotation text.
1147 :     my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);
1148 :     # Check to see if this is a functional assignment for a trusted user.
1149 :     my ($user, $type, $function) = split(/\n/, $text);
1150 :     if ($type =~ m/^set $user function to$/i) {
1151 :     # Here it is a functional assignment. Check the time and the user
1152 :     # name. The time must be recent and the user must be trusted.
1153 :     if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {
1154 :     $retVal = $function;
1155 :     $timeSelected = $time;
1156 :     }
1157 :     }
1158 :     }
1159 :     } else {
1160 :     # Here we have a non-FIG feature ID. In this case the user ID does not
1161 :     # matter. We simply get the information from the External Alias Function
1162 :     # table.
1163 : parrello 1.4 ($retVal) = $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']);
1164 : parrello 1.3 }
1165 : parrello 1.1 # Return the assignment found.
1166 :     return $retVal;
1167 :     }
1168 :    
1169 :     =head3 BBHList
1170 :    
1171 :     C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
1172 :    
1173 :     Return a hash mapping the features in a specified list to their bidirectional best hits
1174 :     on a specified target genome.
1175 :    
1176 :     =over 4
1177 :    
1178 :     =item genomeID
1179 :    
1180 :     ID of the genome from which the best hits should be taken.
1181 :    
1182 :     =item featureList
1183 :    
1184 :     List of the features whose best hits are desired.
1185 :    
1186 :     =item RETURN
1187 :    
1188 :     Returns a reference to a hash that maps the IDs of the incoming features to the IDs of
1189 :     their best hits.
1190 :    
1191 :     =back
1192 :    
1193 :     =cut
1194 : parrello 1.3 #: Return Type %;
1195 : parrello 1.1 sub BBHList {
1196 :     # Get the parameters.
1197 :     my $self = shift @_;
1198 :     my ($genomeID, $featureList) = @_;
1199 :     # Create the return structure.
1200 :     my %retVal = ();
1201 :     # Loop through the incoming features.
1202 :     for my $featureID (@{$featureList}) {
1203 :     # Create a query to get the feature's best hit.
1204 :     my $query = $self->Get(['IsBidirectionalBestHitOf'],
1205 :     "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",
1206 :     [$featureID, $genomeID]);
1207 :     # Look for the best hit.
1208 :     my $bbh = $query->Fetch;
1209 :     if ($bbh) {
1210 :     my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');
1211 :     $retVal{$featureID} = $targetFeature;
1212 :     }
1213 :     }
1214 :     # Return the mapping.
1215 :     return \%retVal;
1216 :     }
1217 :    
1218 :     =head3 FeatureAliases
1219 :    
1220 :     C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
1221 :    
1222 :     Return a list of the aliases for a specified feature.
1223 :    
1224 :     =over 4
1225 :    
1226 :     =item featureID
1227 :    
1228 :     ID of the feature whose aliases are desired.
1229 :    
1230 :     =item RETURN
1231 :    
1232 :     Returns a list of the feature's aliases. If the feature is not found or has no aliases, it will
1233 :     return an empty list.
1234 :    
1235 :     =back
1236 :    
1237 :     =cut
1238 : parrello 1.3 #: Return Type @;
1239 : parrello 1.1 sub FeatureAliases {
1240 :     # Get the parameters.
1241 :     my $self = shift @_;
1242 :     my ($featureID) = @_;
1243 :     # Get the desired feature's aliases
1244 :     my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);
1245 :     # Return the result.
1246 :     return @retVal;
1247 :     }
1248 :    
1249 :     =head3 GenomeOf
1250 :    
1251 :     C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1252 :    
1253 :     Return the genome that contains a specified feature.
1254 :    
1255 :     =over 4
1256 :    
1257 :     =item featureID
1258 :    
1259 :     ID of the feature whose genome is desired.
1260 :    
1261 :     =item RETURN
1262 :    
1263 :     Returns the ID of the genome for the specified feature. If the feature is not found, returns
1264 :     an undefined value.
1265 :    
1266 :     =back
1267 :    
1268 :     =cut
1269 : parrello 1.3 #: Return Type $;
1270 : parrello 1.1 sub GenomeOf {
1271 :     # Get the parameters.
1272 :     my $self = shift @_;
1273 :     my ($featureID) = @_;
1274 :     # Create a query to find the genome associated with the feature.
1275 :     my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);
1276 :     # Declare the return value.
1277 :     my $retVal;
1278 :     # Get the genome ID.
1279 :     if (my $relationship = $query->Fetch()) {
1280 :     ($retVal) = $relationship->Value('HasContig(from-link)');
1281 :     }
1282 :     # Return the value found.
1283 :     return $retVal;
1284 :     }
1285 :    
1286 :     =head3 CoupledFeatures
1287 :    
1288 :     C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >>
1289 :    
1290 :     Return the features functionally coupled with a specified feature. Features are considered
1291 :     functionally coupled if they tend to be clustered on the same chromosome.
1292 :    
1293 :     =over 4
1294 :    
1295 :     =item featureID
1296 :    
1297 :     ID of the feature whose functionally-coupled brethren are desired.
1298 :    
1299 :     =item RETURN
1300 :    
1301 :     A hash mapping the functionally-coupled feature IDs to the coupling score.
1302 :    
1303 :     =back
1304 :    
1305 :     =cut
1306 : parrello 1.3 #: Return Type %;
1307 : parrello 1.1 sub CoupledFeatures {
1308 :     # Get the parameters.
1309 :     my $self = shift @_;
1310 :     my ($featureID) = @_;
1311 :     # Create a query to retrieve the functionally-coupled features. Note that we depend on the
1312 :     # fact that the functional coupling is physically paired. If (A,B) is in the database, then
1313 :     # (B,A) will also be found.
1314 :     my $query = $self->Get(['IsClusteredOnChromosomeWith'],
1315 :     "IsClusteredOnChromosomeWith(from-link) = ?", [$featureID]);
1316 :     # This value will be set to TRUE if we find at least one coupled feature.
1317 :     my $found = 0;
1318 :     # Create the return hash.
1319 :     my %retVal = ();
1320 :     # Retrieve the relationship records and store them in the hash.
1321 :     while (my $clustering = $query->Fetch()) {
1322 :     my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',
1323 :     'IsClusteredOnChromosomeWith(score)']);
1324 :     $retVal{$otherFeatureID} = $score;
1325 :     $found = 1;
1326 :     }
1327 :     # Functional coupling is reflexive. If we found at least one coupled feature, we must add
1328 :     # the incoming feature as well.
1329 :     if ($found) {
1330 :     $retVal{$featureID} = 9999;
1331 :     }
1332 :     # Return the hash.
1333 :     return %retVal;
1334 :     }
1335 :    
1336 :     =head3 GetEntityTypes
1337 :    
1338 :     C<< my @entityList = $sprout->GetEntityTypes(); >>
1339 :    
1340 :     Return the list of supported entity types.
1341 :    
1342 :     =cut
1343 : parrello 1.3 #: Return Type @;
1344 : parrello 1.1 sub GetEntityTypes {
1345 :     # Get the parameters.
1346 :     my $self = shift @_;
1347 :     # Get the underlying database object.
1348 :     my $erdb = $self->{_erdb};
1349 :     # Get its entity type list.
1350 :     my @retVal = $erdb->GetEntityTypes();
1351 :     }
1352 :    
1353 :     =head3 ReadFasta
1354 :    
1355 :     C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>
1356 :    
1357 :     Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by
1358 :     one or more lines of data. The first line begins with a > character and contains an ID.
1359 :     The remaining lines contain the sequence data in order.
1360 :    
1361 :     =over 4
1362 :    
1363 :     =item fileName
1364 :    
1365 :     Name of the FASTA file.
1366 :    
1367 :     =item prefix (optional)
1368 :    
1369 :     Prefix to be put in front of each ID found.
1370 :    
1371 :     =item RETURN
1372 :    
1373 :     Returns a hash that maps each ID to its sequence.
1374 :    
1375 :     =back
1376 :    
1377 :     =cut
1378 : parrello 1.3 #: Return Type %;
1379 : parrello 1.1 sub ReadFasta {
1380 :     # Get the parameters.
1381 :     my ($fileName, $prefix) = @_;
1382 :     # Create the return hash.
1383 :     my %retVal = ();
1384 :     # Open the file for input.
1385 :     open FASTAFILE, '<', $fileName;
1386 :     # Declare the ID variable and clear the sequence accumulator.
1387 :     my $sequence = "";
1388 :     my $id = "";
1389 :     # Loop through the file.
1390 :     while (<FASTAFILE>) {
1391 :     # Get the current line.
1392 :     my $line = $_;
1393 :     # Check for a header line.
1394 :     if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1395 :     # Here we have a new header. Store the current sequence if we have one.
1396 :     if ($id) {
1397 :     $retVal{$id} = $sequence;
1398 :     }
1399 :     # Clear the sequence accumulator and save the new ID.
1400 :     ($id, $sequence) = ("$prefix$1", "");
1401 :     } else {
1402 :     # Here we have a data line, so we add it to the sequence accumulator.
1403 :     # First, we get the actual data out.
1404 :     $line =~ /^\s*(.*?)(\s|\n)/;
1405 :     $sequence .= $1;
1406 :     }
1407 :     }
1408 :     # Flush out the last sequence (if any).
1409 :     if ($sequence) {
1410 :     $retVal {$id} = $sequence;
1411 :     }
1412 :     # Return the hash constructed from the file.
1413 :     return %retVal;
1414 :     }
1415 :    
1416 :     =head3 FormatLocations
1417 :    
1418 :     C<< my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat); >>
1419 :    
1420 :     Insure that a list of feature locations is in the Sprout format. The Sprout feature location
1421 :     format is I<contig>_I<beg*len> where I<*> is C<+> for a forward gene and C<-> for a backward
1422 :     gene. The old format is I<contig>_I<beg>_I<end>.
1423 :    
1424 :     =over 4
1425 :    
1426 :     =item prefix
1427 :    
1428 :     Prefix to be put in front of each contig ID (or an empty string if the contig ID should not
1429 :     be changed.
1430 :    
1431 :     =item locations
1432 :    
1433 :     List of locations to be normalized.
1434 :    
1435 :     =item oldFormat
1436 :    
1437 :     TRUE to convert the locations to the old format, else FALSE
1438 :    
1439 :     =item RETURN
1440 :    
1441 :     Returns a list of updated location descriptors.
1442 :    
1443 :     =back
1444 :    
1445 :     =cut
1446 : parrello 1.3 #: Return Type @;
1447 : parrello 1.1 sub FormatLocations {
1448 :     # Get the parameters.
1449 :     my $self = shift @_;
1450 :     my ($prefix, $locations, $oldFormat) = @_;
1451 :     # Create the return list.
1452 :     my @retVal = ();
1453 :     # Check to see if any locations were passed in.
1454 :     if ($locations eq '') {
1455 :     confess "No locations specified.";
1456 :     } else {
1457 :     # Loop through the locations, converting them to the new format.
1458 :     for my $location (@{$locations}) {
1459 :     # Parse the location elements.
1460 :     my ($contig, $beg, $dir, $len) = ParseLocation($location);
1461 :     # Process according to the desired output format.
1462 :     if (!$oldFormat) {
1463 :     # Here we're producing the new format. Add the location to the return list.
1464 :     push @retVal, "$prefix${contig}_$beg$dir$len";
1465 :     } elsif ($dir eq '+') {
1466 :     # Here we're producing the old format and it's a forward gene.
1467 :     my $end = $beg + $len - 1;
1468 :     push @retVal, "$prefix${contig}_${beg}_$end";
1469 :     } else {
1470 :     # Here we're producting the old format and it's a backward gene.
1471 :     my $end = $beg - $len + 1;
1472 :     push @retVal, "$prefix${contig}_${beg}_$end";
1473 :     }
1474 :     }
1475 :     }
1476 :     # Return the normalized list.
1477 :     return @retVal;
1478 :     }
1479 :    
1480 :     =head3 DumpData
1481 :    
1482 :     C<< $sprout->DumpData(); >>
1483 :    
1484 :     Dump all the tables to tab-delimited DTX files. The files will be stored in the data directory.
1485 :    
1486 :     =cut
1487 :    
1488 :     sub DumpData {
1489 :     # Get the parameters.
1490 :     my $self = shift @_;
1491 :     # Get the data directory name.
1492 :     my $outputDirectory = $self->{_options}->{dataDir};
1493 :     # Dump the relations.
1494 :     $self->{_erdb}->DumpRelations($outputDirectory);
1495 :     }
1496 :    
1497 :     =head3 XMLFileName
1498 :    
1499 :     C<< my $fileName = $sprout->XMLFileName(); >>
1500 :    
1501 :     Return the name of this database's XML definition file.
1502 :    
1503 :     =cut
1504 : parrello 1.3 #: Return Type $;
1505 : parrello 1.1 sub XMLFileName {
1506 :     my $self = shift @_;
1507 :     return $self->{_xmlName};
1508 :     }
1509 :    
1510 :     =head3 Insert
1511 :    
1512 :     C<< $sprout->Insert($objectType, \%fieldHash); >>
1513 :    
1514 :     Insert an entity or relationship instance into the database. The entity or relationship of interest
1515 :     is defined by a type name and then a hash of field names to values. Field values in the primary
1516 :     relation are represented by scalars. (Note that for relationships, the primary relation is
1517 :     the B<only> relation.) Field values for the other relations comprising the entity are always
1518 :     list references. For example, the following line inserts an inactive PEG feature named
1519 :     C<fig|188.1.peg.1> with aliases C<ZP_00210270.1> and C<gi|46206278>.
1520 :    
1521 :     C<< $sprout->Insert('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >>
1522 :    
1523 :     The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
1524 :     property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
1525 :    
1526 :     C<< $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence = 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>
1527 :    
1528 :     =over 4
1529 :    
1530 :     =item newObjectType
1531 :    
1532 :     Type name of the entity or relationship to insert.
1533 :    
1534 :     =item fieldHash
1535 :    
1536 :     Hash of field names to values.
1537 :    
1538 :     =back
1539 :    
1540 :     =cut
1541 : parrello 1.3 #: Return Type ;
1542 : parrello 1.1 sub Insert {
1543 :     # Get the parameters.
1544 :     my $self = shift @_;
1545 :     my ($objectType, $fieldHash) = @_;
1546 :     # Call the underlying method.
1547 :     $self->{_erdb}->InsertObject($objectType, $fieldHash);
1548 :     }
1549 :    
1550 :     =head3 Annotate
1551 :    
1552 :     C<< my $ok = $sprout->Annotate($fid, $timestamp, $user, $text); >>
1553 :    
1554 :     Annotate a feature. This inserts an Annotation record into the database and links it to the
1555 :     specified feature and user.
1556 :    
1557 :     =over 4
1558 :    
1559 :     =item fid
1560 :    
1561 :     ID of the feature to be annotated.
1562 :    
1563 :     =item timestamp
1564 :    
1565 :     Numeric timestamp to apply to the annotation. This is concatenated to the feature ID to create the
1566 :     key.
1567 :    
1568 :     =item user
1569 :    
1570 :     ID of the user who is making the annotation.
1571 :    
1572 :     =item text
1573 :    
1574 :     Text of the annotation.
1575 :    
1576 :     =item RETURN
1577 :    
1578 :     Returns 1 if successful, 2 if an error occurred.
1579 :    
1580 :     =back
1581 :    
1582 :     =cut
1583 : parrello 1.3 #: Return Type $;
1584 : parrello 1.1 sub Annotate {
1585 :     # Get the parameters.
1586 :     my $self = shift @_;
1587 :     my ($fid, $timestamp, $user, $text) = @_;
1588 :     # Create the annotation ID.
1589 :     my $aid = "$fid:$timestamp";
1590 :     # Insert the Annotation object.
1591 :     my $retVal = $self->Insert('Annotation', { id => $aid, time => $timestamp, annotation => $text });
1592 :     if ($retVal) {
1593 :     # Connect it to the user.
1594 :     $retVal = $self->Insert('MadeAnnotation', { 'from-link' => $user, 'to-link' => $aid });
1595 :     if ($retVal) {
1596 :     # Connect it to the feature.
1597 :     $retVal = $self->Insert('IsTargetOfAnnotation', { 'from-link' => $fid,
1598 :     'to-link' => $aid });
1599 :     }
1600 :     }
1601 :     # Return the success indicator.
1602 :     return $retVal;
1603 :     }
1604 :    
1605 :     =head3 AssignFunction
1606 :    
1607 :     C<< my $ok = $sprout->AssignFunction($featureID, $user, $function); >>
1608 :    
1609 :     This method assigns a function to a feature. Functions are a special type of annotation. The general
1610 :     format is "XXXX\nset XXXX function to\nYYYYY" where XXXX is the feature type and YYYY is the functional
1611 :     assignment text.
1612 :    
1613 :     =over 4
1614 :    
1615 :     =item featureID
1616 :    
1617 :     ID of the feature to which the assignment is being made.
1618 :    
1619 :     =item user
1620 :    
1621 :     Name of the user making the assignment. This is frequently a group name, like C<kegg> or C<fig>.
1622 :    
1623 :     =item function
1624 :    
1625 :     Text of the function being assigned.
1626 :    
1627 :     =item RETURN
1628 :    
1629 :     Returns 1 if successful, 0 if an error occurred.
1630 :    
1631 :     =back
1632 :    
1633 :     =cut
1634 : parrello 1.3 #: Return Type $;
1635 : parrello 1.1 sub AssignFunction {
1636 :     # Get the parameters.
1637 :     my $self = shift @_;
1638 :     my ($featureID, $user, $function) = @_;
1639 :     # Create an annotation string from the parameters.
1640 :     my $annotationText = "$user\nset $user function to\n$function";
1641 :     # Get the current time.
1642 :     my $now = time;
1643 :     # Declare the return variable.
1644 :     my $retVal = 1;
1645 :     # Locate the genome containing the feature.
1646 :     my $genome = $self->GenomeOf($featureID);
1647 :     if (!$genome) {
1648 :     # Here the genome was not found. This probably means the feature ID is invalid.
1649 :     Trace("No genome found for feature $featureID.") if T(0);
1650 :     $retVal = 0;
1651 :     } else {
1652 :     # Here we know we have a feature with a genome. Store the annotation.
1653 : parrello 1.5 $retVal = $self->Annotate($featureID, $now, $user, $annotationText);
1654 : parrello 1.1 }
1655 :     # Return the success indicator.
1656 :     return $retVal;
1657 :     }
1658 :    
1659 :     =head3 FeaturesByAlias
1660 :    
1661 :     C<< my @features = $sprout->FeaturesByAlias($alias); >>
1662 :    
1663 :     Returns a list of features with the specified alias. The alias is parsed to determine
1664 :     the type of the alias. A string of digits is a GenBack ID and a string of exactly 6
1665 :     alphanumerics is a UniProt ID. A built-in FIG.pm method is used to analyze the alias
1666 :     string and attach the necessary prefix. If the result is a FIG ID then it is returned
1667 :     unmodified; otherwise, we look for an alias.
1668 :    
1669 :     =over 4
1670 :    
1671 :     =item alias
1672 :    
1673 :     Alias whose features are desired.
1674 :    
1675 :     =item RETURN
1676 :    
1677 :     Returns a list of the features with the given alias.
1678 :    
1679 :     =back
1680 :    
1681 :     =cut
1682 : parrello 1.3 #: Return Type @;
1683 : parrello 1.1 sub FeaturesByAlias {
1684 :     # Get the parameters.
1685 :     my $self = shift @_;
1686 :     my ($alias) = @_;
1687 :     # Declare the return variable.
1688 :     my @retVal = ();
1689 :     # Parse the alias.
1690 :     my ($mappedAlias, $flag) = FIGRules::NormalizeAlias($alias);
1691 :     # If it's a FIG alias, we're done.
1692 :     if ($flag) {
1693 :     push @retVal, $mappedAlias;
1694 :     } else {
1695 :     # Here we have a non-FIG alias. Get the features with the normalized alias.
1696 :     @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');
1697 :     }
1698 :     # Return the result.
1699 :     return @retVal;
1700 :     }
1701 :    
1702 :     =head3 Exists
1703 :    
1704 :     C<< my $found = $sprout->Exists($entityName, $entityID); >>
1705 :    
1706 :     Return TRUE if an entity exists, else FALSE.
1707 :    
1708 :     =over 4
1709 :    
1710 :     =item entityName
1711 :    
1712 :     Name of the entity type (e.g. C<Feature>) relevant to the existence check.
1713 :    
1714 :     =item entityID
1715 :    
1716 :     ID of the entity instance whose existence is to be checked.
1717 :    
1718 :     =item RETURN
1719 :    
1720 :     Returns TRUE if the entity instance exists, else FALSE.
1721 :    
1722 :     =back
1723 :    
1724 :     =cut
1725 : parrello 1.3 #: Return Type $;
1726 : parrello 1.1 sub Exists {
1727 :     # Get the parameters.
1728 :     my $self = shift @_;
1729 :     my ($entityName, $entityID) = @_;
1730 :     # Check for the entity instance.
1731 :     my $testInstance = $self->GetEntity($entityName, $entityID);
1732 :     # Return an existence indicator.
1733 :     my $retVal = ($testInstance ? 1 : 0);
1734 :     return $retVal;
1735 :     }
1736 :    
1737 :     =head3 FeatureTranslation
1738 :    
1739 :     C<< my $translation = $sprout->FeatureTranslation($featureID); >>
1740 :    
1741 :     Return the translation of a feature.
1742 :    
1743 :     =over 4
1744 :    
1745 :     =item featureID
1746 :    
1747 :     ID of the feature whose translation is desired
1748 :    
1749 :     =item RETURN
1750 :    
1751 :     Returns the translation of the specified feature.
1752 :    
1753 :     =back
1754 :    
1755 :     =cut
1756 : parrello 1.3 #: Return Type $;
1757 : parrello 1.1 sub FeatureTranslation {
1758 :     # Get the parameters.
1759 :     my $self = shift @_;
1760 :     my ($featureID) = @_;
1761 :     # Get the specified feature's translation.
1762 :     my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
1763 :     return $retVal;
1764 :     }
1765 :    
1766 :     =head3 Taxonomy
1767 :    
1768 :     C<< my @taxonomyList = $sprout->Taxonomy($genome); >>
1769 :    
1770 :     Return the taxonomy of the specified genome. This will be in the form of a list
1771 :     containing the various classifications in order from domain (eg. C<Bacteria>, C<Archaea>,
1772 :     or C<Eukaryote>) to sub-species. For example,
1773 :    
1774 :     C<< (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12) >>
1775 :    
1776 :     =over 4
1777 :    
1778 :     =item genome
1779 :    
1780 :     ID of the genome whose taxonomy is desired.
1781 :    
1782 :     =item RETURN
1783 :    
1784 :     Returns a list containing all the taxonomy classifications for the specified genome's organism.
1785 :    
1786 :     =back
1787 :    
1788 :     =cut
1789 : parrello 1.3 #: Return Type @;
1790 : parrello 1.1 sub Taxonomy {
1791 :     # Get the parameters.
1792 :     my $self = shift @_;
1793 :     my ($genome) = @_;
1794 :     # Find the specified genome's taxonomy string.
1795 :     my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);
1796 :     # Declare the return variable.
1797 :     my @retVal = ();
1798 :     # If we found the genome, return its taxonomy string.
1799 :     if ($list) {
1800 :     @retVal = split /\s*;\s*/, $list;
1801 :     } else {
1802 :     Trace("Genome \"$genome\" does not have a taxonomy in the database.\n") if T(0);
1803 :     }
1804 :     # Return the value found.
1805 :     return @retVal;
1806 :     }
1807 :    
1808 :     =head3 CrudeDistance
1809 :    
1810 :     C<< my $distance = $sprout->CrudeDistance($genome1, $genome2); >>
1811 :    
1812 :     Returns a crude estimate of the distance between two genomes. The distance is construed so
1813 :     that it will be 0 for genomes with identical taxonomies and 1 for genomes from different domains.
1814 :    
1815 :     =over 4
1816 :    
1817 :     =item genome1
1818 :    
1819 :     ID of the first genome to compare.
1820 :    
1821 :     =item genome2
1822 :    
1823 :     ID of the second genome to compare.
1824 :    
1825 :     =item RETURN
1826 :    
1827 :     Returns a value from 0 to 1, with 0 meaning identical organisms, and 1 meaning organisms from
1828 :     different domains.
1829 :    
1830 :     =back
1831 :    
1832 :     =cut
1833 : parrello 1.3 #: Return Type $;
1834 : parrello 1.1 sub CrudeDistance {
1835 :     # Get the parameters.
1836 :     my $self = shift @_;
1837 :     my ($genome1, $genome2) = @_;
1838 :     # Insure that the distance is commutative by sorting the genome IDs.
1839 :     my ($genomeA, $genomeB);
1840 :     if ($genome2 < $genome2) {
1841 :     ($genomeA, $genomeB) = ($genome1, $genome2);
1842 :     } else {
1843 :     ($genomeA, $genomeB) = ($genome2, $genome1);
1844 :     }
1845 :     my @taxA = $self->Taxonomy($genomeA);
1846 :     my @taxB = $self->Taxonomy($genomeB);
1847 :     # Initialize the distance to 1. We'll reduce it each time we find a match between the
1848 :     # taxonomies.
1849 :     my $retVal = 1.0;
1850 :     # Initialize the subtraction amount. This amount determines the distance reduction caused
1851 :     # by a mismatch at the current level.
1852 :     my $v = 0.5;
1853 :     # Loop through the taxonomies.
1854 :     for (my $i = 0; ($i < @taxA) && ($i < @taxB) && ($taxA[$i] eq $taxB[$i]); $i++) {
1855 :     $retVal -= $v;
1856 :     $v /= 2;
1857 :     }
1858 :     return $retVal;
1859 :     }
1860 :    
1861 :     =head3 RoleName
1862 :    
1863 :     C<< my $roleName = $sprout->RoleName($roleID); >>
1864 :    
1865 :     Return the descriptive name of the role with the specified ID. In general, a role
1866 :     will only have a descriptive name if it is coded as an EC number.
1867 :    
1868 :     =over 4
1869 :    
1870 :     =item roleID
1871 :    
1872 :     ID of the role whose description is desired.
1873 :    
1874 :     =item RETURN
1875 :    
1876 :     Returns the descriptive name of the desired role.
1877 :    
1878 :     =back
1879 :    
1880 :     =cut
1881 : parrello 1.3 #: Return Type $;
1882 : parrello 1.1 sub RoleName {
1883 :     # Get the parameters.
1884 :     my $self = shift @_;
1885 :     my ($roleID) = @_;
1886 :     # Get the specified role's name.
1887 :     my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);
1888 :     # Use the ID if the role has no name.
1889 :     if (!$retVal) {
1890 :     $retVal = $roleID;
1891 :     }
1892 :     # Return the name.
1893 :     return $retVal;
1894 :     }
1895 :    
1896 :     =head3 RoleDiagrams
1897 :    
1898 :     C<< my @diagrams = $sprout->RoleDiagrams($roleID); >>
1899 :    
1900 :     Return a list of the diagrams containing a specified functional role.
1901 :    
1902 :     =over 4
1903 :    
1904 :     =item roleID
1905 :    
1906 :     ID of the role whose diagrams are desired.
1907 :    
1908 :     =item RETURN
1909 :    
1910 :     Returns a list of the IDs for the diagrams that contain the specified functional role.
1911 :    
1912 :     =back
1913 :    
1914 :     =cut
1915 : parrello 1.3 #: Return Type @;
1916 : parrello 1.1 sub RoleDiagrams {
1917 :     # Get the parameters.
1918 :     my $self = shift @_;
1919 :     my ($roleID) = @_;
1920 :     # Query for the diagrams.
1921 :     my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
1922 :     'RoleOccursIn(to-link)');
1923 :     # Return the result.
1924 :     return @retVal;
1925 :     }
1926 :    
1927 :     =head3 FeatureProperties
1928 :    
1929 :     C<< my @properties = $sprout->FeatureProperties($featureID); >>
1930 :    
1931 :     Return a list of the properties for the specified feature. Properties are key-value pairs
1932 :     that specify special characteristics of the feature. For example, a property could indicate
1933 :     that a feature is essential to the survival of the organism or that it has benign influence
1934 :     on the activities of a pathogen. Each property is returned as a triple of the form
1935 :     C<($key,$value,$url)>, where C<$key> is the property name, C<$value> is its value (commonly
1936 :     a 1 or a 0, but possibly a string or a floating-point value), and C<$url> is a string describing
1937 :     the web address or citation in which the property's value for the feature was identified.
1938 :    
1939 :     =over 4
1940 :    
1941 :     =item featureID
1942 :    
1943 :     ID of the feature whose properties are desired.
1944 :    
1945 :     =item RETURN
1946 :    
1947 :     Returns a list of triples, each triple containing the property name, its value, and a URL or
1948 :     citation.
1949 :    
1950 :     =back
1951 :    
1952 :     =cut
1953 : parrello 1.3 #: Return Type @@;
1954 : parrello 1.1 sub FeatureProperties {
1955 :     # Get the parameters.
1956 :     my $self = shift @_;
1957 :     my ($featureID) = @_;
1958 :     # Get the properties.
1959 :     my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],
1960 :     ['Property(property-name)', 'Property(property-value)',
1961 :     'HasProperty(evidence)']);
1962 :     # Return the resulting list.
1963 :     return @retVal;
1964 :     }
1965 :    
1966 :     =head3 DiagramName
1967 :    
1968 :     C<< my $diagramName = $sprout->DiagramName($diagramID); >>
1969 :    
1970 :     Return the descriptive name of a diagram.
1971 :    
1972 :     =over 4
1973 :    
1974 :     =item diagramID
1975 :    
1976 :     ID of the diagram whose description is desired.
1977 :    
1978 :     =item RETURN
1979 :    
1980 :     Returns the descripive name of the specified diagram.
1981 :    
1982 :     =back
1983 :    
1984 :     =cut
1985 : parrello 1.3 #: Return Type $;
1986 : parrello 1.1 sub DiagramName {
1987 :     # Get the parameters.
1988 :     my $self = shift @_;
1989 :     my ($diagramID) = @_;
1990 :     # Get the specified diagram's name and return it.
1991 :     my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);
1992 :     return $retVal;
1993 :     }
1994 :    
1995 :     =head3 MergedAnnotations
1996 :    
1997 :     C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>
1998 :    
1999 :     Returns a merged list of the annotations for the features in a list. Each annotation is
2000 :     represented by a 4-tuple of the form C<($fid, $timestamp, $userID, $annotation)>, where
2001 :     C<$fid> is the ID of a feature, C<$timestamp> is the time at which the annotation was made,
2002 :     C<$userID> is the ID of the user who made the annotation, and C<$annotation> is the annotation
2003 :     text. The list is sorted by timestamp.
2004 :    
2005 :     =over 4
2006 :    
2007 :     =item list
2008 :    
2009 :     List of the IDs for the features whose annotations are desired.
2010 :    
2011 :     =item RETURN
2012 :    
2013 :     Returns a list of annotation descriptions sorted by the annotation time.
2014 :    
2015 :     =back
2016 :    
2017 :     =cut
2018 : parrello 1.3 #: Return Type @;
2019 : parrello 1.1 sub MergedAnnotations {
2020 :     # Get the parameters.
2021 :     my $self = shift @_;
2022 :     my ($list) = @_;
2023 :     # Create a list to hold the annotation tuples found.
2024 :     my @tuples = ();
2025 :     # Loop through the features in the input list.
2026 :     for my $fid (@{$list}) {
2027 :     # Create a list of this feature's annotation tuples.
2028 :     my @newTuples = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
2029 :     "IsTargetOfAnnotation(from-link) = ?", [$fid],
2030 :     ['IsTargetOfAnnotation(from-link)', 'Annotation(time)',
2031 :     'MadeAnnotation(from-link)', 'Annotation(annotation)']);
2032 :     # Put it in the result list.
2033 :     push @tuples, @newTuples;
2034 :     }
2035 :     # Sort the result list by timestamp.
2036 :     my @retVal = sort { $a->[1] <=> $b->[1] } @tuples;
2037 : parrello 1.3 # Loop through and make the time stamps friendly.
2038 :     for my $tuple (@retVal) {
2039 :     $tuple->[1] = FriendlyTimestamp($tuple->[1]);
2040 :     }
2041 : parrello 1.1 # Return the sorted list.
2042 :     return @retVal;
2043 :     }
2044 :    
2045 :     =head3 RoleNeighbors
2046 :    
2047 :     C<< my @roleList = $sprout->RoleNeighbors($roleID); >>
2048 :    
2049 :     Returns a list of the roles that occur in the same diagram as the specified role. Because
2050 :     diagrams and roles are in a many-to-many relationship with each other, the list is
2051 :     essentially the set of roles from all of the maps that contain the incoming role. Such
2052 :     roles are considered neighbors because they are used together in cellular subsystems.
2053 :    
2054 :     =over 4
2055 :    
2056 :     =item roleID
2057 :    
2058 :     ID of the role whose neighbors are desired.
2059 :    
2060 :     =item RETURN
2061 :    
2062 :     Returns a list containing the IDs of the roles that are related to the incoming role.
2063 :    
2064 :     =back
2065 :    
2066 :     =cut
2067 : parrello 1.3 #: Return Type @;
2068 : parrello 1.1 sub RoleNeighbors {
2069 :     # Get the parameters.
2070 :     my $self = shift @_;
2071 :     my ($roleID) = @_;
2072 :     # Get all the diagrams containing this role.
2073 :     my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2074 :     'RoleOccursIn(to-link)');
2075 :     # Create the return list.
2076 :     my @retVal = ();
2077 :     # Loop through the diagrams.
2078 :     for my $diagramID (@diagrams) {
2079 :     # Get all the roles in this diagram.
2080 :     my @roles = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(to-link) = ?", [$diagramID],
2081 :     'RoleOccursIn(from-link)');
2082 :     # Add them to the return list.
2083 :     push @retVal, @roles;
2084 :     }
2085 :     # Merge the duplicates from the list.
2086 :     return Tracer::Merge(@retVal);
2087 :     }
2088 :    
2089 :     =head3 FeatureLinks
2090 :    
2091 :     C<< my @links = $sprout->FeatureLinks($featureID); >>
2092 :    
2093 :     Return a list of the web hyperlinks associated with a feature. The web hyperlinks are
2094 :     to external websites describing either the feature itself or the organism containing it
2095 :     and are represented in raw HTML.
2096 :    
2097 :     =over 4
2098 :    
2099 :     =item featureID
2100 :    
2101 :     ID of the feature whose links are desired.
2102 :    
2103 :     =item RETURN
2104 :    
2105 :     Returns a list of the web links for this feature.
2106 :    
2107 :     =back
2108 :    
2109 :     =cut
2110 : parrello 1.3 #: Return Type @;
2111 : parrello 1.1 sub FeatureLinks {
2112 :     # Get the parameters.
2113 :     my $self = shift @_;
2114 :     my ($featureID) = @_;
2115 :     # Get the feature's links.
2116 :     my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);
2117 :     # Return the feature's links.
2118 :     return @retVal;
2119 :     }
2120 :    
2121 :     =head3 SubsystemsOf
2122 :    
2123 :     C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2124 :    
2125 :     Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped
2126 :     to the role the feature performs.
2127 :    
2128 :     =over 4
2129 :    
2130 :     =item featureID
2131 :    
2132 :     ID of the feature whose subsystems are desired.
2133 :    
2134 :     =item RETURN
2135 :    
2136 :     Returns a hash mapping all the feature's subsystems to the feature's role.
2137 :    
2138 :     =back
2139 :    
2140 :     =cut
2141 : parrello 1.3 #: Return Type %;
2142 : parrello 1.1 sub SubsystemsOf {
2143 :     # Get the parameters.
2144 :     my $self = shift @_;
2145 :     my ($featureID) = @_;
2146 :     # Use the SSCell to connect features to subsystems.
2147 :     my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2148 :     "ContainsFeature(to-link) = ?", [$featureID],
2149 :     ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2150 :     # Create the return value.
2151 :     my %retVal = ();
2152 :     # Loop through the results, adding them to the hash.
2153 :     for my $record (@subsystems) {
2154 :     $retVal{$record->[0]} = $record->[1];
2155 :     }
2156 :     # Return the hash.
2157 :     return %retVal;
2158 :     }
2159 :    
2160 :     =head3 RelatedFeatures
2161 :    
2162 :     C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
2163 :    
2164 :     Return a list of the features which are bi-directional best hits of the specified feature and
2165 :     have been assigned the specified function by the specified user. If no such features exists,
2166 :     an empty list will be returned.
2167 :    
2168 :     =over 4
2169 :    
2170 :     =item featureID
2171 :    
2172 :     ID of the feature to whom the desired features are related.
2173 :    
2174 :     =item function
2175 :    
2176 :     Functional assignment (as returned by C</FunctionOf>) that is used to determine which related
2177 :     features should be selected.
2178 :    
2179 :     =item userID
2180 :    
2181 :     ID of the user whose functional assignments are to be used. If omitted, C<FIG> is assumed.
2182 :    
2183 :     =item RETURN
2184 :    
2185 :     Returns a list of the related features with the specified function.
2186 :    
2187 :     =back
2188 :    
2189 :     =cut
2190 : parrello 1.3 #: Return Type @;
2191 : parrello 1.1 sub RelatedFeatures {
2192 :     # Get the parameters.
2193 :     my $self = shift @_;
2194 :     my ($featureID, $function, $userID) = @_;
2195 :     # Get a list of the features that are BBHs of the incoming feature.
2196 :     my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],
2197 :     "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],
2198 :     'IsBidirectionalBestHitOf(to-link)');
2199 :     # Now we loop through the features, pulling out the ones that have the correct
2200 :     # functional assignment.
2201 :     my @retVal = ();
2202 :     for my $bbhFeature (@bbhFeatures) {
2203 :     # Get this feature's functional assignment.
2204 :     my $newFunction = $self->FunctionOf($bbhFeature, $userID);
2205 :     # If it matches, add it to the result list.
2206 :     if ($newFunction eq $function) {
2207 :     push @retVal, $bbhFeature;
2208 :     }
2209 :     }
2210 :     # Return the result list.
2211 :     return @retVal;
2212 :     }
2213 :    
2214 :     =head3 TaxonomySort
2215 :    
2216 :     C<< my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs); >>
2217 :    
2218 :     Return a list formed by sorting the specified features by the taxonomy of the containing
2219 :     genome. This will cause genomes from similar organisms to float close to each other.
2220 :    
2221 :     This task could almost be handled by the database; however, the taxonomy string in the
2222 :     database is a text field and can't be indexed. Instead, we create a hash table that maps
2223 :     taxonomy strings to lists of features. We then process the hash table using a key sort
2224 :     and merge the feature lists together to create the output.
2225 :    
2226 :     =over 4
2227 :    
2228 :     =item $featureIDs
2229 :    
2230 :     List of features to be taxonomically sorted.
2231 :    
2232 :     =item RETURN
2233 :    
2234 :     Returns the list of features sorted by the taxonomies of the containing genomes.
2235 :    
2236 :     =back
2237 :    
2238 :     =cut
2239 : parrello 1.3 #: Return Type @;
2240 : parrello 1.1 sub TaxonomySort {
2241 :     # Get the parameters.
2242 :     my $self = shift @_;
2243 :     my ($featureIDs) = @_;
2244 :     # Create the working hash table.
2245 :     my %hashBuffer = ();
2246 :     # Loop through the features.
2247 :     for my $fid (@{$featureIDs}) {
2248 :     # Get the taxonomy of the feature's genome.
2249 :     my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
2250 :     [$fid], 'Genome(taxonomy)');
2251 :     # Add this feature to the hash buffer.
2252 :     if (exists $hashBuffer{$taxonomy}) {
2253 :     push @{$hashBuffer{$taxonomy}}, $fid;
2254 :     } else {
2255 :     $hashBuffer{$taxonomy} = [$fid];
2256 :     }
2257 :     }
2258 :     # Sort the keys and get the elements.
2259 :     my @retVal = ();
2260 :     for my $taxon (sort keys %hashBuffer) {
2261 :     push @retVal, @{$hashBuffer{$taxon}};
2262 :     }
2263 :     # Return the result.
2264 :     return @retVal;
2265 :     }
2266 :    
2267 :     =head3 GetAll
2268 :    
2269 :     C<< my @list = $sprout->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>
2270 :    
2271 :     Return a list of values taken from the objects returned by a query. The first three
2272 :     parameters correspond to the parameters of the L</Get> method. The final parameter is
2273 :     a list of the fields desired from each record found by the query. The field name
2274 :     syntax is the standard syntax used for fields in the B<ERDB> system--
2275 :     B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity
2276 :     or relationship and I<fieldName> is the name of the field.
2277 :    
2278 :     The list returned will be a list of lists. Each element of the list will contain
2279 :     the values returned for the fields specified in the fourth parameter. If one of the
2280 :     fields specified returns multiple values, they are flattened in with the rest. For
2281 :     example, the following call will return a list of the features in a particular
2282 :     spreadsheet cell, and each feature will be represented by a list containing the
2283 :     feature ID followed by all of its aliases.
2284 :    
2285 :     C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>
2286 :    
2287 :     =over 4
2288 :    
2289 :     =item objectNames
2290 :    
2291 :     List containing the names of the entity and relationship objects to be retrieved.
2292 :    
2293 :     =item filterClause
2294 :    
2295 :     WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
2296 :     be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
2297 :     B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
2298 :     parameter list as additional parameters. The fields in a filter clause can come from primary
2299 :     entity relations, relationship relations, or secondary entity relations; however, all of the
2300 :     entities and relationships involved must be included in the list of object names.
2301 :    
2302 :     =item parameterList
2303 :    
2304 :     List of the parameters to be substituted in for the parameters marks in the filter clause.
2305 :    
2306 :     =item fields
2307 :    
2308 :     List of the fields to be returned in each element of the list returned.
2309 :    
2310 :     =item count
2311 :    
2312 :     Maximum number of records to return. If omitted or 0, all available records will be returned.
2313 :    
2314 :     =item RETURN
2315 :    
2316 :     Returns a list of list references. Each element of the return list contains the values for the
2317 :     fields specified in the B<fields> parameter.
2318 :    
2319 :     =back
2320 :    
2321 :     =cut
2322 : parrello 1.3 #: Return Type @@;
2323 : parrello 1.1 sub GetAll {
2324 :     # Get the parameters.
2325 :     my $self = shift @_;
2326 :     my ($objectNames, $filterClause, $parameterList, $fields, $count) = @_;
2327 :     # Create the query.
2328 :     my $query = $self->Get($objectNames, $filterClause, $parameterList);
2329 :     # Set up a counter of the number of records read.
2330 :     my $fetched = 0;
2331 :     # Insure the counter has a value.
2332 :     if (!defined $count) {
2333 :     $count = 0;
2334 :     }
2335 :     # Loop through the records returned, extracting the fields. Note that if the
2336 :     # counter is non-zero, we stop when the number of records read hits the count.
2337 :     my @retVal = ();
2338 :     while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {
2339 :     my @rowData = $row->Values($fields);
2340 :     push @retVal, \@rowData;
2341 :     $fetched++;
2342 :     }
2343 :     # Return the resulting list.
2344 :     return @retVal;
2345 :     }
2346 :    
2347 :     =head3 GetFlat
2348 :    
2349 :     C<< my @list = $sprout->GetFlat(\@objectNames, $filterClause, $parameterList, $field); >>
2350 :    
2351 :     This is a variation of L</GetAll> that asks for only a single field per record and
2352 :     returns a single flattened list.
2353 :    
2354 :     =over 4
2355 :    
2356 :     =item objectNames
2357 :    
2358 :     List containing the names of the entity and relationship objects to be retrieved.
2359 :    
2360 :     =item filterClause
2361 :    
2362 :     WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
2363 :     be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
2364 :     B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
2365 :     parameter list as additional parameters. The fields in a filter clause can come from primary
2366 :     entity relations, relationship relations, or secondary entity relations; however, all of the
2367 :     entities and relationships involved must be included in the list of object names.
2368 :    
2369 :     =item parameterList
2370 :    
2371 :     List of the parameters to be substituted in for the parameters marks in the filter clause.
2372 :    
2373 :     =item field
2374 :    
2375 :     Name of the field to be used to get the elements of the list returned.
2376 :    
2377 :     =item RETURN
2378 :    
2379 :     Returns a list of values.
2380 :    
2381 :     =back
2382 :    
2383 :     =cut
2384 : parrello 1.3 #: Return Type @;
2385 : parrello 1.1 sub GetFlat {
2386 :     # Get the parameters.
2387 :     my $self = shift @_;
2388 :     my ($objectNames, $filterClause, $parameterList, $field) = @_;
2389 :     # Construct the query.
2390 :     my $query = $self->Get($objectNames, $filterClause, $parameterList);
2391 :     # Create the result list.
2392 :     my @retVal = ();
2393 :     # Loop through the records, adding the field values found to the result list.
2394 :     while (my $row = $query->Fetch()) {
2395 :     push @retVal, $row->Value($field);
2396 :     }
2397 :     # Return the list created.
2398 :     return @retVal;
2399 :     }
2400 :    
2401 :     =head3 Protein
2402 :    
2403 :     C<< my $protein = Sprout::Protein($sequence, $table); >>
2404 :    
2405 :     Translate a DNA sequence into a protein sequence.
2406 :    
2407 :     =over 4
2408 :    
2409 :     =item sequence
2410 :    
2411 :     DNA sequence to translate.
2412 :    
2413 :     =item table (optional)
2414 :    
2415 :     Reference to a Hash that translates DNA triples to proteins. A triple that does not
2416 :     appear in the hash will be translated automatically to C<X>.
2417 :    
2418 :     =item RETURN
2419 :    
2420 :     Returns the protein sequence that would be created by the DNA sequence.
2421 :    
2422 :     =back
2423 :    
2424 :     =cut
2425 :    
2426 :     # This is the translation table for protein synthesis.
2427 :     my $ProteinTable = { AAA => 'K', AAG => 'K', AAT => 'N', AAC => 'N',
2428 :     AGA => 'R', AGG => 'R', AGT => 'S', AGC => 'S',
2429 :     ATA => 'I', ATG => 'M', ATT => 'I', ATC => 'I',
2430 :     ACA => 'T', ACG => 'T', ACT => 'T', ACC => 'T',
2431 :     GAA => 'E', GAG => 'E', GAT => 'D', GAC => 'D',
2432 :     GTA => 'V', GTG => 'V', GTT => 'V', GTC => 'V',
2433 :     GGA => 'G', GGG => 'G', GGT => 'G', GGC => 'G',
2434 :     GCA => 'A', GCG => 'A', GCT => 'A', GCC => 'A',
2435 :     CAA => 'Q', CAG => 'Q', CAT => 'H', CAC => 'H',
2436 :     CTA => 'L', CTG => 'L', CTT => 'L', CTC => 'L',
2437 :     CGA => 'R', CGG => 'R', CGT => 'R', CGC => 'R',
2438 :     CCA => 'P', CCG => 'P', CCT => 'P', CCC => 'P',
2439 :     TAA => '*', TAG => '*', TAT => 'Y', TAC => 'Y',
2440 :     TGA => '*', TGG => 'W', TGT => 'C', TGC => 'C',
2441 :     TTA => 'L', TTG => 'L', TTT => 'F', TTC => 'F',
2442 :     TCA => 'S', TCG => 'S', TCT => 'S', TCC => 'S',
2443 :     AAR => 'K', AAY => 'N',
2444 :     AGR => 'R', AGY => 'S',
2445 :     ATY => 'I',
2446 :     ACR => 'T', ACY => 'T', 'ACX' => 'T',
2447 :     GAR => 'E', GAY => 'D',
2448 :     GTR => 'V', GTY => 'V', GTX => 'V',
2449 :     GGR => 'G', GGY => 'G', GGX => 'G',
2450 :     GCR => 'A', GCY => 'A', GCX => 'A',
2451 :     CAR => 'Q', CAY => 'H',
2452 :     CTR => 'L', CTY => 'L', CTX => 'L',
2453 :     CGR => 'R', CGY => 'R', CGX => 'R',
2454 :     CCR => 'P', CCY => 'P', CCX => 'P',
2455 :     TAR => '*', TAY => 'Y',
2456 :     TGY => 'C',
2457 :     TTR => 'L', TTY => 'F',
2458 :     TCR => 'S', TCY => 'S', TCX => 'S'
2459 :     };
2460 :    
2461 :     sub Protein {
2462 :     # Get the paraeters.
2463 :     my ($sequence, $table) = @_;
2464 :     # If no table was specified, use the default.
2465 :     if (!$table) {
2466 :     $table = $ProteinTable;
2467 :     }
2468 :     # Create the return value.
2469 :     my $retVal = "";
2470 :     # Loop through the input triples.
2471 :     my $n = length $sequence;
2472 :     for (my $i = 0; $i < $n; $i += 3) {
2473 :     # Get the current triple from the sequence.
2474 :     my $triple = substr($sequence, $i, 3);
2475 :     # Translate it using the table.
2476 :     my $protein = "X";
2477 :     if (exists $table->{$triple}) { $protein = $table->{$triple}; }
2478 :     $retVal .= $protein;
2479 :     }
2480 :     # Remove the stop codon (if any).
2481 :     $retVal =~ s/\*$//;
2482 :     # Return the result.
2483 :     return $retVal;
2484 :     }
2485 :    
2486 :     =head3 LoadInfo
2487 :    
2488 :     C<< my ($dirName, @relNames) = $sprout->LoadInfo(); >>
2489 :    
2490 :     Return the name of the directory from which data is to be loaded and a list of the relation
2491 :     names. This information is useful when trying to analyze what needs to be put where in order
2492 :     to load the entire database.
2493 :    
2494 :     =cut
2495 : parrello 1.3 #: Return Type @;
2496 : parrello 1.1 sub LoadInfo {
2497 :     # Get the parameters.
2498 :     my $self = shift @_;
2499 :     # Create the return list, priming it with the name of the data directory.
2500 :     my @retVal = ($self->{_options}->{dataDir});
2501 :     # Concatenate the table names.
2502 :     push @retVal, $self->{_erdb}->GetTableNames();
2503 :     # Return the result.
2504 :     return @retVal;
2505 :     }
2506 :    
2507 :     =head3 LowBBHs
2508 :    
2509 :     C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>
2510 :    
2511 :     Return the bidirectional best hits of a feature whose score is no greater than a
2512 :     specified cutoff value. A higher cutoff value will allow inclusion of hits with
2513 :     a greater score. The value returned is a map of feature IDs to scores.
2514 :    
2515 :     =over 4
2516 :    
2517 :     =item featureID
2518 :    
2519 :     ID of the feature whose best hits are desired.
2520 :    
2521 :     =item cutoff
2522 :    
2523 :     Maximum permissible score for inclusion in the results.
2524 :    
2525 :     =item RETURN
2526 :    
2527 :     Returns a hash mapping feature IDs to scores.
2528 :    
2529 :     =back
2530 :    
2531 :     =cut
2532 : parrello 1.3 #: Return Type %;
2533 : parrello 1.1 sub LowBBHs {
2534 :     # Get the parsameters.
2535 :     my $self = shift @_;
2536 :     my ($featureID, $cutoff) = @_;
2537 :     # Create the return hash.
2538 :     my %retVal = ();
2539 :     # Create a query to get the desired BBHs.
2540 :     my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],
2541 :     'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',
2542 :     [$cutoff, $featureID],
2543 :     ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);
2544 :     # Form the results into the return hash.
2545 :     for my $pair (@bbhList) {
2546 :     $retVal{$pair->[0]} = $pair->[1];
2547 :     }
2548 :     # Return the result.
2549 :     return %retVal;
2550 :     }
2551 :    
2552 :     =head2 Internal Utility Methods
2553 :    
2554 :     =head3 ParseAssignment
2555 :    
2556 :     Parse annotation text to determine whether or not it is a functional assignment. If it is,
2557 :     the user and function text will be returned as a 2-element list. If it isn't, an empty list
2558 :     will be returned.
2559 :    
2560 :     This is a static method.
2561 :    
2562 :     =over 4
2563 :    
2564 :     =item text
2565 :    
2566 :     Text of the annotation.
2567 :    
2568 :     =item RETURN
2569 :    
2570 :     Returns an empty list if the annotation is not a functional assignment; otherwise, returns
2571 :     a two-element list containing the user name and the function text.
2572 :    
2573 :     =back
2574 :    
2575 :     =cut
2576 :    
2577 :     sub ParseAssignment {
2578 :     # Get the parameters.
2579 :     my ($text) = @_;
2580 :     # Declare the return value.
2581 :     my @retVal = ();
2582 :     # Check to see if this is a functional assignment.
2583 :     my ($user, $type, $function) = split(/\n/, $text);
2584 :     if ($type =~ m/^set $user function to$/i) {
2585 :     # Here it is, so we return the user name and function text.
2586 :     @retVal = ($user, $function);
2587 :     }
2588 :     # Return the result list.
2589 :     return @retVal;
2590 :     }
2591 :    
2592 : parrello 1.3 =head3 FriendlyTimestamp
2593 :    
2594 :     Convert a time number to a user-friendly time stamp for display.
2595 :    
2596 :     This is a static method.
2597 :    
2598 :     =over 4
2599 :    
2600 :     =item timeValue
2601 :    
2602 :     Numeric time value.
2603 :    
2604 :     =item RETURN
2605 :    
2606 :     Returns a string containing the same time in user-readable format.
2607 :    
2608 :     =back
2609 :    
2610 :     =cut
2611 :    
2612 :     sub FriendlyTimestamp {
2613 :     my ($timeValue) = @_;
2614 :     my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));
2615 :     return $retVal;
2616 :     }
2617 :    
2618 : parrello 1.1 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3