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

Diff of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.22, Fri Sep 9 21:10:46 2005 UTC revision 1.86, Sun Sep 24 17:14:16 2006 UTC
# Line 1  Line 1 
1  package Sprout;  package Sprout;
2    
3        require Exporter;
4        use ERDB;
5        @ISA = qw(Exporter ERDB);
6      use Data::Dumper;      use Data::Dumper;
7      use strict;      use strict;
8      use Carp;      use Carp;
# Line 7  Line 10 
10      use XML::Simple;      use XML::Simple;
11      use DBQuery;      use DBQuery;
12      use DBObject;      use DBObject;
     use ERDB;  
13      use Tracer;      use Tracer;
14      use FIGRules;      use FIGRules;
15        use FidCheck;
16      use Stats;      use Stats;
17      use POSIX qw(strftime);      use POSIX qw(strftime);
18        use BasicLocation;
19    
20  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
21    
# Line 32  Line 35 
35  query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and  query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and
36  L</dna_seq> returns the DNA sequence for a specified genome location.  L</dna_seq> returns the DNA sequence for a specified genome location.
37    
38    The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.
39    
40  =cut  =cut
41    
42  #: Constructor SFXlate->new_sprout_only();  #: Constructor SFXlate->new_sprout_only();
# Line 62  Line 67 
67    
68  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)
69    
70  * B<userData> user name and password, delimited by a slash (default C<root/>)  * B<userData> user name and password, delimited by a slash (default same as SEED)
71    
72  * B<port> connection port (default C<0>)  * B<port> connection port (default C<0>)
73    
74    * B<sock> connection socket (default same as SEED)
75    
76  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
77    
78  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
79    
80    * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
81    
82  =back  =back
83    
84  For example, the following constructor call specifies a database named I<Sprout> and a user name of  For example, the following constructor call specifies a database named I<Sprout> and a user name of
# Line 83  Line 92 
92  sub new {  sub new {
93      # Get the parameters.      # Get the parameters.
94      my ($class, $dbName, $options) = @_;      my ($class, $dbName, $options) = @_;
95        # Compute the DBD directory.
96        my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
97                                                      $FIG_Config::fig );
98      # Compute the options. We do this by starting with a table of defaults and overwriting with      # Compute the options. We do this by starting with a table of defaults and overwriting with
99      # the incoming data.      # the incoming data.
100      my $optionTable = Tracer::GetOptions({      my $optionTable = Tracer::GetOptions({
# Line 90  Line 102 
102                                                          # database type                                                          # database type
103                         dataDir      => $FIG_Config::sproutData,                         dataDir      => $FIG_Config::sproutData,
104                                                          # data file directory                                                          # data file directory
105                         xmlFileName  => "$FIG_Config::sproutData/SproutDBD.xml",                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
106                                                          # database definition file name                                                          # database definition file name
107                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
108                                                          # user name and password                                                          # user name and password
109                         port         => $FIG_Config::dbport,                         port         => $FIG_Config::dbport,
110                                                          # database connection port                                                          # database connection port
111                           sock         => $FIG_Config::dbsock,
112                           host         => $FIG_Config::dbhost,
113                         maxSegmentLength => 4500,        # maximum feature segment length                         maxSegmentLength => 4500,        # maximum feature segment length
114                         maxSequenceLength => 8000,       # maximum contig sequence length                         maxSequenceLength => 8000,       # maximum contig sequence length
115                           noDBOpen     => 0,               # 1 to suppress the database open
116                        }, $options);                        }, $options);
117      # Get the data directory.      # Get the data directory.
118      my $dataDir = $optionTable->{dataDir};      my $dataDir = $optionTable->{dataDir};
# Line 105  Line 120 
120      $optionTable->{userData} =~ m!([^/]*)/(.*)$!;      $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
121      my ($userName, $password) = ($1, $2);      my ($userName, $password) = ($1, $2);
122      # Connect to the database.      # Connect to the database.
123      my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
124        if (! $optionTable->{noDBOpen}) {
125            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
126                                    $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
127        }
128      # Create the ERDB object.      # Create the ERDB object.
129      my $xmlFileName = "$optionTable->{xmlFileName}";      my $xmlFileName = "$optionTable->{xmlFileName}";
130      my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
131      # Create this object.      # Add the option table and XML file name.
132      my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
133      # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
134      bless $self;      # Set up space for the group file data.
135      return $self;      $retVal->{groupHash} = undef;
136        # Return it.
137        return $retVal;
138  }  }
139    
140  =head3 MaxSegment  =head3 MaxSegment
# Line 148  Line 169 
169      return $self->{_options}->{maxSequenceLength};      return $self->{_options}->{maxSequenceLength};
170  }  }
171    
 =head3 Get  
   
 C<< my $query = $sprout->Get(\@objectNames, $filterClause, \@parameterList); >>  
   
 This method allows a general query against the Sprout data using a specified filter clause.  
   
 The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each  
 field name represented in the form B<I<objectName>(I<fieldName>)>. For example, the  
 following call requests all B<Genome> objects for the genus specified in the variable  
 $genus.  
   
 C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>  
   
 The WHERE clause contains a single question mark, so there is a single additional  
 parameter representing the parameter value. It would also be possible to code  
   
 C<< $query = $sprout->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>  
   
 however, this version of the call would generate a syntax error if there were any quote  
 characters inside the variable C<$genus>.  
   
 The use of the strange parenthesized notation for field names enables us to distinguish  
 hyphens contained within field names from minus signs that participate in the computation  
 of the WHERE clause. All of the methods that manipulate fields will use this same notation.  
   
 It is possible to specify multiple entity and relationship names in order to retrieve more than  
 one object's data at the same time, which allows highly complex joined queries. For example,  
   
 C<< $query = $sprout->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>  
   
 This query returns all the genomes for a particular genus and allows access to the  
 sources from which they came. The join clauses to go from Genome to Source are generated  
 automatically.  
   
 Finally, the filter clause can contain sort information. To do this, simply put an C<ORDER BY>  
 clause at the end of the filter. Field references in the ORDER BY section follow the same rules  
 as they do in the filter itself; in other words, each one must be of the form B<I<objectName>(I<fieldName>)>.  
 For example, the following filter string gets all genomes for a particular genus and sorts  
 them by species name.  
   
 C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ? ORDER BY Genome(species)", [$genus]); >>  
   
 It is also permissible to specify I<only> an ORDER BY clause. For example, the following invocation gets  
 all genomes ordered by genus and species.  
   
 C<< $query = $sprout->Get(['Genome'], "ORDER BY Genome(genus), Genome(species)"); >>  
   
 Odd things may happen if one of the ORDER BY fields is in a secondary relation. So, for example, an  
 attempt to order B<Feature>s by alias may (depending on the underlying database engine used) cause  
 a single feature to appear more than once.  
   
 If multiple names are specified, then the query processor will automatically determine a  
 join path between the entities and relationships. The algorithm used is very simplistic.  
 In particular, you can't specify any entity or relationship more than once, and if a  
 relationship is recursive, the path is determined by the order in which the entity  
 and the relationship appear. For example, consider a recursive relationship B<IsParentOf>  
 which relates B<People> objects to other B<People> objects. If the join path is  
 coded as C<['People', 'IsParentOf']>, then the people returned will be parents. If, however,  
 the join path is C<['IsParentOf', 'People']>, then the people returned will be children.  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item RETURN  
   
 Returns a B<DBQuery> that can be used to iterate through all of the results.  
   
 =back  
   
 =cut  
   
 sub Get {  
     # Get the parameters.  
     my ($self, $objectNames, $filterClause, $parameterList) = @_;  
     # We differ from the ERDB Get method in that the parameter list is passed in as a list reference  
     # rather than a list of parameters. The next step is to convert the parameters from a reference  
     # to a real list. We can only do this if the parameters have been specified.  
     my @parameters;  
     if ($parameterList) { @parameters = @{$parameterList}; }  
     return $self->{_erdb}->Get($objectNames, $filterClause, @parameters);  
 }  
   
 =head3 GetEntity  
   
 C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>  
   
 Return an object describing the entity instance with a specified ID.  
   
 =over 4  
   
 =item entityType  
   
 Entity type name.  
   
 =item ID  
   
 ID of the desired entity.  
   
 =item RETURN  
   
 Returns a B<DBObject> representing the desired entity instance, or an undefined value if no  
 instance is found with the specified key.  
   
 =back  
   
 =cut  
   
 sub GetEntity {  
     # Get the parameters.  
     my ($self, $entityType, $ID) = @_;  
     # Call the ERDB method.  
     return $self->{_erdb}->GetEntity($entityType, $ID);  
 }  
   
 =head3 GetEntityValues  
   
 C<< my @values = GetEntityValues($entityType, $ID, \@fields); >>  
   
 Return a list of values from a specified entity instance.  
   
 =over 4  
   
 =item entityType  
   
 Entity type name.  
   
 =item ID  
   
 ID of the desired entity.  
   
 =item fields  
   
 List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.  
   
 =item RETURN  
   
 Returns a flattened list of the values of the specified fields for the specified entity.  
   
 =back  
   
 =cut  
 #: Return Type @;  
 sub GetEntityValues {  
     # Get the parameters.  
     my ($self, $entityType, $ID, $fields) = @_;  
     # Call the ERDB method.  
     return $self->{_erdb}->GetEntityValues($entityType, $ID, $fields);  
 }  
   
 =head3 ShowMetaData  
   
 C<< $sprout->ShowMetaData($fileName); >>  
   
 This method outputs a description of the database to an HTML file in the data directory.  
   
 =over 4  
   
 =item fileName  
   
 Fully-qualified name to give to the output file.  
   
 =back  
   
 =cut  
   
 sub ShowMetaData {  
     # Get the parameters.  
     my ($self, $fileName) = @_;  
     # Compute the file name.  
     my $options = $self->{_options};  
     # Call the show method on the underlying ERDB object.  
     $self->{_erdb}->ShowMetaData($fileName);  
 }  
   
