[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.21, Fri Sep 9 20:40:41 2005 UTC revision 1.66, Sun Jun 18 07:33:53 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 90  Line 98 
98                                                          # database type                                                          # database type
99                         dataDir      => $FIG_Config::sproutData,                         dataDir      => $FIG_Config::sproutData,
100                                                          # data file directory                                                          # data file directory
101                         xmlFileName  => "$FIG_Config::sproutData/SproutDBD.xml",                         xmlFileName  => "$FIG_Config::fig/SproutDBD.xml",
102                                                          # database definition file name                                                          # database definition file name
103                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
104                                                          # user name and password                                                          # user name and password
105                         port         => $FIG_Config::dbport,                         port         => $FIG_Config::dbport,
106                                                          # database connection port                                                          # 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 105  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 148  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 372  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 415  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 430  Line 250 
250              Trace("No load file found for $tableName in $dataDir.") if T(0);              Trace("No load file found for $tableName in $dataDir.") if T(0);
251          } else {          } 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          }          }
# Line 439  Line 259 
259      return $retVal;      return $retVal;
260  }  }
261    
262    =head3 GenomeCounts
263    
264    C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>
265    
266    Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
267    genomes will be included in the counts.
268    
269    =over 4
270    
271    =item complete
272    
273    TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
274    counted
275    
276    =item RETURN
277    
278    A six-element list containing the number of genomes in each of six categories--
279    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
280    
281    =back
282    
283    =cut
284    
285    sub GenomeCounts {
286        # Get the parameters.
287        my ($self, $complete) = @_;
288        # Set the filter based on the completeness flag.
289        my $filter = ($complete ? "Genome(complete) = 1" : "");
290        # Get all the genomes and the related taxonomy information.
291        my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
292        # Clear the counters.
293        my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
294        # Loop through, counting the domains.
295        for my $genome (@genomes) {
296            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
297            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
298            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
299            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
300            elsif ($genome->[1] =~ /^env/i)      { ++$env }
301            else  { ++$unk }
302        }
303        # Return the counts.
304        return ($arch, $bact, $euk, $vir, $env, $unk);
305    }
306    
307    =head3 ContigCount
308    
309    C<< my $count = $sprout->ContigCount($genomeID); >>
310    
311    Return the number of contigs for the specified genome ID.
312    
313    =over 4
314    
315    =item genomeID
316    
317    ID of the genome whose contig count is desired.
318    
319    =item RETURN
320    
321    Returns the number of contigs for the specified genome.
322    
323    =back
324    
325    =cut
326    
327    sub ContigCount {
328        # Get the parameters.
329        my ($self, $genomeID) = @_;
330        # Get the contig count.
331        my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
332        # Return the result.
333        return $retVal;
334    }
335    
336    =head3 GeneMenu
337    
338    C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params); >>
339    
340    Return an HTML select menu of genomes. Each genome will be an option in the menu,
341    and will be displayed by name with the ID and a contig count attached. The selection
342    value will be the genome ID. The genomes will be sorted by genus/species name.
343    
344    =over 4
345    
346    =item attributes
347    
348    Reference to a hash mapping attributes to values for the SELECT tag generated.
349    
350    =item filterString
351    
352    A filter string for use in selecting the genomes. The filter string must conform
353    to the rules for the C<< ERDB->Get >> method.
354    
355    =item params
356    
357    Reference to a list of values to be substituted in for the parameter marks in
358    the filter string.
359    
360    =item RETURN
361    
362    Returns an HTML select menu with the specified genomes as selectable options.
363    
364    =back
365    
366    =cut
367    
368    sub GeneMenu {
369        # Get the parameters.
370        my ($self, $attributes, $filterString, $params) = @_;
371        # Start the menu.
372        my $retVal = "<select " .
373            join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
374            ">\n";
375        # Get the genomes.
376        my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
377                                                                         'Genome(genus)',
378                                                                         'Genome(species)']);
379        # Sort them by name.
380        my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
381        # Loop through the genomes, creating the option tags.
382        for my $genomeData (@sorted) {
383            # Get the data for this genome.
384            my ($genomeID, $genus, $species) = @{$genomeData};
385            # Get the contig count.
386            my $count = $self->ContigCount($genomeID);
387            my $counting = ($count == 1 ? "contig" : "contigs");
388            # Build the option tag.
389            $retVal .= "<option value=\"$genomeID\">$genus $species ($genomeID) [$count $counting]</option>\n";
390        }
391        # Close the SELECT tag.
392        $retVal .= "</select>\n";
393        # Return the result.
394        return $retVal;
395    }
396  =head3 Build  =head3 Build
397    
398  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 453  Line 407 
407      # Get the parameters.      # Get the parameters.
408      my ($self) = @_;      my ($self) = @_;
409      # Create the tables.      # Create the tables.
410      $self->{_erdb}->CreateTables;      $self->CreateTables();
411  }  }
412    
413  =head3 Genomes  =head3 Genomes
# Line 603  Line 557 
557          if ($prevContig eq $contigID && $dir eq $prevDir) {          if ($prevContig eq $contigID && $dir eq $prevDir) {
558              # Here the new segment is in the same direction on the same contig. Insure the              # Here the new segment is in the same direction on the same contig. Insure the
559              # new segment's beginning is next to the old segment's end.              # new segment's beginning is next to the old segment's end.
560              if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||              if ($dir eq "-" && $beg + $len == $prevBeg) {
561                  ($dir eq "+" && $beg == $prevBeg + $prevLen)) {                  # Here we're merging two backward blocks, so we keep the new begin point
562                  # Here we need to merge two segments. Adjust the beginning and length values                  # and adjust the length.
563                  # to include both segments.                  $len += $prevLen;
564                    # Pop the old segment off. The new one will replace it later.
565                    pop @retVal;
566                } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
567                    # Here we need to merge two forward blocks. Adjust the beginning and
568                    # length values to include both segments.
569                  $beg = $prevBeg;                  $beg = $prevBeg;
570                  $len += $prevLen;                  $len += $prevLen;
571                  # Pop the old segment off. The new one will replace it later.                  # Pop the old segment off. The new one will replace it later.
# Line 615  Line 574 
574          }          }
575          # Remember this specifier for the adjacent-segment test the next time through.          # Remember this specifier for the adjacent-segment test the next time through.
576          ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);          ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
577            # Compute the initial base pair.
578            my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
579          # Add the specifier to the list.          # Add the specifier to the list.
580          push @retVal, "${contigID}_$beg$dir$len";          push @retVal, "${contigID}_$start$dir$len";
581      }      }
582      # Return the list in the format indicated by the context.      # Return the list in the format indicated by the context.
583      return (wantarray ? @retVal : join(',', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
# Line 650  Line 611 
611      shift if UNIVERSAL::isa($_[0],__PACKAGE__);      shift if UNIVERSAL::isa($_[0],__PACKAGE__);
612      my ($location) = @_;      my ($location) = @_;
613      # Parse it into segments.      # Parse it into segments.
614      $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
615      my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);      my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
616      # If the direction is an underscore, convert it to a + or -.      # If the direction is an underscore, convert it to a + or -.
617      if ($dir eq "_") {      if ($dir eq "_") {
# Line 726  Line 687 
687  should be of the form returned by L</featureLocation> when in a list context. In other words,  should be of the form returned by L</featureLocation> when in a list context. In other words,
688  each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.  each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.
689    
690    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
691    between positions 1401 and 1532, inclusive.
692    
693        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
694    
695  =over 4  =over 4
696    
697  =item locationList  =item locationList
698    
699  List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<end> (see  List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<len> or
700  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
701    
702  =item RETURN  =item RETURN
703    
# Line 758  Line 724 
724          # the start point is the ending. Note that in the latter case we must reverse the DNA string          # the start point is the ending. Note that in the latter case we must reverse the DNA string
725          # before putting it in the return value.          # before putting it in the return value.
726          my ($start, $stop);          my ($start, $stop);
727            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
728          if ($dir eq "+") {          if ($dir eq "+") {
729              $start = $beg;              $start = $beg;
730              $stop = $beg + $len - 1;              $stop = $beg + $len - 1;
731          } else {          } else {
732              $start = $beg + $len + 1;              $start = $beg - $len + 1;
733              $stop = $beg;              $stop = $beg;
734          }          }
735            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
736          my $query = $self->Get(['IsMadeUpOf','Sequence'],          my $query = $self->Get(['IsMadeUpOf','Sequence'],
737              "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .              "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
738              " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",              " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 776  Line 744 
744                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
745                                     'IsMadeUpOf(len)']);                                     'IsMadeUpOf(len)']);
746              my $stopPosition = $startPosition + $sequenceLength;              my $stopPosition = $startPosition + $sequenceLength;
747                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
748              # Figure out the start point and length of the relevant section.              # Figure out the start point and length of the relevant section.
749              my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);              my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
750              my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
751                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
752              # Add the relevant data to the location data.              # Add the relevant data to the location data.
753              $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
754          }          }
755          # Add this location's data to the return string. Note that we may need to reverse it.          # Add this location's data to the return string. Note that we may need to reverse it.
756          if ($dir eq '+') {          if ($dir eq '+') {
757              $retVal .= $locationDNA;              $retVal .= $locationDNA;
758          } else {          } else {
759              $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
             $retVal .= $locationDNA;  
760          }          }
761      }      }
762      # Return the result.      # Return the result.
# Line 824  Line 793 
793      return @retVal;      return @retVal;
794  }  }
795    
796    =head3 GenomeLength
797    
798    C<< my $length = $sprout->GenomeLength($genomeID); >>
799    
800    Return the length of the specified genome in base pairs.
801    
802    =over 4
803    
804    =item genomeID
805    
806    ID of the genome whose base pair count is desired.
807    
808    =item RETURN
809    
810    Returns the number of base pairs in all the contigs of the specified
811    genome.
812    
813    =back
814    
815    =cut
816    
817    sub GenomeLength {
818        # Get the parameters.
819        my ($self, $genomeID) = @_;
820        # Declare the return variable.
821        my $retVal = 0;
822        # Get the genome's contig sequence lengths.
823        my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
824                           [$genomeID], 'IsMadeUpOf(len)');
825        # Sum the lengths.
826        map { $retVal += $_ } @lens;
827        # Return the result.
828        return $retVal;
829    }
830    
831    =head3 FeatureCount
832    
833    C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
834    
835    Return the number of features of the specified type in the specified genome.
836    
837    =over 4
838    
839    =genomeID
840    
841    ID of the genome whose feature count is desired.
842    
843    =item type
844    
845    Type of feature to count (eg. C<peg>, C<rna>, etc.).
846    
847    =item RETURN
848    
849    Returns the number of features of the specified type for the specified genome.
850    
851    =back
852    
853    =cut
854    
855    sub FeatureCount {
856        # Get the parameters.
857        my ($self, $genomeID, $type) = @_;
858        # Compute the count.
859        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
860                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
861                                    [$genomeID, $type]);
862        # Return the result.
863        return $retVal;
864    }
865    
866    =head3 GenomeAssignments
867    
868    C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
869    
870    Return a list of a genome's assigned features. The return hash will contain each
871    assigned feature of the genome mapped to the text of its most recent functional
872    assignment.
873    
874    =over 4
875    
876    =item genomeID
877    
878    ID of the genome whose functional assignments are desired.
879    
880    =item RETURN
881    
882    Returns a reference to a hash which maps each feature to its most recent
883    functional assignment.
884    
885    =back
886    
887    =cut
888    
889    sub GenomeAssignments {
890        # Get the parameters.
891        my ($self, $genomeID) = @_;
892        # Declare the return variable.
893        my $retVal = {};
894        # Query the genome's features and annotations. We'll put the oldest annotations
895        # first so that the last assignment to go into the hash will be the correct one.
896        my $query = $self->Get(['HasFeature', 'IsTargetOfAnnotation', 'Annotation'],
897                               "HasFeature(from-link) = ? ORDER BY Annotation(time)",
898                               [$genomeID]);
899        # Loop through the annotations.
900        while (my $data = $query->Fetch) {
901            # Get the feature ID and annotation text.
902            my ($fid, $annotation) = $data->Values(['HasFeature(from-link)',
903                                                    'Annotation(annotation)']);
904            # Check to see if this is an assignment. Note that the user really
905            # doesn't matter to us, other than we use it to determine whether or
906            # not this is an assignment.
907            my ($user, $assignment) = _ParseAssignment('fig', $annotation);
908            if ($user) {
909                # Here it's an assignment. We put it in the return hash, overwriting
910                # any older assignment that might be present.
911                $retVal->{$fid} = $assignment;
912            }
913        }
914        # Return the result.
915        return $retVal;
916    }
917    
918  =head3 ContigLength  =head3 ContigLength
919    
920  C<< my $length = $sprout->ContigLength($contigID); >>  C<< my $length = $sprout->ContigLength($contigID); >>
# Line 857  Line 948 
948      # Set it from the sequence data, if any.      # Set it from the sequence data, if any.
949      if ($sequence) {      if ($sequence) {
950          my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);          my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
951          $retVal = $start + $len;          $retVal = $start + $len - 1;
952        }
953        # Return the result.
954        return $retVal;
955    }
956    
957    =head3 ClusterPEGs
958    
959    C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
960    
961    Cluster the PEGs in a list according to the cluster coding scheme of the specified
962    subsystem. In order for this to work properly, the subsystem object must have
963    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
964    This causes the cluster numbers to be pulled into the subsystem's color hash.
965    If a PEG is not found in the color hash, it will not appear in the output
966    sequence.
967    
968    =over 4
969    
970    =item sub
971    
972    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
973    method.
974    
975    =item pegs
976    
977    Reference to the list of PEGs to be clustered.
978    
979    =item RETURN
980    
981    Returns a list of the PEGs, grouped into smaller lists by cluster number.
982    
983    =back
984    
985    =cut
986    #: Return Type $@@;
987    sub ClusterPEGs {
988        # Get the parameters.
989        my ($self, $sub, $pegs) = @_;
990        # Declare the return variable.
991        my $retVal = [];
992        # Loop through the PEGs, creating arrays for each cluster.
993        for my $pegID (@{$pegs}) {
994            my $clusterNumber = $sub->get_cluster_number($pegID);
995            # Only proceed if the PEG is in a cluster.
996            if ($clusterNumber >= 0) {
997                # Push this PEG onto the sub-list for the specified cluster number.
998                push @{$retVal->[$clusterNumber]}, $pegID;
999            }
1000      }      }
1001      # Return the result.      # Return the result.
1002      return $retVal;      return $retVal;
# Line 1007  Line 1146 
1146    
1147  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1148    
1149  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1150    
1151  Return the annotations of a feature.  Return the annotations of a feature.
1152    
# Line 1017  Line 1156 
1156    
1157  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1158    
1159    =item rawFlag
1160    
1161    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1162    will be returned in human-readable form.
1163    
1164  =item RETURN  =item RETURN
1165    
1166  Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.  Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.
1167    
1168  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1169    
1170  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1171    
1172  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1173    
# Line 1035  Line 1179 
1179  #: Return Type @%;  #: Return Type @%;
1180  sub FeatureAnnotations {  sub FeatureAnnotations {
1181      # Get the parameters.      # Get the parameters.
1182      my ($self, $featureID) = @_;      my ($self, $featureID, $rawFlag) = @_;
1183      # Create a query to get the feature's annotations and the associated users.      # Create a query to get the feature's annotations and the associated users.
1184      my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],      my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1185                             "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                             "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 1048  Line 1192 
1192              $annotation->Values(['IsTargetOfAnnotation(from-link)',              $annotation->Values(['IsTargetOfAnnotation(from-link)',
1193                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1194                                   'Annotation(annotation)']);                                   'Annotation(annotation)']);
1195            # Convert the time, if necessary.
1196            if (! $rawFlag) {
1197                $timeStamp = FriendlyTimestamp($timeStamp);
1198            }
1199          # Assemble them into a hash.          # Assemble them into a hash.
1200          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1201                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1202                                 user => $user, text => $text };                                 user => $user, text => $text };
1203          # Add it to the return list.          # Add it to the return list.
1204          push @retVal, $annotationHash;          push @retVal, $annotationHash;
# Line 1079  Line 1227 
1227    
1228  =item RETURN  =item RETURN
1229    
1230  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1231    
1232  =back  =back
1233    
# Line 1089  Line 1237 
1237      # Get the parameters.      # Get the parameters.
1238      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1239      # Get all of the feature's annotations.      # Get all of the feature's annotations.
1240      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1241                              "IsTargetOfAnnotation(from-link) = ?",                              "IsTargetOfAnnotation(from-link) = ?",
1242                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1243                                               'MadeAnnotation(from-link)']);
1244      # Declare the return hash.      # Declare the return hash.
1245      my %retVal;      my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1246      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1247      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1248      # Loop until we run out of annotations.      # Loop until we run out of annotations.
1249      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1250          # Get the annotation fields.          # Get the annotation fields.
1251          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1252          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
1253          my ($user, $function) = _ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1254          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1255              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1256              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1257              # return hash.              # return hash.
1258              $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1259          }          }
1260      }      }
1261      # Return the hash of assignments found.      # Return the hash of assignments found.
# Line 1126  Line 1271 
1271  The functional assignment is handled differently depending on the type of feature. If  The functional assignment is handled differently depending on the type of feature. If
1272  the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional  the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1273  assignment is a type of annotation. The format of an assignment is described in  assignment is a type of annotation. The format of an assignment is described in
1274  L</ParseLocation>. Its worth noting that we cannot filter on the content of the  L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1275  annotation itself because it's a text field; however, this is not a big problem because  annotation itself because it's a text field; however, this is not a big problem because
1276  most features only have a small number of annotations.  most features only have a small number of annotations.
1277    
# Line 1188  Line 1333 
1333              }              }
1334          }          }
1335          # Build a query for all of the feature's annotations, sorted by date.          # Build a query for all of the feature's annotations, sorted by date.
1336          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1337                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1338                                 [$featureID]);                                 [$featureID]);
1339          my $timeSelected = 0;          my $timeSelected = 0;
1340          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1341          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1342              # Get the annotation text.              # Get the annotation text.
1343              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);              my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1344                                                         'Annotation(time)', 'MadeAnnotation(from-link)']);
1345              # Check to see if this is a functional assignment for a trusted user.              # Check to see if this is a functional assignment for a trusted user.
1346              my ($user, $function) = _ParseAssignment($text);              my ($actualUser, $function) = _ParseAssignment($user, $text);
1347              if ($user) {              Trace("Assignment user is $actualUser, text is $function.") if T(4);
1348                if ($actualUser) {
1349                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1350                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1351                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                  if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1352                      $retVal = $function;                      $retVal = $function;
1353                      $timeSelected = $time;                      $timeSelected = $time;
1354                  }                  }
# Line 1217  Line 1364 
1364      return $retVal;      return $retVal;
1365  }  }
1366    
1367    =head3 FunctionsOf
1368    
1369    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1370    
1371    Return the functional assignments of a particular feature.
1372    
1373    The functional assignment is handled differently depending on the type of feature. If
1374    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1375    assignment is a type of annotation. The format of an assignment is described in
1376    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1377    annotation itself because it's a text field; however, this is not a big problem because
1378    most features only have a small number of annotations.
1379    
1380    If the feature is B<not> identified by a FIG ID, then the functional assignment
1381    information is taken from the B<ExternalAliasFunc> table. If the table does
1382    not contain an entry for the feature, an empty list is returned.
1383    
1384    =over 4
1385    
1386    =item featureID
1387    
1388    ID of the feature whose functional assignments are desired.
1389    
1390    =item RETURN
1391    
1392    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1393    that user.
1394    
1395    =back
1396    
1397    =cut
1398    #: Return Type @@;
1399    sub FunctionsOf {
1400        # Get the parameters.
1401        my ($self, $featureID) = @_;
1402        # Declare the return value.
1403        my @retVal = ();
1404        # Determine the ID type.
1405        if ($featureID =~ m/^fig\|/) {
1406            # Here we have a FIG feature ID. We must build the list of trusted
1407            # users.
1408            my %trusteeTable = ();
1409            # Build a query for all of the feature's annotations, sorted by date.
1410            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1411                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1412                                   [$featureID]);
1413            my $timeSelected = 0;
1414            # Loop until we run out of annotations.
1415            while (my $annotation = $query->Fetch()) {
1416                # Get the annotation text.
1417                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1418                                                                'Annotation(time)',
1419                                                                'MadeAnnotation(user)']);
1420                # Check to see if this is a functional assignment for a trusted user.
1421                my ($actualUser, $function) = _ParseAssignment($user, $text);
1422                if ($actualUser) {
1423                    # Here it is a functional assignment.
1424                    push @retVal, [$actualUser, $function];
1425                }
1426            }
1427        } else {
1428            # Here we have a non-FIG feature ID. In this case the user ID does not
1429            # matter. We simply get the information from the External Alias Function
1430            # table.
1431            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1432                                                     ['ExternalAliasFunc(func)']);
1433            push @retVal, map { ['master', $_] } @assignments;
1434        }
1435        # Return the assignments found.
1436        return @retVal;
1437    }
1438    
1439  =head3 BBHList  =head3 BBHList
1440    
1441  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1254  Line 1473 
1473          my $query = $self->Get(['IsBidirectionalBestHitOf'],          my $query = $self->Get(['IsBidirectionalBestHitOf'],
1474                                 "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",                                 "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",
1475                                 [$featureID, $genomeID]);                                 [$featureID, $genomeID]);
1476          # Look for the best hit.          # Peel off the BBHs found.
1477          my $bbh = $query->Fetch;          my @found = ();
1478          if ($bbh) {          while (my $bbh = $query->Fetch) {
1479              my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');
             $retVal{$featureID} = $targetFeature;  
1480          }          }
1481            $retVal{$featureID} = \@found;
1482      }      }
1483      # Return the mapping.      # Return the mapping.
1484      return \%retVal;      return \%retVal;
# Line 1337  Line 1556 
1556      my $genomeData = $self->GetEntity('Genome', $genomeID);      my $genomeData = $self->GetEntity('Genome', $genomeID);
1557      if ($genomeData) {      if ($genomeData) {
1558          # The genome exists, so get the completeness flag.          # The genome exists, so get the completeness flag.
1559          ($retVal) = $genomeData->Value('complete');          ($retVal) = $genomeData->Value('Genome(complete)');
1560      }      }
1561      # Return the result.      # Return the result.
1562      return $retVal;      return $retVal;
# Line 1377  Line 1596 
1596    
1597  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1598    
1599  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1600    
1601  =over 4  =over 4
1602    
1603  =item featureID  =item featureID
1604    
1605  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1606    
1607  =item RETURN  =item RETURN
1608    
1609  Returns the ID of the genome for the specified feature. If the feature is not found, returns  Returns the ID of the genome for the specified feature or contig. If the feature or contig is not
1610  an undefined value.  found, returns an undefined value.
1611    
1612  =back  =back
1613    
# Line 1397  Line 1616 
1616  sub GenomeOf {  sub GenomeOf {
1617      # Get the parameters.      # Get the parameters.
1618      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1619      # Create a query to find the genome associated with the feature.      # Create a query to find the genome associated with the incoming ID.
1620      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1621                               [$featureID, $featureID]);
1622      # Declare the return value.      # Declare the return value.
1623      my $retVal;      my $retVal;
1624      # Get the genome ID.      # Get the genome ID.
# Line 1445  Line 1665 
1665          # Get the ID and score of the coupling.          # Get the ID and score of the coupling.
1666          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1667                                                          'Coupling(score)']);                                                          'Coupling(score)']);
1668          # The coupling ID contains the two feature IDs separated by a space. We use          # Get the other feature that participates in the coupling.
1669          # this information to find the ID of the other feature.          my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],
1670          my ($fid1, $fid2) = split / /, $couplingID;                                             "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",
1671          my $otherFeatureID = ($featureID eq $fid1 ? $fid2 : $fid1);                                             [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');
1672          # Attach the other feature's score to its ID.          # Attach the other feature's score to its ID.
1673          $retVal{$otherFeatureID} = $score;          $retVal{$otherFeatureID} = $score;
1674          $found = 1;          $found = 1;
# Line 1538  Line 1758 
1758              Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);              Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1759              push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];              push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1760          }          }
1761            Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1762      }      }
1763      # Return the result.      # Return the result.
1764      return @retVal;      return @retVal;
# Line 1587  Line 1808 
1808                                   [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);                                   [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1809      # Check to see if we found anything.      # Check to see if we found anything.
1810      if (!@pegs) {      if (!@pegs) {
1811            Trace("No coupling found.") if T(Coupling => 4);
1812          # No coupling, so undefine the return value.          # No coupling, so undefine the return value.
1813          $retVal = undef;          $retVal = undef;
1814      } else {      } else {
1815          # We have a coupling! Get the score and check for inversion.          # We have a coupling! Get the score and check for inversion.
1816          $score = $pegs[0]->[1];          $score = $pegs[0]->[1];
1817          $inverted = ($pegs[0]->[0] eq $peg1);          my $firstFound = $pegs[0]->[0];
1818            $inverted = ($firstFound ne $peg1);
1819            Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1820      }      }
1821      # Return the result.      # Return the result.
1822      return ($retVal, $inverted, $score);      return ($retVal, $inverted, $score);
# Line 1636  Line 1860 
1860      return join " ", sort @_;      return join " ", sort @_;
1861  }  }
1862    
 =head3 GetEntityTypes  
   
 C<< my @entityList = $sprout->GetEntityTypes(); >>  
   
 Return the list of supported entity types.  
   
 =cut  
 #: Return Type @;  
 sub GetEntityTypes {  
     # Get the parameters.  
     my ($self) = @_;  
     # Get the underlying database object.  
     my $erdb = $self->{_erdb};  
     # Get its entity type list.  
     my @retVal = $erdb->GetEntityTypes();  
 }  
   
