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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3