172  =head3 Load  =head3 Load
173    
174  C<< $sprout->Load($rebuild); >>;  C<< $sprout->Load($rebuild); >>;
# Line 372  Line 203 
203  sub Load {  sub Load {
204      # Get the parameters.      # Get the parameters.
205      my ($self, $rebuild) = @_;      my ($self, $rebuild) = @_;
     # Get the database object.  
     my $erdb = $self->{_erdb};  
206      # Load the tables from the data directory.      # Load the tables from the data directory.
207      my $retVal = $erdb->LoadTables($self->{_options}->{dataDir}, $rebuild);      my $retVal = $self->LoadTables($self->{_options}->{dataDir}, $rebuild);
208      # Return the statistics.      # Return the statistics.
209      return $retVal;      return $retVal;
210  }  }
211    
212  =head3 LoadUpdate  =head3 LoadUpdate
213    
214  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
215    
216  Load updates to one or more database tables. This method enables the client to make changes to one  Load updates to one or more database tables. This method enables the client to make changes to one
217  or two tables without reloading the whole database. For each table, there must be a corresponding  or two tables without reloading the whole database. For each table, there must be a corresponding
# Line 415  Line 244 
244  sub LoadUpdate {  sub LoadUpdate {
245      # Get the parameters.      # Get the parameters.
246      my ($self, $truncateFlag, $tableList) = @_;      my ($self, $truncateFlag, $tableList) = @_;
     # Get the database object.  
     my $erdb = $self->{_erdb};  
247      # Declare the return value.      # Declare the return value.
248      my $retVal = Stats->new();      my $retVal = Stats->new();
249      # Get the data directory.      # Get the data directory.
# Line 430  Line 257 
257              Trace("No load file found for $tableName in $dataDir.") if T(0);              Trace("No load file found for $tableName in $dataDir.") if T(0);
258          } else {          } else {
259              # Attempt to load this table.              # Attempt to load this table.
260              my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);              my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);
261              # Accumulate the resulting statistics.              # Accumulate the resulting statistics.
262              $retVal->Accumulate($result);              $retVal->Accumulate($result);
263          }          }
# Line 439  Line 266 
266      return $retVal;      return $retVal;
267  }  }
268    
269    =head3 GenomeCounts
270    
271    C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>
272    
273    Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
274    genomes will be included in the counts.
275    
276    =over 4
277    
278    =item complete
279    
280    TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
281    counted
282    
283    =item RETURN
284    
285    A six-element list containing the number of genomes in each of six categories--
286    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
287    
288    =back
289    
290    =cut
291    
292    sub GenomeCounts {
293        # Get the parameters.
294        my ($self, $complete) = @_;
295        # Set the filter based on the completeness flag.
296        my $filter = ($complete ? "Genome(complete) = 1" : "");
297        # Get all the genomes and the related taxonomy information.
298        my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
299        # Clear the counters.
300        my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
301        # Loop through, counting the domains.
302        for my $genome (@genomes) {
303            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
304            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
305            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
306            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
307            elsif ($genome->[1] =~ /^env/i)      { ++$env }
308            else  { ++$unk }
309        }
310        # Return the counts.
311        return ($arch, $bact, $euk, $vir, $env, $unk);
312    }
313    
314    =head3 ContigCount
315    
316    C<< my $count = $sprout->ContigCount($genomeID); >>
317    
318    Return the number of contigs for the specified genome ID.
319    
320    =over 4
321    
322    =item genomeID
323    
324    ID of the genome whose contig count is desired.
325    
326    =item RETURN
327    
328    Returns the number of contigs for the specified genome.
329    
330    =back
331    
332    =cut
333    
334    sub ContigCount {
335        # Get the parameters.
336        my ($self, $genomeID) = @_;
337        # Get the contig count.
338        my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
339        # Return the result.
340        return $retVal;
341    }
342    
343    =head3 GeneMenu
344    
345    C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected); >>
346    
347    Return an HTML select menu of genomes. Each genome will be an option in the menu,
348    and will be displayed by name with the ID and a contig count attached. The selection
349    value will be the genome ID. The genomes will be sorted by genus/species name.
350    
351    =over 4
352    
353    =item attributes
354    
355    Reference to a hash mapping attributes to values for the SELECT tag generated.
356    
357    =item filterString
358    
359    A filter string for use in selecting the genomes. The filter string must conform
360    to the rules for the C<< ERDB->Get >> method.
361    
362    =item params
363    
364    Reference to a list of values to be substituted in for the parameter marks in
365    the filter string.
366    
367    =item selected (optional)
368    
369    ID of the genome to be initially selected.
370    
371    =item fast (optional)
372    
373    If specified and TRUE, the contig counts will be omitted to improve performance.
374    
375    =item RETURN
376    
377    Returns an HTML select menu with the specified genomes as selectable options.
378    
379    =back
380    
381    =cut
382    
383    sub GeneMenu {
384        # Get the parameters.
385        my ($self, $attributes, $filterString, $params, $selected, $fast) = @_;
386        my $slowMode = ! $fast;
387        # Default to nothing selected. This prevents an execution warning if "$selected"
388        # is undefined.
389        $selected = "" unless defined $selected;
390        Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3);
391        # Start the menu.
392        my $retVal = "<select " .
393            join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
394            ">\n";
395        # Get the genomes.
396        my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
397                                                                         'Genome(genus)',
398                                                                         'Genome(species)',
399                                                                         'Genome(unique-characterization)']);
400        # Sort them by name.
401        my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
402        # Loop through the genomes, creating the option tags.
403        for my $genomeData (@sorted) {
404            # Get the data for this genome.
405            my ($genomeID, $genus, $species, $strain) = @{$genomeData};
406            # Get the contig count.
407            my $contigInfo = "";
408            if ($slowMode) {
409                my $count = $self->ContigCount($genomeID);
410                my $counting = ($count == 1 ? "contig" : "contigs");
411                $contigInfo = "[$count $counting]";
412            }
413            # Find out if we're selected.
414            my $selectOption = ($selected eq $genomeID ? " selected" : "");
415            # Build the option tag.
416            $retVal .= "<option value=\"$genomeID\"$selectOption>$genus $species $strain ($genomeID)$contigInfo</option>\n";
417        }
418        # Close the SELECT tag.
419        $retVal .= "</select>\n";
420        # Return the result.
421        return $retVal;
422    }
423    
424  =head3 Build  =head3 Build
425    
426  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 453  Line 435 
435      # Get the parameters.      # Get the parameters.
436      my ($self) = @_;      my ($self) = @_;
437      # Create the tables.      # Create the tables.
438      $self->{_erdb}->CreateTables;      $self->CreateTables();
439    }
440    
441    =head3 NmpdrGenomeMenu
442    
443    C<< my $htmlText = $sprout->NmpdrGenomeMenu(\%options, \@selected); >>
444    
445    This method creates a hierarchical HTML menu for NMPDR genomes organized by category. The
446    category indicates the low-level NMPDR group. Organizing the genomes in this way makes it
447    easier to select all genomes from a particular category.
448    
449    =over 4
450    
451    =item options
452    
453    Reference to a hash containing the options to be applied to the C<SELECT> tag form the menu.
454    Typical options would include C<name> to specify the field name, C<multiple> to specify
455    that multiple selections are allowed, and C<size> to set the number of rows to display
456    in the menu.
457    
458    =item selected
459    
460    Reference to a list containing the IDs of the genomes to be pre-selected. If the menu
461    is not intended to allow multiple selections, the list should be a singleton. If the
462    list is empty, nothing will be pre-selected.
463    
464    =item RETURN
465    
466    Returns the HTML text to generate a C<SELECT> menu inside a form.
467    
468    =back
469    
470    =cut
471    
472    sub NmpdrGenomeMenu {
473        # Get the parameters.
474        my ($self, $options, $selected) = @_;
475        # Get a list of all the genomes in group order. In fact, we only need them ordered
476        # by name (genus,species,strain), but putting primary-group in front enables us to
477        # take advantage of an existing index.
478        my @genomeList = $self->GetAll(['Genome'],
479                                       "ORDER BY Genome(primary-group), Genome(genus), Genome(species), Genome(unique-characterization)",
480                                       [], ['Genome(primary-group)', 'Genome(id)',
481                                            'Genome(genus)', 'Genome(species)',
482                                            'Genome(unique-characterization)']);
483        # Create a hash to organize the genomes by group. Each group will contain a list of
484        # 2-tuples, the first element being the genome ID and the second being the genome
485        # name.
486        my %groupHash = ();
487        for my $genome (@genomeList) {
488            # Get the genome data.
489            my ($group, $genomeID, $genus, $species, $strain) = @{$genome};
490            # Form the genome name.
491            my $name = "$genus $species";
492            if ($strain) {
493                $name .= " $strain";
494            }
495            # Push the genome into the group's list.
496            push @{$groupHash{$group}}, [$genomeID, $name];
497        }
498        # Now we are ready to unroll the menu out of the group hash. First, we sort the groups, putting
499        # the supporting-genome group last.
500        my @groups = sort grep { $_ ne $FIG_Config::otherGroup } keys %groupHash;
501        push @groups, $FIG_Config::otherGroup;
502        # Next, create a hash that specifies the pre-selected entries.
503        my %selectedHash = map { $_ => 1 } @{$selected};
504        # Create the SELECT tag and stuff it into the output array.
505        my $select = "<" . join(" ", 'SELECT', map { "$_=\"$options->{$_}\"" } keys %{$options}) . ">";
506        my @lines = ($select);
507        # Loop through the groups.
508        for my $group (@groups) {
509            # Create the option group tag.
510            my $tag = "<OPTGROUP name=\"$group\">";
511            push @lines, "  $tag";
512            # Get the genomes in the group.
513            for my $genome (@{$groupHash{$group}}) {
514                my ($genomeID, $name) = @{$genome};
515                # See if it's selected.
516                my $select = ($selectedHash{$genomeID} ? " selected" : "");
517                # Generate the option tag.
518                my $optionTag = "<OPTION value=\"$genomeID\"$select>$name</OPTION>";
519                push @lines, "    $optionTag";
520            }
521            # Close the option group.
522            push @lines, "  </OPTGROUP>";
523        }
524        # Close the SELECT tag.
525        push @lines, "</SELECT>";
526        # Assemble the lines into a string.
527        my $retVal = join("\n", @lines, "");
528        # Return the result.
529        return $retVal;
530  }  }
531    
532  =head3 Genomes  =head3 Genomes
# Line 603  Line 676 
676          if ($prevContig eq $contigID && $dir eq $prevDir) {          if ($prevContig eq $contigID && $dir eq $prevDir) {
677              # Here the new segment is in the same direction on the same contig. Insure the              # Here the new segment is in the same direction on the same contig. Insure the
678              # new segment's beginning is next to the old segment's end.              # new segment's beginning is next to the old segment's end.
679              if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||              if ($dir eq "-" && $beg + $len == $prevBeg) {
680                  ($dir eq "+" && $beg == $prevBeg + $prevLen)) {                  # Here we're merging two backward blocks, so we keep the new begin point
681                  # Here we need to merge two segments. Adjust the beginning and length values                  # and adjust the length.
682                  # to include both segments.                  $len += $prevLen;
683                    # Pop the old segment off. The new one will replace it later.
684                    pop @retVal;
685                } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
686                    # Here we need to merge two forward blocks. Adjust the beginning and
687                    # length values to include both segments.
688                  $beg = $prevBeg;                  $beg = $prevBeg;
689                  $len += $prevLen;                  $len += $prevLen;
690                  # Pop the old segment off. The new one will replace it later.                  # Pop the old segment off. The new one will replace it later.
# Line 615  Line 693 
693          }          }
694          # Remember this specifier for the adjacent-segment test the next time through.          # Remember this specifier for the adjacent-segment test the next time through.
695          ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);          ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
696            # Compute the initial base pair.
697            my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
698          # Add the specifier to the list.          # Add the specifier to the list.
699          push @retVal, "${contigID}_$beg$dir$len";          push @retVal, "${contigID}_$start$dir$len";
700      }      }
701      # Return the list in the format indicated by the context.      # Return the list in the format indicated by the context.
702      return (wantarray ? @retVal : join(',', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
# Line 650  Line 730 
730      shift if UNIVERSAL::isa($_[0],__PACKAGE__);      shift if UNIVERSAL::isa($_[0],__PACKAGE__);
731      my ($location) = @_;      my ($location) = @_;
732      # Parse it into segments.      # Parse it into segments.
733      $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
734      my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);      my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
735      # If the direction is an underscore, convert it to a + or -.      # If the direction is an underscore, convert it to a + or -.
736      if ($dir eq "_") {      if ($dir eq "_") {
# Line 666  Line 746 
746      return ($contigID, $start, $dir, $len);      return ($contigID, $start, $dir, $len);
747  }  }
748    
749    
750    
751  =head3 PointLocation  =head3 PointLocation
752    
753  C<< my $found = Sprout::PointLocation($location, $point); >>  C<< my $found = Sprout::PointLocation($location, $point); >>
# Line 726  Line 808 
808  should be of the form returned by L</featureLocation> when in a list context. In other words,  should be of the form returned by L</featureLocation> when in a list context. In other words,
809  each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.  each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.
810    
811    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
812    between positions 1401 and 1532, inclusive.
813    
814        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
815    
816  =over 4  =over 4
817    
818  =item locationList  =item locationList
819    
820  List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<end> (see  List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<len> or
821  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
822    
823  =item RETURN  =item RETURN
824    
# Line 758  Line 845 
845          # the start point is the ending. Note that in the latter case we must reverse the DNA string          # the start point is the ending. Note that in the latter case we must reverse the DNA string
846          # before putting it in the return value.          # before putting it in the return value.
847          my ($start, $stop);          my ($start, $stop);
848            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
849          if ($dir eq "+") {          if ($dir eq "+") {
850              $start = $beg;              $start = $beg;
851              $stop = $beg + $len - 1;              $stop = $beg + $len - 1;
852          } else {          } else {
853              $start = $beg + $len + 1;              $start = $beg - $len + 1;
854              $stop = $beg;              $stop = $beg;
855          }          }
856            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
857          my $query = $self->Get(['IsMadeUpOf','Sequence'],          my $query = $self->Get(['IsMadeUpOf','Sequence'],
858              "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .              "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
859              " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",              " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 776  Line 865 
865                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
866                                     'IsMadeUpOf(len)']);                                     'IsMadeUpOf(len)']);
867              my $stopPosition = $startPosition + $sequenceLength;              my $stopPosition = $startPosition + $sequenceLength;
868                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
869              # Figure out the start point and length of the relevant section.              # Figure out the start point and length of the relevant section.
870              my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);              my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
871              my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
872                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
873              # Add the relevant data to the location data.              # Add the relevant data to the location data.
874              $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
875          }          }
876          # Add this location's data to the return string. Note that we may need to reverse it.          # Add this location's data to the return string. Note that we may need to reverse it.
877          if ($dir eq '+') {          if ($dir eq '+') {
878              $retVal .= $locationDNA;              $retVal .= $locationDNA;
879          } else {          } else {
880              $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
             $retVal .= $locationDNA;  
881          }          }
882      }      }
883      # Return the result.      # Return the result.
# Line 824  Line 914 
914      return @retVal;      return @retVal;
915  }  }
916    
917    =head3 GenomeLength
918    
919    C<< my $length = $sprout->GenomeLength($genomeID); >>
920    
921    Return the length of the specified genome in base pairs.
922    
923    =over 4
924    
925    =item genomeID
926    
927    ID of the genome whose base pair count is desired.
928    
929    =item RETURN
930    
931    Returns the number of base pairs in all the contigs of the specified
932    genome.
933    
934    =back
935    
936    =cut
937    
938    sub GenomeLength {
939        # Get the parameters.
940        my ($self, $genomeID) = @_;
941        # Declare the return variable.
942        my $retVal = 0;
943        # Get the genome's contig sequence lengths.
944        my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
945                           [$genomeID], 'IsMadeUpOf(len)');
946        # Sum the lengths.
947        map { $retVal += $_ } @lens;
948        # Return the result.
949        return $retVal;
950    }
951    
952    =head3 FeatureCount
953    
954    C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
955    
956    Return the number of features of the specified type in the specified genome.
957    
958    =over 4
959    
960    =item genomeID
961    
962    ID of the genome whose feature count is desired.
963    
964    =item type
965    
966    Type of feature to count (eg. C<peg>, C<rna>, etc.).
967    
968    =item RETURN
969    
970    Returns the number of features of the specified type for the specified genome.
971    
972    =back
973    
974    =cut
975    
976    sub FeatureCount {
977        # Get the parameters.
978        my ($self, $genomeID, $type) = @_;
979        # Compute the count.
980        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
981                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
982                                    [$genomeID, $type]);
983        # Return the result.
984        return $retVal;
985    }
986    
987    =head3 GenomeAssignments
988    
989    C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
990    
991    Return a list of a genome's assigned features. The return hash will contain each
992    assigned feature of the genome mapped to the text of its most recent functional
993    assignment.
994    
995    =over 4
996    
997    =item genomeID
998    
999    ID of the genome whose functional assignments are desired.
1000    
1001    =item RETURN
1002    
1003    Returns a reference to a hash which maps each feature to its most recent
1004    functional assignment.
1005    
1006    =back
1007    
1008    =cut
1009    
1010    sub GenomeAssignments {
1011        # Get the parameters.
1012        my ($self, $genomeID) = @_;
1013        # Declare the return variable.
1014        my $retVal = {};
1015        # Query the genome's features and annotations. We'll put the oldest annotations
1016        # first so that the last assignment to go into the hash will be the correct one.
1017        my $query = $self->Get(['HasFeature', 'IsTargetOfAnnotation', 'Annotation'],
1018                               "HasFeature(from-link) = ? ORDER BY Annotation(time)",
1019                               [$genomeID]);
1020        # Loop through the annotations.
1021        while (my $data = $query->Fetch) {
1022            # Get the feature ID and annotation text.
1023            my ($fid, $annotation) = $data->Values(['HasFeature(to-link)',
1024                                                    'Annotation(annotation)']);
1025            # Check to see if this is an assignment. Note that the user really
1026            # doesn't matter to us, other than we use it to determine whether or
1027            # not this is an assignment.
1028            my ($user, $assignment) = _ParseAssignment('fig', $annotation);
1029            if ($user) {
1030                # Here it's an assignment. We put it in the return hash, overwriting
1031                # any older assignment that might be present.
1032                $retVal->{$fid} = $assignment;
1033            }
1034        }
1035        # Return the result.
1036        return $retVal;
1037    }
1038    
1039  =head3 ContigLength  =head3 ContigLength
1040    
1041  C<< my $length = $sprout->ContigLength($contigID); >>  C<< my $length = $sprout->ContigLength($contigID); >>
# Line 857  Line 1069 
1069      # Set it from the sequence data, if any.      # Set it from the sequence data, if any.
1070      if ($sequence) {      if ($sequence) {
1071          my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);          my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
1072          $retVal = $start + $len;          $retVal = $start + $len - 1;
1073        }
1074        # Return the result.
1075        return $retVal;
1076    }
1077    
1078    =head3 ClusterPEGs
1079    
1080    C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
1081    
1082    Cluster the PEGs in a list according to the cluster coding scheme of the specified
1083    subsystem. In order for this to work properly, the subsystem object must have
1084    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
1085    This causes the cluster numbers to be pulled into the subsystem's color hash.
1086    If a PEG is not found in the color hash, it will not appear in the output
1087    sequence.
1088    
1089    =over 4
1090    
1091    =item sub
1092    
1093    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
1094    method.
1095    
1096    =item pegs
1097    
1098    Reference to the list of PEGs to be clustered.
1099    
1100    =item RETURN
1101    
1102    Returns a list of the PEGs, grouped into smaller lists by cluster number.
1103    
1104    =back
1105    
1106    =cut
1107    #: Return Type $@@;
1108    sub ClusterPEGs {
1109        # Get the parameters.
1110        my ($self, $sub, $pegs) = @_;
1111        # Declare the return variable.
1112        my $retVal = [];
1113        # Loop through the PEGs, creating arrays for each cluster.
1114        for my $pegID (@{$pegs}) {
1115            my $clusterNumber = $sub->get_cluster_number($pegID);
1116            # Only proceed if the PEG is in a cluster.
1117            if ($clusterNumber >= 0) {
1118                # Push this PEG onto the sub-list for the specified cluster number.
1119                push @{$retVal->[$clusterNumber]}, $pegID;
1120            }
1121      }      }
1122      # Return the result.      # Return the result.
1123      return $retVal;      return $retVal;
# Line 1007  Line 1267 
1267    
1268  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1269    
1270  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1271    
1272  Return the annotations of a feature.  Return the annotations of a feature.
1273    
# Line 1017  Line 1277 
1277    
1278  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1279    
1280    =item rawFlag
1281    
1282    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1283    will be returned in human-readable form.
1284    
1285  =item RETURN  =item RETURN
1286    
1287  Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.  Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.
1288    
1289  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1290    
1291  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1292    
1293  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1294    
# Line 1035  Line 1300 
1300  #: Return Type @%;  #: Return Type @%;
1301  sub FeatureAnnotations {  sub FeatureAnnotations {
1302      # Get the parameters.      # Get the parameters.
1303      my ($self, $featureID) = @_;      my ($self, $featureID, $rawFlag) = @_;
1304      # Create a query to get the feature's annotations and the associated users.      # Create a query to get the feature's annotations and the associated users.
1305      my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],      my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1306                             "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                             "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 1048  Line 1313 
1313              $annotation->Values(['IsTargetOfAnnotation(from-link)',              $annotation->Values(['IsTargetOfAnnotation(from-link)',
1314                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1315                                   'Annotation(annotation)']);                                   'Annotation(annotation)']);
1316            # Convert the time, if necessary.
1317            if (! $rawFlag) {
1318                $timeStamp = FriendlyTimestamp($timeStamp);
1319            }
1320          # Assemble them into a hash.          # Assemble them into a hash.
1321          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1322                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1323                                 user => $user, text => $text };                                 user => $user, text => $text };
1324          # Add it to the return list.          # Add it to the return list.
1325          push @retVal, $annotationHash;          push @retVal, $annotationHash;
# Line 1079  Line 1348 
1348    
1349  =item RETURN  =item RETURN
1350    
1351  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1352    
1353  =back  =back
1354    
# Line 1089  Line 1358 
1358      # Get the parameters.      # Get the parameters.
1359      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1360      # Get all of the feature's annotations.      # Get all of the feature's annotations.
1361      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1362                              "IsTargetOfAnnotation(from-link) = ?",                              "IsTargetOfAnnotation(from-link) = ?",
1363                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1364                                               'MadeAnnotation(from-link)']);
1365      # Declare the return hash.      # Declare the return hash.
1366      my %retVal;      my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1367      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1368      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1369      # Loop until we run out of annotations.      # Loop until we run out of annotations.
1370      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1371          # Get the annotation fields.          # Get the annotation fields.
1372          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1373          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
1374          my ($user, $function) = _ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1375          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1376              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1377              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1378              # return hash.              # return hash.
1379              $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1380          }          }
1381      }      }
1382      # Return the hash of assignments found.      # Return the hash of assignments found.
# Line 1126  Line 1392 
1392  The functional assignment is handled differently depending on the type of feature. If  The functional assignment is handled differently depending on the type of feature. If
1393  the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional  the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1394  assignment is a type of annotation. The format of an assignment is described in  assignment is a type of annotation. The format of an assignment is described in
1395  L</ParseLocation>. Its worth noting that we cannot filter on the content of the  L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1396  annotation itself because it's a text field; however, this is not a big problem because  annotation itself because it's a text field; however, this is not a big problem because
1397  most features only have a small number of annotations.  most features only have a small number of annotations.
1398    
# Line 1188  Line 1454 
1454              }              }
1455          }          }
1456          # Build a query for all of the feature's annotations, sorted by date.          # Build a query for all of the feature's annotations, sorted by date.
1457          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1458                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1459                                 [$featureID]);                                 [$featureID]);
1460          my $timeSelected = 0;          my $timeSelected = 0;
1461          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1462          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1463              # Get the annotation text.              # Get the annotation text.
1464              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);              my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1465                                                         'Annotation(time)', 'MadeAnnotation(from-link)']);
1466              # Check to see if this is a functional assignment for a trusted user.              # Check to see if this is a functional assignment for a trusted user.
1467              my ($user, $function) = _ParseAssignment($text);              my ($actualUser, $function) = _ParseAssignment($user, $text);
1468              if ($user) {              Trace("Assignment user is $actualUser, text is $function.") if T(4);
1469                if ($actualUser) {
1470                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1471                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1472                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                  if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1473                      $retVal = $function;                      $retVal = $function;
1474                      $timeSelected = $time;                      $timeSelected = $time;
1475                  }                  }
# Line 1217  Line 1485 
1485      return $retVal;      return $retVal;
1486  }  }
1487    
1488    =head3 FunctionsOf
1489    
1490    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1491    
1492    Return the functional assignments of a particular feature.
1493    
1494    The functional assignment is handled differently depending on the type of feature. If
1495    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1496    assignment is a type of annotation. The format of an assignment is described in
1497    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1498    annotation itself because it's a text field; however, this is not a big problem because
1499    most features only have a small number of annotations.
1500    
1501    If the feature is B<not> identified by a FIG ID, then the functional assignment
1502    information is taken from the B<ExternalAliasFunc> table. If the table does
1503    not contain an entry for the feature, an empty list is returned.
1504    
1505    =over 4
1506    
1507    =item featureID
1508    
1509    ID of the feature whose functional assignments are desired.
1510    
1511    =item RETURN
1512    
1513    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1514    that user.
1515    
1516    =back
1517    
1518    =cut
1519    #: Return Type @@;
1520    sub FunctionsOf {
1521        # Get the parameters.
1522        my ($self, $featureID) = @_;
1523        # Declare the return value.
1524        my @retVal = ();
1525        # Determine the ID type.
1526        if ($featureID =~ m/^fig\|/) {
1527            # Here we have a FIG feature ID. We must build the list of trusted
1528            # users.
1529            my %trusteeTable = ();
1530            # Build a query for all of the feature's annotations, sorted by date.
1531            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1532                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1533                                   [$featureID]);
1534            my $timeSelected = 0;
1535            # Loop until we run out of annotations.
1536            while (my $annotation = $query->Fetch()) {
1537                # Get the annotation text.
1538                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1539                                                                'Annotation(time)',
1540                                                                'MadeAnnotation(user)']);
1541                # Check to see if this is a functional assignment for a trusted user.
1542                my ($actualUser, $function) = _ParseAssignment($user, $text);
1543                if ($actualUser) {
1544                    # Here it is a functional assignment.
1545                    push @retVal, [$actualUser, $function];
1546                }
1547            }
1548        } else {
1549            # Here we have a non-FIG feature ID. In this case the user ID does not
1550            # matter. We simply get the information from the External Alias Function
1551            # table.
1552            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1553                                                     ['ExternalAliasFunc(func)']);
1554            push @retVal, map { ['master', $_] } @assignments;
1555        }
1556        # Return the assignments found.
1557        return @retVal;
1558    }
1559    
1560  =head3 BBHList  =head3 BBHList
1561    
1562  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1250  Line 1590 
1590      my %retVal = ();      my %retVal = ();
1591      # Loop through the incoming features.      # Loop through the incoming features.
1592      for my $featureID (@{$featureList}) {      for my $featureID (@{$featureList}) {
1593          # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1594          my $query = $self->Get(['IsBidirectionalBestHitOf'],          my @bbhData = FIGRules::BBHData($featureID);
1595                                 "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",          # Peel off the BBHs found.
1596                                 [$featureID, $genomeID]);          my @found = ();
1597          # Look for the best hit.          for my $bbh (@bbhData) {
1598          my $bbh = $query->Fetch;              push @found, $bbh->[0];
         if ($bbh) {  
             my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');  
             $retVal{$featureID} = $targetFeature;  
1599          }          }
1600            $retVal{$featureID} = \@found;
1601      }      }
1602      # Return the mapping.      # Return the mapping.
1603      return \%retVal;      return \%retVal;
# Line 1271  Line 1609 
1609    
1610  Return a list of the similarities to the specified feature.  Return a list of the similarities to the specified feature.
1611    
1612  Sprout does not support real similarities, so this method just returns the bidirectional  This method just returns the bidirectional best hits for performance reasons.
 best hits.  