1863  =head3 ReadFasta  =head3 ReadFasta
1864    
1865  C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>  C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>
# Line 1697  Line 1904 
1904          if ($line =~ m/^>\s*(.+?)(\s|\n)/) {          if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1905              # Here we have a new header. Store the current sequence if we have one.              # Here we have a new header. Store the current sequence if we have one.
1906              if ($id) {              if ($id) {
1907                  $retVal{$id} = uc $sequence;                  $retVal{$id} = lc $sequence;
1908              }              }
1909              # Clear the sequence accumulator and save the new ID.              # Clear the sequence accumulator and save the new ID.
1910              ($id, $sequence) = ("$prefix$1", "");              ($id, $sequence) = ("$prefix$1", "");
1911          } else {          } else {
1912              # Here we have a data line, so we add it to the sequence accumulator.              # Here we have a data line, so we add it to the sequence accumulator.
1913              # First, we get the actual data out. Note that we normalize to upper              # First, we get the actual data out. Note that we normalize to lower
1914              # case.              # case.
1915              $line =~ /^\s*(.*?)(\s|\n)/;              $line =~ /^\s*(.*?)(\s|\n)/;
1916              $sequence .= $1;              $sequence .= $1;
# Line 1711  Line 1918 
1918      }      }
1919      # Flush out the last sequence (if any).      # Flush out the last sequence (if any).
1920      if ($sequence) {      if ($sequence) {
1921          $retVal{$id} = uc $sequence;          $retVal{$id} = lc $sequence;
1922      }      }
1923      # Close the file.      # Close the file.
1924      close FASTAFILE;      close FASTAFILE;
# Line 1798  Line 2005 
2005      # Get the data directory name.      # Get the data directory name.
2006      my $outputDirectory = $self->{_options}->{dataDir};      my $outputDirectory = $self->{_options}->{dataDir};
2007      # Dump the relations.      # Dump the relations.
2008      $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2009  }  }
2010    
2011  =head3 XMLFileName  =head3 XMLFileName
# Line 1850  Line 2057 
2057      # Get the parameters.      # Get the parameters.
2058      my ($self, $objectType, $fieldHash) = @_;      my ($self, $objectType, $fieldHash) = @_;
2059      # Call the underlying method.      # Call the underlying method.
2060      $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2061  }  }
2062    
2063  =head3 Annotate  =head3 Annotate
# Line 2037  Line 2244 
2244      # Get the parameters.      # Get the parameters.
2245      my ($self, $entityName, $entityID) = @_;      my ($self, $entityName, $entityID) = @_;
2246      # Check for the entity instance.      # Check for the entity instance.
2247        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
2248      my $testInstance = $self->GetEntity($entityName, $entityID);      my $testInstance = $self->GetEntity($entityName, $entityID);
2249      # Return an existence indicator.      # Return an existence indicator.
2250      my $retVal = ($testInstance ? 1 : 0);      my $retVal = ($testInstance ? 1 : 0);
# Line 2530  Line 2738 
2738                                      ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                      ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2739      # Create the return value.      # Create the return value.
2740      my %retVal = ();      my %retVal = ();
2741        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2742        # in two spreadsheet cells.
2743        my %dupHash = ();
2744      # Loop through the results, adding them to the hash.      # Loop through the results, adding them to the hash.
2745      for my $record (@subsystems) {      for my $record (@subsystems) {
2746            # Get this subsystem and role.
2747          my ($subsys, $role) = @{$record};          my ($subsys, $role) = @{$record};
2748          if (exists $retVal{$subsys}) {          # Insure it's the first time for both.
2749            my $dupKey = "$subsys\n$role";
2750            if (! exists $dupHash{"$subsys\n$role"}) {
2751                $dupHash{$dupKey} = 1;
2752              push @{$retVal{$subsys}}, $role;              push @{$retVal{$subsys}}, $role;
         } else {  
             $retVal{$subsys} = [$role];  
2753          }          }
2754      }      }
2755      # Return the hash.      # Return the hash.
# Line 2575  Line 2788 
2788      return @retVal;      return @retVal;
2789  }  }
2790    
2791    
2792    
2793  =head3 RelatedFeatures  =head3 RelatedFeatures
2794    
2795  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2676  Line 2891 
2891      return @retVal;      return @retVal;
2892  }  }
2893    
 =head3 GetAll  
   
 C<< my @list = $sprout->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>  
   
 Return a list of values taken from the objects returned by a query. The first three  
 parameters correspond to the parameters of the L</Get> method. The final parameter is  
 a list of the fields desired from each record found by the query. The field name  
 syntax is the standard syntax used for fields in the B<ERDB> system--  
 B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity  
 or relationship and I<fieldName> is the name of the field.  
   
 The list returned will be a list of lists. Each element of the list will contain  
 the values returned for the fields specified in the fourth parameter. If one of the  
 fields specified returns multiple values, they are flattened in with the rest. For  
 example, the following call will return a list of the features in a particular  
 spreadsheet cell, and each feature will be represented by a list containing the  
 feature ID followed by all of its aliases.  
   
 C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item fields  
   
 List of the fields to be returned in each element of the list returned.  
   
 =item count  
   
 Maximum number of records to return. If omitted or 0, all available records will be returned.  
   
 =item RETURN  
   
 Returns a list of list references. Each element of the return list contains the values for the  
 fields specified in the B<fields> parameter.  
   
 =back  
   
 =cut  
 #: Return Type @@;  
 sub GetAll {  
     # Get the parameters.  
     my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;  
     # Call the ERDB method.  
     my @retVal = $self->{_erdb}->GetAll($objectNames, $filterClause, $parameterList,  
                                         $fields, $count);  
     # Return the resulting list.  
     return @retVal;  
 }  
   
 =head3 GetFlat  
   
 C<< my @list = $sprout->GetFlat(\@objectNames, $filterClause, $parameterList, $field); >>  
   
 This is a variation of L</GetAll> that asks for only a single field per record and  
 returns a single flattened list.  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item field  
   
 Name of the field to be used to get the elements of the list returned.  
   
 =item RETURN  
   
 Returns a list of values.  
   
 =back  
   
 =cut  
 #: Return Type @;  
 sub GetFlat {  
     # Get the parameters.  
     my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;  
     # Construct the query.  
     my $query = $self->Get($objectNames, $filterClause, $parameterList);  
     # Create the result list.  
     my @retVal = ();  
     # Loop through the records, adding the field values found to the result list.  
     while (my $row = $query->Fetch()) {  
         push @retVal, $row->Value($field);  
     }  
     # Return the list created.  
     return @retVal;  
 }  
   
