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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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