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

Annotation of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3