2894  =head3 Protein  =head3 Protein
2895    
2896  C<< my $protein = Sprout::Protein($sequence, $table); >>  C<< my $protein = Sprout::Protein($sequence, $table); >>
# Line 2896  Line 2992 
2992      # Create the return list, priming it with the name of the data directory.      # Create the return list, priming it with the name of the data directory.
2993      my @retVal = ($self->{_options}->{dataDir});      my @retVal = ($self->{_options}->{dataDir});
2994      # Concatenate the table names.      # Concatenate the table names.
2995      push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
2996      # Return the result.      # Return the result.
2997      return @retVal;      return @retVal;
2998  }  }
2999    
3000  =head3 LowBBHs  =head3 LowBBHs
3001    
3002  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
3003    
3004  Return the bidirectional best hits of a feature whose score is no greater than a  Return the bidirectional best hits of a feature whose score is no greater than a
3005  specified cutoff value. A higher cutoff value will allow inclusion of hits with  specified cutoff value. A higher cutoff value will allow inclusion of hits with
# Line 3066  Line 3162 
3162      return $retVal;      return $retVal;
3163  }  }
3164    
3165    =head3 DeleteGenome
3166    
3167    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3168    
3169    Delete a genome from the database.
3170    
3171    =over 4
3172    
3173    =item genomeID
3174    
3175    ID of the genome to delete
3176    
3177    =item testFlag
3178    
3179    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3180    
3181    =item RETURN
3182    
3183    Returns a statistics object describing the rows deleted.
3184    
3185    =back
3186    
3187    =cut
3188    #: Return Type $%;
3189    sub DeleteGenome {
3190        # Get the parameters.
3191        my ($self, $genomeID, $testFlag) = @_;
3192        # Perform the delete for the genome's features.
3193        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);
3194        # Perform the delete for the primary genome data.
3195        my $stats = $self->Delete('Genome', $genomeID, $testFlag);
3196        $retVal->Accumulate($stats);
3197        # Return the result.
3198        return $retVal;
3199    }
3200    
3201  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3202    
3203  =head3 ParseAssignment  =head3 ParseAssignment
# Line 3076  Line 3208 
3208    
3209  A functional assignment is always of the form  A functional assignment is always of the form
3210    
3211      I<XXXX>C<\nset >I<YYYY>C< function to\n>I<ZZZZZ>      C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3212    
3213    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3214    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3215    not always the case.
3216    
3217  where I<XXXX> is the B<assigning user>, I<YYYY> is the B<user>, and I<ZZZZ> is the  In addition, the functional role may contain extra data that is stripped, such as
3218  actual functional role. In most cases, the user and the assigning user will be the  terminating spaces or a comment separated from the rest of the text by a tab.
 same, but that is not always the case.  
