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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3