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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3