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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3