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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3