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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3