1613    
1614  =over 4  =over 4
1615    
# Line 1292  Line 1629 
1629      # Get the parameters.      # Get the parameters.
1630      my ($self, $featureID, $count) = @_;      my ($self, $featureID, $count) = @_;
1631      # Ask for the best hits.      # Ask for the best hits.
1632      my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],      my @lists = FIGRules::BBHData($featureID);
                               "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",  
                               [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],  
                               $count);  
1633      # Create the return value.      # Create the return value.
1634      my %retVal = ();      my %retVal = ();
1635      for my $tuple (@lists) {      for my $tuple (@lists) {
# Line 1305  Line 1639 
1639      return %retVal;      return %retVal;
1640  }  }
1641    
   
   
1642  =head3 IsComplete  =head3 IsComplete
1643    
1644  C<< my $flag = $sprout->IsComplete($genomeID); >>  C<< my $flag = $sprout->IsComplete($genomeID); >>
# Line 1337  Line 1669 
1669      my $genomeData = $self->GetEntity('Genome', $genomeID);      my $genomeData = $self->GetEntity('Genome', $genomeID);
1670      if ($genomeData) {      if ($genomeData) {
1671          # The genome exists, so get the completeness flag.          # The genome exists, so get the completeness flag.
1672          ($retVal) = $genomeData->Value('complete');          ($retVal) = $genomeData->Value('Genome(complete)');
1673      }      }
1674      # Return the result.      # Return the result.
1675      return $retVal;      return $retVal;
# Line 1377  Line 1709 
1709    
1710  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1711    
1712  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1713    
1714  =over 4  =over 4
1715    
1716  =item featureID  =item featureID
1717    
1718  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1719    
1720  =item RETURN  =item RETURN
1721    
1722  Returns the ID of the genome for the specified feature. If the feature is not found, returns  Returns the ID of the genome for the specified feature or contig. If the feature or contig is not
1723  an undefined value.  found, returns an undefined value.
1724    
1725  =back  =back
1726    
# Line 1397  Line 1729 
1729  sub GenomeOf {  sub GenomeOf {
1730      # Get the parameters.      # Get the parameters.
1731      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1732      # Create a query to find the genome associated with the feature.      # Create a query to find the genome associated with the incoming ID.
1733      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1734                               [$featureID, $featureID]);
1735      # Declare the return value.      # Declare the return value.
1736      my $retVal;      my $retVal;
1737      # Get the genome ID.      # Get the genome ID.
# Line 1433  Line 1766 
1766  sub CoupledFeatures {  sub CoupledFeatures {
1767      # Get the parameters.      # Get the parameters.
1768      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1769        Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1770      # Create a query to retrieve the functionally-coupled features.      # Create a query to retrieve the functionally-coupled features.
1771      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1772                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);
# Line 1445  Line 1779 
1779          # Get the ID and score of the coupling.          # Get the ID and score of the coupling.
1780          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1781                                                          'Coupling(score)']);                                                          'Coupling(score)']);
1782          # The coupling ID contains the two feature IDs separated by a space. We use          Trace("$featureID coupled with score $score to ID $couplingID.") if T(coupling => 4);
1783          # this information to find the ID of the other feature.          # Get the other feature that participates in the coupling.
1784          my ($fid1, $fid2) = split / /, $couplingID;          my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],
1785          my $otherFeatureID = ($featureID eq $fid1 ? $fid2 : $fid1);                                             "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",
1786                                               [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');
1787            Trace("$couplingID target feature is $otherFeatureID.") if T(coupling => 4);
1788          # Attach the other feature's score to its ID.          # Attach the other feature's score to its ID.
1789          $retVal{$otherFeatureID} = $score;          $retVal{$otherFeatureID} = $score;
1790          $found = 1;          $found = 1;
# Line 1581  Line 1917 
1917      my ($self, $peg1, $peg2) = @_;      my ($self, $peg1, $peg2) = @_;
1918      # Declare the return values. We'll start with the coupling ID and undefine the      # Declare the return values. We'll start with the coupling ID and undefine the
1919      # flag and score until we have more information.      # flag and score until we have more information.
1920      my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);      my ($retVal, $inverted, $score) = ($self->CouplingID($peg1, $peg2), undef, undef);
1921      # Find the coupling data.      # Find the coupling data.
1922      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1923                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1924                                   [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);                                   [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1925      # Check to see if we found anything.      # Check to see if we found anything.
1926      if (!@pegs) {      if (!@pegs) {
1927            Trace("No coupling found.") if T(Coupling => 4);
1928          # No coupling, so undefine the return value.          # No coupling, so undefine the return value.
1929          $retVal = undef;          $retVal = undef;
1930      } else {      } else {
1931          # We have a coupling! Get the score and check for inversion.          # We have a coupling! Get the score and check for inversion.
1932          $score = $pegs[0]->[1];          $score = $pegs[0]->[1];
1933          $inverted = ($pegs[0]->[0] eq $peg1);          my $firstFound = $pegs[0]->[0];
1934            $inverted = ($firstFound ne $peg1);
1935            Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1936        }
1937        # Return the result.
1938        return ($retVal, $inverted, $score);
1939    }
1940    
1941    =head3 GetSynonymGroup
1942    
1943    C<< my $id = $sprout->GetSynonymGroup($fid); >>
1944    
1945    Return the synonym group name for the specified feature.
1946    
1947    =over 4
1948    
1949    =item fid
1950    
1951    ID of the feature whose synonym group is desired.
1952    
1953    =item RETURN
1954    
1955    The name of the synonym group to which the feature belongs. If the feature does
1956    not belong to a synonym group, the feature ID itself is returned.
1957    
1958    =back
1959    
1960    =cut
1961    
1962    sub GetSynonymGroup {
1963        # Get the parameters.
1964        my ($self, $fid) = @_;
1965        # Declare the return variable.
1966        my $retVal;
1967        # Find the synonym group.
1968        my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1969                                       [$fid], 'IsSynonymGroupFor(from-link)');
1970        # Check to see if we found anything.
1971        if (@groups) {
1972            $retVal = $groups[0];
1973        } else {
1974            $retVal = $fid;
1975        }
1976        # Return the result.
1977        return $retVal;
1978    }
1979    
1980    =head3 GetBoundaries
1981    
1982    C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>
1983    
1984    Determine the begin and end boundaries for the locations in a list. All of the
1985    locations must belong to the same contig and have mostly the same direction in
1986    order for this method to produce a meaningful result. The resulting
1987    begin/end pair will contain all of the bases in any of the locations.
1988    
1989    =over 4
1990    
1991    =item locList
1992    
1993    List of locations to process.
1994    
1995    =item RETURN
1996    
1997    Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1998    and the ending boundary. The beginning boundary will be left of the
1999    end for mostly-forward locations and right of the end for mostly-backward
2000    locations.
2001    
2002    =back
2003    
2004    =cut
2005    
2006    sub GetBoundaries {
2007        # Get the parameters.
2008        my ($self, @locList) = @_;
2009        # Set up the counters used to determine the most popular direction.
2010        my %counts = ( '+' => 0, '-' => 0 );
2011        # Get the last location and parse it.
2012        my $locObject = BasicLocation->new(pop @locList);
2013        # Prime the loop with its data.
2014        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
2015        # Count its direction.
2016        $counts{$locObject->Dir}++;
2017        # Loop through the remaining locations. Note that in most situations, this loop
2018        # will not iterate at all, because most of the time we will be dealing with a
2019        # singleton list.
2020        for my $loc (@locList) {
2021            # Create a location object.
2022            my $locObject = BasicLocation->new($loc);
2023            # Count the direction.
2024            $counts{$locObject->Dir}++;
2025            # Get the left end and the right end.
2026            my $left = $locObject->Left;
2027            my $right = $locObject->Right;
2028            # Merge them into the return variables.
2029            if ($left < $beg) {
2030                $beg = $left;
2031            }
2032            if ($right > $end) {
2033                $end = $right;
2034            }
2035        }
2036        # If the most common direction is reverse, flip the begin and end markers.
2037        if ($counts{'-'} > $counts{'+'}) {
2038            ($beg, $end) = ($end, $beg);
2039      }      }
2040      # Return the result.      # Return the result.
2041      return ($retVal, $inverted, $score);      return ($contig, $beg, $end);
2042  }  }
2043    
2044  =head3 CouplingID  =head3 CouplingID
2045    
2046  C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>  C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >>
2047    
2048  Return the coupling ID for a pair of feature IDs.  Return the coupling ID for a pair of feature IDs.
2049    
# Line 1634  Line 2076 
2076  =cut  =cut
2077  #: Return Type $;  #: Return Type $;
2078  sub CouplingID {  sub CouplingID {
2079      return join " ", sort @_;      my ($self, @pegs) = @_;
2080  }      return $self->DigestKey(join " ", sort @pegs);
   
 =head3 GetEntityTypes  
   
 C<< my @entityList = $sprout->GetEntityTypes(); >>  
   
 Return the list of supported entity types.  
   
 =cut  
 #: Return Type @;  
 sub GetEntityTypes {  
     # Get the parameters.  
     my ($self) = @_;  
     # Get the underlying database object.  
     my $erdb = $self->{_erdb};  
     # Get its entity type list.  
     my @retVal = $erdb->GetEntityTypes();  
2081  }  }
2082    
2083  =head3 ReadFasta  =head3 ReadFasta
# Line 1698  Line 2124 
2124          if ($line =~ m/^>\s*(.+?)(\s|\n)/) {          if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
2125              # Here we have a new header. Store the current sequence if we have one.              # Here we have a new header. Store the current sequence if we have one.
2126              if ($id) {              if ($id) {
2127                  $retVal{$id} = uc $sequence;                  $retVal{$id} = lc $sequence;
2128              }              }
2129              # Clear the sequence accumulator and save the new ID.              # Clear the sequence accumulator and save the new ID.
2130              ($id, $sequence) = ("$prefix$1", "");              ($id, $sequence) = ("$prefix$1", "");
2131          } else {          } else {
2132              # Here we have a data line, so we add it to the sequence accumulator.              # Here we have a data line, so we add it to the sequence accumulator.
2133              # First, we get the actual data out. Note that we normalize to upper              # First, we get the actual data out. Note that we normalize to lower
2134              # case.              # case.
2135              $line =~ /^\s*(.*?)(\s|\n)/;              $line =~ /^\s*(.*?)(\s|\n)/;
2136              $sequence .= $1;              $sequence .= $1;
# Line 1712  Line 2138 
2138      }      }
2139      # Flush out the last sequence (if any).      # Flush out the last sequence (if any).
2140      if ($sequence) {      if ($sequence) {
2141          $retVal{$id} = uc $sequence;          $retVal{$id} = lc $sequence;
2142      }      }
2143      # Close the file.      # Close the file.
2144      close FASTAFILE;      close FASTAFILE;
# Line 1799  Line 2225 
2225      # Get the data directory name.      # Get the data directory name.
2226      my $outputDirectory = $self->{_options}->{dataDir};      my $outputDirectory = $self->{_options}->{dataDir};
2227      # Dump the relations.      # Dump the relations.
2228      $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2229  }  }
2230    
2231  =head3 XMLFileName  =head3 XMLFileName
# Line 1851  Line 2277 
2277      # Get the parameters.      # Get the parameters.
2278      my ($self, $objectType, $fieldHash) = @_;      my ($self, $objectType, $fieldHash) = @_;
2279      # Call the underlying method.      # Call the underlying method.
2280      $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2281  }  }
2282    
2283  =head3 Annotate  =head3 Annotate
# Line 2010  Line 2436 
2436      return @retVal;      return @retVal;
2437  }  }
2438    
 =head3 Exists  
   
 C<< my $found = $sprout->Exists($entityName, $entityID); >>  
   
 Return TRUE if an entity exists, else FALSE.  
   
 =over 4  
   
 =item entityName  
   
 Name of the entity type (e.g. C<Feature>) relevant to the existence check.  
   
 =item entityID  
   
 ID of the entity instance whose existence is to be checked.  
   
 =item RETURN  
   
 Returns TRUE if the entity instance exists, else FALSE.  
   
 =back  
   
 =cut  
 #: Return Type $;  
 sub Exists {  
     # Get the parameters.  
     my ($self, $entityName, $entityID) = @_;  
     # Check for the entity instance.  
     my $testInstance = $self->GetEntity($entityName, $entityID);  
     # Return an existence indicator.  
     my $retVal = ($testInstance ? 1 : 0);  
     return $retVal;  
 }  
   