3219    
3220  This is a static method.  This is a static method.
3221    
3222  =over 4  =over 4
3223    
3224    =item user
3225    
3226    Name of the assigning user.
3227    
3228  =item text  =item text
3229    
3230  Text of the annotation.  Text of the annotation.
# Line 3101  Line 3240 
3240    
3241  sub _ParseAssignment {  sub _ParseAssignment {
3242      # Get the parameters.      # Get the parameters.
3243      my ($text) = @_;      my ($user, $text) = @_;
3244      # Declare the return value.      # Declare the return value.
3245      my @retVal = ();      my @retVal = ();
3246      # Check to see if this is a functional assignment.      # Check to see if this is a functional assignment.
3247      my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3248      if ($type =~ m/^set ([^ ]+) function to$/i) {      if ($type =~ m/^set function to$/i) {
3249          # Here it is, so we return the user name (which is in $1), the functional role text,          # Here we have an assignment without a user, so we use the incoming user ID.
3250          # and the assigning user.          @retVal = ($user, $function);
3251          @retVal = ($1, $function, $user);      } elsif ($type =~ m/^set (\S+) function to$/i) {
3252            # Here we have an assignment with a user that is passed back to the caller.
3253            @retVal = ($1, $function);
3254        }
3255        # If we have an assignment, we need to clean the function text. There may be
3256        # extra junk at the end added as a note from the user.
3257        if (@retVal) {
3258            $retVal[1] =~ s/(\t\S)?\s*$//;
3259      }      }
3260      # Return the result list.      # Return the result list.
3261      return @retVal;      return @retVal;
# Line 3137  Line 3283 
3283    
3284  sub FriendlyTimestamp {  sub FriendlyTimestamp {
3285      my ($timeValue) = @_;      my ($timeValue) = @_;
3286      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
3287      return $retVal;      return $retVal;
3288  }  }
3289    
# Line 3199  Line 3345 
3345  }  }
3346    
3347    
   
3348  1;  1;

Legend:
Removed from v.1.21  
changed lines
  Added in v.1.66

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3