[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.32, Wed Sep 14 13:24:14 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 628  Line 622 
622                  }                  }
623                  # Remember this specifier for the adjacent-segment test the next time through.                  # Remember this specifier for the adjacent-segment test the next time through.
624                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
625            # Compute the initial base pair.
626            my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
627                  # Add the specifier to the list.                  # Add the specifier to the list.
628                  push @retVal, "${contigID}_$beg$dir$len";                  push @retVal, "${contigID}_$beg$dir$len";
629          }          }
630          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
631          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
632  }  }
633    
634  =head3 ParseLocation  =head3 ParseLocation
# Line 656  Line 652 
652  =back  =back
653    
654  =cut  =cut
655    #: Return Type @;
656  sub ParseLocation {  sub ParseLocation {
657          # Get the parameter.      # Get the parameter. Note that if we're called as an instance method, we ignore
658        # the first parameter.
659        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
660          my ($location) = @_;          my ($location) = @_;
661          # Parse it into segments.          # Parse it into segments.
662          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;
# Line 677  Line 675 
675          return ($contigID, $start, $dir, $len);          return ($contigID, $start, $dir, $len);
676  }  }
677    
678    =head3 PointLocation
679    
680    C<< my $found = Sprout::PointLocation($location, $point); >>
681    
682    Return the offset into the specified location of the specified point on the contig. If
683    the specified point is before the location, a negative value will be returned. If it is
684    beyond the location, an undefined value will be returned. It is assumed that the offset
685    is for the location's contig. The location can either be new-style (using a C<+> or C<->
686    and a length) or old-style (using C<_> and start and end positions.
687    
688    =over 4
689    
690    =item location
691    
692    A location specifier (see L</FeatureLocation> for a description).
693    
694    =item point
695    
696    The offset into the contig of the point in which we're interested.
697    
698    =item RETURN
699    
700    Returns the offset inside the specified location of the specified point, a negative
701    number if the point is before the location, or an undefined value if the point is past
702    the location. If the length of the location is 0, this method will B<always> denote
703    that it is outside the location. The offset will always be relative to the left-most
704    position in the location.
705    
706    =back
707    
708    =cut
709    #: Return Type $;
710    sub PointLocation {
711        # Get the parameter. Note that if we're called as an instance method, we ignore
712        # the first parameter.
713        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
714        my ($location, $point) = @_;
715        # Parse out the location elements. Note that this works on both old-style and new-style
716        # locations.
717        my ($contigID, $start, $dir, $len) = ParseLocation($location);
718        # Declare the return variable.
719        my $retVal;
720        # Compute the offset. The computation is dependent on the direction of the location.
721        my $offset = (($dir == '+') ? $point - $start : $point - ($start - $len + 1));
722        # Return the offset if it's valid.
723        if ($offset < $len) {
724            $retVal = $offset;
725        }
726        # Return the offset found.
727        return $retVal;
728    }
729    
730  =head3 DNASeq  =head3 DNASeq
731    
732  C<< my $sequence = $sprout->DNASeq(\@locationList); >>  C<< my $sequence = $sprout->DNASeq(\@locationList); >>
# Line 699  Line 749 
749  =back  =back
750    
751  =cut  =cut
752    #: Return Type $;
753  sub DNASeq {  sub DNASeq {
754          # Get the parameters.          # Get the parameters.
755          my $self = shift @_;      my ($self, $locationList) = @_;
         my ($locationList) = @_;  
756          # Create the return string.          # Create the return string.
757          my $retVal = "";          my $retVal = "";
758          # Loop through the locations.          # Loop through the locations.
# Line 718  Line 767 
767                  # the start point is the ending. Note that in the latter case we must reverse the DNA string                  # the start point is the ending. Note that in the latter case we must reverse the DNA string
768                  # before putting it in the return value.                  # before putting it in the return value.
769                  my ($start, $stop);                  my ($start, $stop);
770            Trace("Parsed location is $beg$dir$len.") if T(SDNA => 4);
771                  if ($dir eq "+") {                  if ($dir eq "+") {
772                          $start = $beg;                          $start = $beg;
773                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
774                  } else {                  } else {
775                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
776                          $stop = $beg;                          $stop = $beg;
777                  }                  }
778            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
779                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
780                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
781                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 736  Line 787 
787                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
788                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
789                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
790                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
791                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
792                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
793                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;
794                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
795                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
796                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
797                  }                  }
798                  # 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.
799                  if ($dir eq '+') {                  if ($dir eq '+') {
800                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
801                  } else {                  } else {
802                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
803                  }                  }
804          }          }
805          # Return the result.          # Return the result.
# Line 773  Line 825 
825  =back  =back
826    
827  =cut  =cut
828    #: Return Type @;
829  sub AllContigs {  sub AllContigs {
830          # Get the parameters.          # Get the parameters.
831          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
832          # Ask for the genome's Contigs.          # Ask for the genome's Contigs.
833          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],
834                                                                  'HasContig(to-link)');                                                                  'HasContig(to-link)');
# Line 797  Line 848 
848    
849  ID of the contig whose length is desired.  ID of the contig whose length is desired.
850    
851    =item RETURN
852    
853    Returns the number of positions in the contig.
854    
855  =back  =back
856    
857  =cut  =cut
858    #: Return Type $;
859  sub ContigLength {  sub ContigLength {
860          # Get the parameters.          # Get the parameters.
861          my $self = shift @_;      my ($self, $contigID) = @_;
         my ($contigID) = @_;  
862          # Get the contig's last sequence.          # Get the contig's last sequence.
863          my $query = $self->Get(['IsMadeUpOf'],          my $query = $self->Get(['IsMadeUpOf'],
864                  "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",                  "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
# Line 846  Line 900 
900  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
901  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
902  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
903  the start and stop values.  the start and stop values. The first element (that is, the list of features) is sorted
904    roughly by location.
905    
906  =back  =back
907    
908  =cut  =cut
909    #: Return Type @@;
910  sub GenesInRegion {  sub GenesInRegion {
911          # Get the parameters.          # Get the parameters.
912          my $self = shift @_;      my ($self, $contigID, $start, $stop) = @_;
         my ($contigID, $start, $stop) = @_;  
913          # Get the maximum segment length.          # Get the maximum segment length.
914          my $maximumSegmentLength = $self->MaxSegment;          my $maximumSegmentLength = $self->MaxSegment;
915          # 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
916          # duplicates easily.      # duplicates easily. The hash key will be the feature ID. The value will be a two-element
917        # containing the minimum and maximum offsets. We will use the offsets to sort the results
918        # when we're building the result set.
919          my %featuresFound = ();          my %featuresFound = ();
920          # Prime the values we'll use for the returned beginning and end.          # Prime the values we'll use for the returned beginning and end.
921          my ($min, $max) = ($self->ContigLength($contigID), 0);      my @initialMinMax = ($self->ContigLength($contigID), 0);
922        my ($min, $max) = @initialMinMax;
923          # 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
924          # 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,
925          # 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 949 
949                                          $found = 1;                                          $found = 1;
950                                  }                                  }
951                          } elsif ($dir eq '-') {                          } elsif ($dir eq '-') {
952                                  $end = $beg - $len;                  # Note we switch things around so that the beginning is to the left of the
953                                  if ($end <= $stop) {                  # ending.
954                    ($beg, $end) = ($beg - $len, $beg);
955                    if ($beg <= $stop) {
956                                          # Denote we found a useful feature.                                          # Denote we found a useful feature.
957                                          $found = 1;                                          $found = 1;
958                                  }                                  }
959                          }                          }
960                          if ($found) {                          if ($found) {
961                                  # 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,
962                                  $featuresFound{$featureID} = 1;                  # get the current entry for the specified feature.
963                                  if ($beg < $min) { $min = $beg; }                  my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :
964                                  if ($end < $min) { $min = $end; }                                       @initialMinMax);
965                                  if ($beg > $max) { $max = $beg; }                  # Merge the current segment's begin and end into the feature begin and end and the
966                                  if ($end > $max) { $max = $end; }                  # global min and max.
967                    if ($beg < $loc1) {
968                        $loc1 = $beg;
969                        $min = $beg if $beg < $min;
970                    }
971                    if ($end > $loc2) {
972                        $loc2 = $end;
973                        $max = $end if $end > $max;
974                    }
975                    # Store the entry back into the hash table.
976                    $featuresFound{$featureID} = [$loc1, $loc2];
977                          }                          }
978                  }                  }
979          }          }
980          # 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
981          my @list = (sort (keys %featuresFound));      # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
982        # but the result of the sort will be the same.)
983        my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;
984        # Now we sort by midpoint and yank out the feature IDs.
985        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
986          # Return it along with the min and max.          # Return it along with the min and max.
987          return (\@list, $min, $max);      return (\@retVal, $min, $max);
988  }  }
989    
990  =head3 FType  =head3 FType
# Line 934  Line 1007 
1007  =back  =back
1008    
1009  =cut  =cut
1010    #: Return Type $;
1011  sub FType {  sub FType {
1012          # Get the parameters.          # Get the parameters.
1013          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1014          # Get the specified feature's type.          # Get the specified feature's type.
1015          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
1016          # Return the result.          # Return the result.
# Line 963  Line 1035 
1035    
1036  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1037    
1038  * B<timeStamp> time the annotation was made.  * B<timeStamp> time the annotation was made, in user-friendly format.
1039    
1040  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1041    
# Line 972  Line 1044 
1044  =back  =back
1045    
1046  =cut  =cut
1047    #: Return Type @%;
1048  sub FeatureAnnotations {  sub FeatureAnnotations {
1049          # Get the parameters.          # Get the parameters.
1050          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1051          # 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.
1052          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1053                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 990  Line 1061 
1061                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1062                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1063                  # Assemble them into a hash.                  # Assemble them into a hash.
1064                  my $annotationHash = { featureID => $featureID, timeStamp => $timeStamp,          my $annotationHash = { featureID => $featureID,
1065                                   timeStamp => FriendlyTimestamp($timeStamp),
1066                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1067                  # Add it to the return list.                  # Add it to the return list.
1068                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1004  Line 1076 
1076  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>
1077    
1078  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
1079  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,
1080  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
1081  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,
1082  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.
1083  features only have a small number of annotations.  Finally, if a single user has multiple functional assignments, we will only keep the most
1084    recent one.
1085    
1086  =over 4  =over 4
1087    
# Line 1016  Line 1089 
1089    
1090  ID of the feature whose functional assignments are desired.  ID of the feature whose functional assignments are desired.
1091    
1092    =item RETURN
1093    
1094    Returns a hash mapping the functional assignment IDs to user IDs.
1095    
1096  =back  =back
1097    
1098  =cut  =cut
1099    #: Return Type %;
1100  sub AllFunctionsOf {  sub AllFunctionsOf {
1101          # Get the parameters.          # Get the parameters.
1102          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1103          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1104          my @query = $self->GetFlat(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],
1105                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1106                                                          [$featureID], 'Annotation(annotation)');                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);
1107          # Declare the return hash.          # Declare the return hash.
1108          my %retVal;          my %retVal;
1109        # Declare a hash for insuring we only make one assignment per user.
1110        my %timeHash = ();
1111        # Now we sort the assignments by timestamp in reverse.
1112        my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1113          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1114          for my $text (@query) {      for my $annotation (@sortedQuery) {
1115            # Get the annotation fields.
1116            my ($timeStamp, $text) = @{$annotation};
1117                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1118                  my ($user, $function) = ParseAssignment($text);          my ($user, $function) = _ParseAssignment($text);
1119                  if ($user) {          if ($user && ! exists $timeHash{$user}) {
1120                          # Here it is, so stuff it in the return hash.              # Here it is a functional assignment and there has been no
1121                # previous assignment for this user, so we stuff it in the
1122                # return hash.
1123                          $retVal{$function} = $user;                          $retVal{$function} = $user;
1124                # Insure we don't assign to this user again.
1125                $timeHash{$user} = 1;
1126                  }                  }
1127          }          }
1128          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1047  Line 1133 
1133    
1134  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>
1135    
1136  Return the most recently-determined functional assignment of a particular feature. A functional  Return the most recently-determined functional assignment of a particular feature.
1137  assignment is a type of annotation. It has the format "XXXX\nset XXXX function to\nYYYYY". In this  
1138  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
1139  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
1140  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
1141    L</ParseLocation>. Its worth noting that we cannot filter on the content of the
1142    annotation itself because it's a text field; however, this is not a big problem because
1143    most features only have a small number of annotations.
1144    
1145    Each user has an associated list of trusted users. The assignment returned will be the most
1146    recent one by at least one of the trusted users. If no trusted user list is available, then
1147    the specified user and FIG are considered trusted. If the user ID is omitted, only FIG
1148    is trusted.
1149    
1150    If the feature is B<not> identified by a FIG ID, then the functional assignment
1151    information is taken from the B<ExternalAliasFunc> table. If the table does
1152    not contain an entry for the feature, an undefined value is returned.
1153    
1154  =over 4  =over 4
1155    
# Line 1061  Line 1159 
1159    
1160  =item userID (optional)  =item userID (optional)
1161    
1162  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
1163    C<FIG> assignment will be returned.
1164    
1165  =item RETURN  =item RETURN
1166    
# Line 1070  Line 1169 
1169  =back  =back
1170    
1171  =cut  =cut
1172    #: Return Type $;
1173  sub FunctionOf {  sub FunctionOf {
1174          # Get the parameters.          # Get the parameters.
1175          my $self = shift @_;      my ($self, $featureID, $userID) = @_;
1176          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.  
1177          my $retVal;          my $retVal;
1178        # Determine the ID type.
1179        if ($featureID =~ m/^fig\|/) {
1180            # Here we have a FIG feature ID. We must build the list of trusted
1181            # users.
1182            my %trusteeTable = ();
1183            # Check the user ID.
1184            if (!$userID) {
1185                # No user ID, so only FIG is trusted.
1186                $trusteeTable{FIG} = 1;
1187            } else {
1188                # Add this user's ID.
1189                $trusteeTable{$userID} = 1;
1190                # Look for the trusted users in the database.
1191                my @trustees = $self->GetFlat(['IsTrustedBy'], 'IsTrustedBy(from-link) = ?', [$userID], 'IsTrustedBy(to-link)');
1192                if (! @trustees) {
1193                    # None were found, so build a default list.
1194                    $trusteeTable{FIG} = 1;
1195                } else {
1196                    # Otherwise, put all the trustees in.
1197                    for my $trustee (@trustees) {
1198                        $trusteeTable{$trustee} = 1;
1199                    }
1200                }
1201            }
1202            # Build a query for all of the feature's annotations, sorted by date.
1203            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],
1204                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1205                                   [$featureID]);
1206          my $timeSelected = 0;          my $timeSelected = 0;
1207          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1208          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1209                  # Get the annotation text.                  # Get the annotation text.
1210                  my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);                  my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);
1211                  # 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.
1212                  my ($user, $type, $function) = split(/\n/, $text);              my ($user, $function) = _ParseAssignment($text);
1213                  if ($type =~ m/^set $userID function to$/i) {              if ($user) {
1214                          # 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
1215                          if ($time > $timeSelected) {                  # name. The time must be recent and the user must be trusted.
1216                    if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {
1217                                  $retVal = $function;                                  $retVal = $function;
1218                                  $timeSelected = $time;                                  $timeSelected = $time;
1219                          }                          }
1220                  }                  }
1221          }          }
1222        } else {
1223            # Here we have a non-FIG feature ID. In this case the user ID does not
1224            # matter. We simply get the information from the External Alias Function
1225            # table.
1226            ($retVal) = $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']);
1227        }
1228          # Return the assignment found.          # Return the assignment found.
1229          return $retVal;          return $retVal;
1230  }  }
# Line 1120  Line 1248 
1248    
1249  =item RETURN  =item RETURN
1250    
1251  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
1252  their best hits.  on the target genome.
1253    
1254  =back  =back
1255    
1256  =cut  =cut
1257    #: Return Type %;
1258  sub BBHList {  sub BBHList {
1259          # Get the parameters.          # Get the parameters.
1260          my $self = shift @_;      my ($self, $genomeID, $featureList) = @_;
         my ($genomeID, $featureList) = @_;  
1261          # Create the return structure.          # Create the return structure.
1262          my %retVal = ();          my %retVal = ();
1263          # Loop through the incoming features.          # Loop through the incoming features.
# Line 1150  Line 1277 
1277          return \%retVal;          return \%retVal;
1278  }  }
1279    
1280    =head3 SimList
1281    
1282    C<< my %similarities = $sprout->SimList($featureID, $count); >>
1283    
1284    Return a list of the similarities to the specified feature.
1285    
1286    Sprout does not support real similarities, so this method just returns the bidirectional
1287    best hits.
1288    
1289    =over 4
1290    
1291    =item featureID
1292    
1293    ID of the feature whose similarities are desired.
1294    
1295    =item count
1296    
1297    Maximum number of similar features to be returned, or C<0> to return them all.
1298    
1299    =back
1300    
1301    =cut
1302    #: Return Type %;
1303    sub SimList {
1304        # Get the parameters.
1305        my ($self, $featureID, $count) = @_;
1306        # Ask for the best hits.
1307        my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],
1308                                  "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",
1309                                  [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],
1310                                  $count);
1311        # Create the return value.
1312        my %retVal = ();
1313        for my $tuple (@lists) {
1314            $retVal{$tuple->[0]} = $tuple->[1];
1315        }
1316        # Return the result.
1317        return %retVal;
1318    }
1319    
1320    
1321    
1322    =head3 IsComplete
1323    
1324    C<< my $flag = $sprout->IsComplete($genomeID); >>
1325    
1326    Return TRUE if the specified genome is complete, else FALSE.
1327    
1328    =over 4
1329    
1330    =item genomeID
1331    
1332    ID of the genome whose completeness status is desired.
1333    
1334    =item RETURN
1335    
1336    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1337    not found.
1338    
1339    =back
1340    
1341    =cut
1342    #: Return Type $;
1343    sub IsComplete {
1344        # Get the parameters.
1345        my ($self, $genomeID) = @_;
1346        # Declare the return variable.
1347        my $retVal;
1348        # Get the genome's data.
1349        my $genomeData = $self->GetEntity('Genome', $genomeID);
1350        if ($genomeData) {
1351            # The genome exists, so get the completeness flag.
1352            ($retVal) = $genomeData->Value('complete');
1353        }
1354        # Return the result.
1355        return $retVal;
1356    }
1357    
1358  =head3 FeatureAliases  =head3 FeatureAliases
1359    
1360  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
# Line 1170  Line 1375 
1375  =back  =back
1376    
1377  =cut  =cut
1378    #: Return Type @;
1379  sub FeatureAliases {  sub FeatureAliases {
1380          # Get the parameters.          # Get the parameters.
1381          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1382          # Get the desired feature's aliases          # Get the desired feature's aliases
1383          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);
1384          # Return the result.          # Return the result.
# Line 1201  Line 1405 
1405  =back  =back
1406    
1407  =cut  =cut
1408    #: Return Type $;
1409  sub GenomeOf {  sub GenomeOf {
1410          # Get the parameters.          # Get the parameters.
1411          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1412          # Create a query to find the genome associated with the feature.          # Create a query to find the genome associated with the feature.
1413          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);
1414          # Declare the return value.          # Declare the return value.
# Line 1238  Line 1441 
1441  =back  =back
1442    
1443  =cut  =cut
1444    #: Return Type %;
1445  sub CoupledFeatures {  sub CoupledFeatures {
1446          # Get the parameters.          # Get the parameters.
1447          my $self = shift @_;      my ($self, $featureID) = @_;
1448          my ($featureID) = @_;      # Create a query to retrieve the functionally-coupled features.
1449          # Create a query to retrieve the functionally-coupled features. Note that we depend on the      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1450          # 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]);  
1451          # 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.
1452          my $found = 0;          my $found = 0;
1453          # Create the return hash.          # Create the return hash.
1454          my %retVal = ();          my %retVal = ();
1455          # Retrieve the relationship records and store them in the hash.          # Retrieve the relationship records and store them in the hash.
1456          while (my $clustering = $query->Fetch()) {          while (my $clustering = $query->Fetch()) {
1457                  my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',          # Get the ID and score of the coupling.
1458                                                                      'IsClusteredOnChromosomeWith(score)']);          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1459                                                            'Coupling(score)']);
1460            # The coupling ID contains the two feature IDs separated by a space. We use
1461            # this information to find the ID of the other feature.
1462            my ($fid1, $fid2) = split / /, $couplingID;
1463            my $otherFeatureID = ($featureID eq $fid1 ? $fid2 : $fid1);
1464            # Attach the other feature's score to its ID.
1465                  $retVal{$otherFeatureID} = $score;                  $retVal{$otherFeatureID} = $score;
1466                  $found = 1;                  $found = 1;
1467          }          }
# Line 1268  Line 1474 
1474          return %retVal;          return %retVal;
1475  }  }
1476    
1477    =head3 CouplingEvidence
1478    
1479    C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1480    
1481    Return the evidence for a functional coupling.
1482    
1483    A pair of features is considered evidence of a coupling between two other
1484    features if they occur close together on a contig and both are similar to
1485    the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1486    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1487    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1488    similar to B<A2>.
1489    
1490    The score of a coupling is determined by the number of pieces of evidence
1491    that are considered I<representative>. If several evidence items belong to
1492    a group of genomes that are close to each other, only one of those items
1493    is considered representative. The other evidence items are presumed to be
1494    there because of the relationship between the genomes rather than because
1495    the two proteins generated by the features have a related functionality.
1496    
1497    Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1498    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1499    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1500    and FALSE otherwise.
1501    
1502    =over 4
1503    
1504    =item peg1
1505    
1506    ID of the feature of interest.
1507    
1508    =item peg2
1509    
1510    ID of a feature functionally coupled to the feature of interest.
1511    
1512    =item RETURN
1513    
1514    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1515    of interest, a feature similar to the functionally coupled feature, and a flag
1516    that is TRUE for a representative piece of evidence and FALSE otherwise.
1517    
1518    =back
1519    
1520    =cut
1521    #: Return Type @@;
1522    sub CouplingEvidence {
1523        # Get the parameters.
1524        my ($self, $peg1, $peg2) = @_;
1525        # Declare the return variable.
1526        my @retVal = ();
1527        # Our first task is to find out the nature of the coupling: whether or not
1528        # it exists, its score, and whether the features are stored in the same
1529        # order as the ones coming in.
1530        my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1531        # Only proceed if a coupling exists.
1532        if ($couplingID) {
1533            # Determine the ordering to place on the evidence items. If we're
1534            # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1535            # we want feature 1 before feature 2 (normal).
1536            Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);
1537            my $ordering = ($inverted ? "DESC" : "");
1538            # Get the coupling evidence.
1539            my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
1540                                              "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",
1541                                              [$couplingID],
1542                                              ['PCH(used)', 'UsesAsEvidence(to-link)']);
1543            # Loop through the evidence items. Each piece of evidence is represented by two
1544            # positions in the evidence list, one for each feature on the other side of the
1545            # evidence link. If at some point we want to generalize to couplings with
1546            # more than two positions, this section of code will need to be re-done.
1547            while (@evidenceList > 0) {
1548                my $peg1Data = shift @evidenceList;
1549                my $peg2Data = shift @evidenceList;
1550                Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1551                push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1552            }
1553            Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1554        }
1555        # Return the result.
1556        return @retVal;
1557    }
1558    
1559    =head3 GetCoupling
1560    
1561    C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>
1562    
1563    Return the coupling (if any) for the specified pair of PEGs. If a coupling
1564    exists, we return the coupling ID along with an indicator of whether the
1565    coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.
1566    In the second case, we say the coupling is I<inverted>. The importance of an
1567    inverted coupling is that the PEGs in the evidence will appear in reverse order.
1568    
1569    =over 4
1570    
1571    =item peg1
1572    
1573    ID of the feature of interest.
1574    
1575    =item peg2
1576    
1577    ID of the potentially coupled feature.
1578    
1579    =item RETURN
1580    
1581    Returns a three-element list. The first element contains the database ID of
1582    the coupling. The second element is FALSE if the coupling is stored in the
1583    database in the caller specified order and TRUE if it is stored in the
1584    inverted order. The third element is the coupling's score. If the coupling
1585    does not exist, all three list elements will be C<undef>.
1586    
1587    =back
1588    
1589    =cut
1590    #: Return Type $%@;
1591    sub GetCoupling {
1592        # Get the parameters.
1593        my ($self, $peg1, $peg2) = @_;
1594        # Declare the return values. We'll start with the coupling ID and undefine the
1595        # flag and score until we have more information.
1596        my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);
1597        # Find the coupling data.
1598        my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1599                                     "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1600                                     [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1601        # Check to see if we found anything.
1602        if (!@pegs) {
1603            Trace("No coupling found.") if T(Coupling => 4);
1604            # No coupling, so undefine the return value.
1605            $retVal = undef;
1606        } else {
1607            # We have a coupling! Get the score and check for inversion.
1608            $score = $pegs[0]->[1];
1609            my $firstFound = $pegs[0]->[0];
1610            $inverted = ($firstFound ne $peg1);
1611            Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1612        }
1613        # Return the result.
1614        return ($retVal, $inverted, $score);
1615    }
1616    
1617    =head3 CouplingID
1618    
1619    C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>
1620    
1621    Return the coupling ID for a pair of feature IDs.
1622    
1623    The coupling ID is currently computed by joining the feature IDs in
1624    sorted order with a space. Client modules (that is, modules which
1625    use Sprout) should not, however, count on this always being the
1626    case. This method provides a way for abstracting the concept of a
1627    coupling ID. All that we know for sure about it is that it can be
1628    generated easily from the feature IDs and the order of the IDs
1629    in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>
1630    will have the same value as C<CouplingID("b1", "a1")>.
1631    
1632    =over 4
1633    
1634    =item peg1
1635    
1636    First feature of interest.
1637    
1638    =item peg2
1639    
1640    Second feature of interest.
1641    
1642    =item RETURN
1643    
1644    Returns the ID that would be used to represent a functional coupling of
1645    the two specified PEGs.
1646    
1647    =back
1648    
1649    =cut
1650    #: Return Type $;
1651    sub CouplingID {
1652        return join " ", sort @_;
1653    }
1654    
1655  =head3 GetEntityTypes  =head3 GetEntityTypes
1656    
1657  C<< my @entityList = $sprout->GetEntityTypes(); >>  C<< my @entityList = $sprout->GetEntityTypes(); >>
# Line 1275  Line 1659 
1659  Return the list of supported entity types.  Return the list of supported entity types.
1660    
1661  =cut  =cut
1662    #: Return Type @;
1663  sub GetEntityTypes {  sub GetEntityTypes {
1664          # Get the parameters.          # Get the parameters.
1665          my $self = shift @_;      my ($self) = @_;
1666          # Get the underlying database object.          # Get the underlying database object.
1667          my $erdb = $self->{_erdb};          my $erdb = $self->{_erdb};
1668          # Get its entity type list.          # Get its entity type list.
# Line 1310  Line 1694 
1694  =back  =back
1695    
1696  =cut  =cut
1697    #: Return Type %;
1698  sub ReadFasta {  sub ReadFasta {
1699          # Get the parameters.          # Get the parameters.
1700          my ($fileName, $prefix) = @_;          my ($fileName, $prefix) = @_;
# Line 1329  Line 1713 
1713                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1714                          # 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.
1715                          if ($id) {                          if ($id) {
1716                                  $retVal{$id} = $sequence;                  $retVal{$id} = lc $sequence;
1717                          }                          }
1718                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
1719                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
1720                  } else {                  } else {
1721                          # 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.
1722                          # First, we get the actual data out.              # First, we get the actual data out. Note that we normalize to lower
1723                # case.
1724                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
1725                          $sequence .= $1;                          $sequence .= $1;
1726                  }                  }
1727          }          }
1728          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
1729          if ($sequence) {          if ($sequence) {
1730                  $retVal {$id} = $sequence;          $retVal{$id} = lc $sequence;
1731          }          }
1732        # Close the file.
1733        close FASTAFILE;
1734          # Return the hash constructed from the file.          # Return the hash constructed from the file.
1735          return %retVal;          return %retVal;
1736  }  }
# Line 1354  Line 1741 
1741    
1742  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
1743  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
1744  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,
1745    it will not be changed; otherwise, it will be converted. This method can also be used to
1746    perform the reverse task-- insuring that all the locations are in the old format.
1747    
1748  =over 4  =over 4
1749    
# Line 1378  Line 1767 
1767  =back  =back
1768    
1769  =cut  =cut
1770    #: Return Type @;
1771  sub FormatLocations {  sub FormatLocations {
1772          # Get the parameters.          # Get the parameters.
1773          my $self = shift @_;      my ($self, $prefix, $locations, $oldFormat) = @_;
         my ($prefix, $locations, $oldFormat) = @_;  
1774          # Create the return list.          # Create the return list.
1775          my @retVal = ();          my @retVal = ();
1776          # Check to see if any locations were passed in.          # Check to see if any locations were passed in.
1777          if ($locations eq '') {          if ($locations eq '') {
1778              confess "No locations specified.";          Confess("No locations specified.");
1779          } else {          } else {
1780                  # Loop through the locations, converting them to the new format.                  # Loop through the locations, converting them to the new format.
1781                  for my $location (@{$locations}) {                  for my $location (@{$locations}) {
# Line 1422  Line 1810 
1810    
1811  sub DumpData {  sub DumpData {
1812          # Get the parameters.          # Get the parameters.
1813          my $self = shift @_;      my ($self) = @_;
1814          # Get the data directory name.          # Get the data directory name.
1815          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
1816          # Dump the relations.          # Dump the relations.
# Line 1436  Line 1824 
1824  Return the name of this database's XML definition file.  Return the name of this database's XML definition file.
1825    
1826  =cut  =cut
1827    #: Return Type $;
1828  sub XMLFileName {  sub XMLFileName {
1829          my $self = shift @_;      my ($self) = @_;
1830          return $self->{_xmlName};          return $self->{_xmlName};
1831  }  }
1832    
# Line 1458  Line 1846 
1846  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
1847  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>.
1848    
1849  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'}); >>
1850    
1851  =over 4  =over 4
1852    
# Line 1473  Line 1861 
1861  =back  =back
1862    
1863  =cut  =cut
1864    #: Return Type ;
1865  sub Insert {  sub Insert {
1866          # Get the parameters.          # Get the parameters.
1867          my $self = shift @_;      my ($self, $objectType, $fieldHash) = @_;
         my ($objectType, $fieldHash) = @_;  
1868          # Call the underlying method.          # Call the underlying method.
1869          $self->{_erdb}->InsertObject($objectType, $fieldHash);          $self->{_erdb}->InsertObject($objectType, $fieldHash);
1870  }  }
# Line 1515  Line 1902 
1902  =back  =back
1903    
1904  =cut  =cut
1905    #: Return Type $;
1906  sub Annotate {  sub Annotate {
1907          # Get the parameters.          # Get the parameters.
1908          my $self = shift @_;      my ($self, $fid, $timestamp, $user, $text) = @_;
         my ($fid, $timestamp, $user, $text) = @_;  
1909          # Create the annotation ID.          # Create the annotation ID.
1910          my $aid = "$fid:$timestamp";          my $aid = "$fid:$timestamp";
1911          # Insert the Annotation object.          # Insert the Annotation object.
# Line 1539  Line 1925 
1925    
1926  =head3 AssignFunction  =head3 AssignFunction
1927    
1928  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function); >>  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>
1929    
1930  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
1931  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.  
1932    
1933  =over 4  =over 4
1934    
# Line 1553  Line 1938 
1938    
1939  =item user  =item user
1940    
1941  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>.
1942    
1943  =item function  =item function
1944    
1945  Text of the function being assigned.  Text of the function being assigned.
1946    
1947    =item assigningUser (optional)
1948    
1949    Name of the individual user making the assignment. If omitted, defaults to the user group.
1950    
1951  =item RETURN  =item RETURN
1952    
1953  Returns 1 if successful, 0 if an error occurred.  Returns 1 if successful, 0 if an error occurred.
# Line 1566  Line 1955 
1955  =back  =back
1956    
1957  =cut  =cut
1958    #: Return Type $;
1959  sub AssignFunction {  sub AssignFunction {
1960          # Get the parameters.          # Get the parameters.
1961          my $self = shift @_;      my ($self, $featureID, $user, $function, $assigningUser) = @_;
1962          my ($featureID, $user, $function) = @_;      # Default the assigning user.
1963        if (! $assigningUser) {
1964            $assigningUser = $user;
1965        }
1966          # Create an annotation string from the parameters.          # Create an annotation string from the parameters.
1967          my $annotationText = "$user\nset $user function to\n$function";      my $annotationText = "$assigningUser\nset $user function to\n$function";
1968          # Get the current time.          # Get the current time.
1969          my $now = time;          my $now = time;
1970          # Declare the return variable.          # Declare the return variable.
# Line 1614  Line 2006 
2006  =back  =back
2007    
2008  =cut  =cut
2009    #: Return Type @;
2010  sub FeaturesByAlias {  sub FeaturesByAlias {
2011          # Get the parameters.          # Get the parameters.
2012          my $self = shift @_;      my ($self, $alias) = @_;
         my ($alias) = @_;  
2013          # Declare the return variable.          # Declare the return variable.
2014          my @retVal = ();          my @retVal = ();
2015          # Parse the alias.          # Parse the alias.
# Line 1657  Line 2048 
2048  =back  =back
2049    
2050  =cut  =cut
2051    #: Return Type $;
2052  sub Exists {  sub Exists {
2053          # Get the parameters.          # Get the parameters.
2054          my $self = shift @_;      my ($self, $entityName, $entityID) = @_;
         my ($entityName, $entityID) = @_;  
2055          # Check for the entity instance.          # Check for the entity instance.
2056        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
2057          my $testInstance = $self->GetEntity($entityName, $entityID);          my $testInstance = $self->GetEntity($entityName, $entityID);
2058          # Return an existence indicator.          # Return an existence indicator.
2059          my $retVal = ($testInstance ? 1 : 0);          my $retVal = ($testInstance ? 1 : 0);
# Line 1688  Line 2079 
2079  =back  =back
2080    
2081  =cut  =cut
2082    #: Return Type $;
2083  sub FeatureTranslation {  sub FeatureTranslation {
2084          # Get the parameters.          # Get the parameters.
2085          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2086          # Get the specified feature's translation.          # Get the specified feature's translation.
2087          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
2088          return $retVal;          return $retVal;
# Line 1721  Line 2111 
2111  =back  =back
2112    
2113  =cut  =cut
2114    #: Return Type @;
2115  sub Taxonomy {  sub Taxonomy {
2116          # Get the parameters.          # Get the parameters.
2117          my $self = shift @_;      my ($self, $genome) = @_;
         my ($genome) = @_;  
2118          # Find the specified genome's taxonomy string.          # Find the specified genome's taxonomy string.
2119          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);
2120          # Declare the return variable.          # Declare the return variable.
# Line 1765  Line 2154 
2154  =back  =back
2155    
2156  =cut  =cut
2157    #: Return Type $;
2158  sub CrudeDistance {  sub CrudeDistance {
2159          # Get the parameters.          # Get the parameters.
2160          my $self = shift @_;      my ($self, $genome1, $genome2) = @_;
         my ($genome1, $genome2) = @_;  
2161          # Insure that the distance is commutative by sorting the genome IDs.          # Insure that the distance is commutative by sorting the genome IDs.
2162          my ($genomeA, $genomeB);          my ($genomeA, $genomeB);
2163          if ($genome2 < $genome2) {          if ($genome2 < $genome2) {
# Line 1813  Line 2201 
2201  =back  =back
2202    
2203  =cut  =cut
2204    #: Return Type $;
2205  sub RoleName {  sub RoleName {
2206          # Get the parameters.          # Get the parameters.
2207          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2208          # Get the specified role's name.          # Get the specified role's name.
2209          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);
2210          # Use the ID if the role has no name.          # Use the ID if the role has no name.
# Line 1847  Line 2234 
2234  =back  =back
2235    
2236  =cut  =cut
2237    #: Return Type @;
2238  sub RoleDiagrams {  sub RoleDiagrams {
2239          # Get the parameters.          # Get the parameters.
2240          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2241          # Query for the diagrams.          # Query for the diagrams.
2242          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2243                                                                  'RoleOccursIn(to-link)');                                                                  'RoleOccursIn(to-link)');
# Line 1859  Line 2245 
2245          return @retVal;          return @retVal;
2246  }  }
2247    
2248    =head3 GetProperties
2249    
2250    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2251    
2252    Return a list of the properties with the specified characteristics.
2253    
2254    Properties are arbitrary key-value pairs associated with a feature. (At some point they
2255    will also be associated with genomes.) A property value is represented by a 4-tuple of
2256    the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2257    
2258    =over 4
2259    
2260    =item fid
2261    
2262    ID of the feature possessing the property.
2263    
2264    =item key
2265    
2266    Name or key of the property.
2267    
2268    =item value
2269    
2270    Value of the property.
2271    
2272    =item url
2273    
2274    URL of the document that indicated the property should have this particular value, or an
2275    empty string if no such document exists.
2276    
2277    =back
2278    
2279    The parameters act as a filter for the desired data. Any non-null parameter will
2280    automatically match all the tuples returned. So, specifying just the I<$fid> will
2281    return all the properties of the specified feature; similarly, specifying the I<$key>
2282    and I<$value> parameters will return all the features having the specified property
2283    value.
2284    
2285    A single property key can have many values, representing different ideas about the
2286    feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2287    virulent, and another may declare that it is not virulent. A query about the virulence of
2288    C<fig|83333.1.peg.10> would be coded as
2289    
2290        my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2291    
2292    Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2293    not to be filtered. The tuples returned would be
2294    
2295        ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2296        ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2297    
2298    =cut
2299    #: Return Type @@;
2300    sub GetProperties {
2301        # Get the parameters.
2302        my ($self, @parms) = @_;
2303        # Declare the return variable.
2304        my @retVal = ();
2305        # Now we need to create a WHERE clause that will get us the data we want. First,
2306        # we create a list of the columns containing the data for each parameter.
2307        my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2308                        'Property(property-value)', 'HasProperty(evidence)');
2309        # Now we build the WHERE clause and the list of parameter values.
2310        my @where = ();
2311        my @values = ();
2312        for (my $i = 0; $i <= $#colNames; $i++) {
2313            my $parm = $parms[$i];
2314            if (defined $parm && ($parm ne '')) {
2315                push @where, "$colNames[$i] = ?";
2316                push @values, $parm;
2317            }
2318        }
2319        # Format the WHERE clause.
2320        my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2321        # Ask for all the propertie values with the desired characteristics.
2322        my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2323        while (my $valueObject = $query->Fetch()) {
2324            my @tuple = $valueObject->Values(\@colNames);
2325            push @retVal, \@tuple;
2326        }
2327        # Return the result.
2328        return @retVal;
2329    }
2330    
2331  =head3 FeatureProperties  =head3 FeatureProperties
2332    
2333  C<< my @properties = $sprout->FeatureProperties($featureID); >>  C<< my @properties = $sprout->FeatureProperties($featureID); >>
# Line 1885  Line 2354 
2354  =back  =back
2355    
2356  =cut  =cut
2357    #: Return Type @@;
2358  sub FeatureProperties {  sub FeatureProperties {
2359          # Get the parameters.          # Get the parameters.
2360          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2361          # Get the properties.          # Get the properties.
2362          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],
2363                                                          ['Property(property-name)', 'Property(property-value)',                                                          ['Property(property-name)', 'Property(property-value)',
# Line 1917  Line 2385 
2385  =back  =back
2386    
2387  =cut  =cut
2388    #: Return Type $;
2389  sub DiagramName {  sub DiagramName {
2390          # Get the parameters.          # Get the parameters.
2391          my $self = shift @_;      my ($self, $diagramID) = @_;
         my ($diagramID) = @_;  
2392          # Get the specified diagram's name and return it.          # Get the specified diagram's name and return it.
2393          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);
2394          return $retVal;          return $retVal;
# Line 1950  Line 2417 
2417  =back  =back
2418    
2419  =cut  =cut
2420    #: Return Type @;
2421  sub MergedAnnotations {  sub MergedAnnotations {
2422          # Get the parameters.          # Get the parameters.
2423          my $self = shift @_;      my ($self, $list) = @_;
         my ($list) = @_;  
2424          # Create a list to hold the annotation tuples found.          # Create a list to hold the annotation tuples found.
2425          my @tuples = ();          my @tuples = ();
2426          # Loop through the features in the input list.          # Loop through the features in the input list.
# Line 1969  Line 2435 
2435          }          }
2436          # Sort the result list by timestamp.          # Sort the result list by timestamp.
2437          my @retVal = sort { $a->[1] <=> $b->[1] } @tuples;          my @retVal = sort { $a->[1] <=> $b->[1] } @tuples;
2438        # Loop through and make the time stamps friendly.
2439        for my $tuple (@retVal) {
2440            $tuple->[1] = FriendlyTimestamp($tuple->[1]);
2441        }
2442          # Return the sorted list.          # Return the sorted list.
2443          return @retVal;          return @retVal;
2444  }  }
# Line 1995  Line 2465 
2465  =back  =back
2466    
2467  =cut  =cut
2468    #: Return Type @;
2469  sub RoleNeighbors {  sub RoleNeighbors {
2470          # Get the parameters.          # Get the parameters.
2471          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2472          # Get all the diagrams containing this role.          # Get all the diagrams containing this role.
2473          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2474                                                                    'RoleOccursIn(to-link)');                                                                    'RoleOccursIn(to-link)');
# Line 2038  Line 2507 
2507  =back  =back
2508    
2509  =cut  =cut
2510    #: Return Type @;
2511  sub FeatureLinks {  sub FeatureLinks {
2512          # Get the parameters.          # Get the parameters.
2513          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2514          # Get the feature's links.          # Get the feature's links.
2515          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);
2516          # Return the feature's links.          # Return the feature's links.
# Line 2054  Line 2522 
2522  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2523    
2524  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
2525  to the role the feature performs.  to the roles the feature performs.
2526    
2527  =over 4  =over 4
2528    
# Line 2064  Line 2532 
2532    
2533  =item RETURN  =item RETURN
2534    
2535  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.
2536    
2537  =back  =back
2538    
2539  =cut  =cut
2540    #: Return Type %@;
2541  sub SubsystemsOf {  sub SubsystemsOf {
2542          # Get the parameters.          # Get the parameters.
2543          my $self = shift @_;      my ($self, $featureID) = @_;
2544          my ($featureID) = @_;      # Get the subsystem list.
         # Use the SSCell to connect features to subsystems.  
2545          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2546                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2547                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
# Line 2082  Line 2549 
2549          my %retVal = ();          my %retVal = ();
2550          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
2551          for my $record (@subsystems) {          for my $record (@subsystems) {
2552                  $retVal{$record->[0]} = $record->[1];          my ($subsys, $role) = @{$record};
2553            if (exists $retVal{$subsys}) {
2554                push @{$retVal{$subsys}}, $role;
2555            } else {
2556                $retVal{$subsys} = [$role];
2557            }
2558          }          }
2559          # Return the hash.          # Return the hash.
2560          return %retVal;          return %retVal;
2561  }  }
2562    
2563    =head3 SubsystemList
2564    
2565    C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2566    
2567    Return a list containing the names of the subsystems in which the specified
2568    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2569    subsystem names, not the roles.
2570    
2571    =over 4
2572    
2573    =item featureID
2574    
2575    ID of the feature whose subsystem names are desired.
2576    
2577    =item RETURN
2578    
2579    Returns a list of the names of the subsystems in which the feature participates.
2580    
2581    =back
2582    
2583    =cut
2584    #: Return Type @;
2585    sub SubsystemList {
2586        # Get the parameters.
2587        my ($self, $featureID) = @_;
2588        # Get the list of names.
2589        my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",
2590                                    [$featureID], 'HasSSCell(from-link)');
2591        # Return the result.
2592        return @retVal;
2593    }
2594    
2595  =head3 RelatedFeatures  =head3 RelatedFeatures
2596    
2597  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2118  Line 2622 
2622  =back  =back
2623    
2624  =cut  =cut
2625    #: Return Type @;
2626  sub RelatedFeatures {  sub RelatedFeatures {
2627          # Get the parameters.          # Get the parameters.
2628          my $self = shift @_;      my ($self, $featureID, $function, $userID) = @_;
         my ($featureID, $function, $userID) = @_;  
2629          # 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.
2630          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],
2631                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],
# Line 2167  Line 2670 
2670  =back  =back
2671    
2672  =cut  =cut
2673    #: Return Type @;
2674  sub TaxonomySort {  sub TaxonomySort {
2675          # Get the parameters.          # Get the parameters.
2676          my $self = shift @_;      my ($self, $featureIDs) = @_;
         my ($featureIDs) = @_;  
2677          # Create the working hash table.          # Create the working hash table.
2678          my %hashBuffer = ();          my %hashBuffer = ();
2679          # Loop through the features.          # Loop through the features.
# Line 2180  Line 2682 
2682                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
2683                                                                                  [$fid], 'Genome(taxonomy)');                                                                                  [$fid], 'Genome(taxonomy)');
2684                  # Add this feature to the hash buffer.                  # Add this feature to the hash buffer.
2685                  if (exists $hashBuffer{$taxonomy}) {          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);
                         push @{$hashBuffer{$taxonomy}}, $fid;  
                 } else {  
                         $hashBuffer{$taxonomy} = [$fid];  
                 }  
2686          }          }
2687          # Sort the keys and get the elements.          # Sort the keys and get the elements.
2688          my @retVal = ();          my @retVal = ();
# Line 2250  Line 2748 
2748  =back  =back
2749    
2750  =cut  =cut
2751    #: Return Type @@;
2752  sub GetAll {  sub GetAll {
2753          # Get the parameters.          # Get the parameters.
2754          my $self = shift @_;      my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
2755          my ($objectNames, $filterClause, $parameterList, $fields, $count) = @_;      # Call the ERDB method.
2756          # Create the query.      my @retVal = $self->{_erdb}->GetAll($objectNames, $filterClause, $parameterList,
2757          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++;  
         }  
2758          # Return the resulting list.          # Return the resulting list.
2759          return @retVal;          return @retVal;
2760  }  }
# Line 2312  Line 2796 
2796  =back  =back
2797    
2798  =cut  =cut
2799    #: Return Type @;
2800  sub GetFlat {  sub GetFlat {
2801          # Get the parameters.          # Get the parameters.
2802          my $self = shift @_;      my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
         my ($objectNames, $filterClause, $parameterList, $field) = @_;  
2803          # Construct the query.          # Construct the query.
2804          my $query = $self->Get($objectNames, $filterClause, $parameterList);          my $query = $self->Get($objectNames, $filterClause, $parameterList);
2805          # Create the result list.          # Create the result list.
# Line 2423  Line 2906 
2906  to load the entire database.  to load the entire database.
2907    
2908  =cut  =cut
2909    #: Return Type @;
2910  sub LoadInfo {  sub LoadInfo {
2911          # Get the parameters.          # Get the parameters.
2912          my $self = shift @_;      my ($self) = @_;
2913          # 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.
2914          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
2915          # Concatenate the table names.          # Concatenate the table names.
# Line 2460  Line 2943 
2943  =back  =back
2944    
2945  =cut  =cut
2946    #: Return Type %;
2947  sub LowBBHs {  sub LowBBHs {
2948          # Get the parsameters.          # Get the parsameters.
2949          my $self = shift @_;      my ($self, $featureID, $cutoff) = @_;
         my ($featureID, $cutoff) = @_;  
2950          # Create the return hash.          # Create the return hash.
2951          my %retVal = ();          my %retVal = ();
2952          # Create a query to get the desired BBHs.          # Create a query to get the desired BBHs.
# Line 2480  Line 2962 
2962          return %retVal;          return %retVal;
2963  }  }
2964    
2965    =head3 GetGroups
2966    
2967    C<< my %groups = $sprout->GetGroups(\@groupList); >>
2968    
2969    Return a hash mapping each group to the IDs of the genomes in the group.
2970    A list of groups may be specified, in which case only those groups will be
2971    shown. Alternatively, if no parameter is supplied, all groups will be
2972    included. Genomes that are not in any group are omitted.
2973    
2974    =cut
2975    #: Return Type %@;
2976    sub GetGroups {
2977        # Get the parameters.
2978        my ($self, $groupList) = @_;
2979        # Declare the return value.
2980        my %retVal = ();
2981        # Determine whether we are getting all the groups or just some.
2982        if (defined $groupList) {
2983            # Here we have a group list. Loop through them individually,
2984            # getting a list of the relevant genomes.
2985            for my $group (@{$groupList}) {
2986                my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",
2987                    [$group], "Genome(id)");
2988                $retVal{$group} = \@genomeIDs;
2989            }
2990        } else {
2991            # Here we need all of the groups. In this case, we run through all
2992            # of the genome records, putting each one found into the appropriate
2993            # group. Note that we use a filter clause to insure that only genomes
2994            # in groups are included in the return set.
2995            my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],
2996                                        ['Genome(id)', 'Genome(group-name)']);
2997            # Loop through the genomes found.
2998            for my $genome (@genomes) {
2999                # Pop this genome's ID off the current list.
3000                my @groups = @{$genome};
3001                my $genomeID = shift @groups;
3002                # Loop through the groups, adding the genome ID to each group's
3003                # list.
3004                for my $group (@groups) {
3005                    Tracer::AddToListMap(\%retVal, $group, $genomeID);
3006                }
3007            }
3008        }
3009        # Return the hash we just built.
3010        return %retVal;
3011    }
3012    
3013    =head3 MyGenomes
3014    
3015    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
3016    
3017    Return a list of the genomes to be included in the Sprout.
3018    
3019    This method is provided for use during the Sprout load. It presumes the Genome load file has
3020    already been created. (It will be in the Sprout data directory and called either C<Genome>
3021    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3022    IDs.
3023    
3024    =over 4
3025    
3026    =item dataDir
3027    
3028    Directory containing the Sprout load files.
3029    
3030    =back
3031    
3032    =cut
3033    #: Return Type @;
3034    sub MyGenomes {
3035        # Get the parameters.
3036        my ($dataDir) = @_;
3037        # Compute the genome file name.
3038        my $genomeFileName = LoadFileName($dataDir, "Genome");
3039        # Extract the genome IDs from the files.
3040        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3041        # Return the result.
3042        return @retVal;
3043    }
3044    
3045    =head3 LoadFileName
3046    
3047    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3048    
3049    Return the name of the load file for the specified table in the specified data
3050    directory.
3051    
3052    =over 4
3053    
3054    =item dataDir
3055    
3056    Directory containing the Sprout load files.
3057    
3058    =item tableName
3059    
3060    Name of the table whose load file is desired.
3061    
3062    =item RETURN
3063    
3064    Returns the name of the file containing the load data for the specified table, or
3065    C<undef> if no load file is present.
3066    
3067    =back
3068    
3069    =cut
3070    #: Return Type $;
3071    sub LoadFileName {
3072        # Get the parameters.
3073        my ($dataDir, $tableName) = @_;
3074        # Declare the return variable.
3075        my $retVal;
3076        # Check for the various file names.
3077        if (-e "$dataDir/$tableName") {
3078            $retVal = "$dataDir/$tableName";
3079        } elsif (-e "$dataDir/$tableName.dtx") {
3080            $retVal = "$dataDir/$tableName.dtx";
3081        }
3082        # Return the result.
3083        return $retVal;
3084    }
3085    
3086  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3087    
3088  =head3 ParseAssignment  =head3 ParseAssignment
3089    
3090  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,
3091  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
3092  will be returned.  isn't, an empty list will be returned.
3093    
3094    A functional assignment is always of the form
3095    
3096        I<XXXX>C<\nset >I<YYYY>C< function to\n>I<ZZZZZ>
3097    
3098    where I<XXXX> is the B<assigning user>, I<YYYY> is the B<user>, and I<ZZZZ> is the
3099    actual functional role. In most cases, the user and the assigning user will be the
3100    same, but that is not always the case.
3101    
3102  This is a static method.  This is a static method.
3103    
# Line 2505  Line 3116 
3116    
3117  =cut  =cut
3118    
3119  sub ParseAssignment {  sub _ParseAssignment {
3120          # Get the parameters.          # Get the parameters.
3121          my ($text) = @_;          my ($text) = @_;
3122          # Declare the return value.          # Declare the return value.
3123          my @retVal = ();          my @retVal = ();
3124          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3125          my ($user, $type, $function) = split(/\n/, $text);          my ($user, $type, $function) = split(/\n/, $text);
3126          if ($type =~ m/^set $user function to$/i) {      if ($type =~ m/^set ([^ ]+) function to$/i) {
3127                  # 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,
3128                  @retVal = ($user, $function);          # and the assigning user.
3129            @retVal = ($1, $function, $user);
3130          }          }
3131          # Return the result list.          # Return the result list.
3132          return @retVal;          return @retVal;
3133  }  }
3134    
3135    =head3 FriendlyTimestamp
3136    
3137    Convert a time number to a user-friendly time stamp for display.
3138    
3139    This is a static method.
3140    
3141    =over 4
3142    
3143    =item timeValue
3144    
3145    Numeric time value.
3146    
3147    =item RETURN
3148    
3149    Returns a string containing the same time in user-readable format.
3150    
3151    =back
3152    
3153    =cut
3154    
3155    sub FriendlyTimestamp {
3156        my ($timeValue) = @_;
3157        my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));
3158        return $retVal;
3159    }
3160    
3161    =head3 AddProperty
3162    
3163    C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>
3164    
3165    Add a new attribute value (Property) to a feature. In the SEED system, attributes can
3166    be added to almost any object. In Sprout, they can only be added to features. In
3167    Sprout, attributes are implemented using I<properties>. A property represents a key/value
3168    pair. If the particular key/value pair coming in is not already in the database, a new
3169    B<Property> record is created to hold it.
3170    
3171    =over 4
3172    
3173    =item peg
3174    
3175    ID of the feature to which the attribute is to be replied.
3176    
3177    =item key
3178    
3179    Name of the attribute (key).
3180    
3181    =item value
3182    
3183    Value of the attribute.
3184    
3185    =item url
3186    
3187    URL or text citation from which the property was obtained.
3188    
3189    =back
3190    
3191    =cut
3192    #: Return Type ;
3193    sub AddProperty {
3194        # Get the parameters.
3195        my ($self, $featureID, $key, $value, $url) = @_;
3196        # Declare the variable to hold the desired property ID.
3197        my $propID;
3198        # Attempt to find a property record for this key/value pair.
3199        my @properties = $self->GetFlat(['Property'],
3200                                       "Property(property-name) = ? AND Property(property-value) = ?",
3201                                       [$key, $value], 'Property(id)');
3202        if (@properties) {
3203            # Here the property is already in the database. We save its ID.
3204            $propID = $properties[0];
3205            # Here the property value does not exist. We need to generate an ID. It will be set
3206            # to a number one greater than the maximum value in the database. This call to
3207            # GetAll will stop after one record.
3208            my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],
3209                                            1);
3210            $propID = $maxProperty[0]->[0] + 1;
3211            # Insert the new property value.
3212            $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });
3213        }
3214        # Now we connect the incoming feature to the property.
3215        $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3216    }
3217    
3218    
3219    
3220  1;  1;

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3