2439  =head3 FeatureTranslation  =head3 FeatureTranslation
2440    
2441  C<< my $translation = $sprout->FeatureTranslation($featureID); >>  C<< my $translation = $sprout->FeatureTranslation($featureID); >>
# Line 2531  Line 2923 
2923                                      ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                      ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2924      # Create the return value.      # Create the return value.
2925      my %retVal = ();      my %retVal = ();
2926        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2927        # in two spreadsheet cells.
2928        my %dupHash = ();
2929      # Loop through the results, adding them to the hash.      # Loop through the results, adding them to the hash.
2930      for my $record (@subsystems) {      for my $record (@subsystems) {
2931            # Get this subsystem and role.
2932          my ($subsys, $role) = @{$record};          my ($subsys, $role) = @{$record};
2933          if (exists $retVal{$subsys}) {          # Insure it's the first time for both.
2934            my $dupKey = "$subsys\n$role";
2935            if (! exists $dupHash{"$subsys\n$role"}) {
2936                $dupHash{$dupKey} = 1;
2937              push @{$retVal{$subsys}}, $role;              push @{$retVal{$subsys}}, $role;
         } else {  
             $retVal{$subsys} = [$role];  
2938          }          }
2939      }      }
2940      # Return the hash.      # Return the hash.
# Line 2576  Line 2973 
2973      return @retVal;      return @retVal;
2974  }  }
2975    
2976    =head3 GenomeSubsystemData
2977    
2978    C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>
2979    
2980    Return a hash mapping genome features to their subsystem roles.
2981    
2982    =over 4
2983    
2984    =item genomeID
2985    
2986    ID of the genome whose subsystem feature map is desired.
2987    
2988    =item RETURN
2989    
2990    Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb
2991    2-tuple contains a subsystem name followed by a role ID.
2992    
2993    =back
2994    
2995    =cut
2996    
2997    sub GenomeSubsystemData {
2998        # Get the parameters.
2999        my ($self, $genomeID) = @_;
3000        # Declare the return variable.
3001        my %retVal = ();
3002        # Get a list of the genome features that participate in subsystems. For each
3003        # feature we get its spreadsheet cells and the corresponding roles.
3004        my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],
3005                                 "HasFeature(from-link) = ?", [$genomeID],
3006                                 ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);
3007        # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems
3008        # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the
3009        # list. We use it at the beginning to get all the spreadsheet cells for the genome and
3010        # again at the end to filter out participation in subsystems with a negative variant code.
3011        my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],
3012                                     "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?",
3013                                     [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']);
3014        # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features.
3015        # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We
3016        # link these two lists together to create the result. First, we want a hash mapping
3017        # spreadsheet cells to subsystem names.
3018        my %subHash = map { $_->[0] => $_->[1] } @cellData;
3019        # We loop through @cellData to build the hash.
3020        for my $roleEntry (@roleData) {
3021            # Get the data for this feature and cell.
3022            my ($fid, $cellID, $role) = @{$roleEntry};
3023            # Check for a subsystem name.
3024            my $subsys = $subHash{$cellID};
3025            if ($subsys) {
3026                # Insure this feature has an entry in the return hash.
3027                if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
3028                # Merge in this new data.
3029                push @{$retVal{$fid}}, [$subsys, $role];
3030            }
3031        }
3032        # Return the result.
3033        return %retVal;
3034    }
3035    
3036  =head3 RelatedFeatures  =head3 RelatedFeatures
3037    
3038  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2611  Line 3068 
3068      # Get the parameters.      # Get the parameters.
3069      my ($self, $featureID, $function, $userID) = @_;      my ($self, $featureID, $function, $userID) = @_;
3070      # Get a list of the features that are BBHs of the incoming feature.      # Get a list of the features that are BBHs of the incoming feature.
3071      my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
                                      "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],  
                                      'IsBidirectionalBestHitOf(to-link)');  
