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

Legend:
Removed from v.1.12  
changed lines
  Added in v.1.69

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3