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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3