3072      # Now we loop through the features, pulling out the ones that have the correct      # Now we loop through the features, pulling out the ones that have the correct
3073      # functional assignment.      # functional assignment.
3074      my @retVal = ();      my @retVal = ();
# Line 2677  Line 3132 
3132      return @retVal;      return @retVal;
3133  }  }
3134    
 =head3 GetAll  
   
 C<< my @list = $sprout->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>  
   
 Return a list of values taken from the objects returned by a query. The first three  
 parameters correspond to the parameters of the L</Get> method. The final parameter is  
 a list of the fields desired from each record found by the query. The field name  
 syntax is the standard syntax used for fields in the B<ERDB> system--  
 B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity  
 or relationship and I<fieldName> is the name of the field.  
   
 The list returned will be a list of lists. Each element of the list will contain  
 the values returned for the fields specified in the fourth parameter. If one of the  
 fields specified returns multiple values, they are flattened in with the rest. For  
 example, the following call will return a list of the features in a particular  
 spreadsheet cell, and each feature will be represented by a list containing the  
 feature ID followed by all of its aliases.  
   
 C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item fields  
   
 List of the fields to be returned in each element of the list returned.  
   
 =item count  
   
 Maximum number of records to return. If omitted or 0, all available records will be returned.  
   
 =item RETURN  
   
 Returns a list of list references. Each element of the return list contains the values for the  
 fields specified in the B<fields> parameter.  
   
 =back  
   
 =cut  
 #: Return Type @@;  
 sub GetAll {  
     # Get the parameters.  
     my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;  
     # Call the ERDB method.  
     my @retVal = $self->{_erdb}->GetAll($objectNames, $filterClause, $parameterList,  
                                         $fields, $count);  
     # Return the resulting list.  
     return @retVal;  
 }  
   
 =head3 GetFlat  
   
 C<< my @list = $sprout->GetFlat(\@objectNames, $filterClause, $parameterList, $field); >>  
   
 This is a variation of L</GetAll> that asks for only a single field per record and  
 returns a single flattened list.  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item field  
   
 Name of the field to be used to get the elements of the list returned.  
   
 =item RETURN  
   
 Returns a list of values.  
   
 =back  
   
 =cut  
 #: Return Type @;  
 sub GetFlat {  
     # Get the parameters.  
     my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;  
     # Construct the query.  
     my $query = $self->Get($objectNames, $filterClause, $parameterList);  
     # Create the result list.  
     my @retVal = ();  
     # Loop through the records, adding the field values found to the result list.  
     while (my $row = $query->Fetch()) {  
         push @retVal, $row->Value($field);  
     }  
     # Return the list created.  
     return @retVal;  
 }  
   
