[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.9, Mon Feb 7 00:32:07 2005 UTC revision 1.58, Tue Jun 6 05:07:15 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 124  Line 143 
143  =cut  =cut
144  #: Return Type $;  #: Return Type $;
145  sub MaxSegment {  sub MaxSegment {
146          my $self = shift @_;      my ($self) = @_;
147          return $self->{_options}->{maxSegmentLength};          return $self->{_options}->{maxSegmentLength};
148  }  }
149    
# Line 139  Line 158 
158  =cut  =cut
159  #: Return Type $;  #: Return Type $;
160  sub MaxSequence {  sub MaxSequence {
161          my $self = shift @_;      my ($self) = @_;
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 = shift @_;  
         my ($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 = shift @_;  
         my ($entityType, $ID) = @_;  
         # Create a query.  
         my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);  
         # Get the first (and only) object.  
         my $retVal = $query->Fetch();  
         # Return the result.  
         return $retVal;  
 }  
   
 =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 = shift @_;  
         my ($entityType, $ID, $fields) = @_;  
         # Get the specified entity.  
         my $entity = $self->GetEntity($entityType, $ID);  
         # Declare the return list.  
         my @retVal = ();  
         # If we found the entity, push the values into the return list.  
         if ($entity) {  
                 push @retVal, $entity->Values($fields);  
         }  
         # Return the result.  
         return @retVal;  
 }  
   
 =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 = shift @_;  
         my ($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 382  Line 195 
195  #: Return Type %;  #: Return Type %;
196  sub Load {  sub Load {
197          # Get the parameters.          # Get the parameters.
198          my $self = shift @_;      my ($self, $rebuild) = @_;
         my ($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 426  Line 236 
236  #: Return Type $%;  #: Return Type $%;
237  sub LoadUpdate {  sub LoadUpdate {
238          # Get the parameters.          # Get the parameters.
239          my $self = shift @_;      my ($self, $truncateFlag, $tableList) = @_;
         my ($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 438  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 Build  =head3 Build
308    
309  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 463  Line 316 
316  #: Return Type ;  #: Return Type ;
317  sub Build {  sub Build {
318          # Get the parameters.          # Get the parameters.
319          my $self = shift @_;      my ($self) = @_;
320          # Create the tables.          # Create the tables.
321          $self->{_erdb}->CreateTables;      $self->CreateTables();
322  }  }
323    
324  =head3 Genomes  =head3 Genomes
# Line 478  Line 331 
331  #: Return Type @;  #: Return Type @;
332  sub Genomes {  sub Genomes {
333          # Get the parameters.          # Get the parameters.
334          my $self = shift @_;      my ($self) = @_;
335          # Get all the genomes.          # Get all the genomes.
336          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');
337          # Return the list of IDs.          # Return the list of IDs.
# Line 508  Line 361 
361  #: Return Type $;  #: Return Type $;
362  sub GenusSpecies {  sub GenusSpecies {
363          # Get the parameters.          # Get the parameters.
364          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
365          # Get the data for the specified genome.          # Get the data for the specified genome.
366          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',
367                                                                                                                            'Genome(unique-characterization)']);                                                                                                                            'Genome(unique-characterization)']);
# Line 545  Line 397 
397  #: Return Type @;  #: Return Type @;
398  sub FeaturesOf {  sub FeaturesOf {
399          # Get the parameters.          # Get the parameters.
400          my $self = shift @_;      my ($self, $genomeID,$ftype) = @_;
         my ($genomeID,$ftype) = @_;  
401          # Get the features we want.          # Get the features we want.
402          my @features;          my @features;
403          if (!$ftype) {          if (!$ftype) {
# Line 590  Line 441 
441  =item RETURN  =item RETURN
442    
443  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
444  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context.
445    
446  =back  =back
447    
# Line 599  Line 450 
450  #: Return Type $;  #: Return Type $;
451  sub FeatureLocation {  sub FeatureLocation {
452          # Get the parameters.          # Get the parameters.
453          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
454          # Create a query for the feature locations.          # Create a query for the feature locations.
455          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",
456                                                     [$featureID]);                                                     [$featureID]);
# Line 618  Line 468 
468                  if ($prevContig eq $contigID && $dir eq $prevDir) {                  if ($prevContig eq $contigID && $dir eq $prevDir) {
469                          # 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
470                          # new segment's beginning is next to the old segment's end.                          # new segment's beginning is next to the old segment's end.
471                          if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||              if ($dir eq "-" && $beg + $len == $prevBeg) {
472                                  ($dir eq "+" && $beg == $prevBeg + $prevLen)) {                  # Here we're merging two backward blocks, so we keep the new begin point
473                                  # Here we need to merge two segments. Adjust the beginning and length values                  # and adjust the length.
474                                  # to include both segments.                  $len += $prevLen;
475                    # Pop the old segment off. The new one will replace it later.
476                    pop @retVal;
477                } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
478                    # Here we need to merge two forward blocks. Adjust the beginning and
479                    # length values to include both segments.
480                                  $beg = $prevBeg;                                  $beg = $prevBeg;
481                                  $len += $prevLen;                                  $len += $prevLen;
482                                  # 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 630  Line 485 
485                  }                  }
486                  # Remember this specifier for the adjacent-segment test the next time through.                  # Remember this specifier for the adjacent-segment test the next time through.
487                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
488            # Compute the initial base pair.
489            my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
490                  # Add the specifier to the list.                  # Add the specifier to the list.
491                  push @retVal, "${contigID}_$beg$dir$len";          push @retVal, "${contigID}_$start$dir$len";
492          }          }
493          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
494          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
495  }  }
496    
497  =head3 ParseLocation  =head3 ParseLocation
# Line 660  Line 517 
517  =cut  =cut
518  #: Return Type @;  #: Return Type @;
519  sub ParseLocation {  sub ParseLocation {
520          # Get the parameter.      # Get the parameter. Note that if we're called as an instance method, we ignore
521        # the first parameter.
522        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
523          my ($location) = @_;          my ($location) = @_;
524          # Parse it into segments.          # Parse it into segments.
525          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
526          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
527          # If the direction is an underscore, convert it to a + or -.          # If the direction is an underscore, convert it to a + or -.
528          if ($dir eq "_") {          if ($dir eq "_") {
# Line 679  Line 538 
538          return ($contigID, $start, $dir, $len);          return ($contigID, $start, $dir, $len);
539  }  }
540    
541    =head3 PointLocation
542    
543    C<< my $found = Sprout::PointLocation($location, $point); >>
544    
545    Return the offset into the specified location of the specified point on the contig. If
546    the specified point is before the location, a negative value will be returned. If it is
547    beyond the location, an undefined value will be returned. It is assumed that the offset
548    is for the location's contig. The location can either be new-style (using a C<+> or C<->
549    and a length) or old-style (using C<_> and start and end positions.
550    
551    =over 4
552    
553    =item location
554    
555    A location specifier (see L</FeatureLocation> for a description).
556    
557    =item point
558    
559    The offset into the contig of the point in which we're interested.
560    
561    =item RETURN
562    
563    Returns the offset inside the specified location of the specified point, a negative
564    number if the point is before the location, or an undefined value if the point is past
565    the location. If the length of the location is 0, this method will B<always> denote
566    that it is outside the location. The offset will always be relative to the left-most
567    position in the location.
568    
569    =back
570    
571    =cut
572    #: Return Type $;
573    sub PointLocation {
574        # Get the parameter. Note that if we're called as an instance method, we ignore
575        # the first parameter.
576        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
577        my ($location, $point) = @_;
578        # Parse out the location elements. Note that this works on both old-style and new-style
579        # locations.
580        my ($contigID, $start, $dir, $len) = ParseLocation($location);
581        # Declare the return variable.
582        my $retVal;
583        # Compute the offset. The computation is dependent on the direction of the location.
584        my $offset = (($dir == '+') ? $point - $start : $point - ($start - $len + 1));
585        # Return the offset if it's valid.
586        if ($offset < $len) {
587            $retVal = $offset;
588        }
589        # Return the offset found.
590        return $retVal;
591    }
592    
593  =head3 DNASeq  =head3 DNASeq
594    
595  C<< my $sequence = $sprout->DNASeq(\@locationList); >>  C<< my $sequence = $sprout->DNASeq(\@locationList); >>
# Line 687  Line 598 
598  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,
599  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>.
600    
601    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
602    between positions 1401 and 1532, inclusive.
603    
604        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
605    
606  =over 4  =over 4
607    
608  =item locationList  =item locationList
609    
610  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
611  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
612    
613  =item RETURN  =item RETURN
614    
# Line 704  Line 620 
620  #: Return Type $;  #: Return Type $;
621  sub DNASeq {  sub DNASeq {
622          # Get the parameters.          # Get the parameters.
623          my $self = shift @_;      my ($self, $locationList) = @_;
         my ($locationList) = @_;  
624          # Create the return string.          # Create the return string.
625          my $retVal = "";          my $retVal = "";
626          # Loop through the locations.          # Loop through the locations.
# Line 720  Line 635 
635                  # 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
636                  # before putting it in the return value.                  # before putting it in the return value.
637                  my ($start, $stop);                  my ($start, $stop);
638            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
639                  if ($dir eq "+") {                  if ($dir eq "+") {
640                          $start = $beg;                          $start = $beg;
641                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
642                  } else {                  } else {
643                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
644                          $stop = $beg;                          $stop = $beg;
645                  }                  }
646            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
647                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
648                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
649                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 738  Line 655 
655                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
656                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
657                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
658                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
659                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
660                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
661                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
662                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
663                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
664                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
665                  }                  }
666                  # 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.
667                  if ($dir eq '+') {                  if ($dir eq '+') {
668                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
669                  } else {                  } else {
670                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
671                  }                  }
672          }          }
673          # Return the result.          # Return the result.
# Line 778  Line 696 
696  #: Return Type @;  #: Return Type @;
697  sub AllContigs {  sub AllContigs {
698          # Get the parameters.          # Get the parameters.
699          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
700          # Ask for the genome's Contigs.          # Ask for the genome's Contigs.
701          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],
702                                                                  'HasContig(to-link)');                                                                  'HasContig(to-link)');
# Line 809  Line 726 
726  #: Return Type $;  #: Return Type $;
727  sub ContigLength {  sub ContigLength {
728          # Get the parameters.          # Get the parameters.
729          my $self = shift @_;      my ($self, $contigID) = @_;
         my ($contigID) = @_;  
730          # Get the contig's last sequence.          # Get the contig's last sequence.
731          my $query = $self->Get(['IsMadeUpOf'],          my $query = $self->Get(['IsMadeUpOf'],
732                  "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",                  "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
# Line 821  Line 737 
737          # Set it from the sequence data, if any.          # Set it from the sequence data, if any.
738          if ($sequence) {          if ($sequence) {
739                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
740                  $retVal = $start + $len;          $retVal = $start + $len - 1;
741        }
742        # Return the result.
743        return $retVal;
744    }
745    
746    =head3 ClusterPEGs
747    
748    C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
749    
750    Cluster the PEGs in a list according to the cluster coding scheme of the specified
751    subsystem. In order for this to work properly, the subsystem object must have
752    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
753    This causes the cluster numbers to be pulled into the subsystem's color hash.
754    If a PEG is not found in the color hash, it will not appear in the output
755    sequence.
756    
757    =over 4
758    
759    =item sub
760    
761    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
762    method.
763    
764    =item pegs
765    
766    Reference to the list of PEGs to be clustered.
767    
768    =item RETURN
769    
770    Returns a list of the PEGs, grouped into smaller lists by cluster number.
771    
772    =back
773    
774    =cut
775    #: Return Type $@@;
776    sub ClusterPEGs {
777        # Get the parameters.
778        my ($self, $sub, $pegs) = @_;
779        # Declare the return variable.
780        my $retVal = [];
781        # Loop through the PEGs, creating arrays for each cluster.
782        for my $pegID (@{$pegs}) {
783            my $clusterNumber = $sub->get_cluster_number($pegID);
784            # Only proceed if the PEG is in a cluster.
785            if ($clusterNumber >= 0) {
786                # Push this PEG onto the sub-list for the specified cluster number.
787                push @{$retVal->[$clusterNumber]}, $pegID;
788            }
789          }          }
790          # Return the result.          # Return the result.
791          return $retVal;          return $retVal;
# Line 861  Line 825 
825  #: Return Type @@;  #: Return Type @@;
826  sub GenesInRegion {  sub GenesInRegion {
827          # Get the parameters.          # Get the parameters.
828          my $self = shift @_;      my ($self, $contigID, $start, $stop) = @_;
         my ($contigID, $start, $stop) = @_;  
829          # Get the maximum segment length.          # Get the maximum segment length.
830          my $maximumSegmentLength = $self->MaxSegment;          my $maximumSegmentLength = $self->MaxSegment;
831          # Create a hash to receive the feature list. We use a hash so that we can eliminate          # Create a hash to receive the feature list. We use a hash so that we can eliminate
# Line 963  Line 926 
926  #: Return Type $;  #: Return Type $;
927  sub FType {  sub FType {
928          # Get the parameters.          # Get the parameters.
929          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
930          # Get the specified feature's type.          # Get the specified feature's type.
931          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
932          # Return the result.          # Return the result.
# Line 973  Line 935 
935    
936  =head3 FeatureAnnotations  =head3 FeatureAnnotations
937    
938  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
939    
940  Return the annotations of a feature.  Return the annotations of a feature.
941    
# Line 983  Line 945 
945    
946  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
947    
948    =item rawFlag
949    
950    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
951    will be returned in human-readable form.
952    
953  =item RETURN  =item RETURN
954    
955  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.
956    
957  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
958    
959  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
960    
961  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
962    
# Line 1001  Line 968 
968  #: Return Type @%;  #: Return Type @%;
969  sub FeatureAnnotations {  sub FeatureAnnotations {
970          # Get the parameters.          # Get the parameters.
971          my $self = shift @_;      my ($self, $featureID, $rawFlag) = @_;
         my ($featureID) = @_;  
972          # 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.
973          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
974                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 1015  Line 981 
981                          $annotation->Values(['IsTargetOfAnnotation(from-link)',                          $annotation->Values(['IsTargetOfAnnotation(from-link)',
982                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
983                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
984            # Convert the time, if necessary.
985            if (! $rawFlag) {
986                $timeStamp = FriendlyTimestamp($timeStamp);
987            }
988                  # Assemble them into a hash.                  # Assemble them into a hash.
989          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
990                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
991                                                             user => $user, text => $text };                                                             user => $user, text => $text };
992                  # Add it to the return list.                  # Add it to the return list.
993                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1031  Line 1001 
1001  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>
1002    
1003  Return all of the functional assignments for a particular feature. The data is returned as a  Return all of the functional assignments for a particular feature. The data is returned as a
1004  hash of functional assignments to user IDs. A functional assignment is a type of annotation.  hash of functional assignments to user IDs. A functional assignment is a type of annotation,
1005  It has the format "XXXX\nset XXXX function to\nYYYYY". In this instance, XXXX is the user ID  Functional assignments are described in the L</ParseAssignment> function. Its worth noting that
1006  and YYYYY is the functional assignment text. Its worth noting that we cannot filter on the content  we cannot filter on the content of the annotation itself because it's a text field; however,
1007  of the annotation itself because it's a text field; however, this is not a big problem because most  this is not a big problem because most features only have a small number of annotations.
1008  features only have a small number of annotations. Finally, if a single user has multiple  Finally, if a single user has multiple functional assignments, we will only keep the most
1009  functional assignments, we will only keep the most recent one.  recent one.
1010    
1011  =over 4  =over 4
1012    
# Line 1046  Line 1016 
1016    
1017  =item RETURN  =item RETURN
1018    
1019  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1020    
1021  =back  =back
1022    
# Line 1054  Line 1024 
1024  #: Return Type %;  #: Return Type %;
1025  sub AllFunctionsOf {  sub AllFunctionsOf {
1026          # Get the parameters.          # Get the parameters.
1027          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1028          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1029      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1030                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1031                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1032                                               'MadeAnnotation(from-link)']);
1033          # Declare the return hash.          # Declare the return hash.
1034          my %retVal;          my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1035      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1036      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1037          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1038      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1039          # Get the annotation fields.          # Get the annotation fields.
1040          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1041                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1042                  my ($user, $function) = ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1043          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1044              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1045              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1046              # return hash.              # return hash.
1047                          $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1048                  }                  }
1049          }          }
1050          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1093  Line 1059 
1059    
1060  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
1061  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
1062  assignment is a type of annotation. It has the format "XXXX\nset XXXX function to\nYYYYY". In this  assignment is a type of annotation. The format of an assignment is described in
1063  instance, XXXX is the user ID and YYYYY is the functional assignment text. Its worth noting that  L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1064  we cannot filter on the content of the annotation itself because it's a text field; however, this  annotation itself because it's a text field; however, this is not a big problem because
1065  is not a big problem because most features only have a small number of annotations.  most features only have a small number of annotations.
1066    
1067  Each user has an associated list of trusted users. The assignment returned will be the most  Each user has an associated list of trusted users. The assignment returned will be the most
1068  recent one by at least one of the trusted users. If no trusted user list is available, then  recent one by at least one of the trusted users. If no trusted user list is available, then
# Line 1128  Line 1094 
1094  #: Return Type $;  #: Return Type $;
1095  sub FunctionOf {  sub FunctionOf {
1096          # Get the parameters.          # Get the parameters.
1097          my $self = shift @_;      my ($self, $featureID, $userID) = @_;
         my ($featureID, $userID) = @_;  
1098      # Declare the return value.      # Declare the return value.
1099      my $retVal;      my $retVal;
1100      # Determine the ID type.      # Determine the ID type.
# Line 1157  Line 1122 
1122              }              }
1123          }          }
1124          # 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.
1125          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1126                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1127                                 [$featureID]);                                 [$featureID]);
1128          my $timeSelected = 0;          my $timeSelected = 0;
1129          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1130          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1131              # Get the annotation text.              # Get the annotation text.
1132              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);              my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1133                                                         'Annotation(time)', 'MadeAnnotation(from-link)']);
1134              # 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.
1135              my ($user, $type, $function) = split(/\n/, $text);              my ($actualUser, $function) = _ParseAssignment($user, $text);
1136              if ($type =~ m/^set $user function to$/i) {              Trace("Assignment user is $actualUser, text is $function.") if T(4);
1137                if ($actualUser) {
1138                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1139                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1140                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                  if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1141                      $retVal = $function;                      $retVal = $function;
1142                      $timeSelected = $time;                      $timeSelected = $time;
1143                  }                  }
# Line 1186  Line 1153 
1153          return $retVal;          return $retVal;
1154  }  }
1155    
1156    =head3 FunctionsOf
1157    
1158    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1159    
1160    Return the functional assignments of a particular feature.
1161    
1162    The functional assignment is handled differently depending on the type of feature. If
1163    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1164    assignment is a type of annotation. The format of an assignment is described in
1165    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1166    annotation itself because it's a text field; however, this is not a big problem because
1167    most features only have a small number of annotations.
1168    
1169    If the feature is B<not> identified by a FIG ID, then the functional assignment
1170    information is taken from the B<ExternalAliasFunc> table. If the table does
1171    not contain an entry for the feature, an empty list is returned.
1172    
1173    =over 4
1174    
1175    =item featureID
1176    
1177    ID of the feature whose functional assignments are desired.
1178    
1179    =item RETURN
1180    
1181    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1182    that user.
1183    
1184    =back
1185    
1186    =cut
1187    #: Return Type @@;
1188    sub FunctionsOf {
1189        # Get the parameters.
1190        my ($self, $featureID) = @_;
1191        # Declare the return value.
1192        my @retVal = ();
1193        # Determine the ID type.
1194        if ($featureID =~ m/^fig\|/) {
1195            # Here we have a FIG feature ID. We must build the list of trusted
1196            # users.
1197            my %trusteeTable = ();
1198            # Build a query for all of the feature's annotations, sorted by date.
1199            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1200                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1201                                   [$featureID]);
1202            my $timeSelected = 0;
1203            # Loop until we run out of annotations.
1204            while (my $annotation = $query->Fetch()) {
1205                # Get the annotation text.
1206                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1207                                                                'Annotation(time)',
1208                                                                'MadeAnnotation(user)']);
1209                # Check to see if this is a functional assignment for a trusted user.
1210                my ($actualUser, $function) = _ParseAssignment($user, $text);
1211                if ($actualUser) {
1212                    # Here it is a functional assignment.
1213                    push @retVal, [$actualUser, $function];
1214                }
1215            }
1216        } else {
1217            # Here we have a non-FIG feature ID. In this case the user ID does not
1218            # matter. We simply get the information from the External Alias Function
1219            # table.
1220            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1221                                                     ['ExternalAliasFunc(func)']);
1222            push @retVal, map { ['master', $_] } @assignments;
1223        }
1224        # Return the assignments found.
1225        return @retVal;
1226    }
1227    
1228  =head3 BBHList  =head3 BBHList
1229    
1230  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1205  Line 1244 
1244    
1245  =item RETURN  =item RETURN
1246    
1247  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
1248  their best hits.  on the target genome.
1249    
1250  =back  =back
1251    
# Line 1214  Line 1253 
1253  #: Return Type %;  #: Return Type %;
1254  sub BBHList {  sub BBHList {
1255          # Get the parameters.          # Get the parameters.
1256          my $self = shift @_;      my ($self, $genomeID, $featureList) = @_;
         my ($genomeID, $featureList) = @_;  
1257          # Create the return structure.          # Create the return structure.
1258          my %retVal = ();          my %retVal = ();
1259          # Loop through the incoming features.          # Loop through the incoming features.
# Line 1224  Line 1262 
1262                  my $query = $self->Get(['IsBidirectionalBestHitOf'],                  my $query = $self->Get(['IsBidirectionalBestHitOf'],
1263                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",
1264                                                             [$featureID, $genomeID]);                                                             [$featureID, $genomeID]);
1265                  # Look for the best hit.          # Peel off the BBHs found.
1266                  my $bbh = $query->Fetch;          my @found = ();
1267                  if ($bbh) {          while (my $bbh = $query->Fetch) {
1268                          my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');
                         $retVal{$featureID} = $targetFeature;  
1269                  }                  }
1270            $retVal{$featureID} = \@found;
1271          }          }
1272          # Return the mapping.          # Return the mapping.
1273          return \%retVal;          return \%retVal;
1274  }  }
1275    
1276    =head3 SimList
1277    
1278    C<< my %similarities = $sprout->SimList($featureID, $count); >>
1279    
1280    Return a list of the similarities to the specified feature.
1281    
1282    Sprout does not support real similarities, so this method just returns the bidirectional
1283    best hits.
1284    
1285    =over 4
1286    
1287    =item featureID
1288    
1289    ID of the feature whose similarities are desired.
1290    
1291    =item count
1292    
1293    Maximum number of similar features to be returned, or C<0> to return them all.
1294    
1295    =back
1296    
1297    =cut
1298    #: Return Type %;
1299    sub SimList {
1300        # Get the parameters.
1301        my ($self, $featureID, $count) = @_;
1302        # Ask for the best hits.
1303        my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],
1304                                  "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",
1305                                  [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],
1306                                  $count);
1307        # Create the return value.
1308        my %retVal = ();
1309        for my $tuple (@lists) {
1310            $retVal{$tuple->[0]} = $tuple->[1];
1311        }
1312        # Return the result.
1313        return %retVal;
1314    }
1315    
1316    
1317    
1318    =head3 IsComplete
1319    
1320    C<< my $flag = $sprout->IsComplete($genomeID); >>
1321    
1322    Return TRUE if the specified genome is complete, else FALSE.
1323    
1324    =over 4
1325    
1326    =item genomeID
1327    
1328    ID of the genome whose completeness status is desired.
1329    
1330    =item RETURN
1331    
1332    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1333    not found.
1334    
1335    =back
1336    
1337    =cut
1338    #: Return Type $;
1339    sub IsComplete {
1340        # Get the parameters.
1341        my ($self, $genomeID) = @_;
1342        # Declare the return variable.
1343        my $retVal;
1344        # Get the genome's data.
1345        my $genomeData = $self->GetEntity('Genome', $genomeID);
1346        if ($genomeData) {
1347            # The genome exists, so get the completeness flag.
1348            ($retVal) = $genomeData->Value('Genome(complete)');
1349        }
1350        # Return the result.
1351        return $retVal;
1352    }
1353    
1354  =head3 FeatureAliases  =head3 FeatureAliases
1355    
1356  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
# Line 1258  Line 1374 
1374  #: Return Type @;  #: Return Type @;
1375  sub FeatureAliases {  sub FeatureAliases {
1376          # Get the parameters.          # Get the parameters.
1377          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1378          # Get the desired feature's aliases          # Get the desired feature's aliases
1379          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);
1380          # Return the result.          # Return the result.
# Line 1270  Line 1385 
1385    
1386  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1387    
1388  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1389    
1390  =over 4  =over 4
1391    
1392  =item featureID  =item featureID
1393    
1394  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1395    
1396  =item RETURN  =item RETURN
1397    
1398  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
1399  an undefined value.  found, returns an undefined value.
1400    
1401  =back  =back
1402    
# Line 1289  Line 1404 
1404  #: Return Type $;  #: Return Type $;
1405  sub GenomeOf {  sub GenomeOf {
1406          # Get the parameters.          # Get the parameters.
1407          my $self = shift @_;      my ($self, $featureID) = @_;
1408          my ($featureID) = @_;      # Create a query to find the genome associated with the incoming ID.
1409          # Create a query to find the genome associated with the feature.      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1410          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);                             [$featureID, $featureID]);
1411          # Declare the return value.          # Declare the return value.
1412          my $retVal;          my $retVal;
1413          # Get the genome ID.          # Get the genome ID.
# Line 1312  Line 1427 
1427    
1428  =over 4  =over 4
1429    
1430  =item featureID  =item featureID
1431    
1432    ID of the feature whose functionally-coupled brethren are desired.
1433    
1434    =item RETURN
1435    
1436    A hash mapping the functionally-coupled feature IDs to the coupling score.
1437    
1438    =back
1439    
1440    =cut
1441    #: Return Type %;
1442    sub CoupledFeatures {
1443        # Get the parameters.
1444        my ($self, $featureID) = @_;
1445        # Create a query to retrieve the functionally-coupled features.
1446        my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1447                               "ParticipatesInCoupling(from-link) = ?", [$featureID]);
1448        # This value will be set to TRUE if we find at least one coupled feature.
1449        my $found = 0;
1450        # Create the return hash.
1451        my %retVal = ();
1452        # Retrieve the relationship records and store them in the hash.
1453        while (my $clustering = $query->Fetch()) {
1454            # Get the ID and score of the coupling.
1455            my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1456                                                            'Coupling(score)']);
1457            # The coupling ID contains the two feature IDs separated by a space. We use
1458            # this information to find the ID of the other feature.
1459            my ($fid1, $fid2) = split / /, $couplingID;
1460            my $otherFeatureID = ($featureID eq $fid1 ? $fid2 : $fid1);
1461            # Attach the other feature's score to its ID.
1462            $retVal{$otherFeatureID} = $score;
1463            $found = 1;
1464        }
1465        # Functional coupling is reflexive. If we found at least one coupled feature, we must add
1466        # the incoming feature as well.
1467        if ($found) {
1468            $retVal{$featureID} = 9999;
1469        }
1470        # Return the hash.
1471        return %retVal;
1472    }
1473    
1474    =head3 CouplingEvidence
1475    
1476    C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1477    
1478    Return the evidence for a functional coupling.
1479    
1480    A pair of features is considered evidence of a coupling between two other
1481    features if they occur close together on a contig and both are similar to
1482    the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1483    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1484    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1485    similar to B<A2>.
1486    
1487    The score of a coupling is determined by the number of pieces of evidence
1488    that are considered I<representative>. If several evidence items belong to
1489    a group of genomes that are close to each other, only one of those items
1490    is considered representative. The other evidence items are presumed to be
1491    there because of the relationship between the genomes rather than because
1492    the two proteins generated by the features have a related functionality.
1493    
1494    Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1495    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1496    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1497    and FALSE otherwise.
1498    
1499    =over 4
1500    
1501    =item peg1
1502    
1503    ID of the feature of interest.
1504    
1505    =item peg2
1506    
1507    ID of a feature functionally coupled to the feature of interest.
1508    
1509    =item RETURN
1510    
1511    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1512    of interest, a feature similar to the functionally coupled feature, and a flag
1513    that is TRUE for a representative piece of evidence and FALSE otherwise.
1514    
1515    =back
1516    
1517    =cut
1518    #: Return Type @@;
1519    sub CouplingEvidence {
1520        # Get the parameters.
1521        my ($self, $peg1, $peg2) = @_;
1522        # Declare the return variable.
1523        my @retVal = ();
1524        # Our first task is to find out the nature of the coupling: whether or not
1525        # it exists, its score, and whether the features are stored in the same
1526        # order as the ones coming in.
1527        my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1528        # Only proceed if a coupling exists.
1529        if ($couplingID) {
1530            # Determine the ordering to place on the evidence items. If we're
1531            # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1532            # we want feature 1 before feature 2 (normal).
1533            Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);
1534            my $ordering = ($inverted ? "DESC" : "");
1535            # Get the coupling evidence.
1536            my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
1537                                              "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",
1538                                              [$couplingID],
1539                                              ['PCH(used)', 'UsesAsEvidence(to-link)']);
1540            # Loop through the evidence items. Each piece of evidence is represented by two
1541            # positions in the evidence list, one for each feature on the other side of the
1542            # evidence link. If at some point we want to generalize to couplings with
1543            # more than two positions, this section of code will need to be re-done.
1544            while (@evidenceList > 0) {
1545                my $peg1Data = shift @evidenceList;
1546                my $peg2Data = shift @evidenceList;
1547                Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1548                push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1549            }
1550            Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1551        }
1552        # Return the result.
1553        return @retVal;
1554    }
1555    
1556    =head3 GetCoupling
1557    
1558    C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>
1559    
1560    Return the coupling (if any) for the specified pair of PEGs. If a coupling
1561    exists, we return the coupling ID along with an indicator of whether the
1562    coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.
1563    In the second case, we say the coupling is I<inverted>. The importance of an
1564    inverted coupling is that the PEGs in the evidence will appear in reverse order.
1565    
1566    =over 4
1567    
1568    =item peg1
1569    
1570  ID of the feature whose functionally-coupled brethren are desired.  ID of the feature of interest.
1571    
1572    =item peg2
1573    
1574    ID of the potentially coupled feature.
1575    
1576  =item RETURN  =item RETURN
1577    
1578  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
1579    the coupling. The second element is FALSE if the coupling is stored in the
1580    database in the caller specified order and TRUE if it is stored in the
1581    inverted order. The third element is the coupling's score. If the coupling
1582    does not exist, all three list elements will be C<undef>.
1583    
1584  =back  =back
1585    
1586  =cut  =cut
1587  #: Return Type %;  #: Return Type $%@;
1588  sub CoupledFeatures {  sub GetCoupling {
1589          # Get the parameters.          # Get the parameters.
1590          my $self = shift @_;      my ($self, $peg1, $peg2) = @_;
1591          my ($featureID) = @_;      # Declare the return values. We'll start with the coupling ID and undefine the
1592          # Create a query to retrieve the functionally-coupled features. Note that we depend on the      # flag and score until we have more information.
1593          # fact that the functional coupling is physically paired. If (A,B) is in the database, then      my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);
1594          # (B,A) will also be found.      # Find the coupling data.
1595          my $query = $self->Get(['IsClusteredOnChromosomeWith'],      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1596                                                     "IsClusteredOnChromosomeWith(from-link) = ?", [$featureID]);                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1597          # This value will be set to TRUE if we find at least one coupled feature.                                   [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1598          my $found = 0;      # Check to see if we found anything.
1599          # Create the return hash.      if (!@pegs) {
1600          my %retVal = ();          Trace("No coupling found.") if T(Coupling => 4);
1601          # Retrieve the relationship records and store them in the hash.          # No coupling, so undefine the return value.
1602          while (my $clustering = $query->Fetch()) {          $retVal = undef;
1603                  my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',      } else {
1604                                                                      'IsClusteredOnChromosomeWith(score)']);          # We have a coupling! Get the score and check for inversion.
1605                  $retVal{$otherFeatureID} = $score;          $score = $pegs[0]->[1];
1606                  $found = 1;          my $firstFound = $pegs[0]->[0];
1607          }          $inverted = ($firstFound ne $peg1);
1608          # Functional coupling is reflexive. If we found at least one coupled feature, we must add          Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
         # the incoming feature as well.  
         if ($found) {  
                 $retVal{$featureID} = 9999;  
1609      }      }
1610          # Return the hash.      # Return the result.
1611          return %retVal;      return ($retVal, $inverted, $score);
1612  }  }
1613    
1614  =head3 GetEntityTypes  =head3 CouplingID
1615    
1616    C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>
1617    
1618    Return the coupling ID for a pair of feature IDs.
1619    
1620    The coupling ID is currently computed by joining the feature IDs in
1621    sorted order with a space. Client modules (that is, modules which
1622    use Sprout) should not, however, count on this always being the
1623    case. This method provides a way for abstracting the concept of a
1624    coupling ID. All that we know for sure about it is that it can be
1625    generated easily from the feature IDs and the order of the IDs
1626    in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>
1627    will have the same value as C<CouplingID("b1", "a1")>.
1628    
1629    =over 4
1630    
1631    =item peg1
1632    
1633    First feature of interest.
1634    
1635  C<< my @entityList = $sprout->GetEntityTypes(); >>  =item peg2
1636    
1637  Return the list of supported entity types.  Second feature of interest.
1638    
1639    =item RETURN
1640    
1641    Returns the ID that would be used to represent a functional coupling of
1642    the two specified PEGs.
1643    
1644    =back
1645    
1646  =cut  =cut
1647  #: Return Type @;  #: Return Type $;
1648  sub GetEntityTypes {  sub CouplingID {
1649          # Get the parameters.      return join " ", sort @_;
         my $self = shift @_;  
         # Get the underlying database object.  
         my $erdb = $self->{_erdb};  
         # Get its entity type list.  
         my @retVal = $erdb->GetEntityTypes();  
1650  }  }
1651    
1652  =head3 ReadFasta  =head3 ReadFasta
# Line 1414  Line 1693 
1693                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1694                          # 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.
1695                          if ($id) {                          if ($id) {
1696                                  $retVal{$id} = $sequence;                  $retVal{$id} = lc $sequence;
1697                          }                          }
1698                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
1699                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
1700                  } else {                  } else {
1701                          # 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.
1702                          # First, we get the actual data out.              # First, we get the actual data out. Note that we normalize to lower
1703                # case.
1704                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
1705                          $sequence .= $1;                          $sequence .= $1;
1706                  }                  }
1707          }          }
1708          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
1709          if ($sequence) {          if ($sequence) {
1710                  $retVal {$id} = $sequence;          $retVal{$id} = lc $sequence;
1711          }          }
1712        # Close the file.
1713        close FASTAFILE;
1714          # Return the hash constructed from the file.          # Return the hash constructed from the file.
1715          return %retVal;          return %retVal;
1716  }  }
# Line 1439  Line 1721 
1721    
1722  Insure that a list of feature locations is in the Sprout format. The Sprout feature location  Insure that a list of feature locations is in the Sprout format. The Sprout feature location
1723  format is I<contig>_I<beg*len> where I<*> is C<+> for a forward gene and C<-> for a backward  format is I<contig>_I<beg*len> where I<*> is C<+> for a forward gene and C<-> for a backward
1724  gene. The old format is I<contig>_I<beg>_I<end>.  gene. The old format is I<contig>_I<beg>_I<end>. If a feature is in the new format already,
1725    it will not be changed; otherwise, it will be converted. This method can also be used to
1726    perform the reverse task-- insuring that all the locations are in the old format.
1727    
1728  =over 4  =over 4
1729    
# Line 1466  Line 1750 
1750  #: Return Type @;  #: Return Type @;
1751  sub FormatLocations {  sub FormatLocations {
1752          # Get the parameters.          # Get the parameters.
1753          my $self = shift @_;      my ($self, $prefix, $locations, $oldFormat) = @_;
         my ($prefix, $locations, $oldFormat) = @_;  
1754          # Create the return list.          # Create the return list.
1755          my @retVal = ();          my @retVal = ();
1756          # Check to see if any locations were passed in.          # Check to see if any locations were passed in.
1757          if ($locations eq '') {          if ($locations eq '') {
1758              confess "No locations specified.";          Confess("No locations specified.");
1759          } else {          } else {
1760                  # Loop through the locations, converting them to the new format.                  # Loop through the locations, converting them to the new format.
1761                  for my $location (@{$locations}) {                  for my $location (@{$locations}) {
# Line 1507  Line 1790 
1790    
1791  sub DumpData {  sub DumpData {
1792          # Get the parameters.          # Get the parameters.
1793          my $self = shift @_;      my ($self) = @_;
1794          # Get the data directory name.          # Get the data directory name.
1795          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
1796          # Dump the relations.          # Dump the relations.
1797          $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
1798  }  }
1799    
1800  =head3 XMLFileName  =head3 XMLFileName
# Line 1523  Line 1806 
1806  =cut  =cut
1807  #: Return Type $;  #: Return Type $;
1808  sub XMLFileName {  sub XMLFileName {
1809          my $self = shift @_;      my ($self) = @_;
1810          return $self->{_xmlName};          return $self->{_xmlName};
1811  }  }
1812    
# Line 1543  Line 1826 
1826  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
1827  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>.
1828    
1829  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'}); >>
1830    
1831  =over 4  =over 4
1832    
# Line 1561  Line 1844 
1844  #: Return Type ;  #: Return Type ;
1845  sub Insert {  sub Insert {
1846          # Get the parameters.          # Get the parameters.
1847          my $self = shift @_;      my ($self, $objectType, $fieldHash) = @_;
         my ($objectType, $fieldHash) = @_;  
1848          # Call the underlying method.          # Call the underlying method.
1849          $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
1850  }  }
1851    
1852  =head3 Annotate  =head3 Annotate
# Line 1603  Line 1885 
1885  #: Return Type $;  #: Return Type $;
1886  sub Annotate {  sub Annotate {
1887          # Get the parameters.          # Get the parameters.
1888          my $self = shift @_;      my ($self, $fid, $timestamp, $user, $text) = @_;
         my ($fid, $timestamp, $user, $text) = @_;  
1889          # Create the annotation ID.          # Create the annotation ID.
1890          my $aid = "$fid:$timestamp";          my $aid = "$fid:$timestamp";
1891          # Insert the Annotation object.          # Insert the Annotation object.
# Line 1624  Line 1905 
1905    
1906  =head3 AssignFunction  =head3 AssignFunction
1907    
1908  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function); >>  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>
1909    
1910  This method assigns a function to a feature. Functions are a special type of annotation. The general  This method assigns a function to a feature. Functions are a special type of annotation. The general
1911  format is "XXXX\nset XXXX function to\nYYYYY" where XXXX is the feature type and YYYY is the functional  format is described in L</ParseAssignment>.
 assignment text.  
1912    
1913  =over 4  =over 4
1914    
# Line 1638  Line 1918 
1918    
1919  =item user  =item user
1920    
1921  Name of the user making the assignment. This is frequently a group name, like C<kegg> or C<fig>.  Name of the user group making the assignment, such as C<kegg> or C<fig>.
1922    
1923  =item function  =item function
1924    
1925  Text of the function being assigned.  Text of the function being assigned.
1926    
1927    =item assigningUser (optional)
1928    
1929    Name of the individual user making the assignment. If omitted, defaults to the user group.
1930    
1931  =item RETURN  =item RETURN
1932    
1933  Returns 1 if successful, 0 if an error occurred.  Returns 1 if successful, 0 if an error occurred.
# Line 1654  Line 1938 
1938  #: Return Type $;  #: Return Type $;
1939  sub AssignFunction {  sub AssignFunction {
1940          # Get the parameters.          # Get the parameters.
1941          my $self = shift @_;      my ($self, $featureID, $user, $function, $assigningUser) = @_;
1942          my ($featureID, $user, $function) = @_;      # Default the assigning user.
1943        if (! $assigningUser) {
1944            $assigningUser = $user;
1945        }
1946          # Create an annotation string from the parameters.          # Create an annotation string from the parameters.
1947          my $annotationText = "$user\nset $user function to\n$function";      my $annotationText = "$assigningUser\nset $user function to\n$function";
1948          # Get the current time.          # Get the current time.
1949          my $now = time;          my $now = time;
1950          # Declare the return variable.          # Declare the return variable.
# Line 1702  Line 1989 
1989  #: Return Type @;  #: Return Type @;
1990  sub FeaturesByAlias {  sub FeaturesByAlias {
1991          # Get the parameters.          # Get the parameters.
1992          my $self = shift @_;      my ($self, $alias) = @_;
         my ($alias) = @_;  
1993          # Declare the return variable.          # Declare the return variable.
1994          my @retVal = ();          my @retVal = ();
1995          # Parse the alias.          # Parse the alias.
# Line 1745  Line 2031 
2031  #: Return Type $;  #: Return Type $;
2032  sub Exists {  sub Exists {
2033          # Get the parameters.          # Get the parameters.
2034          my $self = shift @_;      my ($self, $entityName, $entityID) = @_;
         my ($entityName, $entityID) = @_;  
2035          # Check for the entity instance.          # Check for the entity instance.
2036        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
2037          my $testInstance = $self->GetEntity($entityName, $entityID);          my $testInstance = $self->GetEntity($entityName, $entityID);
2038          # Return an existence indicator.          # Return an existence indicator.
2039          my $retVal = ($testInstance ? 1 : 0);          my $retVal = ($testInstance ? 1 : 0);
# Line 1776  Line 2062 
2062  #: Return Type $;  #: Return Type $;
2063  sub FeatureTranslation {  sub FeatureTranslation {
2064          # Get the parameters.          # Get the parameters.
2065          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2066          # Get the specified feature's translation.          # Get the specified feature's translation.
2067          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
2068          return $retVal;          return $retVal;
# Line 1809  Line 2094 
2094  #: Return Type @;  #: Return Type @;
2095  sub Taxonomy {  sub Taxonomy {
2096          # Get the parameters.          # Get the parameters.
2097          my $self = shift @_;      my ($self, $genome) = @_;
         my ($genome) = @_;  
2098          # Find the specified genome's taxonomy string.          # Find the specified genome's taxonomy string.
2099          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);
2100          # Declare the return variable.          # Declare the return variable.
# Line 1853  Line 2137 
2137  #: Return Type $;  #: Return Type $;
2138  sub CrudeDistance {  sub CrudeDistance {
2139          # Get the parameters.          # Get the parameters.
2140          my $self = shift @_;      my ($self, $genome1, $genome2) = @_;
         my ($genome1, $genome2) = @_;  
2141          # Insure that the distance is commutative by sorting the genome IDs.          # Insure that the distance is commutative by sorting the genome IDs.
2142          my ($genomeA, $genomeB);          my ($genomeA, $genomeB);
2143          if ($genome2 < $genome2) {          if ($genome2 < $genome2) {
# Line 1901  Line 2184 
2184  #: Return Type $;  #: Return Type $;
2185  sub RoleName {  sub RoleName {
2186          # Get the parameters.          # Get the parameters.
2187          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2188          # Get the specified role's name.          # Get the specified role's name.
2189          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);
2190          # Use the ID if the role has no name.          # Use the ID if the role has no name.
# Line 1935  Line 2217 
2217  #: Return Type @;  #: Return Type @;
2218  sub RoleDiagrams {  sub RoleDiagrams {
2219          # Get the parameters.          # Get the parameters.
2220          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2221          # Query for the diagrams.          # Query for the diagrams.
2222          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2223                                                                  'RoleOccursIn(to-link)');                                                                  'RoleOccursIn(to-link)');
# Line 1944  Line 2225 
2225          return @retVal;          return @retVal;
2226  }  }
2227    
2228    =head3 GetProperties
2229    
2230    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2231    
2232    Return a list of the properties with the specified characteristics.
2233    
2234    Properties are arbitrary key-value pairs associated with a feature. (At some point they
2235    will also be associated with genomes.) A property value is represented by a 4-tuple of
2236    the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2237    
2238    =over 4
2239    
2240    =item fid
2241    
2242    ID of the feature possessing the property.
2243    
2244    =item key
2245    
2246    Name or key of the property.
2247    
2248    =item value
2249    
2250    Value of the property.
2251    
2252    =item url
2253    
2254    URL of the document that indicated the property should have this particular value, or an
2255    empty string if no such document exists.
2256    
2257    =back
2258    
2259    The parameters act as a filter for the desired data. Any non-null parameter will
2260    automatically match all the tuples returned. So, specifying just the I<$fid> will
2261    return all the properties of the specified feature; similarly, specifying the I<$key>
2262    and I<$value> parameters will return all the features having the specified property
2263    value.
2264    
2265    A single property key can have many values, representing different ideas about the
2266    feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2267    virulent, and another may declare that it is not virulent. A query about the virulence of
2268    C<fig|83333.1.peg.10> would be coded as
2269    
2270        my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2271    
2272    Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2273    not to be filtered. The tuples returned would be
2274    
2275        ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2276        ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2277    
2278    =cut
2279    #: Return Type @@;
2280    sub GetProperties {
2281        # Get the parameters.
2282        my ($self, @parms) = @_;
2283        # Declare the return variable.
2284        my @retVal = ();
2285        # Now we need to create a WHERE clause that will get us the data we want. First,
2286        # we create a list of the columns containing the data for each parameter.
2287        my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2288                        'Property(property-value)', 'HasProperty(evidence)');
2289        # Now we build the WHERE clause and the list of parameter values.
2290        my @where = ();
2291        my @values = ();
2292        for (my $i = 0; $i <= $#colNames; $i++) {
2293            my $parm = $parms[$i];
2294            if (defined $parm && ($parm ne '')) {
2295                push @where, "$colNames[$i] = ?";
2296                push @values, $parm;
2297            }
2298        }
2299        # Format the WHERE clause.
2300        my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2301        # Ask for all the propertie values with the desired characteristics.
2302        my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2303        while (my $valueObject = $query->Fetch()) {
2304            my @tuple = $valueObject->Values(\@colNames);
2305            push @retVal, \@tuple;
2306        }
2307        # Return the result.
2308        return @retVal;
2309    }
2310    
2311  =head3 FeatureProperties  =head3 FeatureProperties
2312    
2313  C<< my @properties = $sprout->FeatureProperties($featureID); >>  C<< my @properties = $sprout->FeatureProperties($featureID); >>
# Line 1973  Line 2337 
2337  #: Return Type @@;  #: Return Type @@;
2338  sub FeatureProperties {  sub FeatureProperties {
2339          # Get the parameters.          # Get the parameters.
2340          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2341          # Get the properties.          # Get the properties.
2342          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],
2343                                                          ['Property(property-name)', 'Property(property-value)',                                                          ['Property(property-name)', 'Property(property-value)',
# Line 2005  Line 2368 
2368  #: Return Type $;  #: Return Type $;
2369  sub DiagramName {  sub DiagramName {
2370          # Get the parameters.          # Get the parameters.
2371          my $self = shift @_;      my ($self, $diagramID) = @_;
         my ($diagramID) = @_;  
2372          # Get the specified diagram's name and return it.          # Get the specified diagram's name and return it.
2373          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);
2374          return $retVal;          return $retVal;
# Line 2038  Line 2400 
2400  #: Return Type @;  #: Return Type @;
2401  sub MergedAnnotations {  sub MergedAnnotations {
2402          # Get the parameters.          # Get the parameters.
2403          my $self = shift @_;      my ($self, $list) = @_;
         my ($list) = @_;  
2404          # Create a list to hold the annotation tuples found.          # Create a list to hold the annotation tuples found.
2405          my @tuples = ();          my @tuples = ();
2406          # Loop through the features in the input list.          # Loop through the features in the input list.
# Line 2087  Line 2448 
2448  #: Return Type @;  #: Return Type @;
2449  sub RoleNeighbors {  sub RoleNeighbors {
2450          # Get the parameters.          # Get the parameters.
2451          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2452          # Get all the diagrams containing this role.          # Get all the diagrams containing this role.
2453          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2454                                                                    'RoleOccursIn(to-link)');                                                                    'RoleOccursIn(to-link)');
# Line 2130  Line 2490 
2490  #: Return Type @;  #: Return Type @;
2491  sub FeatureLinks {  sub FeatureLinks {
2492          # Get the parameters.          # Get the parameters.
2493          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2494          # Get the feature's links.          # Get the feature's links.
2495          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);
2496          # Return the feature's links.          # Return the feature's links.
# Line 2143  Line 2502 
2502  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2503    
2504  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
2505  to the role the feature performs.  to the roles the feature performs.
2506    
2507  =over 4  =over 4
2508    
# Line 2153  Line 2512 
2512    
2513  =item RETURN  =item RETURN
2514    
2515  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.
2516    
2517  =back  =back
2518    
2519  =cut  =cut
2520  #: Return Type %;  #: Return Type %@;
2521  sub SubsystemsOf {  sub SubsystemsOf {
2522          # Get the parameters.          # Get the parameters.
2523          my $self = shift @_;      my ($self, $featureID) = @_;
2524          my ($featureID) = @_;      # Get the subsystem list.
         # Use the SSCell to connect features to subsystems.  
2525          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2526                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2527                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2528          # Create the return value.          # Create the return value.
2529          my %retVal = ();          my %retVal = ();
2530        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2531        # in two spreadsheet cells.
2532        my %dupHash = ();
2533          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
2534          for my $record (@subsystems) {          for my $record (@subsystems) {
2535                  $retVal{$record->[0]} = $record->[1];          # Get this subsystem and role.
2536            my ($subsys, $role) = @{$record};
2537            # Insure it's the first time for both.
2538            my $dupKey = "$subsys\n$role";
2539            if (! exists $dupHash{"$subsys\n$role"}) {
2540                $dupHash{$dupKey} = 1;
2541                push @{$retVal{$subsys}}, $role;
2542            }
2543          }          }
2544          # Return the hash.          # Return the hash.
2545          return %retVal;          return %retVal;
2546  }  }
2547    
2548    =head3 SubsystemList
2549    
2550    C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2551    
2552    Return a list containing the names of the subsystems in which the specified
2553    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2554    subsystem names, not the roles.
2555    
2556    =over 4
2557    
2558    =item featureID
2559    
2560    ID of the feature whose subsystem names are desired.
2561    
2562    =item RETURN
2563    
2564    Returns a list of the names of the subsystems in which the feature participates.
2565    
2566    =back
2567    
2568    =cut
2569    #: Return Type @;
2570    sub SubsystemList {
2571        # Get the parameters.
2572        my ($self, $featureID) = @_;
2573        # Get the list of names.
2574        my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",
2575                                    [$featureID], 'HasSSCell(from-link)');
2576        # Return the result.
2577        return @retVal;
2578    }
2579    
2580    
2581    
2582  =head3 RelatedFeatures  =head3 RelatedFeatures
2583    
2584  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2210  Line 2612 
2612  #: Return Type @;  #: Return Type @;
2613  sub RelatedFeatures {  sub RelatedFeatures {
2614          # Get the parameters.          # Get the parameters.
2615          my $self = shift @_;      my ($self, $featureID, $function, $userID) = @_;
         my ($featureID, $function, $userID) = @_;  
2616          # Get a list of the features that are BBHs of the incoming feature.          # Get a list of the features that are BBHs of the incoming feature.
2617          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],
2618                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],
# Line 2259  Line 2660 
2660  #: Return Type @;  #: Return Type @;
2661  sub TaxonomySort {  sub TaxonomySort {
2662          # Get the parameters.          # Get the parameters.
2663          my $self = shift @_;      my ($self, $featureIDs) = @_;
         my ($featureIDs) = @_;  
2664          # Create the working hash table.          # Create the working hash table.
2665          my %hashBuffer = ();          my %hashBuffer = ();
2666          # Loop through the features.          # Loop through the features.
# Line 2269  Line 2669 
2669                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
2670                                                                                  [$fid], 'Genome(taxonomy)');                                                                                  [$fid], 'Genome(taxonomy)');
2671                  # Add this feature to the hash buffer.                  # Add this feature to the hash buffer.
2672                  if (exists $hashBuffer{$taxonomy}) {          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);
                         push @{$hashBuffer{$taxonomy}}, $fid;  
                 } else {  
                         $hashBuffer{$taxonomy} = [$fid];  
                 }  
2673          }          }
2674          # Sort the keys and get the elements.          # Sort the keys and get the elements.
2675          my @retVal = ();          my @retVal = ();
# Line 2284  Line 2680 
2680          return @retVal;          return @retVal;
2681  }  }
2682    
 =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 = shift @_;  
         my ($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 = shift @_;  
         my ($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;  
 }  
   
2683  =head3 Protein  =head3 Protein
2684    
2685  C<< my $protein = Sprout::Protein($sequence, $table); >>  C<< my $protein = Sprout::Protein($sequence, $table); >>
# Line 2515  Line 2777 
2777  #: Return Type @;  #: Return Type @;
2778  sub LoadInfo {  sub LoadInfo {
2779          # Get the parameters.          # Get the parameters.
2780          my $self = shift @_;      my ($self) = @_;
2781          # 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.
2782          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
2783          # Concatenate the table names.          # Concatenate the table names.
2784          push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
2785          # Return the result.          # Return the result.
2786          return @retVal;          return @retVal;
2787  }  }
2788    
2789  =head3 LowBBHs  =head3 LowBBHs
2790    
2791  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
2792    
2793  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
2794  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 2552  Line 2814 
2814  #: Return Type %;  #: Return Type %;
2815  sub LowBBHs {  sub LowBBHs {
2816          # Get the parsameters.          # Get the parsameters.
2817          my $self = shift @_;      my ($self, $featureID, $cutoff) = @_;
         my ($featureID, $cutoff) = @_;  
2818          # Create the return hash.          # Create the return hash.
2819          my %retVal = ();          my %retVal = ();
2820          # Create a query to get the desired BBHs.          # Create a query to get the desired BBHs.
# Line 2582  Line 2843 
2843  #: Return Type %@;  #: Return Type %@;
2844  sub GetGroups {  sub GetGroups {
2845      # Get the parameters.      # Get the parameters.
2846      my $self = shift @_;      my ($self, $groupList) = @_;
     my ($groupList) = @_;  
2847      # Declare the return value.      # Declare the return value.
2848      my %retVal = ();      my %retVal = ();
2849      # Determine whether we are getting all the groups or just some.      # Determine whether we are getting all the groups or just some.
# Line 2610  Line 2870 
2870              # Loop through the groups, adding the genome ID to each group's              # Loop through the groups, adding the genome ID to each group's
2871              # list.              # list.
2872              for my $group (@groups) {              for my $group (@groups) {
2873                  if (exists $retVal{$group}) {                  Tracer::AddToListMap(\%retVal, $group, $genomeID);
                     push @{$retVal{$group}}, $genomeID;  
                 } else {  
                     $retVal{$group} = [$genomeID];  
                 }  
2874              }              }
2875          }          }
2876      }      }
# Line 2622  Line 2878 
2878      return %retVal;      return %retVal;
2879  }  }
2880    
2881    =head3 MyGenomes
2882    
2883    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
2884    
2885    Return a list of the genomes to be included in the Sprout.
2886    
2887    This method is provided for use during the Sprout load. It presumes the Genome load file has
2888    already been created. (It will be in the Sprout data directory and called either C<Genome>
2889    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
2890    IDs.
2891    
2892    =over 4
2893    
2894    =item dataDir
2895    
2896    Directory containing the Sprout load files.
2897    
2898    =back
2899    
2900    =cut
2901    #: Return Type @;
2902    sub MyGenomes {
2903        # Get the parameters.
2904        my ($dataDir) = @_;
2905        # Compute the genome file name.
2906        my $genomeFileName = LoadFileName($dataDir, "Genome");
2907        # Extract the genome IDs from the files.
2908        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
2909        # Return the result.
2910        return @retVal;
2911    }
2912    
2913    =head3 LoadFileName
2914    
2915    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
2916    
2917    Return the name of the load file for the specified table in the specified data
2918    directory.
2919    
2920    =over 4
2921    
2922    =item dataDir
2923    
2924    Directory containing the Sprout load files.
2925    
2926    =item tableName
2927    
2928    Name of the table whose load file is desired.
2929    
2930    =item RETURN
2931    
2932    Returns the name of the file containing the load data for the specified table, or
2933    C<undef> if no load file is present.
2934    
2935    =back
2936    
2937    =cut
2938    #: Return Type $;
2939    sub LoadFileName {
2940        # Get the parameters.
2941        my ($dataDir, $tableName) = @_;
2942        # Declare the return variable.
2943        my $retVal;
2944        # Check for the various file names.
2945        if (-e "$dataDir/$tableName") {
2946            $retVal = "$dataDir/$tableName";
2947        } elsif (-e "$dataDir/$tableName.dtx") {
2948            $retVal = "$dataDir/$tableName.dtx";
2949        }
2950        # Return the result.
2951        return $retVal;
2952    }
2953    
2954    =head3 DeleteGenome
2955    
2956    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
2957    
2958    Delete a genome from the database.
2959    
2960    =over 4
2961    
2962    =item genomeID
2963    
2964    ID of the genome to delete
2965    
2966    =item testFlag
2967    
2968    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
2969    
2970    =item RETURN
2971    
2972    Returns a statistics object describing the rows deleted.
2973    
2974    =back
2975    
2976    =cut
2977    #: Return Type $%;
2978    sub DeleteGenome {
2979        # Get the parameters.
2980        my ($self, $genomeID, $testFlag) = @_;
2981        # Perform the delete for the genome's features.
2982        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);
2983        # Perform the delete for the primary genome data.
2984        my $stats = $self->Delete('Genome', $genomeID, $testFlag);
2985        $retVal->Accumulate($stats);
2986        # Return the result.
2987        return $retVal;
2988    }
2989    
2990  =head2 Internal Utility Methods  =head2 Internal Utility Methods
2991    
2992  =head3 ParseAssignment  =head3 ParseAssignment
2993    
2994  Parse annotation text to determine whether or not it is a functional assignment. If it is,  Parse annotation text to determine whether or not it is a functional assignment. If it is,
2995  the user and function text will be returned as a 2-element list. If it isn't, an empty list  the user, function text, and assigning user will be returned as a 3-element list. If it
2996  will be returned.  isn't, an empty list will be returned.
2997    
2998    A functional assignment is always of the form
2999    
3000        C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3001    
3002    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3003    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3004    not always the case.
3005    
3006    In addition, the functional role may contain extra data that is stripped, such as
3007    terminating spaces or a comment separated from the rest of the text by a tab.
3008    
3009  This is a static method.  This is a static method.
3010    
3011  =over 4  =over 4
3012    
3013    =item user
3014    
3015    Name of the assigning user.
3016    
3017  =item text  =item text
3018    
3019  Text of the annotation.  Text of the annotation.
# Line 2647  Line 3027 
3027    
3028  =cut  =cut
3029    
3030  sub ParseAssignment {  sub _ParseAssignment {
3031          # Get the parameters.          # Get the parameters.
3032          my ($text) = @_;      my ($user, $text) = @_;
3033          # Declare the return value.          # Declare the return value.
3034          my @retVal = ();          my @retVal = ();
3035          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3036          my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3037          if ($type =~ m/^set $user function to$/i) {      if ($type =~ m/^set function to$/i) {
3038                  # Here it is, so we return the user name and function text.          # Here we have an assignment without a user, so we use the incoming user ID.
3039                  @retVal = ($user, $function);                  @retVal = ($user, $function);
3040        } elsif ($type =~ m/^set (\S+) function to$/i) {
3041            # Here we have an assignment with a user that is passed back to the caller.
3042            @retVal = ($1, $function);
3043        }
3044        # If we have an assignment, we need to clean the function text. There may be
3045        # extra junk at the end added as a note from the user.
3046        if (@retVal) {
3047            $retVal[1] =~ s/(\t\S)?\s*$//;
3048          }          }
3049          # Return the result list.          # Return the result list.
3050          return @retVal;          return @retVal;
# Line 2684  Line 3072 
3072    
3073  sub FriendlyTimestamp {  sub FriendlyTimestamp {
3074      my ($timeValue) = @_;      my ($timeValue) = @_;
3075      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
3076      return $retVal;      return $retVal;
3077  }  }
3078    
3079    =head3 AddProperty
3080    
3081    C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>
3082    
3083    Add a new attribute value (Property) to a feature. In the SEED system, attributes can
3084    be added to almost any object. In Sprout, they can only be added to features. In
3085    Sprout, attributes are implemented using I<properties>. A property represents a key/value
3086    pair. If the particular key/value pair coming in is not already in the database, a new
3087    B<Property> record is created to hold it.
3088    
3089    =over 4
3090    
3091    =item peg
3092    
3093    ID of the feature to which the attribute is to be replied.
3094    
3095    =item key
3096    
3097    Name of the attribute (key).
3098    
3099    =item value
3100    
3101    Value of the attribute.
3102    
3103    =item url
3104    
3105    URL or text citation from which the property was obtained.
3106    
3107    =back
3108    
3109    =cut
3110    #: Return Type ;
3111    sub AddProperty {
3112        # Get the parameters.
3113        my ($self, $featureID, $key, $value, $url) = @_;
3114        # Declare the variable to hold the desired property ID.
3115        my $propID;
3116        # Attempt to find a property record for this key/value pair.
3117        my @properties = $self->GetFlat(['Property'],
3118                                       "Property(property-name) = ? AND Property(property-value) = ?",
3119                                       [$key, $value], 'Property(id)');
3120        if (@properties) {
3121            # Here the property is already in the database. We save its ID.
3122            $propID = $properties[0];
3123            # Here the property value does not exist. We need to generate an ID. It will be set
3124            # to a number one greater than the maximum value in the database. This call to
3125            # GetAll will stop after one record.
3126            my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],
3127                                            1);
3128            $propID = $maxProperty[0]->[0] + 1;
3129            # Insert the new property value.
3130            $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });
3131        }
3132        # Now we connect the incoming feature to the property.
3133        $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3134    }
3135    
3136    
3137  1;  1;

Legend:
Removed from v.1.9  
changed lines
  Added in v.1.58

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3