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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3