3135  =head3 Protein  =head3 Protein
3136    
3137  C<< my $protein = Sprout::Protein($sequence, $table); >>  C<< my $protein = Sprout::Protein($sequence, $table); >>
# Line 2897  Line 3233 
3233      # Create the return list, priming it with the name of the data directory.      # Create the return list, priming it with the name of the data directory.
3234      my @retVal = ($self->{_options}->{dataDir});      my @retVal = ($self->{_options}->{dataDir});
3235      # Concatenate the table names.      # Concatenate the table names.
3236      push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
3237      # Return the result.      # Return the result.
3238      return @retVal;      return @retVal;
3239  }  }
3240    
3241  =head3 LowBBHs  =head3 LowBBHs
3242    
3243  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
3244    
3245  Return the bidirectional best hits of a feature whose score is no greater than a  Return the bidirectional best hits of a feature whose score is no greater than a
3246  specified cutoff value. A higher cutoff value will allow inclusion of hits with  specified cutoff value. A higher cutoff value will allow inclusion of hits with
# Line 2933  Line 3269 
3269      my ($self, $featureID, $cutoff) = @_;      my ($self, $featureID, $cutoff) = @_;
3270      # Create the return hash.      # Create the return hash.
3271      my %retVal = ();      my %retVal = ();
3272      # Create a query to get the desired BBHs.      # Query for the desired BBHs.
3273      my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BBHData($featureID, $cutoff);
                                 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',  
                                 [$cutoff, $featureID],  
                                 ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);  
