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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3