[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.2, Sun Jan 23 22:31:29 2005 UTC revision 1.29, Wed Sep 14 13:06:53 2005 UTC
# Line 11  Line 11 
11          use Tracer;          use Tracer;
12          use FIGRules;          use FIGRules;
13          use Stats;          use Stats;
14        use POSIX qw(strftime);
15    
16    
17  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
# Line 33  Line 34 
34    
35  =cut  =cut
36    
37  #  #: Constructor SFXlate->new_sprout_only();
38    
39  =head2 Public Methods  =head2 Public Methods
40    
# Line 69  Line 70 
70    
71  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
72    
73    * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
74    
75  =back  =back
76    
77  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 85  Line 88 
88          # 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
89          # the incoming data.          # the incoming data.
90          my $optionTable = Tracer::GetOptions({          my $optionTable = Tracer::GetOptions({
91                                             dbType               => 'mysql',                     # database type                         dbType       => $FIG_Config::dbms,
92                                             dataDir              => 'Data',                      # data file directory                                                          # database type
93                                             xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
94                                             userData             => 'root/',                     # user name and password                                                          # data file directory
95                                             port                 => 0,                           # database connection port                         xmlFileName  => "$FIG_Config::sproutData/SproutDBD.xml",
96                                                            # database definition file name
97                           userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
98                                                            # user name and password
99                           port         => $FIG_Config::dbport,
100                                                            # database connection port
101                                             maxSegmentLength => 4500,            # maximum feature segment length                                             maxSegmentLength => 4500,            # maximum feature segment length
102                                             maxSequenceLength => 8000,           # maximum contig sequence length                                             maxSequenceLength => 8000,           # maximum contig sequence length
103                           noDBOpen     => 0,               # 1 to suppress the database open
104                                            }, $options);                                            }, $options);
105          # Get the data directory.          # Get the data directory.
106          my $dataDir = $optionTable->{dataDir};          my $dataDir = $optionTable->{dataDir};
# Line 99  Line 108 
108          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
109          my ($userName, $password) = ($1, $2);          my ($userName, $password) = ($1, $2);
110          # Connect to the database.          # Connect to the database.
111          my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
112        if (! $optionTable->{noDBOpen}) {
113            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
114                                    $password, $optionTable->{port});
115        }
116          # Create the ERDB object.          # Create the ERDB object.
117          my $xmlFileName = "$optionTable->{xmlFileName}";          my $xmlFileName = "$optionTable->{xmlFileName}";
118          my $erdb = ERDB->new($dbh, $xmlFileName);          my $erdb = ERDB->new($dbh, $xmlFileName);
# Line 121  Line 134 
134  and 10999.  and 10999.
135    
136  =cut  =cut
137    #: Return Type $;
138  sub MaxSegment {  sub MaxSegment {
139          my $self = shift @_;      my ($self) = @_;
140          return $self->{_options}->{maxSegmentLength};          return $self->{_options}->{maxSegmentLength};
141  }  }
142    
# Line 136  Line 149 
149  we generally only need a few sequences in memory rather than the entire contig.  we generally only need a few sequences in memory rather than the entire contig.
150    
151  =cut  =cut
152    #: Return Type $;
153  sub MaxSequence {  sub MaxSequence {
154          my $self = shift @_;      my ($self) = @_;
155          return $self->{_options}->{maxSequenceLength};          return $self->{_options}->{maxSequenceLength};
156  }  }
157    
# Line 231  Line 244 
244    
245  sub Get {  sub Get {
246          # Get the parameters.          # Get the parameters.
247          my $self = shift @_;      my ($self, $objectNames, $filterClause, $parameterList) = @_;
         my ($objectNames, $filterClause, $parameterList) = @_;  
248          # We differ from the ERDB Get method in that the parameter list is passed in as a list reference          # We differ from the ERDB Get method in that the parameter list is passed in as a list reference
249          # rather than a list of parameters. The next step is to convert the parameters from a reference          # rather than a list of parameters. The next step is to convert the parameters from a reference
250          # to a real list. We can only do this if the parameters have been specified.          # to a real list. We can only do this if the parameters have been specified.
# Line 268  Line 280 
280    
281  sub GetEntity {  sub GetEntity {
282          # Get the parameters.          # Get the parameters.
283          my $self = shift @_;      my ($self, $entityType, $ID) = @_;
284          my ($entityType, $ID) = @_;      # Call the ERDB method.
285          # Create a query.      return $self->{_erdb}->GetEntity($entityType, $ID);
         my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);  
         # Get the first (and only) object.  
         my $retVal = $query->Fetch();  
         # Return the result.  
         return $retVal;  
286  }  }
287    
288  =head3 GetEntityValues  =head3 GetEntityValues
# Line 305  Line 312 
312  =back  =back
313    
314  =cut  =cut
315    #: Return Type @;
316  sub GetEntityValues {  sub GetEntityValues {
317          # Get the parameters.          # Get the parameters.
318          my $self = shift @_;      my ($self, $entityType, $ID, $fields) = @_;
319          my ($entityType, $ID, $fields) = @_;      # Call the ERDB method.
320          # Get the specified entity.      return $self->{_erdb}->GetEntityValues($entityType, $ID, $fields);
         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;  
321  }  }
322    
323  =head3 ShowMetaData  =head3 ShowMetaData
# Line 340  Line 338 
338    
339  sub ShowMetaData {  sub ShowMetaData {
340          # Get the parameters.          # Get the parameters.
341          my $self = shift @_;      my ($self, $fileName) = @_;
         my ($fileName) = @_;  
342          # Compute the file name.          # Compute the file name.
343          my $options = $self->{_options};          my $options = $self->{_options};
344          # Call the show method on the underlying ERDB object.          # Call the show method on the underlying ERDB object.
# Line 378  Line 375 
375  =back  =back
376    
377  =cut  =cut
378    #: Return Type %;
379  sub Load {  sub Load {
380          # Get the parameters.          # Get the parameters.
381          my $self = shift @_;      my ($self, $rebuild) = @_;
         my ($rebuild) = @_;  
382          # Get the database object.          # Get the database object.
383          my $erdb = $self->{_erdb};          my $erdb = $self->{_erdb};
384          # Load the tables from the data directory.          # Load the tables from the data directory.
# Line 422  Line 418 
418  =back  =back
419    
420  =cut  =cut
421    #: Return Type $%;
422  sub LoadUpdate {  sub LoadUpdate {
423          # Get the parameters.          # Get the parameters.
424          my $self = shift @_;      my ($self, $truncateFlag, $tableList) = @_;
         my ($truncateFlag, $tableList) = @_;  
425          # Get the database object.          # Get the database object.
426          my $erdb = $self->{_erdb};          my $erdb = $self->{_erdb};
427          # Declare the return value.          # Declare the return value.
# Line 437  Line 432 
432          # Loop through the incoming table names.          # Loop through the incoming table names.
433          for my $tableName (@{$tableList}) {          for my $tableName (@{$tableList}) {
434                  # Find the table's file.                  # Find the table's file.
435                  my $fileName = "$dataDir/$tableName";          my $fileName = LoadFileName($dataDir, $tableName);
436                  if (! -e $fileName) {          if (! $fileName) {
437                          $fileName = "$fileName.dtx";              Trace("No load file found for $tableName in $dataDir.") if T(0);
438                  }          } else {
439                  # Attempt to load this table.                  # Attempt to load this table.
440                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);
441                  # Accumulate the resulting statistics.                  # Accumulate the resulting statistics.
442                  $retVal->Accumulate($result);                  $retVal->Accumulate($result);
443          }          }
444        }
445          # Return the statistics.          # Return the statistics.
446          return $retVal;          return $retVal;
447  }  }
# Line 459  Line 455 
455  changed.  changed.
456    
457  =cut  =cut
458    #: Return Type ;
459  sub Build {  sub Build {
460          # Get the parameters.          # Get the parameters.
461          my $self = shift @_;      my ($self) = @_;
462          # Create the tables.          # Create the tables.
463          $self->{_erdb}->CreateTables;          $self->{_erdb}->CreateTables;
464  }  }
# Line 474  Line 470 
470  Return a list of all the genome IDs.  Return a list of all the genome IDs.
471    
472  =cut  =cut
473    #: Return Type @;
474  sub Genomes {  sub Genomes {
475          # Get the parameters.          # Get the parameters.
476          my $self = shift @_;      my ($self) = @_;
477          # Get all the genomes.          # Get all the genomes.
478          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');
479          # Return the list of IDs.          # Return the list of IDs.
# Line 504  Line 500 
500  =back  =back
501    
502  =cut  =cut
503    #: Return Type $;
504  sub GenusSpecies {  sub GenusSpecies {
505          # Get the parameters.          # Get the parameters.
506          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
507          # Get the data for the specified genome.          # Get the data for the specified genome.
508          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',
509                                                                                                                            'Genome(unique-characterization)']);                                                                                                                            'Genome(unique-characterization)']);
# Line 541  Line 536 
536  =back  =back
537    
538  =cut  =cut
539    #: Return Type @;
540  sub FeaturesOf {  sub FeaturesOf {
541          # Get the parameters.          # Get the parameters.
542          my $self = shift @_;      my ($self, $genomeID,$ftype) = @_;
         my ($genomeID,$ftype) = @_;  
543          # Get the features we want.          # Get the features we want.
544          my @features;          my @features;
545          if (!$ftype) {          if (!$ftype) {
# Line 589  Line 583 
583  =item RETURN  =item RETURN
584    
585  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
586  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context.
587    
588  =back  =back
589    
590  =cut  =cut
591    #: Return Type @;
592    #: Return Type $;
593  sub FeatureLocation {  sub FeatureLocation {
594          # Get the parameters.          # Get the parameters.
595          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
596          # Create a query for the feature locations.          # Create a query for the feature locations.
597          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",
598                                                     [$featureID]);                                                     [$featureID]);
# Line 632  Line 626 
626                  push @retVal, "${contigID}_$beg$dir$len";                  push @retVal, "${contigID}_$beg$dir$len";
627          }          }
628          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
629          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
630  }  }
631    
632  =head3 ParseLocation  =head3 ParseLocation
# Line 656  Line 650 
650  =back  =back
651    
652  =cut  =cut
653    #: Return Type @;
654  sub ParseLocation {  sub ParseLocation {
655          # Get the parameter.      # Get the parameter. Note that if we're called as an instance method, we ignore
656        # the first parameter.
657        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
658          my ($location) = @_;          my ($location) = @_;
659          # Parse it into segments.          # Parse it into segments.
660          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;
# Line 677  Line 673 
673          return ($contigID, $start, $dir, $len);          return ($contigID, $start, $dir, $len);
674  }  }
675    
676    =head3 PointLocation
677    
678    C<< my $found = Sprout::PointLocation($location, $point); >>
679    
680    Return the offset into the specified location of the specified point on the contig. If
681    the specified point is before the location, a negative value will be returned. If it is
682    beyond the location, an undefined value will be returned. It is assumed that the offset
683    is for the location's contig. The location can either be new-style (using a C<+> or C<->
684    and a length) or old-style (using C<_> and start and end positions.
685    
686    =over 4
687    
688    =item location
689    
690    A location specifier (see L</FeatureLocation> for a description).
691    
692    =item point
693    
694    The offset into the contig of the point in which we're interested.
695    
696    =item RETURN
697    
698    Returns the offset inside the specified location of the specified point, a negative
699    number if the point is before the location, or an undefined value if the point is past
700    the location. If the length of the location is 0, this method will B<always> denote
701    that it is outside the location. The offset will always be relative to the left-most
702    position in the location.
703    
704    =back
705    
706    =cut
707    #: Return Type $;
708    sub PointLocation {
709        # Get the parameter. Note that if we're called as an instance method, we ignore
710        # the first parameter.
711        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
712        my ($location, $point) = @_;
713        # Parse out the location elements. Note that this works on both old-style and new-style
714        # locations.
715        my ($contigID, $start, $dir, $len) = ParseLocation($location);
716        # Declare the return variable.
717        my $retVal;
718        # Compute the offset. The computation is dependent on the direction of the location.
719        my $offset = (($dir == '+') ? $point - $start : $point - ($start - $len + 1));
720        # Return the offset if it's valid.
721        if ($offset < $len) {
722            $retVal = $offset;
723        }
724        # Return the offset found.
725        return $retVal;
726    }
727    
728  =head3 DNASeq  =head3 DNASeq
729    
730  C<< my $sequence = $sprout->DNASeq(\@locationList); >>  C<< my $sequence = $sprout->DNASeq(\@locationList); >>
# Line 699  Line 747 
747  =back  =back
748    
749  =cut  =cut
750    #: Return Type $;
751  sub DNASeq {  sub DNASeq {
752          # Get the parameters.          # Get the parameters.
753          my $self = shift @_;      my ($self, $locationList) = @_;
         my ($locationList) = @_;  
754          # Create the return string.          # Create the return string.
755          my $retVal = "";          my $retVal = "";
756          # Loop through the locations.          # Loop through the locations.
# Line 722  Line 769 
769                          $start = $beg;                          $start = $beg;
770                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
771                  } else {                  } else {
772                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
773                          $stop = $beg;                          $stop = $beg;
774                  }                  }
775            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
776                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
777                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
778                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 736  Line 784 
784                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
785                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
786                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
787                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
788                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
789                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
790                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;
791                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
792                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
793                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
794                  }                  }
795                  # 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.
796                  if ($dir eq '+') {                  if ($dir eq '+') {
797                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
798                  } else {                  } else {
799                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
800                  }                  }
801          }          }
802          # Return the result.          # Return the result.
# Line 773  Line 822 
822  =back  =back
823    
824  =cut  =cut
825    #: Return Type @;
826  sub AllContigs {  sub AllContigs {
827          # Get the parameters.          # Get the parameters.
828          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
829          # Ask for the genome's Contigs.          # Ask for the genome's Contigs.
830          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],
831                                                                  'HasContig(to-link)');                                                                  'HasContig(to-link)');
# Line 797  Line 845 
845    
846  ID of the contig whose length is desired.  ID of the contig whose length is desired.
847    
848    =item RETURN
849    
850    Returns the number of positions in the contig.
851    
852  =back  =back
853    
854  =cut  =cut
855    #: Return Type $;
856  sub ContigLength {  sub ContigLength {
857          # Get the parameters.          # Get the parameters.
858          my $self = shift @_;      my ($self, $contigID) = @_;
         my ($contigID) = @_;  
859          # Get the contig's last sequence.          # Get the contig's last sequence.
860          my $query = $self->Get(['IsMadeUpOf'],          my $query = $self->Get(['IsMadeUpOf'],
861                  "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",                  "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
# Line 846  Line 897 
897  Returns a three-element list. The first element is a list of feature IDs for the features that  Returns a three-element list. The first element is a list of feature IDs for the features that
898  overlap the region of interest. The second and third elements are the minimum and maximum  overlap the region of interest. The second and third elements are the minimum and maximum
899  locations of the features provided on the specified contig. These may extend outside  locations of the features provided on the specified contig. These may extend outside
900  the start and stop values.  the start and stop values. The first element (that is, the list of features) is sorted
901    roughly by location.
902    
903  =back  =back
904    
905  =cut  =cut
906    #: Return Type @@;
907  sub GenesInRegion {  sub GenesInRegion {
908          # Get the parameters.          # Get the parameters.
909          my $self = shift @_;      my ($self, $contigID, $start, $stop) = @_;
         my ($contigID, $start, $stop) = @_;  
910          # Get the maximum segment length.          # Get the maximum segment length.
911          my $maximumSegmentLength = $self->MaxSegment;          my $maximumSegmentLength = $self->MaxSegment;
912          # 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
913          # duplicates easily.      # duplicates easily. The hash key will be the feature ID. The value will be a two-element
914        # containing the minimum and maximum offsets. We will use the offsets to sort the results
915        # when we're building the result set.
916          my %featuresFound = ();          my %featuresFound = ();
917          # Prime the values we'll use for the returned beginning and end.          # Prime the values we'll use for the returned beginning and end.
918          my ($min, $max) = ($self->ContigLength($contigID), 0);      my @initialMinMax = ($self->ContigLength($contigID), 0);
919        my ($min, $max) = @initialMinMax;
920          # Create a table of parameters for each query. Each query looks for features travelling in          # Create a table of parameters for each query. Each query looks for features travelling in
921          # a particular direction. The query parameters include the contig ID, the feature direction,          # a particular direction. The query parameters include the contig ID, the feature direction,
922          # the lowest possible start position, and the highest possible start position. This works          # the lowest possible start position, and the highest possible start position. This works
# Line 892  Line 946 
946                                          $found = 1;                                          $found = 1;
947                                  }                                  }
948                          } elsif ($dir eq '-') {                          } elsif ($dir eq '-') {
949                                  $end = $beg - $len;                  # Note we switch things around so that the beginning is to the left of the
950                                  if ($end <= $stop) {                  # ending.
951                    ($beg, $end) = ($beg - $len, $beg);
952                    if ($beg <= $stop) {
953                                          # Denote we found a useful feature.                                          # Denote we found a useful feature.
954                                          $found = 1;                                          $found = 1;
955                                  }                                  }
956                          }                          }
957                          if ($found) {                          if ($found) {
958                                  # Here we need to record the feature and update the minimum and maximum.                  # Here we need to record the feature and update the minima and maxima. First,
959                                  $featuresFound{$featureID} = 1;                  # get the current entry for the specified feature.
960                                  if ($beg < $min) { $min = $beg; }                  my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :
961                                  if ($end < $min) { $min = $end; }                                       @initialMinMax);
962                                  if ($beg > $max) { $max = $beg; }                  # Merge the current segment's begin and end into the feature begin and end and the
963                                  if ($end > $max) { $max = $end; }                  # global min and max.
964                    if ($beg < $loc1) {
965                        $loc1 = $beg;
966                        $min = $beg if $beg < $min;
967                    }
968                    if ($end > $loc2) {
969                        $loc2 = $end;
970                        $max = $end if $end > $max;
971                    }
972                    # Store the entry back into the hash table.
973                    $featuresFound{$featureID} = [$loc1, $loc2];
974                          }                          }
975                  }                  }
976          }          }
977          # Compute a list of the IDs for the features found.      # Now we must compute the list of the IDs for the features found. We start with a list
978          my @list = (sort (keys %featuresFound));      # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
979        # but the result of the sort will be the same.)
980        my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;
981        # Now we sort by midpoint and yank out the feature IDs.
982        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
983          # Return it along with the min and max.          # Return it along with the min and max.
984          return (\@list, $min, $max);      return (\@retVal, $min, $max);
985  }  }
986    
987  =head3 FType  =head3 FType
# Line 934  Line 1004 
1004  =back  =back
1005    
1006  =cut  =cut
1007    #: Return Type $;
1008  sub FType {  sub FType {
1009          # Get the parameters.          # Get the parameters.
1010          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1011          # Get the specified feature's type.          # Get the specified feature's type.
1012          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
1013          # Return the result.          # Return the result.
# Line 963  Line 1032 
1032    
1033  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1034    
1035  * B<timeStamp> time the annotation was made.  * B<timeStamp> time the annotation was made, in user-friendly format.
1036    
1037  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1038    
# Line 972  Line 1041 
1041  =back  =back
1042    
1043  =cut  =cut
1044    #: Return Type @%;
1045  sub FeatureAnnotations {  sub FeatureAnnotations {
1046          # Get the parameters.          # Get the parameters.
1047          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1048          # 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.
1049          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1050                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 990  Line 1058 
1058                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1059                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1060                  # Assemble them into a hash.                  # Assemble them into a hash.
1061                  my $annotationHash = { featureID => $featureID, timeStamp => $timeStamp,          my $annotationHash = { featureID => $featureID,
1062                                   timeStamp => FriendlyTimestamp($timeStamp),
1063                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1064                  # Add it to the return list.                  # Add it to the return list.
1065                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1004  Line 1073 
1073  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>
1074    
1075  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
1076  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,
1077  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
1078  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,
1079  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.
1080  features only have a small number of annotations.  Finally, if a single user has multiple functional assignments, we will only keep the most
1081    recent one.
1082    
1083  =over 4  =over 4
1084    
# Line 1016  Line 1086 
1086    
1087  ID of the feature whose functional assignments are desired.  ID of the feature whose functional assignments are desired.
1088    
1089    =item RETURN
1090    
1091    Returns a hash mapping the functional assignment IDs to user IDs.
1092    
1093  =back  =back
1094    
1095  =cut  =cut
1096    #: Return Type %;
1097  sub AllFunctionsOf {  sub AllFunctionsOf {
1098          # Get the parameters.          # Get the parameters.
1099          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1100          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1101          my @query = $self->GetFlat(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],
1102                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1103                                                          [$featureID], 'Annotation(annotation)');                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);
1104          # Declare the return hash.          # Declare the return hash.
1105          my %retVal;          my %retVal;
1106        # Declare a hash for insuring we only make one assignment per user.
1107        my %timeHash = ();
1108        # Now we sort the assignments by timestamp in reverse.
1109        my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1110          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1111          for my $text (@query) {      for my $annotation (@sortedQuery) {
1112            # Get the annotation fields.
1113            my ($timeStamp, $text) = @{$annotation};
1114                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1115                  my ($user, $function) = ParseAssignment($text);          my ($user, $function) = _ParseAssignment($text);
1116                  if ($user) {          if ($user && ! exists $timeHash{$user}) {
1117                          # Here it is, so stuff it in the return hash.              # Here it is a functional assignment and there has been no
1118                # previous assignment for this user, so we stuff it in the
1119                # return hash.
1120                          $retVal{$function} = $user;                          $retVal{$function} = $user;
1121                # Insure we don't assign to this user again.
1122                $timeHash{$user} = 1;
1123                  }                  }
1124          }          }
1125          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1047  Line 1130 
1130    
1131  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>
1132    
1133  Return the most recently-determined functional assignment of a particular feature. A functional  Return the most recently-determined functional assignment of a particular feature.
1134  assignment is a type of annotation. It has the format "XXXX\nset XXXX function to\nYYYYY". In this  
1135  instance, XXXX is the user ID and YYYYY is the functional assignment text. Its worth noting that  The functional assignment is handled differently depending on the type of feature. If
1136  we cannot filter on the content of the annotation itself because it's a text field; however, this  the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1137  is not a big problem because most features only have a small number of annotations.  assignment is a type of annotation. The format of an assignment is described in
1138    L</ParseLocation>. Its worth noting that we cannot filter on the content of the
1139    annotation itself because it's a text field; however, this is not a big problem because
1140    most features only have a small number of annotations.
1141    
1142    Each user has an associated list of trusted users. The assignment returned will be the most
1143    recent one by at least one of the trusted users. If no trusted user list is available, then
1144    the specified user and FIG are considered trusted. If the user ID is omitted, only FIG
1145    is trusted.
1146    
1147    If the feature is B<not> identified by a FIG ID, then the functional assignment
1148    information is taken from the B<ExternalAliasFunc> table. If the table does
1149    not contain an entry for the feature, an undefined value is returned.
1150    
1151  =over 4  =over 4
1152    
# Line 1061  Line 1156 
1156    
1157  =item userID (optional)  =item userID (optional)
1158    
1159  ID of the user whose function determination is desired. If omitted, C<FIG> is assumed.  ID of the user whose function determination is desired. If omitted, only the latest
1160    C<FIG> assignment will be returned.
1161    
1162  =item RETURN  =item RETURN
1163    
# Line 1070  Line 1166 
1166  =back  =back
1167    
1168  =cut  =cut
1169    #: Return Type $;
1170  sub FunctionOf {  sub FunctionOf {
1171          # Get the parameters.          # Get the parameters.
1172          my $self = shift @_;      my ($self, $featureID, $userID) = @_;
1173          my ($featureID, $userID) = @_;      # Declare the return value.
         if (!$userID) { $userID = 'FIG'; }  
         # Build a query for all of the feature's annotation, sorted by date.  
         my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],  
                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);  
         # Declare the return value. We'll set this to the most recent annotation for the  
         # specified user.  
1174          my $retVal;          my $retVal;
1175        # Determine the ID type.
1176        if ($featureID =~ m/^fig\|/) {
1177            # Here we have a FIG feature ID. We must build the list of trusted
1178            # users.
1179            my %trusteeTable = ();
1180            # Check the user ID.
1181            if (!$userID) {
1182                # No user ID, so only FIG is trusted.
1183                $trusteeTable{FIG} = 1;
1184            } else {
1185                # Add this user's ID.
1186                $trusteeTable{$userID} = 1;
1187                # Look for the trusted users in the database.
1188                my @trustees = $self->GetFlat(['IsTrustedBy'], 'IsTrustedBy(from-link) = ?', [$userID], 'IsTrustedBy(to-link)');
1189                if (! @trustees) {
1190                    # None were found, so build a default list.
1191                    $trusteeTable{FIG} = 1;
1192                } else {
1193                    # Otherwise, put all the trustees in.
1194                    for my $trustee (@trustees) {
1195                        $trusteeTable{$trustee} = 1;
1196                    }
1197                }
1198            }
1199            # Build a query for all of the feature's annotations, sorted by date.
1200            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],
1201                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1202                                   [$featureID]);
1203          my $timeSelected = 0;          my $timeSelected = 0;
1204          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1205          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1206                  # Get the annotation text.                  # Get the annotation text.
1207                  my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);                  my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);
1208                  # Check to see if this is a functional assignment for the desired user.              # Check to see if this is a functional assignment for a trusted user.
1209                  my ($user, $type, $function) = split(/\n/, $text);              my ($user, $function) = _ParseAssignment($text);
1210                  if ($type =~ m/^set $userID function to$/i) {              if ($user) {
1211                          # Here it is, so we check the time and save the assignment value.                  # Here it is a functional assignment. Check the time and the user
1212                          if ($time > $timeSelected) {                  # name. The time must be recent and the user must be trusted.
1213                    if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {
1214                                  $retVal = $function;                                  $retVal = $function;
1215                                  $timeSelected = $time;                                  $timeSelected = $time;
1216                          }                          }
1217                  }                  }
1218          }          }
1219        } else {
1220            # Here we have a non-FIG feature ID. In this case the user ID does not
1221            # matter. We simply get the information from the External Alias Function
1222            # table.
1223            ($retVal) = $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']);
1224        }
1225          # Return the assignment found.          # Return the assignment found.
1226          return $retVal;          return $retVal;
1227  }  }
# Line 1120  Line 1245 
1245    
1246  =item RETURN  =item RETURN
1247    
1248  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
1249  their best hits.  on the target genome.
1250    
1251  =back  =back
1252    
1253  =cut  =cut
1254    #: Return Type %;
1255  sub BBHList {  sub BBHList {
1256          # Get the parameters.          # Get the parameters.
1257          my $self = shift @_;      my ($self, $genomeID, $featureList) = @_;
         my ($genomeID, $featureList) = @_;  
1258          # Create the return structure.          # Create the return structure.
1259          my %retVal = ();          my %retVal = ();
1260          # Loop through the incoming features.          # Loop through the incoming features.
# Line 1150  Line 1274 
1274          return \%retVal;          return \%retVal;
1275  }  }
1276    
1277    =head3 SimList
1278    
1279    C<< my %similarities = $sprout->SimList($featureID, $count); >>
1280    
1281    Return a list of the similarities to the specified feature.
1282    
1283    Sprout does not support real similarities, so this method just returns the bidirectional
1284    best hits.
1285    
1286    =over 4
1287    
1288    =item featureID
1289    
1290    ID of the feature whose similarities are desired.
1291    
1292    =item count
1293    
1294    Maximum number of similar features to be returned, or C<0> to return them all.
1295    
1296    =back
1297    
1298    =cut
1299    #: Return Type %;
1300    sub SimList {
1301        # Get the parameters.
1302        my ($self, $featureID, $count) = @_;
1303        # Ask for the best hits.
1304        my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],
1305                                  "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",
1306                                  [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],
1307                                  $count);
1308        # Create the return value.
1309        my %retVal = ();
1310        for my $tuple (@lists) {
1311            $retVal{$tuple->[0]} = $tuple->[1];
1312        }
1313        # Return the result.
1314        return %retVal;
1315    }
1316    
1317    
1318    
1319    =head3 IsComplete
1320    
1321    C<< my $flag = $sprout->IsComplete($genomeID); >>
1322    
1323    Return TRUE if the specified genome is complete, else FALSE.
1324    
1325    =over 4
1326    
1327    =item genomeID
1328    
1329    ID of the genome whose completeness status is desired.
1330    
1331    =item RETURN
1332    
1333    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1334    not found.
1335    
1336    =back
1337    
1338    =cut
1339    #: Return Type $;
1340    sub IsComplete {
1341        # Get the parameters.
1342        my ($self, $genomeID) = @_;
1343        # Declare the return variable.
1344        my $retVal;
1345        # Get the genome's data.
1346        my $genomeData = $self->GetEntity('Genome', $genomeID);
1347        if ($genomeData) {
1348            # The genome exists, so get the completeness flag.
1349            ($retVal) = $genomeData->Value('complete');
1350        }
1351        # Return the result.
1352        return $retVal;
1353    }
1354    
1355  =head3 FeatureAliases  =head3 FeatureAliases
1356    
1357  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
# Line 1170  Line 1372 
1372  =back  =back
1373    
1374  =cut  =cut
1375    #: Return Type @;
1376  sub FeatureAliases {  sub FeatureAliases {
1377          # Get the parameters.          # Get the parameters.
1378          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1379          # Get the desired feature's aliases          # Get the desired feature's aliases
1380          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);
1381          # Return the result.          # Return the result.
# Line 1201  Line 1402 
1402  =back  =back
1403    
1404  =cut  =cut
1405    #: Return Type $;
1406  sub GenomeOf {  sub GenomeOf {
1407          # Get the parameters.          # Get the parameters.
1408          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1409          # Create a query to find the genome associated with the feature.          # Create a query to find the genome associated with the feature.
1410          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);
1411          # Declare the return value.          # Declare the return value.
# Line 1238  Line 1438 
1438  =back  =back
1439    
1440  =cut  =cut
1441    #: Return Type %;
1442  sub CoupledFeatures {  sub CoupledFeatures {
1443          # Get the parameters.          # Get the parameters.
1444          my $self = shift @_;      my ($self, $featureID) = @_;
1445          my ($featureID) = @_;      # Create a query to retrieve the functionally-coupled features.
1446          # Create a query to retrieve the functionally-coupled features. Note that we depend on the      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1447          # fact that the functional coupling is physically paired. If (A,B) is in the database, then                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);
         # (B,A) will also be found.  
         my $query = $self->Get(['IsClusteredOnChromosomeWith'],  
                                                    "IsClusteredOnChromosomeWith(from-link) = ?", [$featureID]);  
1448          # This value will be set to TRUE if we find at least one coupled feature.          # This value will be set to TRUE if we find at least one coupled feature.
1449          my $found = 0;          my $found = 0;
1450          # Create the return hash.          # Create the return hash.
1451          my %retVal = ();          my %retVal = ();
1452          # Retrieve the relationship records and store them in the hash.          # Retrieve the relationship records and store them in the hash.
1453          while (my $clustering = $query->Fetch()) {          while (my $clustering = $query->Fetch()) {
1454                  my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',          # Get the ID and score of the coupling.
1455                                                                      'IsClusteredOnChromosomeWith(score)']);          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;                  $retVal{$otherFeatureID} = $score;
1463                  $found = 1;                  $found = 1;
1464          }          }
# Line 1268  Line 1471 
1471          return %retVal;          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 of interest.
1571    
1572    =item peg2
1573    
1574    ID of the potentially coupled feature.
1575    
1576    =item RETURN
1577    
1578    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
1585    
1586    =cut
1587    #: Return Type $%@;
1588    sub GetCoupling {
1589        # Get the parameters.
1590        my ($self, $peg1, $peg2) = @_;
1591        # Declare the return values. We'll start with the coupling ID and undefine the
1592        # flag and score until we have more information.
1593        my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);
1594        # Find the coupling data.
1595        my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1596                                     "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1597                                     [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1598        # Check to see if we found anything.
1599        if (!@pegs) {
1600            Trace("No coupling found.") if T(Coupling => 4);
1601            # No coupling, so undefine the return value.
1602            $retVal = undef;
1603        } else {
1604            # We have a coupling! Get the score and check for inversion.
1605            $score = $pegs[0]->[1];
1606            my $firstFound = $pegs[0]->[0];
1607            $inverted = ($firstFound ne $peg1);
1608            Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1609        }
1610        # Return the result.
1611        return ($retVal, $inverted, $score);
1612    }
1613    
1614    =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    =item peg2
1636    
1637    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
1647    #: Return Type $;
1648    sub CouplingID {
1649        return join " ", sort @_;
1650    }
1651    
1652  =head3 GetEntityTypes  =head3 GetEntityTypes
1653    
1654  C<< my @entityList = $sprout->GetEntityTypes(); >>  C<< my @entityList = $sprout->GetEntityTypes(); >>
# Line 1275  Line 1656 
1656  Return the list of supported entity types.  Return the list of supported entity types.
1657    
1658  =cut  =cut
1659    #: Return Type @;
1660  sub GetEntityTypes {  sub GetEntityTypes {
1661          # Get the parameters.          # Get the parameters.
1662          my $self = shift @_;      my ($self) = @_;
1663          # Get the underlying database object.          # Get the underlying database object.
1664          my $erdb = $self->{_erdb};          my $erdb = $self->{_erdb};
1665          # Get its entity type list.          # Get its entity type list.
# Line 1310  Line 1691 
1691  =back  =back
1692    
1693  =cut  =cut
1694    #: Return Type %;
1695  sub ReadFasta {  sub ReadFasta {
1696          # Get the parameters.          # Get the parameters.
1697          my ($fileName, $prefix) = @_;          my ($fileName, $prefix) = @_;
# Line 1329  Line 1710 
1710                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1711                          # 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.
1712                          if ($id) {                          if ($id) {
1713                                  $retVal{$id} = $sequence;                  $retVal{$id} = lc $sequence;
1714                          }                          }
1715                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
1716                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
1717                  } else {                  } else {
1718                          # 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.
1719                          # First, we get the actual data out.              # First, we get the actual data out. Note that we normalize to lower
1720                # case.
1721                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
1722                          $sequence .= $1;                          $sequence .= $1;
1723                  }                  }
1724          }          }
1725          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
1726          if ($sequence) {          if ($sequence) {
1727                  $retVal {$id} = $sequence;          $retVal{$id} = lc $sequence;
1728          }          }
1729        # Close the file.
1730        close FASTAFILE;
1731          # Return the hash constructed from the file.          # Return the hash constructed from the file.
1732          return %retVal;          return %retVal;
1733  }  }
# Line 1354  Line 1738 
1738    
1739  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
1740  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
1741  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,
1742    it will not be changed; otherwise, it will be converted. This method can also be used to
1743    perform the reverse task-- insuring that all the locations are in the old format.
1744    
1745  =over 4  =over 4
1746    
# Line 1378  Line 1764 
1764  =back  =back
1765    
1766  =cut  =cut
1767    #: Return Type @;
1768  sub FormatLocations {  sub FormatLocations {
1769          # Get the parameters.          # Get the parameters.
1770          my $self = shift @_;      my ($self, $prefix, $locations, $oldFormat) = @_;
         my ($prefix, $locations, $oldFormat) = @_;  
1771          # Create the return list.          # Create the return list.
1772          my @retVal = ();          my @retVal = ();
1773          # Check to see if any locations were passed in.          # Check to see if any locations were passed in.
1774          if ($locations eq '') {          if ($locations eq '') {
1775              confess "No locations specified.";          Confess("No locations specified.");
1776          } else {          } else {
1777                  # Loop through the locations, converting them to the new format.                  # Loop through the locations, converting them to the new format.
1778                  for my $location (@{$locations}) {                  for my $location (@{$locations}) {
# Line 1422  Line 1807 
1807    
1808  sub DumpData {  sub DumpData {
1809          # Get the parameters.          # Get the parameters.
1810          my $self = shift @_;      my ($self) = @_;
1811          # Get the data directory name.          # Get the data directory name.
1812          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
1813          # Dump the relations.          # Dump the relations.
# Line 1436  Line 1821 
1821  Return the name of this database's XML definition file.  Return the name of this database's XML definition file.
1822    
1823  =cut  =cut
1824    #: Return Type $;
1825  sub XMLFileName {  sub XMLFileName {
1826          my $self = shift @_;      my ($self) = @_;
1827          return $self->{_xmlName};          return $self->{_xmlName};
1828  }  }
1829    
# Line 1458  Line 1843 
1843  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
1844  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>.
1845    
1846  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'}); >>
1847    
1848  =over 4  =over 4
1849    
# Line 1473  Line 1858 
1858  =back  =back
1859    
1860  =cut  =cut
1861    #: Return Type ;
1862  sub Insert {  sub Insert {
1863          # Get the parameters.          # Get the parameters.
1864          my $self = shift @_;      my ($self, $objectType, $fieldHash) = @_;
         my ($objectType, $fieldHash) = @_;  
1865          # Call the underlying method.          # Call the underlying method.
1866          $self->{_erdb}->InsertObject($objectType, $fieldHash);          $self->{_erdb}->InsertObject($objectType, $fieldHash);
1867  }  }
# Line 1515  Line 1899 
1899  =back  =back
1900    
1901  =cut  =cut
1902    #: Return Type $;
1903  sub Annotate {  sub Annotate {
1904          # Get the parameters.          # Get the parameters.
1905          my $self = shift @_;      my ($self, $fid, $timestamp, $user, $text) = @_;
         my ($fid, $timestamp, $user, $text) = @_;  
1906          # Create the annotation ID.          # Create the annotation ID.
1907          my $aid = "$fid:$timestamp";          my $aid = "$fid:$timestamp";
1908          # Insert the Annotation object.          # Insert the Annotation object.
# Line 1539  Line 1922 
1922    
1923  =head3 AssignFunction  =head3 AssignFunction
1924    
1925  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function); >>  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>
1926    
1927  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
1928  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.  
1929    
1930  =over 4  =over 4
1931    
# Line 1553  Line 1935 
1935    
1936  =item user  =item user
1937    
1938  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>.
1939    
1940  =item function  =item function
1941    
1942  Text of the function being assigned.  Text of the function being assigned.
1943    
1944    =item assigningUser (optional)
1945    
1946    Name of the individual user making the assignment. If omitted, defaults to the user group.
1947    
1948  =item RETURN  =item RETURN
1949    
1950  Returns 1 if successful, 0 if an error occurred.  Returns 1 if successful, 0 if an error occurred.
# Line 1566  Line 1952 
1952  =back  =back
1953    
1954  =cut  =cut
1955    #: Return Type $;
1956  sub AssignFunction {  sub AssignFunction {
1957          # Get the parameters.          # Get the parameters.
1958          my $self = shift @_;      my ($self, $featureID, $user, $function, $assigningUser) = @_;
1959          my ($featureID, $user, $function) = @_;      # Default the assigning user.
1960        if (! $assigningUser) {
1961            $assigningUser = $user;
1962        }
1963          # Create an annotation string from the parameters.          # Create an annotation string from the parameters.
1964          my $annotationText = "$user\nset $user function to\n$function";      my $annotationText = "$assigningUser\nset $user function to\n$function";
1965          # Get the current time.          # Get the current time.
1966          my $now = time;          my $now = time;
1967          # Declare the return variable.          # Declare the return variable.
# Line 1614  Line 2003 
2003  =back  =back
2004    
2005  =cut  =cut
2006    #: Return Type @;
2007  sub FeaturesByAlias {  sub FeaturesByAlias {
2008          # Get the parameters.          # Get the parameters.
2009          my $self = shift @_;      my ($self, $alias) = @_;
         my ($alias) = @_;  
2010          # Declare the return variable.          # Declare the return variable.
2011          my @retVal = ();          my @retVal = ();
2012          # Parse the alias.          # Parse the alias.
# Line 1657  Line 2045 
2045  =back  =back
2046    
2047  =cut  =cut
2048    #: Return Type $;
2049  sub Exists {  sub Exists {
2050          # Get the parameters.          # Get the parameters.
2051          my $self = shift @_;      my ($self, $entityName, $entityID) = @_;
         my ($entityName, $entityID) = @_;  
2052          # Check for the entity instance.          # Check for the entity instance.
2053        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
2054          my $testInstance = $self->GetEntity($entityName, $entityID);          my $testInstance = $self->GetEntity($entityName, $entityID);
2055          # Return an existence indicator.          # Return an existence indicator.
2056          my $retVal = ($testInstance ? 1 : 0);          my $retVal = ($testInstance ? 1 : 0);
# Line 1688  Line 2076 
2076  =back  =back
2077    
2078  =cut  =cut
2079    #: Return Type $;
2080  sub FeatureTranslation {  sub FeatureTranslation {
2081          # Get the parameters.          # Get the parameters.
2082          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2083          # Get the specified feature's translation.          # Get the specified feature's translation.
2084          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
2085          return $retVal;          return $retVal;
# Line 1721  Line 2108 
2108  =back  =back
2109    
2110  =cut  =cut
2111    #: Return Type @;
2112  sub Taxonomy {  sub Taxonomy {
2113          # Get the parameters.          # Get the parameters.
2114          my $self = shift @_;      my ($self, $genome) = @_;
         my ($genome) = @_;  
2115          # Find the specified genome's taxonomy string.          # Find the specified genome's taxonomy string.
2116          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);
2117          # Declare the return variable.          # Declare the return variable.
# Line 1765  Line 2151 
2151  =back  =back
2152    
2153  =cut  =cut
2154    #: Return Type $;
2155  sub CrudeDistance {  sub CrudeDistance {
2156          # Get the parameters.          # Get the parameters.
2157          my $self = shift @_;      my ($self, $genome1, $genome2) = @_;
         my ($genome1, $genome2) = @_;  
2158          # Insure that the distance is commutative by sorting the genome IDs.          # Insure that the distance is commutative by sorting the genome IDs.
2159          my ($genomeA, $genomeB);          my ($genomeA, $genomeB);
2160          if ($genome2 < $genome2) {          if ($genome2 < $genome2) {
# Line 1813  Line 2198 
2198  =back  =back
2199    
2200  =cut  =cut
2201    #: Return Type $;
2202  sub RoleName {  sub RoleName {
2203          # Get the parameters.          # Get the parameters.
2204          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2205          # Get the specified role's name.          # Get the specified role's name.
2206          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);
2207          # Use the ID if the role has no name.          # Use the ID if the role has no name.
# Line 1847  Line 2231 
2231  =back  =back
2232    
2233  =cut  =cut
2234    #: Return Type @;
2235  sub RoleDiagrams {  sub RoleDiagrams {
2236          # Get the parameters.          # Get the parameters.
2237          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2238          # Query for the diagrams.          # Query for the diagrams.
2239          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2240                                                                  'RoleOccursIn(to-link)');                                                                  'RoleOccursIn(to-link)');
# Line 1859  Line 2242 
2242          return @retVal;          return @retVal;
2243  }  }
2244    
2245    =head3 GetProperties
2246    
2247    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2248    
2249    Return a list of the properties with the specified characteristics.
2250    
2251    Properties are arbitrary key-value pairs associated with a feature. (At some point they
2252    will also be associated with genomes.) A property value is represented by a 4-tuple of
2253    the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2254    
2255    =over 4
2256    
2257    =item fid
2258    
2259    ID of the feature possessing the property.
2260    
2261    =item key
2262    
2263    Name or key of the property.
2264    
2265    =item value
2266    
2267    Value of the property.
2268    
2269    =item url
2270    
2271    URL of the document that indicated the property should have this particular value, or an
2272    empty string if no such document exists.
2273    
2274    =back
2275    
2276    The parameters act as a filter for the desired data. Any non-null parameter will
2277    automatically match all the tuples returned. So, specifying just the I<$fid> will
2278    return all the properties of the specified feature; similarly, specifying the I<$key>
2279    and I<$value> parameters will return all the features having the specified property
2280    value.
2281    
2282    A single property key can have many values, representing different ideas about the
2283    feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2284    virulent, and another may declare that it is not virulent. A query about the virulence of
2285    C<fig|83333.1.peg.10> would be coded as
2286    
2287        my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2288    
2289    Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2290    not to be filtered. The tuples returned would be
2291    
2292        ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2293        ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2294    
2295    =cut
2296    #: Return Type @@;
2297    sub GetProperties {
2298        # Get the parameters.
2299        my ($self, @parms) = @_;
2300        # Declare the return variable.
2301        my @retVal = ();
2302        # Now we need to create a WHERE clause that will get us the data we want. First,
2303        # we create a list of the columns containing the data for each parameter.
2304        my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2305                        'Property(property-value)', 'HasProperty(evidence)');
2306        # Now we build the WHERE clause and the list of parameter values.
2307        my @where = ();
2308        my @values = ();
2309        for (my $i = 0; $i <= $#colNames; $i++) {
2310            my $parm = $parms[$i];
2311            if (defined $parm && ($parm ne '')) {
2312                push @where, "$colNames[$i] = ?";
2313                push @values, $parm;
2314            }
2315        }
2316        # Format the WHERE clause.
2317        my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2318        # Ask for all the propertie values with the desired characteristics.
2319        my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2320        while (my $valueObject = $query->Fetch()) {
2321            my @tuple = $valueObject->Values(\@colNames);
2322            push @retVal, \@tuple;
2323        }
2324        # Return the result.
2325        return @retVal;
2326    }
2327    
2328  =head3 FeatureProperties  =head3 FeatureProperties
2329    
2330  C<< my @properties = $sprout->FeatureProperties($featureID); >>  C<< my @properties = $sprout->FeatureProperties($featureID); >>
# Line 1885  Line 2351 
2351  =back  =back
2352    
2353  =cut  =cut
2354    #: Return Type @@;
2355  sub FeatureProperties {  sub FeatureProperties {
2356          # Get the parameters.          # Get the parameters.
2357          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2358          # Get the properties.          # Get the properties.
2359          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],
2360                                                          ['Property(property-name)', 'Property(property-value)',                                                          ['Property(property-name)', 'Property(property-value)',
# Line 1917  Line 2382 
2382  =back  =back
2383    
2384  =cut  =cut
2385    #: Return Type $;
2386  sub DiagramName {  sub DiagramName {
2387          # Get the parameters.          # Get the parameters.
2388          my $self = shift @_;      my ($self, $diagramID) = @_;
         my ($diagramID) = @_;  
2389          # Get the specified diagram's name and return it.          # Get the specified diagram's name and return it.
2390          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);
2391          return $retVal;          return $retVal;
# Line 1950  Line 2414 
2414  =back  =back
2415    
2416  =cut  =cut
2417    #: Return Type @;
2418  sub MergedAnnotations {  sub MergedAnnotations {
2419          # Get the parameters.          # Get the parameters.
2420          my $self = shift @_;      my ($self, $list) = @_;
         my ($list) = @_;  
2421          # Create a list to hold the annotation tuples found.          # Create a list to hold the annotation tuples found.
2422          my @tuples = ();          my @tuples = ();
2423          # Loop through the features in the input list.          # Loop through the features in the input list.
# Line 1969  Line 2432 
2432          }          }
2433          # Sort the result list by timestamp.          # Sort the result list by timestamp.
2434          my @retVal = sort { $a->[1] <=> $b->[1] } @tuples;          my @retVal = sort { $a->[1] <=> $b->[1] } @tuples;
2435        # Loop through and make the time stamps friendly.
2436        for my $tuple (@retVal) {
2437            $tuple->[1] = FriendlyTimestamp($tuple->[1]);
2438        }
2439          # Return the sorted list.          # Return the sorted list.
2440          return @retVal;          return @retVal;
2441  }  }
# Line 1995  Line 2462 
2462  =back  =back
2463    
2464  =cut  =cut
2465    #: Return Type @;
2466  sub RoleNeighbors {  sub RoleNeighbors {
2467          # Get the parameters.          # Get the parameters.
2468          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2469          # Get all the diagrams containing this role.          # Get all the diagrams containing this role.
2470          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2471                                                                    'RoleOccursIn(to-link)');                                                                    'RoleOccursIn(to-link)');
# Line 2038  Line 2504 
2504  =back  =back
2505    
2506  =cut  =cut
2507    #: Return Type @;
2508  sub FeatureLinks {  sub FeatureLinks {
2509          # Get the parameters.          # Get the parameters.
2510          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2511          # Get the feature's links.          # Get the feature's links.
2512          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);
2513          # Return the feature's links.          # Return the feature's links.
# Line 2054  Line 2519 
2519  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2520    
2521  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
2522  to the role the feature performs.  to the roles the feature performs.
2523    
2524  =over 4  =over 4
2525    
# Line 2064  Line 2529 
2529    
2530  =item RETURN  =item RETURN
2531    
2532  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.
2533    
2534  =back  =back
2535    
2536  =cut  =cut
2537    #: Return Type %@;
2538  sub SubsystemsOf {  sub SubsystemsOf {
2539          # Get the parameters.          # Get the parameters.
2540          my $self = shift @_;      my ($self, $featureID) = @_;
2541          my ($featureID) = @_;      # Get the subsystem list.
         # Use the SSCell to connect features to subsystems.  
2542          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2543                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2544                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
# Line 2082  Line 2546 
2546          my %retVal = ();          my %retVal = ();
2547          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
2548          for my $record (@subsystems) {          for my $record (@subsystems) {
2549                  $retVal{$record->[0]} = $record->[1];          my ($subsys, $role) = @{$record};
2550            if (exists $retVal{$subsys}) {
2551                push @{$retVal{$subsys}}, $role;
2552            } else {
2553                $retVal{$subsys} = [$role];
2554            }
2555          }          }
2556          # Return the hash.          # Return the hash.
2557          return %retVal;          return %retVal;
2558  }  }
2559    
2560    =head3 SubsystemList
2561    
2562    C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2563    
2564    Return a list containing the names of the subsystems in which the specified
2565    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2566    subsystem names, not the roles.
2567    
2568    =over 4
2569    
2570    =item featureID
2571    
2572    ID of the feature whose subsystem names are desired.
2573    
2574    =item RETURN
2575    
2576    Returns a list of the names of the subsystems in which the feature participates.
2577    
2578    =back
2579    
2580    =cut
2581    #: Return Type @;
2582    sub SubsystemList {
2583        # Get the parameters.
2584        my ($self, $featureID) = @_;
2585        # Get the list of names.
2586        my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",
2587                                    [$featureID], 'HasSSCell(from-link)');
2588        # Return the result.
2589        return @retVal;
2590    }
2591    
2592  =head3 RelatedFeatures  =head3 RelatedFeatures
2593    
2594  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2118  Line 2619 
2619  =back  =back
2620    
2621  =cut  =cut
2622    #: Return Type @;
2623  sub RelatedFeatures {  sub RelatedFeatures {
2624          # Get the parameters.          # Get the parameters.
2625          my $self = shift @_;      my ($self, $featureID, $function, $userID) = @_;
         my ($featureID, $function, $userID) = @_;  
2626          # 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.
2627          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],
2628                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],
# Line 2167  Line 2667 
2667  =back  =back
2668    
2669  =cut  =cut
2670    #: Return Type @;
2671  sub TaxonomySort {  sub TaxonomySort {
2672          # Get the parameters.          # Get the parameters.
2673          my $self = shift @_;      my ($self, $featureIDs) = @_;
         my ($featureIDs) = @_;  
2674          # Create the working hash table.          # Create the working hash table.
2675          my %hashBuffer = ();          my %hashBuffer = ();
2676          # Loop through the features.          # Loop through the features.
# Line 2180  Line 2679 
2679                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
2680                                                                                  [$fid], 'Genome(taxonomy)');                                                                                  [$fid], 'Genome(taxonomy)');
2681                  # Add this feature to the hash buffer.                  # Add this feature to the hash buffer.
2682                  if (exists $hashBuffer{$taxonomy}) {          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);
                         push @{$hashBuffer{$taxonomy}}, $fid;  
                 } else {  
                         $hashBuffer{$taxonomy} = [$fid];  
                 }  
2683          }          }
2684          # Sort the keys and get the elements.          # Sort the keys and get the elements.
2685          my @retVal = ();          my @retVal = ();
# Line 2250  Line 2745 
2745  =back  =back
2746    
2747  =cut  =cut
2748    #: Return Type @@;
2749  sub GetAll {  sub GetAll {
2750          # Get the parameters.          # Get the parameters.
2751          my $self = shift @_;      my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
2752          my ($objectNames, $filterClause, $parameterList, $fields, $count) = @_;      # Call the ERDB method.
2753          # Create the query.      my @retVal = $self->{_erdb}->GetAll($objectNames, $filterClause, $parameterList,
2754          my $query = $self->Get($objectNames, $filterClause, $parameterList);                                          $fields, $count);
         # 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++;  
         }  
2755          # Return the resulting list.          # Return the resulting list.
2756          return @retVal;          return @retVal;
2757  }  }
# Line 2312  Line 2793 
2793  =back  =back
2794    
2795  =cut  =cut
2796    #: Return Type @;
2797  sub GetFlat {  sub GetFlat {
2798          # Get the parameters.          # Get the parameters.
2799          my $self = shift @_;      my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
         my ($objectNames, $filterClause, $parameterList, $field) = @_;  
2800          # Construct the query.          # Construct the query.
2801          my $query = $self->Get($objectNames, $filterClause, $parameterList);          my $query = $self->Get($objectNames, $filterClause, $parameterList);
2802          # Create the result list.          # Create the result list.
# Line 2423  Line 2903 
2903  to load the entire database.  to load the entire database.
2904    
2905  =cut  =cut
2906    #: Return Type @;
2907  sub LoadInfo {  sub LoadInfo {
2908          # Get the parameters.          # Get the parameters.
2909          my $self = shift @_;      my ($self) = @_;
2910          # 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.
2911          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
2912          # Concatenate the table names.          # Concatenate the table names.
# Line 2460  Line 2940 
2940  =back  =back
2941    
2942  =cut  =cut
2943    #: Return Type %;
2944  sub LowBBHs {  sub LowBBHs {
2945          # Get the parsameters.          # Get the parsameters.
2946          my $self = shift @_;      my ($self, $featureID, $cutoff) = @_;
         my ($featureID, $cutoff) = @_;  
2947          # Create the return hash.          # Create the return hash.
2948          my %retVal = ();          my %retVal = ();
2949          # Create a query to get the desired BBHs.          # Create a query to get the desired BBHs.
# Line 2480  Line 2959 
2959          return %retVal;          return %retVal;
2960  }  }
2961    
2962    =head3 GetGroups
2963    
2964    C<< my %groups = $sprout->GetGroups(\@groupList); >>
2965    
2966    Return a hash mapping each group to the IDs of the genomes in the group.
2967    A list of groups may be specified, in which case only those groups will be
2968    shown. Alternatively, if no parameter is supplied, all groups will be
2969    included. Genomes that are not in any group are omitted.
2970    
2971    =cut
2972    #: Return Type %@;
2973    sub GetGroups {
2974        # Get the parameters.
2975        my ($self, $groupList) = @_;
2976        # Declare the return value.
2977        my %retVal = ();
2978        # Determine whether we are getting all the groups or just some.
2979        if (defined $groupList) {
2980            # Here we have a group list. Loop through them individually,
2981            # getting a list of the relevant genomes.
2982            for my $group (@{$groupList}) {
2983                my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",
2984                    [$group], "Genome(id)");
2985                $retVal{$group} = \@genomeIDs;
2986            }
2987        } else {
2988            # Here we need all of the groups. In this case, we run through all
2989            # of the genome records, putting each one found into the appropriate
2990            # group. Note that we use a filter clause to insure that only genomes
2991            # in groups are included in the return set.
2992            my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],
2993                                        ['Genome(id)', 'Genome(group-name)']);
2994            # Loop through the genomes found.
2995            for my $genome (@genomes) {
2996                # Pop this genome's ID off the current list.
2997                my @groups = @{$genome};
2998                my $genomeID = shift @groups;
2999                # Loop through the groups, adding the genome ID to each group's
3000                # list.
3001                for my $group (@groups) {
3002                    Tracer::AddToListMap(\%retVal, $group, $genomeID);
3003                }
3004            }
3005        }
3006        # Return the hash we just built.
3007        return %retVal;
3008    }
3009    
3010    =head3 MyGenomes
3011    
3012    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
3013    
3014    Return a list of the genomes to be included in the Sprout.
3015    
3016    This method is provided for use during the Sprout load. It presumes the Genome load file has
3017    already been created. (It will be in the Sprout data directory and called either C<Genome>
3018    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3019    IDs.
3020    
3021    =over 4
3022    
3023    =item dataDir
3024    
3025    Directory containing the Sprout load files.
3026    
3027    =back
3028    
3029    =cut
3030    #: Return Type @;
3031    sub MyGenomes {
3032        # Get the parameters.
3033        my ($dataDir) = @_;
3034        # Compute the genome file name.
3035        my $genomeFileName = LoadFileName($dataDir, "Genome");
3036        # Extract the genome IDs from the files.
3037        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3038        # Return the result.
3039        return @retVal;
3040    }
3041    
3042    =head3 LoadFileName
3043    
3044    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3045    
3046    Return the name of the load file for the specified table in the specified data
3047    directory.
3048    
3049    =over 4
3050    
3051    =item dataDir
3052    
3053    Directory containing the Sprout load files.
3054    
3055    =item tableName
3056    
3057    Name of the table whose load file is desired.
3058    
3059    =item RETURN
3060    
3061    Returns the name of the file containing the load data for the specified table, or
3062    C<undef> if no load file is present.
3063    
3064    =back
3065    
3066    =cut
3067    #: Return Type $;
3068    sub LoadFileName {
3069        # Get the parameters.
3070        my ($dataDir, $tableName) = @_;
3071        # Declare the return variable.
3072        my $retVal;
3073        # Check for the various file names.
3074        if (-e "$dataDir/$tableName") {
3075            $retVal = "$dataDir/$tableName";
3076        } elsif (-e "$dataDir/$tableName.dtx") {
3077            $retVal = "$dataDir/$tableName.dtx";
3078        }
3079        # Return the result.
3080        return $retVal;
3081    }
3082    
3083  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3084    
3085  =head3 ParseAssignment  =head3 ParseAssignment
3086    
3087  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,
3088  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
3089  will be returned.  isn't, an empty list will be returned.
3090    
3091    A functional assignment is always of the form
3092    
3093        I<XXXX>C<\nset >I<YYYY>C< function to\n>I<ZZZZZ>
3094    
3095    where I<XXXX> is the B<assigning user>, I<YYYY> is the B<user>, and I<ZZZZ> is the
3096    actual functional role. In most cases, the user and the assigning user will be the
3097    same, but that is not always the case.
3098    
3099  This is a static method.  This is a static method.
3100    
# Line 2505  Line 3113 
3113    
3114  =cut  =cut
3115    
3116  sub ParseAssignment {  sub _ParseAssignment {
3117          # Get the parameters.          # Get the parameters.
3118          my ($text) = @_;          my ($text) = @_;
3119          # Declare the return value.          # Declare the return value.
3120          my @retVal = ();          my @retVal = ();
3121          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3122          my ($user, $type, $function) = split(/\n/, $text);          my ($user, $type, $function) = split(/\n/, $text);
3123          if ($type =~ m/^set $user function to$/i) {      if ($type =~ m/^set ([^ ]+) function to$/i) {
3124                  # Here it is, so we return the user name and function text.          # Here it is, so we return the user name (which is in $1), the functional role text,
3125                  @retVal = ($user, $function);          # and the assigning user.
3126            @retVal = ($1, $function, $user);
3127          }          }
3128          # Return the result list.          # Return the result list.
3129          return @retVal;          return @retVal;
3130  }  }
3131    
3132    =head3 FriendlyTimestamp
3133    
3134    Convert a time number to a user-friendly time stamp for display.
3135    
3136    This is a static method.
3137    
3138    =over 4
3139    
3140    =item timeValue
3141    
3142    Numeric time value.
3143    
3144    =item RETURN
3145    
3146    Returns a string containing the same time in user-readable format.
3147    
3148    =back
3149    
3150    =cut
3151    
3152    sub FriendlyTimestamp {
3153        my ($timeValue) = @_;
3154        my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));
3155        return $retVal;
3156    }
3157    
3158    =head3 AddProperty
3159    
3160    C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>
3161    
3162    Add a new attribute value (Property) to a feature. In the SEED system, attributes can
3163    be added to almost any object. In Sprout, they can only be added to features. In
3164    Sprout, attributes are implemented using I<properties>. A property represents a key/value
3165    pair. If the particular key/value pair coming in is not already in the database, a new
3166    B<Property> record is created to hold it.
3167    
3168    =over 4
3169    
3170    =item peg
3171    
3172    ID of the feature to which the attribute is to be replied.
3173    
3174    =item key
3175    
3176    Name of the attribute (key).
3177    
3178    =item value
3179    
3180    Value of the attribute.
3181    
3182    =item url
3183    
3184    URL or text citation from which the property was obtained.
3185    
3186    =back
3187    
3188    =cut
3189    #: Return Type ;
3190    sub AddProperty {
3191        # Get the parameters.
3192        my ($self, $featureID, $key, $value, $url) = @_;
3193        # Declare the variable to hold the desired property ID.
3194        my $propID;
3195        # Attempt to find a property record for this key/value pair.
3196        my @properties = $self->GetFlat(['Property'],
3197                                       "Property(property-name) = ? AND Property(property-value) = ?",
3198                                       [$key, $value], 'Property(id)');
3199        if (@properties) {
3200            # Here the property is already in the database. We save its ID.
3201            $propID = $properties[0];
3202            # Here the property value does not exist. We need to generate an ID. It will be set
3203            # to a number one greater than the maximum value in the database. This call to
3204            # GetAll will stop after one record.
3205            my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],
3206                                            1);
3207            $propID = $maxProperty[0]->[0] + 1;
3208            # Insert the new property value.
3209            $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });
3210        }
3211        # Now we connect the incoming feature to the property.
3212        $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3213    }
3214    
3215    
3216    
3217  1;  1;

Legend:
Removed from v.1.2  
changed lines
  Added in v.1.29

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3