3274      # Form the results into the return hash.      # Form the results into the return hash.
3275      for my $pair (@bbhList) {      for my $pair (@bbhList) {
3276          $retVal{$pair->[0]} = $pair->[1];          $retVal{$pair->[0]} = $pair->[1];
# Line 2946  Line 3279 
3279      return %retVal;      return %retVal;
3280  }  }
3281    
3282    =head3 Sims
3283    
3284    C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>
3285    
3286    Get a list of similarities for a specified feature. Similarity information is not kept in the
3287    Sprout database; rather, they are retrieved from a network server. The similarities are
3288    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3289    so that its elements can be accessed by name.
3290    
3291    Similarities can be either raw or expanded. The raw similarities are basic
3292    hits between features with similar DNA. Expanding a raw similarity drags in any
3293    features considered substantially identical. So, for example, if features B<A1>,
3294    B<A2>, and B<A3> are all substatially identical to B<A>, then a raw similarity
3295    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3296    
3297    =over 4
3298    
3299    =item fid
3300    
3301    ID of the feature whose similarities are desired.
3302    
3303    =item maxN
3304    
3305    Maximum number of similarities to return.
3306    
3307    =item maxP
3308    
3309    Minumum allowable similarity score.
3310    
3311    =item select
3312    
3313    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3314    means only similarities to FIG features are returned; C<all> means all expanded
3315    similarities are returned; and C<figx> means similarities are expanded until the
3316    number of FIG features equals the maximum.
3317    
3318    =item max_expand
3319    
3320    The maximum number of features to expand.
3321    
3322    =item filters
3323    
3324    Reference to a hash containing filter information, or a subroutine that can be
3325    used to filter the sims.
3326    
3327    =item RETURN
3328    
3329    Returns a reference to a list of similarity objects, or C<undef> if an error
3330    occurred.
3331    
3332    =back
3333    
3334    =cut
3335    
3336    sub Sims {
3337        # Get the parameters.
3338        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3339        # Create the shim object to test for deleted FIDs.
3340        my $shim = FidCheck->new($self);
3341        # Ask the network for sims.
3342        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3343        # Return the result.
3344        return $retVal;
3345    }
3346    
3347  =head3 GetGroups  =head3 GetGroups
3348    
3349  C<< my %groups = $sprout->GetGroups(\@groupList); >>  C<< my %groups = $sprout->GetGroups(\@groupList); >>
# Line 2967  Line 3365 
3365          # Here we have a group list. Loop through them individually,          # Here we have a group list. Loop through them individually,
3366          # getting a list of the relevant genomes.          # getting a list of the relevant genomes.
3367          for my $group (@{$groupList}) {          for my $group (@{$groupList}) {
3368              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3369                  [$group], "Genome(id)");                  [$group], "Genome(id)");
3370              $retVal{$group} = \@genomeIDs;              $retVal{$group} = \@genomeIDs;
3371          }          }
# Line 2975  Line 3373 
3373          # Here we need all of the groups. In this case, we run through all          # Here we need all of the groups. In this case, we run through all
3374          # of the genome records, putting each one found into the appropriate          # of the genome records, putting each one found into the appropriate
3375          # group. Note that we use a filter clause to insure that only genomes          # group. Note that we use a filter clause to insure that only genomes
3376          # in groups are included in the return set.          # in real NMPDR groups are included in the return set.
3377          my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],          my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3378                                      ['Genome(id)', 'Genome(group-name)']);                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3379          # Loop through the genomes found.          # Loop through the genomes found.
3380          for my $genome (@genomes) {          for my $genome (@genomes) {
3381              # Pop this genome's ID off the current list.              # Pop this genome's ID off the current list.
# Line 3067  Line 3465 
3465      return $retVal;      return $retVal;
3466  }  }
3467    
3468    =head3 DeleteGenome
3469    
3470    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3471    
3472    Delete a genome from the database.
3473    
3474    =over 4
3475    
3476    =item genomeID
3477    
3478    ID of the genome to delete
3479    
3480    =item testFlag
3481    
3482    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3483    
3484    =item RETURN
3485    
3486    Returns a statistics object describing the rows deleted.
3487    
3488    =back
3489    
3490    =cut
3491    #: Return Type $%;
3492    sub DeleteGenome {
3493        # Get the parameters.
3494        my ($self, $genomeID, $testFlag) = @_;
3495        # Perform the delete for the genome's features.
3496        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);
3497        # Perform the delete for the primary genome data.
3498        my $stats = $self->Delete('Genome', $genomeID, $testFlag);
3499        $retVal->Accumulate($stats);
3500        # Return the result.
3501        return $retVal;
3502    }
3503    
3504    =head3 Fix
3505    
3506    C<< my %fixedHash = Sprout::Fix(%groupHash); >>
3507    
3508    Prepare a genome group hash (like that returned by L</GetGroups> for processing.
3509    Groups with the same primary name will be combined. The primary name is the
3510    first capitalized word in the group name.
3511    
3512    =over 4
3513    
3514    =item groupHash
3515    
3516    Hash to be fixed up.
3517    
3518    =item RETURN
3519    
3520    Returns a fixed-up version of the hash.
3521    
3522    =back
3523    
3524    =cut
3525    
3526    sub Fix {
3527        # Get the parameters.
3528        my (%groupHash) = @_;
3529        # Create the result hash.
3530        my %retVal = ();
3531        # Copy over the genomes.
3532        for my $groupID (keys %groupHash) {
3533            # Make a safety copy of the group ID.
3534            my $realGroupID = $groupID;
3535            # Yank the primary name.
3536            if ($groupID =~ /([A-Z]\w+)/) {
3537                $realGroupID = $1;
3538            }
3539            # Append this group's genomes into the result hash.
3540            Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}});
3541        }
3542        # Return the result hash.
3543        return %retVal;
3544    }
3545    
3546    =head3 GroupPageName
3547    
3548    C<< my $name = $sprout->GroupPageName($group); >>
3549    
3550    Return the name of the page for the specified NMPDR group.
3551    
3552    =over 4
3553    
3554    =item group
3555    
3556    Name of the relevant group.
3557    
3558    =item RETURN
3559    
3560    Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3561    memory it will be read in.
3562    
3563    =back
3564    
3565    =cut
3566    
3567    sub GroupPageName {
3568        # Get the parameters.
3569        my ($self, $group) = @_;
3570        # Declare the return variable.
3571        my $retVal;
3572        # Check for the group file data.
3573        if (! defined $self->{groupHash}) {
3574            # Read the group file.
3575            my %groupData = Sprout::ReadGroupFile($self->{_options}->{dataDir} . "/groups.tbl");
3576            # Store it in our object.
3577            $self->{groupHash} = \%groupData;
3578        }
3579        # Compute the real group name.
3580        my $realGroup = $group;
3581        if ($group =~ /([A-Z]\w+)/) {
3582            $realGroup = $1;
3583        }
3584        # Return the page name.
3585        $retVal = "../content/" . $self->{groupHash}->{$realGroup}->[1];
3586        # Return the result.
3587        return $retVal;
3588    }
3589    
3590    =head3 ReadGroupFile
3591    
3592    C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >>
3593    
3594    Read in the data from the specified group file. The group file contains information
3595    about each of the NMPDR groups.
3596    
3597    =over 4
3598    
3599    =item name
3600    
3601    Name of the group.
3602    
3603    =item page
3604    
3605    Name of the group's page on the web site (e.g. C<campy.php> for
3606    Campylobacter)
3607    
3608    =item genus
3609    
3610    Genus of the group
3611    
3612    =item species
3613    
3614    Species of the group, or an empty string if the group is for an entire
3615    genus. If the group contains more than one species, the species names
3616    should be separated by commas.
3617    
3618    =back
3619    
3620    The parameters to this method are as follows
3621    
3622    =over 4
3623    
3624    =item groupFile
3625    
3626    Name of the file containing the group data.
3627    
3628    =item RETURN
3629    
3630    Returns a hash keyed on group name. The value of each hash
3631    
3632    =back
3633    
3634    =cut
3635    
3636    sub ReadGroupFile {
3637        # Get the parameters.
3638        my ($groupFileName) = @_;
3639        # Declare the return variable.
3640        my %retVal;
3641        # Read the group file.
3642        my @groupLines = Tracer::GetFile($groupFileName);
3643        for my $groupLine (@groupLines) {
3644            my ($name, $page, $genus, $species) = split(/\t/, $groupLine);
3645            $retVal{$name} = [$page, $genus, $species];
3646        }
3647        # Return the result.
3648        return %retVal;
3649    }
3650    
3651  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3652    
3653  =head3 ParseAssignment  =head3 ParseAssignment
# Line 3077  Line 3658 
3658    
3659  A functional assignment is always of the form  A functional assignment is always of the form
3660    
3661      I<XXXX>C<\nset >I<YYYY>C< function to\n>I<ZZZZZ>      C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3662    
3663    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3664    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3665    not always the case.
3666    
3667  where I<XXXX> is the B<assigning user>, I<YYYY> is the B<user>, and I<ZZZZ> is the  In addition, the functional role may contain extra data that is stripped, such as
3668  actual functional role. In most cases, the user and the assigning user will be the  terminating spaces or a comment separated from the rest of the text by a tab.
 same, but that is not always the case.  
