[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.14, Thu Jun 9 19:06:55 2005 UTC revision 1.65, Sun Jun 18 07:20:33 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 Stats;          use Stats;
# Line 32  Line 34 
34  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
35  L</dna_seq> returns the DNA sequence for a specified genome location.  L</dna_seq> returns the DNA sequence for a specified genome location.
36    
37    The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.
38    
39  =cut  =cut
40    
41  #: Constructor SFXlate->new_sprout_only();  #: Constructor SFXlate->new_sprout_only();
# Line 62  Line 66 
66    
67  * 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>)
68    
69  * 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)
70    
71  * B<port> connection port (default C<0>)  * B<port> connection port (default C<0>)
72    
73    * B<sock> connection socket (default same as SEED)
74    
75  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
76    
77  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
78    
79    * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
80    
81  =back  =back
82    
83  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 86  Line 94 
94          # 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
95          # the incoming data.          # the incoming data.
96          my $optionTable = Tracer::GetOptions({          my $optionTable = Tracer::GetOptions({
97                                             dbType               => 'mysql',                     # database type                         dbType       => $FIG_Config::dbms,
98                                             dataDir              => 'Data',                      # data file directory                                                          # database type
99                                             xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
100                                             userData             => 'root/',                     # user name and password                                                          # data file directory
101                                             port                 => 0,                           # database connection port                         xmlFileName  => "$FIG_Config::fig/SproutDBD.xml",
102                                                            # database definition file name
103                           userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
104                                                            # user name and password
105                           port         => $FIG_Config::dbport,
106                                                            # database connection port
107                           sock         => $FIG_Config::dbsock,
108                                             maxSegmentLength => 4500,            # maximum feature segment length                                             maxSegmentLength => 4500,            # maximum feature segment length
109                                             maxSequenceLength => 8000,           # maximum contig sequence length                                             maxSequenceLength => 8000,           # maximum contig sequence length
110                           noDBOpen     => 0,               # 1 to suppress the database open
111                                            }, $options);                                            }, $options);
112          # Get the data directory.          # Get the data directory.
113          my $dataDir = $optionTable->{dataDir};          my $dataDir = $optionTable->{dataDir};
# Line 100  Line 115 
115          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
116          my ($userName, $password) = ($1, $2);          my ($userName, $password) = ($1, $2);
117          # Connect to the database.          # Connect to the database.
118          my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
119        if (! $optionTable->{noDBOpen}) {
120            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
121                                    $password, $optionTable->{port}, undef, $optionTable->{sock});
122        }
123          # Create the ERDB object.          # Create the ERDB object.
124          my $xmlFileName = "$optionTable->{xmlFileName}";          my $xmlFileName = "$optionTable->{xmlFileName}";
125          my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
126          # Create this object.      # Add the option table and XML file name.
127          my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
128          # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
129          bless $self;      # Return it.
130          return $self;      return $retVal;
131  }  }
132    
133  =head3 MaxSegment  =head3 MaxSegment
# Line 143  Line 162 
162          return $self->{_options}->{maxSequenceLength};          return $self->{_options}->{maxSequenceLength};
163  }  }
164    
 =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);  
 }  
   
