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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3