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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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