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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3