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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3