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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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