165  =head3 Load  =head3 Load
166    
167  C<< $sprout->Load($rebuild); >>;  C<< $sprout->Load($rebuild); >>;
# Line 367  Line 196 
196  sub Load {  sub Load {
197          # Get the parameters.          # Get the parameters.
198          my ($self, $rebuild) = @_;          my ($self, $rebuild) = @_;
         # Get the database object.  
         my $erdb = $self->{_erdb};  
199          # Load the tables from the data directory.          # Load the tables from the data directory.
200          my $retVal = $erdb->LoadTables($self->{_options}->{dataDir}, $rebuild);      my $retVal = $self->LoadTables($self->{_options}->{dataDir}, $rebuild);
201          # Return the statistics.          # Return the statistics.
202          return $retVal;          return $retVal;
203  }  }
204    
205  =head3 LoadUpdate  =head3 LoadUpdate
206    
207  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
208    
209  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
210  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 410  Line 237 
237  sub LoadUpdate {  sub LoadUpdate {
238          # Get the parameters.          # Get the parameters.
239          my ($self, $truncateFlag, $tableList) = @_;          my ($self, $truncateFlag, $tableList) = @_;
         # Get the database object.  
         my $erdb = $self->{_erdb};  
240          # Declare the return value.          # Declare the return value.
241          my $retVal = Stats->new();          my $retVal = Stats->new();
242          # Get the data directory.          # Get the data directory.
# Line 420  Line 245 
245          # Loop through the incoming table names.          # Loop through the incoming table names.
246          for my $tableName (@{$tableList}) {          for my $tableName (@{$tableList}) {
247                  # Find the table's file.                  # Find the table's file.
248                  my $fileName = "$dataDir/$tableName";          my $fileName = LoadFileName($dataDir, $tableName);
249                  if (! -e $fileName) {          if (! $fileName) {
250                          $fileName = "$fileName.dtx";              Trace("No load file found for $tableName in $dataDir.") if T(0);
251                  }          } else {
252                  # Attempt to load this table.                  # Attempt to load this table.
253                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);              my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);
254                  # Accumulate the resulting statistics.                  # Accumulate the resulting statistics.
255                  $retVal->Accumulate($result);                  $retVal->Accumulate($result);
256          }          }
257        }
258          # Return the statistics.          # Return the statistics.
259          return $retVal;          return $retVal;
260  }  }
261    
262    =head3 GenomeCounts
263    
264    C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>
265    
266    Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
267    genomes will be included in the counts.
268    
269    =over 4
270    
271    =item complete
272    
273    TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
274    counted
275    
276    =item RETURN
277    
278    A six-element list containing the number of genomes in each of six categories--
279    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
280    
281    =back
282    
283    =cut
284    
285    sub GenomeCounts {
286        # Get the parameters.
287        my ($self, $complete) = @_;
288        # Set the filter based on the completeness flag.
289        my $filter = ($complete ? "Genome(complete) = 1" : "");
290        # Get all the genomes and the related taxonomy information.
291        my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
292        # Clear the counters.
293        my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
294        # Loop through, counting the domains.
295        for my $genome (@genomes) {
296            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
297            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
298            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
299            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
300            elsif ($genome->[1] =~ /^env/i)      { ++$env }
301            else  { ++$unk }
302        }
303        # Return the counts.
304        return ($arch, $bact, $euk, $vir, $env, $unk);
305    }
306    
307    =head3 ContigCount
308    
309    C<< my $count = $sprout->ContigCount($genomeID); >>
310    
311    Return the number of contigs for the specified genome ID.
312    
313    =over 4
314    
315    =item genomeID
316    
317    ID of the genome whose contig count is desired.
318    
319    =item RETURN
320    
321    Returns the number of contigs for the specified genome.
322    
323    =back
324    
325    =cut
326    
327    sub ContigCount {
328        # Get the parameters.
329        my ($self, $genomeID) = @_;
330        # Get the contig count.
331        my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
332        # Return the result.
333        return $retVal;
334    }
335    
336    =head3 GeneMenu
337    
338    C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params); >>
339    
340    Return an HTML select menu of genomes. Each genome will be an option in the menu,
341    and will be displayed by name with the ID and a contig count attached. The selection
342    value will be the genome ID. The genomes will be sorted by genus/species name.
343    
344    =over 4
345    
346    =item attributes
347    
348    Reference to a hash mapping attributes to values for the SELECT tag generated.
349    
350    =item filterString
351    
352    A filter string for use in selecting the genomes. The filter string must conform
353    to the rules for the C<< ERDB->Get >> method.
354    
355    =item params
356    
357    Reference to a list of values to be substituted in for the parameter marks in
358    the filter string.
359    
360    =item RETURN
361    
362    Returns an HTML select menu with the specified genomes as selectable options.
363    
364    =back
365    
366    =cut
367    
368    sub GeneMenu {
369        # Get the parameters.
370        my ($self, $attributes, $filterString, $params) = @_;
371        # Start the menu.
372        my $retVal = "<select " .
373            join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
374            ">\n";
375        # Get the genomes.
376        my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
377                                                                         'Genome(genus)',
378                                                                         'Genome(species)']);
379        # Sort them by name.
380        my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
381        # Loop through the genomes, creating the option tags.
382        for my $genomeData (@sorted) {
383            # Get the data for this genome.
384            my ($genomeID, $genus, $species) = @{$genomeData};
385            # Get the contig count.
386            my $count = $self->ContigCount($genomeID);
387            my $counting = ($count == 1 ? "contig" : "contigs");
388            # Build the option tag.
389            $retVal .= "<option value=\"$genomeID\">$genus $species ($genomeID) [$count $counting]</option>\n";
390        }
391        # Close the SELECT tag.
392        $retVal .= "</select>\n";
393        # Return the result.
394        return $retVal;
395    }
396  =head3 Build  =head3 Build
397    
398  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 447  Line 407 
407          # Get the parameters.          # Get the parameters.
408          my ($self) = @_;          my ($self) = @_;
409          # Create the tables.          # Create the tables.
410          $self->{_erdb}->CreateTables;      $self->CreateTables();
411  }  }
412    
413  =head3 Genomes  =head3 Genomes
# Line 570  Line 530 
530  =item RETURN  =item RETURN
531    
532  Returns a list of the feature's contig segments. The locations are returned as a list in a list  Returns a list of the feature's contig segments. The locations are returned as a list in a list
533  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context.
534    
535  =back  =back
536    
# Line 597  Line 557 
557                  if ($prevContig eq $contigID && $dir eq $prevDir) {                  if ($prevContig eq $contigID && $dir eq $prevDir) {
558                          # 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
559                          # new segment's beginning is next to the old segment's end.                          # new segment's beginning is next to the old segment's end.
560                          if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||              if ($dir eq "-" && $beg + $len == $prevBeg) {
561                                  ($dir eq "+" && $beg == $prevBeg + $prevLen)) {                  # Here we're merging two backward blocks, so we keep the new begin point
562                                  # Here we need to merge two segments. Adjust the beginning and length values                  # and adjust the length.
563                                  # to include both segments.                  $len += $prevLen;
564                    # Pop the old segment off. The new one will replace it later.
565                    pop @retVal;
566                } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
567                    # Here we need to merge two forward blocks. Adjust the beginning and
568                    # length values to include both segments.
569                                  $beg = $prevBeg;                                  $beg = $prevBeg;
570                                  $len += $prevLen;                                  $len += $prevLen;
571                                  # 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 609  Line 574 
574                  }                  }
575                  # Remember this specifier for the adjacent-segment test the next time through.                  # Remember this specifier for the adjacent-segment test the next time through.
576                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
577            # Compute the initial base pair.
578            my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
579                  # Add the specifier to the list.                  # Add the specifier to the list.
580                  push @retVal, "${contigID}_$beg$dir$len";          push @retVal, "${contigID}_$start$dir$len";
581          }          }
582          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
583          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
584  }  }
585    
586  =head3 ParseLocation  =head3 ParseLocation
# Line 644  Line 611 
611      shift if UNIVERSAL::isa($_[0],__PACKAGE__);      shift if UNIVERSAL::isa($_[0],__PACKAGE__);
612          my ($location) = @_;          my ($location) = @_;
613          # Parse it into segments.          # Parse it into segments.
614          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
615          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
616          # If the direction is an underscore, convert it to a + or -.          # If the direction is an underscore, convert it to a + or -.
617          if ($dir eq "_") {          if ($dir eq "_") {
# Line 720  Line 687 
687  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,
688  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>.
689    
690    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
691    between positions 1401 and 1532, inclusive.
692    
693        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
694    
695  =over 4  =over 4
696    
697  =item locationList  =item locationList
698    
699  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
700  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
701    
702  =item RETURN  =item RETURN
703    
# Line 752  Line 724 
724                  # 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
725                  # before putting it in the return value.                  # before putting it in the return value.
726                  my ($start, $stop);                  my ($start, $stop);
727            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
728                  if ($dir eq "+") {                  if ($dir eq "+") {
729                          $start = $beg;                          $start = $beg;
730                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
731                  } else {                  } else {
732                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
733                          $stop = $beg;                          $stop = $beg;
734                  }                  }
735            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
736                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
737                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
738                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 770  Line 744 
744                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
745                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
746                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
747                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
748                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
749                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
750                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
751                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
752                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
753                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
754                  }                  }
755                  # 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.
756                  if ($dir eq '+') {                  if ($dir eq '+') {
757                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
758                  } else {                  } else {
759                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
760                  }                  }
761          }          }
762          # Return the result.          # Return the result.
# Line 818  Line 793 
793          return @retVal;          return @retVal;
794  }  }
795    
796    =head3 GenomeLength
797    
798    C<< my $length = $sprout->GenomeLength($genomeID); >>
799    
800    Return the length of the specified genome in base pairs.
801    
802    =over 4
803    
804    =item genomeID
805    
806    ID of the genome whose base pair count is desired.
807    
808    =item RETURN
809    
810    Returns the number of base pairs in all the contigs of the specified
811    genome.
812    
813    =back
814    
815    =cut
816    
817    sub GenomeLength {
818        # Get the parameters.
819        my ($self, $genomeID) = @_;
820        # Declare the return variable.
821        my $retVal = 0;
822        # Get the genome's contig sequence lengths.
823        my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
824                           [$genomeID], 'IsMadeUpOf(len)');
825        # Sum the lengths.
826        map { $retVal += $_ } @lens;
827        # Return the result.
828        return $retVal;
829    }
830    
831    =head3 FeatureCount
832    
833    C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
834    
835    Return the number of features of the specified type in the specified genome.
836    
837    =over 4
838    
839    =genomeID
840    
841    ID of the genome whose feature count is desired.
842    
843    =item type
844    
845    Type of feature to count (eg. C<peg>, C<rna>, etc.).
846    
847    =item RETURN
848    
849    Returns the number of features of the specified type for the specified genome.
850    
851    =back
852    
853    =cut
854    
855    sub FeatureCount {
856        # Get the parameters.
857        my ($self, $genomeID, $type) = @_;
858        # Compute the count.
859        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
860                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
861                                    [$genomeID, $type]);
862        # Return the result.
863        return $retVal;
864    }
865    
866    =head3 GenomeAssignments
867    
868    C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
869    
870    Return a list of a genome's assigned features. The return hash will contain each
871    assigned feature of the genome mapped to the text of its most recent functional
872    assignment.
873    
874    =over 4
875    
876    =item genomeID
877    
878    ID of the genome whose functional assignments are desired.
879    
880    =item RETURN
881    
882    Returns a reference to a hash which maps each feature to its most recent
883    functional assignment.
884    
885    =back
886    
887    =cut
888    
889    sub GenomeAssignments {
890        # Get the parameters.
891        my ($self, $genomeID) = @_;
892        # Declare the return variable.
893        my $retVal = {};
894        # Query the genome's features and annotations. We'll put the oldest annotations
895        # first so that the last assignment to go into the hash will be the correct one.
896        my $query = $self->Get(['HasFeature', 'IsTargetOfAnnotation', 'Annotation'],
897                               "HasFeature(from-link) = ? ORDER BY Annotation(time)",
898                               [$genomeID]);
899        # Loop through the annotations.
900        while (my $data = $query->Fetch) {
901            # Get the feature ID and annotation text.
902            my ($fid, $annotation) = $data->Values(['HasFeature(from-link)',
903                                                    'Annotation(annotation)']);
904            # Check to see if this is an assignment. Note that the user really
905            # doesn't matter to us, other than we use it to determine whether or
906            # not this is an assignment.
907            my ($user, $assignment) = $self->_ParseAssignment('fig', $annotation);
908            if ($user) {
909                # Here it's an assignment. We put it in the return hash, overwriting
910                # any older assignment that might be present.
911                $retVal->{$fid} = $assignment;
912            }
913        }
914        # Return the result.
915        return $retVal;
916    }
917    
918  =head3 ContigLength  =head3 ContigLength
919    
920  C<< my $length = $sprout->ContigLength($contigID); >>  C<< my $length = $sprout->ContigLength($contigID); >>
# Line 851  Line 948 
948          # Set it from the sequence data, if any.          # Set it from the sequence data, if any.
949          if ($sequence) {          if ($sequence) {
950                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
951                  $retVal = $start + $len;          $retVal = $start + $len - 1;
952        }
953        # Return the result.
954        return $retVal;
955    }
956    
957    =head3 ClusterPEGs
958    
959    C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
960    
961    Cluster the PEGs in a list according to the cluster coding scheme of the specified
962    subsystem. In order for this to work properly, the subsystem object must have
963    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
964    This causes the cluster numbers to be pulled into the subsystem's color hash.
965    If a PEG is not found in the color hash, it will not appear in the output
966    sequence.
967    
968    =over 4
969    
970    =item sub
971    
972    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
973    method.
974    
975    =item pegs
976    
977    Reference to the list of PEGs to be clustered.
978    
979    =item RETURN
980    
981    Returns a list of the PEGs, grouped into smaller lists by cluster number.
982    
983    =back
984    
985    =cut
986    #: Return Type $@@;
987    sub ClusterPEGs {
988        # Get the parameters.
989        my ($self, $sub, $pegs) = @_;
990        # Declare the return variable.
991        my $retVal = [];
992        # Loop through the PEGs, creating arrays for each cluster.
993        for my $pegID (@{$pegs}) {
994            my $clusterNumber = $sub->get_cluster_number($pegID);
995            # Only proceed if the PEG is in a cluster.
996            if ($clusterNumber >= 0) {
997                # Push this PEG onto the sub-list for the specified cluster number.
998                push @{$retVal->[$clusterNumber]}, $pegID;
999            }
1000          }          }
1001          # Return the result.          # Return the result.
1002          return $retVal;          return $retVal;
# Line 1001  Line 1146 
1146    
1147  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1148    
1149  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1150    
1151  Return the annotations of a feature.  Return the annotations of a feature.
1152    
# Line 1011  Line 1156 
1156    
1157  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1158    
1159    =item rawFlag
1160    
1161    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1162    will be returned in human-readable form.
1163    
1164  =item RETURN  =item RETURN
1165    
1166  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.
1167    
1168  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1169    
1170  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1171    
1172  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1173    
# Line 1029  Line 1179 
1179  #: Return Type @%;  #: Return Type @%;
1180  sub FeatureAnnotations {  sub FeatureAnnotations {
1181          # Get the parameters.          # Get the parameters.
1182          my ($self, $featureID) = @_;      my ($self, $featureID, $rawFlag) = @_;
1183          # 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.
1184          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1185                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 1042  Line 1192 
1192                          $annotation->Values(['IsTargetOfAnnotation(from-link)',                          $annotation->Values(['IsTargetOfAnnotation(from-link)',
1193                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1194                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1195            # Convert the time, if necessary.
1196            if (! $rawFlag) {
1197                $timeStamp = FriendlyTimestamp($timeStamp);
1198            }
1199                  # Assemble them into a hash.                  # Assemble them into a hash.
1200          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1201                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1202                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1203                  # Add it to the return list.                  # Add it to the return list.
1204                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1073  Line 1227 
1227    
1228  =item RETURN  =item RETURN
1229    
1230  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1231    
1232  =back  =back
1233    
# Line 1083  Line 1237 
1237          # Get the parameters.          # Get the parameters.
1238          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
1239          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1240      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1241                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1242                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1243                                               'MadeAnnotation(from-link)']);
1244          # Declare the return hash.          # Declare the return hash.
1245          my %retVal;          my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1246      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1247      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1248          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1249      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1250          # Get the annotation fields.          # Get the annotation fields.
1251          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1252                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1253                  my ($user, $function) = _ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1254          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1255              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1256              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1257              # return hash.              # return hash.
1258                          $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1259                  }                  }
1260          }          }
1261          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1120  Line 1271 
1271  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
1272  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
1273  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
1274  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
1275  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
1276  most features only have a small number of annotations.  most features only have a small number of annotations.
1277    
# Line 1182  Line 1333 
1333              }              }
1334          }          }
1335          # 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.
1336          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1337                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1338                                 [$featureID]);                                 [$featureID]);
1339          my $timeSelected = 0;          my $timeSelected = 0;
1340          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1341          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1342              # Get the annotation text.              # Get the annotation text.
1343              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);              my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1344                                                         'Annotation(time)', 'MadeAnnotation(from-link)']);
1345              # 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.
1346              my ($user, $function) = _ParseAssignment($text);              my ($actualUser, $function) = _ParseAssignment($user, $text);
1347              if ($user) {              Trace("Assignment user is $actualUser, text is $function.") if T(4);
1348                if ($actualUser) {
1349                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1350                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1351                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                  if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1352                      $retVal = $function;                      $retVal = $function;
1353                      $timeSelected = $time;                      $timeSelected = $time;
1354                  }                  }
# Line 1211  Line 1364 
1364          return $retVal;          return $retVal;
1365  }  }
1366    
1367    =head3 FunctionsOf
1368    
1369    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1370    
1371    Return the functional assignments of a particular feature.
1372    
1373    The functional assignment is handled differently depending on the type of feature. If
1374    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1375    assignment is a type of annotation. The format of an assignment is described in
1376    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1377    annotation itself because it's a text field; however, this is not a big problem because
1378    most features only have a small number of annotations.
1379    
1380    If the feature is B<not> identified by a FIG ID, then the functional assignment
1381    information is taken from the B<ExternalAliasFunc> table. If the table does
1382    not contain an entry for the feature, an empty list is returned.
1383    
1384    =over 4
1385    
1386    =item featureID
1387    
1388    ID of the feature whose functional assignments are desired.
1389    
1390    =item RETURN
1391    
1392    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1393    that user.
1394    
1395    =back
1396    
1397    =cut
1398    #: Return Type @@;
1399    sub FunctionsOf {
1400        # Get the parameters.
1401        my ($self, $featureID) = @_;
1402        # Declare the return value.
1403        my @retVal = ();
1404        # Determine the ID type.
1405        if ($featureID =~ m/^fig\|/) {
1406            # Here we have a FIG feature ID. We must build the list of trusted
1407            # users.
1408            my %trusteeTable = ();
1409            # Build a query for all of the feature's annotations, sorted by date.
1410            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1411                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1412                                   [$featureID]);
1413            my $timeSelected = 0;
1414            # Loop until we run out of annotations.
1415            while (my $annotation = $query->Fetch()) {
1416                # Get the annotation text.
1417                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1418                                                                'Annotation(time)',
1419                                                                'MadeAnnotation(user)']);
1420                # Check to see if this is a functional assignment for a trusted user.
1421                my ($actualUser, $function) = _ParseAssignment($user, $text);
1422                if ($actualUser) {
1423                    # Here it is a functional assignment.
1424                    push @retVal, [$actualUser, $function];
1425                }
1426            }
1427        } else {
1428            # Here we have a non-FIG feature ID. In this case the user ID does not
1429            # matter. We simply get the information from the External Alias Function
1430            # table.
1431            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1432                                                     ['ExternalAliasFunc(func)']);
1433            push @retVal, map { ['master', $_] } @assignments;
1434        }
1435        # Return the assignments found.
1436        return @retVal;
1437    }
1438    
1439  =head3 BBHList  =head3 BBHList
1440    
1441  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1230  Line 1455 
1455    
1456  =item RETURN  =item RETURN
1457    
1458  Returns a reference to a hash that maps the IDs of the incoming features to the IDs of  Returns a reference to a hash that maps the IDs of the incoming features to the best hits
1459  their best hits.  on the target genome.
1460    
1461  =back  =back
1462    
# Line 1248  Line 1473 
1473                  my $query = $self->Get(['IsBidirectionalBestHitOf'],                  my $query = $self->Get(['IsBidirectionalBestHitOf'],
1474                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",
1475                                                             [$featureID, $genomeID]);                                                             [$featureID, $genomeID]);
1476                  # Look for the best hit.          # Peel off the BBHs found.
1477                  my $bbh = $query->Fetch;          my @found = ();
1478                  if ($bbh) {          while (my $bbh = $query->Fetch) {
1479                          my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');
                         $retVal{$featureID} = $targetFeature;  
1480                  }                  }
1481            $retVal{$featureID} = \@found;
1482          }          }
1483          # Return the mapping.          # Return the mapping.
1484          return \%retVal;          return \%retVal;
1485  }  }
1486    
1487    =head3 SimList
1488    
1489    C<< my %similarities = $sprout->SimList($featureID, $count); >>
1490    
1491    Return a list of the similarities to the specified feature.
1492    
1493    Sprout does not support real similarities, so this method just returns the bidirectional
1494    best hits.
1495    
1496    =over 4
1497    
1498    =item featureID
1499    
1500    ID of the feature whose similarities are desired.
1501    
1502    =item count
1503    
1504    Maximum number of similar features to be returned, or C<0> to return them all.
1505    
1506    =back
1507    
1508    =cut
1509    #: Return Type %;
1510    sub SimList {
1511        # Get the parameters.
1512        my ($self, $featureID, $count) = @_;
1513        # Ask for the best hits.
1514        my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],
1515                                  "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",
1516                                  [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],
1517                                  $count);
1518        # Create the return value.
1519        my %retVal = ();
1520        for my $tuple (@lists) {
1521            $retVal{$tuple->[0]} = $tuple->[1];
1522        }
1523        # Return the result.
1524        return %retVal;
1525    }
1526    
1527    
1528    
1529    =head3 IsComplete
1530    
1531    C<< my $flag = $sprout->IsComplete($genomeID); >>
1532    
1533    Return TRUE if the specified genome is complete, else FALSE.
1534    
1535    =over 4
1536    
1537    =item genomeID
1538    
1539    ID of the genome whose completeness status is desired.
1540    
1541    =item RETURN
1542    
1543    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1544    not found.
1545    
1546    =back
1547    
1548    =cut
1549    #: Return Type $;
1550    sub IsComplete {
1551        # Get the parameters.
1552        my ($self, $genomeID) = @_;
1553        # Declare the return variable.
1554        my $retVal;
1555        # Get the genome's data.
1556        my $genomeData = $self->GetEntity('Genome', $genomeID);
1557        if ($genomeData) {
1558            # The genome exists, so get the completeness flag.
1559            ($retVal) = $genomeData->Value('Genome(complete)');
1560        }
1561        # Return the result.
1562        return $retVal;
1563    }
1564    
1565  =head3 FeatureAliases  =head3 FeatureAliases
1566    
1567  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
# Line 1293  Line 1596 
1596    
1597  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1598    
1599  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1600    
1601  =over 4  =over 4
1602    
1603  =item featureID  =item featureID
1604    
1605  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1606    
1607  =item RETURN  =item RETURN
1608    
1609  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
1610  an undefined value.  found, returns an undefined value.
1611    
1612  =back  =back
1613    
# Line 1313  Line 1616 
1616  sub GenomeOf {  sub GenomeOf {
1617          # Get the parameters.          # Get the parameters.
1618          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
1619          # Create a query to find the genome associated with the feature.      # Create a query to find the genome associated with the incoming ID.
1620          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1621                               [$featureID, $featureID]);
1622          # Declare the return value.          # Declare the return value.
1623          my $retVal;          my $retVal;
1624          # Get the genome ID.          # Get the genome ID.
# Line 1325  Line 1629 
1629          return $retVal;          return $retVal;
1630  }  }
1631    
1632  =head3 CoupledFeatures  =head3 CoupledFeatures
1633    
1634    C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >>
1635    
1636    Return the features functionally coupled with a specified feature. Features are considered
1637    functionally coupled if they tend to be clustered on the same chromosome.
1638    
1639    =over 4
1640    
1641    =item featureID
1642    
1643    ID of the feature whose functionally-coupled brethren are desired.
1644    
1645    =item RETURN
1646    
1647    A hash mapping the functionally-coupled feature IDs to the coupling score.
1648    
1649    =back
1650    
1651    =cut
1652    #: Return Type %;
1653    sub CoupledFeatures {
1654        # Get the parameters.
1655        my ($self, $featureID) = @_;
1656        # Create a query to retrieve the functionally-coupled features.
1657        my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1658                               "ParticipatesInCoupling(from-link) = ?", [$featureID]);
1659        # This value will be set to TRUE if we find at least one coupled feature.
1660        my $found = 0;
1661        # Create the return hash.
1662        my %retVal = ();
1663        # Retrieve the relationship records and store them in the hash.
1664        while (my $clustering = $query->Fetch()) {
1665            # Get the ID and score of the coupling.
1666            my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1667                                                            'Coupling(score)']);
1668            # Get the other feature that participates in the coupling.
1669            my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],
1670                                               "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",
1671                                               [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');
1672            # Attach the other feature's score to its ID.
1673            $retVal{$otherFeatureID} = $score;
1674            $found = 1;
1675        }
1676        # Functional coupling is reflexive. If we found at least one coupled feature, we must add
1677        # the incoming feature as well.
1678        if ($found) {
1679            $retVal{$featureID} = 9999;
1680        }
1681        # Return the hash.
1682        return %retVal;
1683    }
1684    
1685    =head3 CouplingEvidence
1686    
1687    C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1688    
1689    Return the evidence for a functional coupling.
1690    
1691    A pair of features is considered evidence of a coupling between two other
1692    features if they occur close together on a contig and both are similar to
1693    the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1694    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1695    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1696    similar to B<A2>.
1697    
1698    The score of a coupling is determined by the number of pieces of evidence
1699    that are considered I<representative>. If several evidence items belong to
1700    a group of genomes that are close to each other, only one of those items
1701    is considered representative. The other evidence items are presumed to be
1702    there because of the relationship between the genomes rather than because
1703    the two proteins generated by the features have a related functionality.
1704    
1705    Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1706    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1707    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1708    and FALSE otherwise.
1709    
1710    =over 4
1711    
1712    =item peg1
1713    
1714    ID of the feature of interest.
1715    
1716    =item peg2
1717    
1718    ID of a feature functionally coupled to the feature of interest.
1719    
1720    =item RETURN
1721    
1722    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1723    of interest, a feature similar to the functionally coupled feature, and a flag
1724    that is TRUE for a representative piece of evidence and FALSE otherwise.
1725    
1726    =back
1727    
1728    =cut
1729    #: Return Type @@;
1730    sub CouplingEvidence {
1731        # Get the parameters.
1732        my ($self, $peg1, $peg2) = @_;
1733        # Declare the return variable.
1734        my @retVal = ();
1735        # Our first task is to find out the nature of the coupling: whether or not
1736        # it exists, its score, and whether the features are stored in the same
1737        # order as the ones coming in.
1738        my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1739        # Only proceed if a coupling exists.
1740        if ($couplingID) {
1741            # Determine the ordering to place on the evidence items. If we're
1742            # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1743            # we want feature 1 before feature 2 (normal).
1744            Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);
1745            my $ordering = ($inverted ? "DESC" : "");
1746            # Get the coupling evidence.
1747            my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
1748                                              "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",
1749                                              [$couplingID],
1750                                              ['PCH(used)', 'UsesAsEvidence(to-link)']);
1751            # Loop through the evidence items. Each piece of evidence is represented by two
1752            # positions in the evidence list, one for each feature on the other side of the
1753            # evidence link. If at some point we want to generalize to couplings with
1754            # more than two positions, this section of code will need to be re-done.
1755            while (@evidenceList > 0) {
1756                my $peg1Data = shift @evidenceList;
1757                my $peg2Data = shift @evidenceList;
1758                Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1759                push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1760            }
1761            Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1762        }
1763        # Return the result.
1764        return @retVal;
1765    }
1766    
1767    =head3 GetCoupling
1768    
1769  C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >>  C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>
1770    
1771  Return the features functionally coupled with a specified feature. Features are considered  Return the coupling (if any) for the specified pair of PEGs. If a coupling
1772  functionally coupled if they tend to be clustered on the same chromosome.  exists, we return the coupling ID along with an indicator of whether the
1773    coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.
1774    In the second case, we say the coupling is I<inverted>. The importance of an
1775    inverted coupling is that the PEGs in the evidence will appear in reverse order.
1776    
1777  =over 4  =over 4
1778    
1779  =item featureID  =item peg1
1780    
1781  ID of the feature whose functionally-coupled brethren are desired.  ID of the feature of interest.
1782    
1783    =item peg2
1784    
1785    ID of the potentially coupled feature.
1786    
1787  =item RETURN  =item RETURN
1788    
1789  A hash mapping the functionally-coupled feature IDs to the coupling score.  Returns a three-element list. The first element contains the database ID of
1790    the coupling. The second element is FALSE if the coupling is stored in the
1791    database in the caller specified order and TRUE if it is stored in the
1792    inverted order. The third element is the coupling's score. If the coupling
1793    does not exist, all three list elements will be C<undef>.
1794    
1795  =back  =back
1796    
1797  =cut  =cut
1798  #: Return Type %;  #: Return Type $%@;
1799  sub CoupledFeatures {  sub GetCoupling {
1800          # Get the parameters.          # Get the parameters.
1801          my ($self, $featureID) = @_;      my ($self, $peg1, $peg2) = @_;
1802          # Create a query to retrieve the functionally-coupled features.      # Declare the return values. We'll start with the coupling ID and undefine the
1803          my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      # flag and score until we have more information.
1804                                                     "ParticipatesInCoupling(from-link) = ?", [$featureID]);      my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);
1805          # This value will be set to TRUE if we find at least one coupled feature.      # Find the coupling data.
1806          my $found = 0;      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1807          # Create the return hash.                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1808          my %retVal = ();                                   [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1809          # Retrieve the relationship records and store them in the hash.      # Check to see if we found anything.
1810          while (my $clustering = $query->Fetch()) {      if (!@pegs) {
1811                  # Get the ID and score of the coupling.          Trace("No coupling found.") if T(Coupling => 4);
1812                  my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          # No coupling, so undefine the return value.
1813                                                                                  'Coupling(score)']);          $retVal = undef;
1814                  # The coupling ID contains the two feature IDs separated by a space. We use      } else {
1815                  # this information to find the ID of the other feature.          # We have a coupling! Get the score and check for inversion.
1816                  my ($fid1, $fid2) = split / /, $couplingID;          $score = $pegs[0]->[1];
1817                  my $otherFeatureID = ($featureID eq $fid1 ? $fid2 : $fid1);          my $firstFound = $pegs[0]->[0];
1818                  # Attach the other feature's score to its ID.          $inverted = ($firstFound ne $peg1);
1819                  $retVal{$otherFeatureID} = $score;          Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
                 $found = 1;  
         }  
         # Functional coupling is reflexive. If we found at least one coupled feature, we must add  
         # the incoming feature as well.  
         if ($found) {  
                 $retVal{$featureID} = 9999;  
1820      }      }
1821          # Return the hash.      # Return the result.
1822          return %retVal;      return ($retVal, $inverted, $score);
1823  }  }
1824    
1825  =head3 GetEntityTypes  =head3 CouplingID
1826    
1827    C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>
1828    
1829    Return the coupling ID for a pair of feature IDs.
1830    
1831    The coupling ID is currently computed by joining the feature IDs in
1832    sorted order with a space. Client modules (that is, modules which
1833    use Sprout) should not, however, count on this always being the
1834    case. This method provides a way for abstracting the concept of a
1835    coupling ID. All that we know for sure about it is that it can be
1836    generated easily from the feature IDs and the order of the IDs
1837    in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>
1838    will have the same value as C<CouplingID("b1", "a1")>.
1839    
1840    =over 4
1841    
1842    =item peg1
1843    
1844    First feature of interest.
1845    
1846    =item peg2
1847    
1848    Second feature of interest.
1849    
1850    =item RETURN
1851    
1852  C<< my @entityList = $sprout->GetEntityTypes(); >>  Returns the ID that would be used to represent a functional coupling of
1853    the two specified PEGs.
1854    
1855  Return the list of supported entity types.  =back
1856    
1857  =cut  =cut
1858  #: Return Type @;  #: Return Type $;
1859  sub GetEntityTypes {  sub CouplingID {
1860          # Get the parameters.      return join " ", sort @_;
         my ($self) = @_;  
         # Get the underlying database object.  
         my $erdb = $self->{_erdb};  
         # Get its entity type list.  
         my @retVal = $erdb->GetEntityTypes();  
1861  }  }
1862    
1863  =head3 ReadFasta  =head3 ReadFasta
# Line 1439  Line 1904 
1904                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1905                          # 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.
1906                          if ($id) {                          if ($id) {
1907                                  $retVal{$id} = uc $sequence;                  $retVal{$id} = lc $sequence;
1908                          }                          }
1909                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
1910                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
1911                  } else {                  } else {
1912                          # 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.
1913                          # 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
1914                          # case.                          # case.
1915                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
1916                          $sequence .= $1;                          $sequence .= $1;
# Line 1453  Line 1918 
1918          }          }
1919          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
1920          if ($sequence) {          if ($sequence) {
1921                  $retVal{$id} = uc $sequence;          $retVal{$id} = lc $sequence;
1922          }          }
1923          # Close the file.          # Close the file.
1924          close FASTAFILE;          close FASTAFILE;
# Line 1540  Line 2005 
2005          # Get the data directory name.          # Get the data directory name.
2006          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
2007          # Dump the relations.          # Dump the relations.
2008          $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2009  }  }
2010    
2011  =head3 XMLFileName  =head3 XMLFileName
# Line 1572  Line 2037 
2037  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
2038  property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.  property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
2039    
2040  C<< $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence = 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>  C<< $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>
2041    
2042  =over 4  =over 4
2043    
# Line 1592  Line 2057 
2057          # Get the parameters.          # Get the parameters.
2058          my ($self, $objectType, $fieldHash) = @_;          my ($self, $objectType, $fieldHash) = @_;
2059          # Call the underlying method.          # Call the underlying method.
2060          $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2061  }  }
2062    
2063  =head3 Annotate  =head3 Annotate
# Line 1779  Line 2244 
2244          # Get the parameters.          # Get the parameters.
2245          my ($self, $entityName, $entityID) = @_;          my ($self, $entityName, $entityID) = @_;
2246          # Check for the entity instance.          # Check for the entity instance.
2247        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
2248          my $testInstance = $self->GetEntity($entityName, $entityID);          my $testInstance = $self->GetEntity($entityName, $entityID);
2249          # Return an existence indicator.          # Return an existence indicator.
2250          my $retVal = ($testInstance ? 1 : 0);          my $retVal = ($testInstance ? 1 : 0);
# Line 1970  Line 2436 
2436          return @retVal;          return @retVal;
2437  }  }
2438    
2439    =head3 GetProperties
2440    
2441    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2442    
2443    Return a list of the properties with the specified characteristics.
2444    
2445    Properties are arbitrary key-value pairs associated with a feature. (At some point they
2446    will also be associated with genomes.) A property value is represented by a 4-tuple of
2447    the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2448    
2449    =over 4
2450    
2451    =item fid
2452    
2453    ID of the feature possessing the property.
2454    
2455    =item key
2456    
2457    Name or key of the property.
2458    
2459    =item value
2460    
2461    Value of the property.
2462    
2463    =item url
2464    
2465    URL of the document that indicated the property should have this particular value, or an
2466    empty string if no such document exists.
2467    
2468    =back
2469    
2470    The parameters act as a filter for the desired data. Any non-null parameter will
2471    automatically match all the tuples returned. So, specifying just the I<$fid> will
2472    return all the properties of the specified feature; similarly, specifying the I<$key>
2473    and I<$value> parameters will return all the features having the specified property
2474    value.
2475    
2476    A single property key can have many values, representing different ideas about the
2477    feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2478    virulent, and another may declare that it is not virulent. A query about the virulence of
2479    C<fig|83333.1.peg.10> would be coded as
2480    
2481        my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2482    
2483    Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2484    not to be filtered. The tuples returned would be
2485    
2486        ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2487        ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2488    
2489    =cut
2490    #: Return Type @@;
2491    sub GetProperties {
2492        # Get the parameters.
2493        my ($self, @parms) = @_;
2494        # Declare the return variable.
2495        my @retVal = ();
2496        # Now we need to create a WHERE clause that will get us the data we want. First,
2497        # we create a list of the columns containing the data for each parameter.
2498        my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2499                        'Property(property-value)', 'HasProperty(evidence)');
2500        # Now we build the WHERE clause and the list of parameter values.
2501        my @where = ();
2502        my @values = ();
2503        for (my $i = 0; $i <= $#colNames; $i++) {
2504            my $parm = $parms[$i];
2505            if (defined $parm && ($parm ne '')) {
2506                push @where, "$colNames[$i] = ?";
2507                push @values, $parm;
2508            }
2509        }
2510        # Format the WHERE clause.
2511        my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2512        # Ask for all the propertie values with the desired characteristics.
2513        my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2514        while (my $valueObject = $query->Fetch()) {
2515            my @tuple = $valueObject->Values(\@colNames);
2516            push @retVal, \@tuple;
2517        }
2518        # Return the result.
2519        return @retVal;
2520    }
2521    
2522  =head3 FeatureProperties  =head3 FeatureProperties
2523    
2524  C<< my @properties = $sprout->FeatureProperties($featureID); >>  C<< my @properties = $sprout->FeatureProperties($featureID); >>
# Line 2164  Line 2713 
2713  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2714    
2715  Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped  Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped
2716  to the role the feature performs.  to the roles the feature performs.
2717    
2718  =over 4  =over 4
2719    
# Line 2174  Line 2723 
2723    
2724  =item RETURN  =item RETURN
2725    
2726  Returns a hash mapping all the feature's subsystems to the feature's role.  Returns a hash mapping all the feature's subsystems to a list of the feature's roles.
2727    
2728  =back  =back
2729    
2730  =cut  =cut
2731  #: Return Type %;  #: Return Type %@;
2732  sub SubsystemsOf {  sub SubsystemsOf {
2733          # Get the parameters.          # Get the parameters.
2734          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
2735          # Use the SSCell to connect features to subsystems.      # Get the subsystem list.
2736          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2737                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2738                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2739          # Create the return value.          # Create the return value.
2740          my %retVal = ();          my %retVal = ();
2741        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2742        # in two spreadsheet cells.
2743        my %dupHash = ();
2744          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
2745          for my $record (@subsystems) {          for my $record (@subsystems) {
2746                  $retVal{$record->[0]} = $record->[1];          # Get this subsystem and role.
2747            my ($subsys, $role) = @{$record};
2748            # Insure it's the first time for both.
2749            my $dupKey = "$subsys\n$role";
2750            if (! exists $dupHash{"$subsys\n$role"}) {
2751                $dupHash{$dupKey} = 1;
2752                push @{$retVal{$subsys}}, $role;
2753            }
2754          }          }
2755          # Return the hash.          # Return the hash.
2756          return %retVal;          return %retVal;
2757  }  }
2758    
2759    =head3 SubsystemList
2760    
2761    C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2762    
2763    Return a list containing the names of the subsystems in which the specified
2764    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2765    subsystem names, not the roles.
2766    
2767    =over 4
2768    
2769    =item featureID
2770    
2771    ID of the feature whose subsystem names are desired.
2772    
2773    =item RETURN
2774    
2775    Returns a list of the names of the subsystems in which the feature participates.
2776    
2777    =back
2778    
2779    =cut
2780    #: Return Type @;
2781    sub SubsystemList {
2782        # Get the parameters.
2783        my ($self, $featureID) = @_;
2784        # Get the list of names.
2785        my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",
2786                                    [$featureID], 'HasSSCell(from-link)');
2787        # Return the result.
2788        return @retVal;
2789    }
2790    
2791    
2792    
2793  =head3 RelatedFeatures  =head3 RelatedFeatures
2794    
2795  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2298  Line 2891 
2891          return @retVal;          return @retVal;
2892  }  }
2893    
 =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;  
 }  
   
