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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3