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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3