2894  =head3 Protein  =head3 Protein
2895    
2896  C<< my $protein = Sprout::Protein($sequence, $table); >>  C<< my $protein = Sprout::Protein($sequence, $table); >>
# Line 2518  Line 2992 
2992          # 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.
2993          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
2994          # Concatenate the table names.          # Concatenate the table names.
2995          push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
2996          # Return the result.          # Return the result.
2997          return @retVal;          return @retVal;
2998  }  }
2999    
3000  =head3 LowBBHs  =head3 LowBBHs
3001    
3002  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
3003    
3004  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
3005  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 2615  Line 3089 
3089      return %retVal;      return %retVal;
3090  }  }
3091    
3092    =head3 MyGenomes
3093    
3094    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
3095    
3096    Return a list of the genomes to be included in the Sprout.
3097    
3098    This method is provided for use during the Sprout load. It presumes the Genome load file has
3099    already been created. (It will be in the Sprout data directory and called either C<Genome>
3100    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3101    IDs.
3102    
3103    =over 4
3104    
3105    =item dataDir
3106    
3107    Directory containing the Sprout load files.
3108    
3109    =back
3110    
3111    =cut
3112    #: Return Type @;
3113    sub MyGenomes {
3114        # Get the parameters.
3115        my ($dataDir) = @_;
3116        # Compute the genome file name.
3117        my $genomeFileName = LoadFileName($dataDir, "Genome");
3118        # Extract the genome IDs from the files.
3119        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3120        # Return the result.
3121        return @retVal;
3122    }
3123    
3124    =head3 LoadFileName
3125    
3126    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3127    
3128    Return the name of the load file for the specified table in the specified data
3129    directory.
3130    
3131    =over 4
3132    
3133    =item dataDir
3134    
3135    Directory containing the Sprout load files.
3136    
3137    =item tableName
3138    
3139    Name of the table whose load file is desired.
3140    
3141    =item RETURN
3142    
3143    Returns the name of the file containing the load data for the specified table, or
3144    C<undef> if no load file is present.
3145    
3146    =back
3147    
3148    =cut
3149    #: Return Type $;
3150    sub LoadFileName {
3151        # Get the parameters.
3152        my ($dataDir, $tableName) = @_;
3153        # Declare the return variable.
3154        my $retVal;
3155        # Check for the various file names.
3156        if (-e "$dataDir/$tableName") {
3157            $retVal = "$dataDir/$tableName";
3158        } elsif (-e "$dataDir/$tableName.dtx") {
3159            $retVal = "$dataDir/$tableName.dtx";
3160        }
3161        # Return the result.
3162        return $retVal;
3163    }
3164    
3165    =head3 DeleteGenome
3166    
3167    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3168    
3169    Delete a genome from the database.
3170    
3171    =over 4
3172    
3173    =item genomeID
3174    
3175    ID of the genome to delete
3176    
3177    =item testFlag
3178    
3179    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3180    
3181    =item RETURN
3182    
3183    Returns a statistics object describing the rows deleted.
3184    
3185    =back
3186    
3187    =cut
3188    #: Return Type $%;
3189    sub DeleteGenome {
3190        # Get the parameters.
3191        my ($self, $genomeID, $testFlag) = @_;
3192        # Perform the delete for the genome's features.
3193        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);
3194        # Perform the delete for the primary genome data.
3195        my $stats = $self->Delete('Genome', $genomeID, $testFlag);
3196        $retVal->Accumulate($stats);
3197        # Return the result.
3198        return $retVal;
3199    }
3200    
3201  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3202    
3203  =head3 ParseAssignment  =head3 ParseAssignment
# Line 2625  Line 3208 
3208    
3209  A functional assignment is always of the form  A functional assignment is always of the form
3210    
3211      I<XXXX>C<\nset >I<YYYY>C< function to\n>I<ZZZZZ>      C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3212    
3213  where I<XXXX> is the B<assigning user>, I<YYYY> is the B<user>, and I<ZZZZ> is the  where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3214  actual functional role. In most cases, the user and the assigning user will be the  the user and the assigning user (from MadeAnnotation) will be the same, but that is
3215  same, but that is not always the case.  not always the case.
3216    
3217    In addition, the functional role may contain extra data that is stripped, such as
3218    terminating spaces or a comment separated from the rest of the text by a tab.
3219    
3220  This is a static method.  This is a static method.
3221    
3222  =over 4  =over 4
3223    
3224    =item user
3225    
3226    Name of the assigning user.
3227    
3228  =item text  =item text
3229    
3230  Text of the annotation.  Text of the annotation.
# Line 2650  Line 3240 
3240    
3241  sub _ParseAssignment {  sub _ParseAssignment {
3242          # Get the parameters.          # Get the parameters.
3243          my ($text) = @_;      my ($user, $text) = @_;
3244          # Declare the return value.          # Declare the return value.
3245          my @retVal = ();          my @retVal = ();
3246          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3247          my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3248          if ($type =~ m/^set ([^ ]+) function to$/i) {      if ($type =~ m/^set function to$/i) {
3249                  # 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.
3250          # and the assigning user.          @retVal = ($user, $function);
3251                  @retVal = ($1, $function, $user);      } elsif ($type =~ m/^set (\S+) function to$/i) {
3252            # Here we have an assignment with a user that is passed back to the caller.
3253            @retVal = ($1, $function);
3254        }
3255        # If we have an assignment, we need to clean the function text. There may be
3256        # extra junk at the end added as a note from the user.
3257        if (@retVal) {
3258            $retVal[1] =~ s/(\t\S)?\s*$//;
3259          }          }
3260          # Return the result list.          # Return the result list.
3261          return @retVal;          return @retVal;
# Line 2686  Line 3283 
3283    
3284  sub FriendlyTimestamp {  sub FriendlyTimestamp {
3285      my ($timeValue) = @_;      my ($timeValue) = @_;
3286      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
3287      return $retVal;      return $retVal;
3288  }  }
3289    
3290    =head3 AddProperty
3291    
3292    C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>
3293    
3294    Add a new attribute value (Property) to a feature. In the SEED system, attributes can
3295    be added to almost any object. In Sprout, they can only be added to features. In
3296    Sprout, attributes are implemented using I<properties>. A property represents a key/value
3297    pair. If the particular key/value pair coming in is not already in the database, a new
3298    B<Property> record is created to hold it.
3299    
3300    =over 4
3301    
3302    =item peg
3303    
3304    ID of the feature to which the attribute is to be replied.
3305    
3306    =item key
3307    
3308    Name of the attribute (key).
3309    
3310    =item value
3311    
3312    Value of the attribute.
3313    
3314    =item url
3315    
3316    URL or text citation from which the property was obtained.
3317    
3318    =back
3319    
3320    =cut
3321    #: Return Type ;
3322    sub AddProperty {
3323        # Get the parameters.
3324        my ($self, $featureID, $key, $value, $url) = @_;
3325        # Declare the variable to hold the desired property ID.
3326        my $propID;
3327        # Attempt to find a property record for this key/value pair.
3328        my @properties = $self->GetFlat(['Property'],
3329                                       "Property(property-name) = ? AND Property(property-value) = ?",
3330                                       [$key, $value], 'Property(id)');
3331        if (@properties) {
3332            # Here the property is already in the database. We save its ID.
3333            $propID = $properties[0];
3334            # Here the property value does not exist. We need to generate an ID. It will be set
3335            # to a number one greater than the maximum value in the database. This call to
3336            # GetAll will stop after one record.
3337            my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],
3338                                            1);
3339            $propID = $maxProperty[0]->[0] + 1;
3340            # Insert the new property value.
3341            $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });
3342        }
3343        # Now we connect the incoming feature to the property.
3344        $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3345    }
3346    
3347    
3348  1;  1;

Legend:
Removed from v.1.14  
changed lines
  Added in v.1.65

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3