3669    
3670  This is a static method.  This is a static method.
3671    
3672  =over 4  =over 4
3673    
3674    =item user
3675    
3676    Name of the assigning user.
3677    
3678  =item text  =item text
3679    
3680  Text of the annotation.  Text of the annotation.
# Line 3102  Line 3690 
3690    
3691  sub _ParseAssignment {  sub _ParseAssignment {
3692      # Get the parameters.      # Get the parameters.
3693      my ($text) = @_;      my ($user, $text) = @_;
3694      # Declare the return value.      # Declare the return value.
3695      my @retVal = ();      my @retVal = ();
3696      # Check to see if this is a functional assignment.      # Check to see if this is a functional assignment.
3697      my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3698      if ($type =~ m/^set ([^ ]+) function to$/i) {      if ($type =~ m/^set function to$/i) {
3699          # Here it is, so we return the user name (which is in $1), the functional role text,          # Here we have an assignment without a user, so we use the incoming user ID.
3700          # and the assigning user.          @retVal = ($user, $function);
3701          @retVal = ($1, $function, $user);      } elsif ($type =~ m/^set (\S+) function to$/i) {
3702            # Here we have an assignment with a user that is passed back to the caller.
3703            @retVal = ($1, $function);
3704        }
3705        # If we have an assignment, we need to clean the function text. There may be
3706        # extra junk at the end added as a note from the user.
3707        if (defined( $retVal[1] )) {
3708            $retVal[1] =~ s/(\t\S)?\s*$//;
3709      }      }
3710      # Return the result list.      # Return the result list.
3711      return @retVal;      return @retVal;
# Line 3138  Line 3733 
3733    
3734  sub FriendlyTimestamp {  sub FriendlyTimestamp {
3735      my ($timeValue) = @_;      my ($timeValue) = @_;
3736      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
3737      return $retVal;      return $retVal;
3738  }  }
3739    
# Line 3200  Line 3795 
3795  }  }
3796    
3797    
   
3798  1;  1;

Legend:
Removed from v.1.22  
changed lines
  Added in v.1.86

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3