[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.19, Sun Aug 14 23:32:08 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 85  Line 86 
86          # 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
87          # the incoming data.          # the incoming data.
88          my $optionTable = Tracer::GetOptions({          my $optionTable = Tracer::GetOptions({
89                                             dbType               => 'mysql',                     # database type                         dbType       => $FIG_Config::dbms,
90                                             dataDir              => 'Data',                      # data file directory                                                          # database type
91                                             xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
92                                             userData             => 'root/',                     # user name and password                                                          # data file directory
93                                             port                 => 0,                           # database connection port                         xmlFileName  => "$FIG_Config::sproutData/SproutDBD.xml",
94                                                            # database definition file name
95                           userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
96                                                            # user name and password
97                           port         => $FIG_Config::dbport,
98                                                            # database connection port
99                                             maxSegmentLength => 4500,            # maximum feature segment length                                             maxSegmentLength => 4500,            # maximum feature segment length
100                                             maxSequenceLength => 8000,           # maximum contig sequence length                                             maxSequenceLength => 8000,           # maximum contig sequence length
101                                            }, $options);                                            }, $options);
# Line 121  Line 127 
127  and 10999.  and 10999.
128    
129  =cut  =cut
130    #: Return Type $;
131  sub MaxSegment {  sub MaxSegment {
132          my $self = shift @_;      my ($self) = @_;
133          return $self->{_options}->{maxSegmentLength};          return $self->{_options}->{maxSegmentLength};
134  }  }
135    
# Line 136  Line 142 
142  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.
143    
144  =cut  =cut
145    #: Return Type $;
146  sub MaxSequence {  sub MaxSequence {
147          my $self = shift @_;      my ($self) = @_;
148          return $self->{_options}->{maxSequenceLength};          return $self->{_options}->{maxSequenceLength};
149  }  }
150    
# Line 231  Line 237 
237    
238  sub Get {  sub Get {
239          # Get the parameters.          # Get the parameters.
240          my $self = shift @_;      my ($self, $objectNames, $filterClause, $parameterList) = @_;
         my ($objectNames, $filterClause, $parameterList) = @_;  
241          # 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
242          # 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
243          # 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 273 
273    
274  sub GetEntity {  sub GetEntity {
275          # Get the parameters.          # Get the parameters.
276          my $self = shift @_;      my ($self, $entityType, $ID) = @_;
277          my ($entityType, $ID) = @_;      # Call the ERDB method.
278          # 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;  
279  }  }
280    
281  =head3 GetEntityValues  =head3 GetEntityValues
# Line 305  Line 305 
305  =back  =back
306    
307  =cut  =cut
308    #: Return Type @;
309  sub GetEntityValues {  sub GetEntityValues {
310          # Get the parameters.          # Get the parameters.
311          my $self = shift @_;      my ($self, $entityType, $ID, $fields) = @_;
312          my ($entityType, $ID, $fields) = @_;      # Call the ERDB method.
313          # 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;  
314  }  }
315    
316  =head3 ShowMetaData  =head3 ShowMetaData
# Line 340  Line 331 
331    
332  sub ShowMetaData {  sub ShowMetaData {
333          # Get the parameters.          # Get the parameters.
334          my $self = shift @_;      my ($self, $fileName) = @_;
         my ($fileName) = @_;  
335          # Compute the file name.          # Compute the file name.
336          my $options = $self->{_options};          my $options = $self->{_options};
337          # Call the show method on the underlying ERDB object.          # Call the show method on the underlying ERDB object.
# Line 378  Line 368 
368  =back  =back
369    
370  =cut  =cut
371    #: Return Type %;
372  sub Load {  sub Load {
373          # Get the parameters.          # Get the parameters.
374          my $self = shift @_;      my ($self, $rebuild) = @_;
         my ($rebuild) = @_;  
375          # Get the database object.          # Get the database object.
376          my $erdb = $self->{_erdb};          my $erdb = $self->{_erdb};
377          # Load the tables from the data directory.          # Load the tables from the data directory.
# Line 422  Line 411 
411  =back  =back
412    
413  =cut  =cut
414    #: Return Type $%;
415  sub LoadUpdate {  sub LoadUpdate {
416          # Get the parameters.          # Get the parameters.
417          my $self = shift @_;      my ($self, $truncateFlag, $tableList) = @_;
         my ($truncateFlag, $tableList) = @_;  
418          # Get the database object.          # Get the database object.
419          my $erdb = $self->{_erdb};          my $erdb = $self->{_erdb};
420          # Declare the return value.          # Declare the return value.
# Line 437  Line 425 
425          # Loop through the incoming table names.          # Loop through the incoming table names.
426          for my $tableName (@{$tableList}) {          for my $tableName (@{$tableList}) {
427                  # Find the table's file.                  # Find the table's file.
428                  my $fileName = "$dataDir/$tableName";          my $fileName = LoadFileName($dataDir, $tableName);
429                  if (! -e $fileName) {          if (! $fileName) {
430                          $fileName = "$fileName.dtx";              Trace("No load file found for $tableName in $dataDir.") if T(0);
431                  }          } else {
432                  # Attempt to load this table.                  # Attempt to load this table.
433                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);
434                  # Accumulate the resulting statistics.                  # Accumulate the resulting statistics.
435                  $retVal->Accumulate($result);                  $retVal->Accumulate($result);
436          }          }
437        }
438          # Return the statistics.          # Return the statistics.
439          return $retVal;          return $retVal;
440  }  }
# Line 459  Line 448 
448  changed.  changed.
449    
450  =cut  =cut
451    #: Return Type ;
452  sub Build {  sub Build {
453          # Get the parameters.          # Get the parameters.
454          my $self = shift @_;      my ($self) = @_;
455          # Create the tables.          # Create the tables.
456          $self->{_erdb}->CreateTables;          $self->{_erdb}->CreateTables;
457  }  }
# Line 474  Line 463 
463  Return a list of all the genome IDs.  Return a list of all the genome IDs.
464    
465  =cut  =cut
466    #: Return Type @;
467  sub Genomes {  sub Genomes {
468          # Get the parameters.          # Get the parameters.
469          my $self = shift @_;      my ($self) = @_;
470          # Get all the genomes.          # Get all the genomes.
471          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');
472          # Return the list of IDs.          # Return the list of IDs.
# Line 504  Line 493 
493  =back  =back
494    
495  =cut  =cut
496    #: Return Type $;
497  sub GenusSpecies {  sub GenusSpecies {
498          # Get the parameters.          # Get the parameters.
499          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
500          # Get the data for the specified genome.          # Get the data for the specified genome.
501          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',
502                                                                                                                            'Genome(unique-characterization)']);                                                                                                                            'Genome(unique-characterization)']);
# Line 541  Line 529 
529  =back  =back
530    
531  =cut  =cut
532    #: Return Type @;
533  sub FeaturesOf {  sub FeaturesOf {
534          # Get the parameters.          # Get the parameters.
535          my $self = shift @_;      my ($self, $genomeID,$ftype) = @_;
         my ($genomeID,$ftype) = @_;  
536          # Get the features we want.          # Get the features we want.
537          my @features;          my @features;
538          if (!$ftype) {          if (!$ftype) {
# Line 594  Line 581 
581  =back  =back
582    
583  =cut  =cut
584    #: Return Type @;
585    #: Return Type $;
586  sub FeatureLocation {  sub FeatureLocation {
587          # Get the parameters.          # Get the parameters.
588          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
589          # Create a query for the feature locations.          # Create a query for the feature locations.
590          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",
591                                                     [$featureID]);                                                     [$featureID]);
# Line 656  Line 643 
643  =back  =back
644    
645  =cut  =cut
646    #: Return Type @;
647  sub ParseLocation {  sub ParseLocation {
648          # Get the parameter.      # Get the parameter. Note that if we're called as an instance method, we ignore
649        # the first parameter.
650        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
651          my ($location) = @_;          my ($location) = @_;
652          # Parse it into segments.          # Parse it into segments.
653          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;
# Line 677  Line 666 
666          return ($contigID, $start, $dir, $len);          return ($contigID, $start, $dir, $len);
667  }  }
668    
669    =head3 PointLocation
670    
671    C<< my $found = Sprout::PointLocation($location, $point); >>
672    
673    Return the offset into the specified location of the specified point on the contig. If
674    the specified point is before the location, a negative value will be returned. If it is
675    beyond the location, an undefined value will be returned. It is assumed that the offset
676    is for the location's contig. The location can either be new-style (using a C<+> or C<->
677    and a length) or old-style (using C<_> and start and end positions.
678    
679    =over 4
680    
681    =item location
682    
683    A location specifier (see L</FeatureLocation> for a description).
684    
685    =item point
686    
687    The offset into the contig of the point in which we're interested.
688    
689    =item RETURN
690    
691    Returns the offset inside the specified location of the specified point, a negative
692    number if the point is before the location, or an undefined value if the point is past
693    the location. If the length of the location is 0, this method will B<always> denote
694    that it is outside the location. The offset will always be relative to the left-most
695    position in the location.
696    
697    =back
698    
699    =cut
700    #: Return Type $;
701    sub PointLocation {
702        # Get the parameter. Note that if we're called as an instance method, we ignore
703        # the first parameter.
704        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
705        my ($location, $point) = @_;
706        # Parse out the location elements. Note that this works on both old-style and new-style
707        # locations.
708        my ($contigID, $start, $dir, $len) = ParseLocation($location);
709        # Declare the return variable.
710        my $retVal;
711        # Compute the offset. The computation is dependent on the direction of the location.
712        my $offset = (($dir == '+') ? $point - $start : $point - ($start - $len + 1));
713        # Return the offset if it's valid.
714        if ($offset < $len) {
715            $retVal = $offset;
716        }
717        # Return the offset found.
718        return $retVal;
719    }
720    
721  =head3 DNASeq  =head3 DNASeq
722    
723  C<< my $sequence = $sprout->DNASeq(\@locationList); >>  C<< my $sequence = $sprout->DNASeq(\@locationList); >>
# Line 699  Line 740 
740  =back  =back
741    
742  =cut  =cut
743    #: Return Type $;
744  sub DNASeq {  sub DNASeq {
745          # Get the parameters.          # Get the parameters.
746          my $self = shift @_;      my ($self, $locationList) = @_;
         my ($locationList) = @_;  
747          # Create the return string.          # Create the return string.
748          my $retVal = "";          my $retVal = "";
749          # Loop through the locations.          # Loop through the locations.
# Line 773  Line 813 
813  =back  =back
814    
815  =cut  =cut
816    #: Return Type @;
817  sub AllContigs {  sub AllContigs {
818          # Get the parameters.          # Get the parameters.
819          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
820          # Ask for the genome's Contigs.          # Ask for the genome's Contigs.
821          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],
822                                                                  'HasContig(to-link)');                                                                  'HasContig(to-link)');
# Line 797  Line 836 
836    
837  ID of the contig whose length is desired.  ID of the contig whose length is desired.
838    
839    =item RETURN
840    
841    Returns the number of positions in the contig.
842    
843  =back  =back
844    
845  =cut  =cut
846    #: Return Type $;
847  sub ContigLength {  sub ContigLength {
848          # Get the parameters.          # Get the parameters.
849          my $self = shift @_;      my ($self, $contigID) = @_;
         my ($contigID) = @_;  
850          # Get the contig's last sequence.          # Get the contig's last sequence.
851          my $query = $self->Get(['IsMadeUpOf'],          my $query = $self->Get(['IsMadeUpOf'],
852                  "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",                  "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
# Line 846  Line 888 
888  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
889  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
890  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
891  the start and stop values.  the start and stop values. The first element (that is, the list of features) is sorted
892    roughly by location.
893    
894  =back  =back
895    
896  =cut  =cut
897    #: Return Type @@;
898  sub GenesInRegion {  sub GenesInRegion {
899          # Get the parameters.          # Get the parameters.
900          my $self = shift @_;      my ($self, $contigID, $start, $stop) = @_;
         my ($contigID, $start, $stop) = @_;  
901          # Get the maximum segment length.          # Get the maximum segment length.
902          my $maximumSegmentLength = $self->MaxSegment;          my $maximumSegmentLength = $self->MaxSegment;
903          # 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
904          # duplicates easily.      # duplicates easily. The hash key will be the feature ID. The value will be a two-element
905        # containing the minimum and maximum offsets. We will use the offsets to sort the results
906        # when we're building the result set.
907          my %featuresFound = ();          my %featuresFound = ();
908          # Prime the values we'll use for the returned beginning and end.          # Prime the values we'll use for the returned beginning and end.
909          my ($min, $max) = ($self->ContigLength($contigID), 0);      my @initialMinMax = ($self->ContigLength($contigID), 0);
910        my ($min, $max) = @initialMinMax;
911          # 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
912          # 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,
913          # 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 937 
937                                          $found = 1;                                          $found = 1;
938                                  }                                  }
939                          } elsif ($dir eq '-') {                          } elsif ($dir eq '-') {
940                                  $end = $beg - $len;                  # Note we switch things around so that the beginning is to the left of the
941                                  if ($end <= $stop) {                  # ending.
942                    ($beg, $end) = ($beg - $len, $beg);
943                    if ($beg <= $stop) {
944                                          # Denote we found a useful feature.                                          # Denote we found a useful feature.
945                                          $found = 1;                                          $found = 1;
946                                  }                                  }
947                          }                          }
948                          if ($found) {                          if ($found) {
949                                  # 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,
950                                  $featuresFound{$featureID} = 1;                  # get the current entry for the specified feature.
951                                  if ($beg < $min) { $min = $beg; }                  my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :
952                                  if ($end < $min) { $min = $end; }                                       @initialMinMax);
953                                  if ($beg > $max) { $max = $beg; }                  # Merge the current segment's begin and end into the feature begin and end and the
954                                  if ($end > $max) { $max = $end; }                  # global min and max.
955                    if ($beg < $loc1) {
956                        $loc1 = $beg;
957                        $min = $beg if $beg < $min;
958                    }
959                    if ($end > $loc2) {
960                        $loc2 = $end;
961                        $max = $end if $end > $max;
962                    }
963                    # Store the entry back into the hash table.
964                    $featuresFound{$featureID} = [$loc1, $loc2];
965                          }                          }
966                  }                  }
967          }          }
968          # 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
969          my @list = (sort (keys %featuresFound));      # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
970        # but the result of the sort will be the same.)
971        my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;
972        # Now we sort by midpoint and yank out the feature IDs.
973        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
974          # Return it along with the min and max.          # Return it along with the min and max.
975          return (\@list, $min, $max);      return (\@retVal, $min, $max);
976  }  }
977    
978  =head3 FType  =head3 FType
# Line 934  Line 995 
995  =back  =back
996    
997  =cut  =cut
998    #: Return Type $;
999  sub FType {  sub FType {
1000          # Get the parameters.          # Get the parameters.
1001          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1002          # Get the specified feature's type.          # Get the specified feature's type.
1003          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
1004          # Return the result.          # Return the result.
# Line 963  Line 1023 
1023    
1024  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1025    
1026  * B<timeStamp> time the annotation was made.  * B<timeStamp> time the annotation was made, in user-friendly format.
1027    
1028  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1029    
# Line 972  Line 1032 
1032  =back  =back
1033    
1034  =cut  =cut
1035    #: Return Type @%;
1036  sub FeatureAnnotations {  sub FeatureAnnotations {
1037          # Get the parameters.          # Get the parameters.
1038          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1039          # 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.
1040          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1041                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 990  Line 1049 
1049                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1050                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1051                  # Assemble them into a hash.                  # Assemble them into a hash.
1052                  my $annotationHash = { featureID => $featureID, timeStamp => $timeStamp,          my $annotationHash = { featureID => $featureID,
1053                                   timeStamp => FriendlyTimestamp($timeStamp),
1054                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1055                  # Add it to the return list.                  # Add it to the return list.
1056                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1004  Line 1064 
1064  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>
1065    
1066  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
1067  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,
1068  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
1069  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,
1070  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.
1071  features only have a small number of annotations.  Finally, if a single user has multiple functional assignments, we will only keep the most
1072    recent one.
1073    
1074  =over 4  =over 4
1075    
# Line 1016  Line 1077 
1077    
1078  ID of the feature whose functional assignments are desired.  ID of the feature whose functional assignments are desired.
1079    
1080    =item RETURN
1081    
1082    Returns a hash mapping the functional assignment IDs to user IDs.
1083    
1084  =back  =back
1085    
1086  =cut  =cut
1087    #: Return Type %;
1088  sub AllFunctionsOf {  sub AllFunctionsOf {
1089          # Get the parameters.          # Get the parameters.
1090          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1091          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1092          my @query = $self->GetFlat(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],
1093                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1094                                                          [$featureID], 'Annotation(annotation)');                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);
1095          # Declare the return hash.          # Declare the return hash.
1096          my %retVal;          my %retVal;
1097        # Declare a hash for insuring we only make one assignment per user.
1098        my %timeHash = ();
1099        # Now we sort the assignments by timestamp in reverse.
1100        my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1101          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1102          for my $text (@query) {      for my $annotation (@sortedQuery) {
1103            # Get the annotation fields.
1104            my ($timeStamp, $text) = @{$annotation};
1105                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1106                  my ($user, $function) = ParseAssignment($text);          my ($user, $function) = _ParseAssignment($text);
1107                  if ($user) {          if ($user && ! exists $timeHash{$user}) {
1108                          # Here it is, so stuff it in the return hash.              # Here it is a functional assignment and there has been no
1109                # previous assignment for this user, so we stuff it in the
1110                # return hash.
1111                          $retVal{$function} = $user;                          $retVal{$function} = $user;
1112                # Insure we don't assign to this user again.
1113                $timeHash{$user} = 1;
1114                  }                  }
1115          }          }
1116          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1047  Line 1121 
1121    
1122  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>
1123    
1124  Return the most recently-determined functional assignment of a particular feature. A functional  Return the most recently-determined functional assignment of a particular feature.
1125  assignment is a type of annotation. It has the format "XXXX\nset XXXX function to\nYYYYY". In this  
1126  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
1127  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
1128  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
1129    L</ParseLocation>. Its worth noting that we cannot filter on the content of the
1130    annotation itself because it's a text field; however, this is not a big problem because
1131    most features only have a small number of annotations.
1132    
1133    Each user has an associated list of trusted users. The assignment returned will be the most
1134    recent one by at least one of the trusted users. If no trusted user list is available, then
1135    the specified user and FIG are considered trusted. If the user ID is omitted, only FIG
1136    is trusted.
1137    
1138    If the feature is B<not> identified by a FIG ID, then the functional assignment
1139    information is taken from the B<ExternalAliasFunc> table. If the table does
1140    not contain an entry for the feature, an undefined value is returned.
1141    
1142  =over 4  =over 4
1143    
# Line 1061  Line 1147 
1147    
1148  =item userID (optional)  =item userID (optional)
1149    
1150  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
1151    C<FIG> assignment will be returned.
1152    
1153  =item RETURN  =item RETURN
1154    
# Line 1070  Line 1157 
1157  =back  =back
1158    
1159  =cut  =cut
1160    #: Return Type $;
1161  sub FunctionOf {  sub FunctionOf {
1162          # Get the parameters.          # Get the parameters.
1163          my $self = shift @_;      my ($self, $featureID, $userID) = @_;
1164          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.  
1165          my $retVal;          my $retVal;
1166        # Determine the ID type.
1167        if ($featureID =~ m/^fig\|/) {
1168            # Here we have a FIG feature ID. We must build the list of trusted
1169            # users.
1170            my %trusteeTable = ();
1171            # Check the user ID.
1172            if (!$userID) {
1173                # No user ID, so only FIG is trusted.
1174                $trusteeTable{FIG} = 1;
1175            } else {
1176                # Add this user's ID.
1177                $trusteeTable{$userID} = 1;
1178                # Look for the trusted users in the database.
1179                my @trustees = $self->GetFlat(['IsTrustedBy'], 'IsTrustedBy(from-link) = ?', [$userID], 'IsTrustedBy(to-link)');
1180                if (! @trustees) {
1181                    # None were found, so build a default list.
1182                    $trusteeTable{FIG} = 1;
1183                } else {
1184                    # Otherwise, put all the trustees in.
1185                    for my $trustee (@trustees) {
1186                        $trusteeTable{$trustee} = 1;
1187                    }
1188                }
1189            }
1190            # Build a query for all of the feature's annotations, sorted by date.
1191            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],
1192                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1193                                   [$featureID]);
1194          my $timeSelected = 0;          my $timeSelected = 0;
1195          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1196          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1197                  # Get the annotation text.                  # Get the annotation text.
1198                  my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);                  my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);
1199                  # 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.
1200                  my ($user, $type, $function) = split(/\n/, $text);              my ($user, $function) = _ParseAssignment($text);
1201                  if ($type =~ m/^set $userID function to$/i) {              if ($user) {
1202                          # 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
1203                          if ($time > $timeSelected) {                  # name. The time must be recent and the user must be trusted.
1204                    if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {
1205                                  $retVal = $function;                                  $retVal = $function;
1206                                  $timeSelected = $time;                                  $timeSelected = $time;
1207                          }                          }
1208                  }                  }
1209          }          }
1210        } else {
1211            # Here we have a non-FIG feature ID. In this case the user ID does not
1212            # matter. We simply get the information from the External Alias Function
1213            # table.
1214            ($retVal) = $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']);
1215        }
1216          # Return the assignment found.          # Return the assignment found.
1217          return $retVal;          return $retVal;
1218  }  }
# Line 1120  Line 1236 
1236    
1237  =item RETURN  =item RETURN
1238    
1239  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
1240  their best hits.  on the target genome.
1241    
1242  =back  =back
1243    
1244  =cut  =cut
1245    #: Return Type %;
1246  sub BBHList {  sub BBHList {
1247          # Get the parameters.          # Get the parameters.
1248          my $self = shift @_;      my ($self, $genomeID, $featureList) = @_;
         my ($genomeID, $featureList) = @_;  
1249          # Create the return structure.          # Create the return structure.
1250          my %retVal = ();          my %retVal = ();
1251          # Loop through the incoming features.          # Loop through the incoming features.
# Line 1150  Line 1265 
1265          return \%retVal;          return \%retVal;
1266  }  }
1267    
1268    =head3 SimList
1269    
1270    C<< my %similarities = $sprout->SimList($featureID, $count); >>
1271    
1272    Return a list of the similarities to the specified feature.
1273    
1274    Sprout does not support real similarities, so this method just returns the bidirectional
1275    best hits.
1276    
1277    =over 4
1278    
1279    =item featureID
1280    
1281    ID of the feature whose similarities are desired.
1282    
1283    =item count
1284    
1285    Maximum number of similar features to be returned, or C<0> to return them all.
1286    
1287    =back
1288    
1289    =cut
1290    #: Return Type %;
1291    sub SimList {
1292        # Get the parameters.
1293        my ($self, $featureID, $count) = @_;
1294        # Ask for the best hits.
1295        my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],
1296                                  "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",
1297                                  [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],
1298                                  $count);
1299        # Create the return value.
1300        my %retVal = ();
1301        for my $tuple (@lists) {
1302            $retVal{$tuple->[0]} = $tuple->[1];
1303        }
1304        # Return the result.
1305        return %retVal;
1306    }
1307    
1308    
1309    
1310    =head3 IsComplete
1311    
1312    C<< my $flag = $sprout->IsComplete($genomeID); >>
1313    
1314    Return TRUE if the specified genome is complete, else FALSE.
1315    
1316    =over 4
1317    
1318    =item genomeID
1319    
1320    ID of the genome whose completeness status is desired.
1321    
1322    =item RETURN
1323    
1324    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1325    not found.
1326    
1327    =back
1328    
1329    =cut
1330    #: Return Type $;
1331    sub IsComplete {
1332        # Get the parameters.
1333        my ($self, $genomeID) = @_;
1334        # Declare the return variable.
1335        my $retVal;
1336        # Get the genome's data.
1337        my $genomeData = $self->GetEntity('Genome', $genomeID);
1338        if ($genomeData) {
1339            # The genome exists, so get the completeness flag.
1340            ($retVal) = $genomeData->Value('complete');
1341        }
1342        # Return the result.
1343        return $retVal;
1344    }
1345    
1346  =head3 FeatureAliases  =head3 FeatureAliases
1347    
1348  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
# Line 1170  Line 1363 
1363  =back  =back
1364    
1365  =cut  =cut
1366    #: Return Type @;
1367  sub FeatureAliases {  sub FeatureAliases {
1368          # Get the parameters.          # Get the parameters.
1369          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1370          # Get the desired feature's aliases          # Get the desired feature's aliases
1371          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);
1372          # Return the result.          # Return the result.
# Line 1201  Line 1393 
1393  =back  =back
1394    
1395  =cut  =cut
1396    #: Return Type $;
1397  sub GenomeOf {  sub GenomeOf {
1398          # Get the parameters.          # Get the parameters.
1399          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1400          # Create a query to find the genome associated with the feature.          # Create a query to find the genome associated with the feature.
1401          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);
1402          # Declare the return value.          # Declare the return value.
# Line 1238  Line 1429 
1429  =back  =back
1430    
1431  =cut  =cut
1432    #: Return Type %;
1433  sub CoupledFeatures {  sub CoupledFeatures {
1434          # Get the parameters.          # Get the parameters.
1435          my $self = shift @_;      my ($self, $featureID) = @_;
1436          my ($featureID) = @_;      # Create a query to retrieve the functionally-coupled features.
1437          # Create a query to retrieve the functionally-coupled features. Note that we depend on the      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1438          # 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]);  
1439          # 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.
1440          my $found = 0;          my $found = 0;
1441          # Create the return hash.          # Create the return hash.
1442          my %retVal = ();          my %retVal = ();
1443          # Retrieve the relationship records and store them in the hash.          # Retrieve the relationship records and store them in the hash.
1444          while (my $clustering = $query->Fetch()) {          while (my $clustering = $query->Fetch()) {
1445                  my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',          # Get the ID and score of the coupling.
1446                                                                      'IsClusteredOnChromosomeWith(score)']);          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1447                                                            'Coupling(score)']);
1448            # The coupling ID contains the two feature IDs separated by a space. We use
1449            # this information to find the ID of the other feature.
1450            my ($fid1, $fid2) = split / /, $couplingID;
1451            my $otherFeatureID = ($featureID eq $fid1 ? $fid2 : $fid1);
1452            # Attach the other feature's score to its ID.
1453                  $retVal{$otherFeatureID} = $score;                  $retVal{$otherFeatureID} = $score;
1454                  $found = 1;                  $found = 1;
1455          }          }
# Line 1268  Line 1462 
1462          return %retVal;          return %retVal;
1463  }  }
1464    
1465    =head3 CouplingEvidence
1466    
1467    C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1468    
1469    Return the evidence for a functional coupling.
1470    
1471    A pair of features is considered evidence of a coupling between two other
1472    features if they occur close together on a contig and both are similar to
1473    the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1474    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1475    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1476    similar to B<A2>.
1477    
1478    The score of a coupling is determined by the number of pieces of evidence
1479    that are considered I<representative>. If several evidence items belong to
1480    a group of genomes that are close to each other, only one of those items
1481    is considered representative. The other evidence items are presumed to be
1482    there because of the relationship between the genomes rather than because
1483    the two proteins generated by the features have a related functionality.
1484    
1485    Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1486    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1487    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1488    and FALSE otherwise.
1489    
1490    =over 4
1491    
1492    =item peg1
1493    
1494    ID of the feature of interest.
1495    
1496    =item peg2
1497    
1498    ID of a feature functionally coupled to the feature of interest.
1499    
1500    =item RETURN
1501    
1502    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1503    of interest, a feature similar to the functionally coupled feature, and a flag
1504    that is TRUE for a representative piece of evidence and FALSE otherwise.
1505    
1506    =back
1507    
1508    =cut
1509    #: Return Type @@;
1510    sub CouplingEvidence {
1511        # Get the parameters.
1512        my ($self, $peg1, $peg2) = @_;
1513        # Declare the return variable.
1514        my @retVal = ();
1515        # Our first task is to find out the nature of the coupling: whether or not
1516        # it exists, its score, and whether the features are stored in the same
1517        # order as the ones coming in.
1518        my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1519        # Only proceed if a coupling exists.
1520        if ($couplingID) {
1521            # Determine the ordering to place on the evidence items. If we're
1522            # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1523            # we want feature 1 before feature 2 (normal).
1524            my $ordering = ($inverted ? "DESC" : "");
1525            # Get the coupling evidence.
1526            my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
1527                                              "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",
1528                                              [$couplingID],
1529                                              ['PCH(used)', 'UsesAsEvidence(to-link)']);
1530            # Loop through the evidence items. Each piece of evidence is represented by two
1531            # positions in the evidence list, one for each feature on the other side of the
1532            # evidence link. If at some point we want to generalize to couplings with
1533            # more than two positions, this section of code will need to be re-done.
1534            while (@evidenceList > 0) {
1535                my $peg1Data = shift @evidenceList;
1536                my $peg2Data = shift @evidenceList;
1537                push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1538            }
1539        }
1540        # Return the result.
1541        return @retVal;
1542    }
1543    
1544    =head3 GetCoupling
1545    
1546    C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>
1547    
1548    Return the coupling (if any) for the specified pair of PEGs. If a coupling
1549    exists, we return the coupling ID along with an indicator of whether the
1550    coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.
1551    In the second case, we say the coupling is I<inverted>. The importance of an
1552    inverted coupling is that the PEGs in the evidence will appear in reverse order.
1553    
1554    =over 4
1555    
1556    =item peg1
1557    
1558    ID of the feature of interest.
1559    
1560    =item peg2
1561    
1562    ID of the potentially coupled feature.
1563    
1564    =item RETURN
1565    
1566    Returns a three-element list. The first element contains the database ID of
1567    the coupling. The second element is FALSE if the coupling is stored in the
1568    database in the caller specified order and TRUE if it is stored in the
1569    inverted order. The third element is the coupling's score. If the coupling
1570    does not exist, all three list elements will be C<undef>.
1571    
1572    =back
1573    
1574    =cut
1575    #: Return Type $%@;
1576    sub GetCoupling {
1577        # Get the parameters.
1578        my ($self, $peg1, $peg2) = @_;
1579        # Declare the return values. We'll start with the coupling ID and undefine the
1580        # flag and score until we have more information.
1581        my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);
1582        # Find the coupling data.
1583        my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1584                                     "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1585                                     [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1586        # Check to see if we found anything.
1587        if (!@pegs) {
1588            # No coupling, so undefine the return value.
1589            $retVal = undef;
1590        } else {
1591            # We have a coupling! Get the score and check for inversion.
1592            $score = $pegs[0]->[1];
1593            $inverted = ($pegs[0]->[0] eq $peg1);
1594        }
1595        # Return the result.
1596        return ($retVal, $inverted, $score);
1597    }
1598    
1599    =head3 CouplingID
1600    
1601    C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>
1602    
1603    Return the coupling ID for a pair of feature IDs.
1604    
1605    The coupling ID is currently computed by joining the feature IDs in
1606    sorted order with a space. Client modules (that is, modules which
1607    use Sprout) should not, however, count on this always being the
1608    case. This method provides a way for abstracting the concept of a
1609    coupling ID. All that we know for sure about it is that it can be
1610    generated easily from the feature IDs and the order of the IDs
1611    in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>
1612    will have the same value as C<CouplingID("b1", "a1")>.
1613    
1614    =over 4
1615    
1616    =item peg1
1617    
1618    First feature of interest.
1619    
1620    =item peg2
1621    
1622    Second feature of interest.
1623    
1624    =item RETURN
1625    
1626    Returns the ID that would be used to represent a functional coupling of
1627    the two specified PEGs.
1628    
1629    =back
1630    
1631    =cut
1632    #: Return Type $;
1633    sub CouplingID {
1634        return join " ", sort @_;
1635    }
1636    
1637  =head3 GetEntityTypes  =head3 GetEntityTypes
1638    
1639  C<< my @entityList = $sprout->GetEntityTypes(); >>  C<< my @entityList = $sprout->GetEntityTypes(); >>
# Line 1275  Line 1641 
1641  Return the list of supported entity types.  Return the list of supported entity types.
1642    
1643  =cut  =cut
1644    #: Return Type @;
1645  sub GetEntityTypes {  sub GetEntityTypes {
1646          # Get the parameters.          # Get the parameters.
1647          my $self = shift @_;      my ($self) = @_;
1648          # Get the underlying database object.          # Get the underlying database object.
1649          my $erdb = $self->{_erdb};          my $erdb = $self->{_erdb};
1650          # Get its entity type list.          # Get its entity type list.
# Line 1310  Line 1676 
1676  =back  =back
1677    
1678  =cut  =cut
1679    #: Return Type %;
1680  sub ReadFasta {  sub ReadFasta {
1681          # Get the parameters.          # Get the parameters.
1682          my ($fileName, $prefix) = @_;          my ($fileName, $prefix) = @_;
# Line 1329  Line 1695 
1695                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1696                          # 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.
1697                          if ($id) {                          if ($id) {
1698                                  $retVal{$id} = $sequence;                  $retVal{$id} = uc $sequence;
1699                          }                          }
1700                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
1701                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
1702                  } else {                  } else {
1703                          # 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.
1704                          # First, we get the actual data out.              # First, we get the actual data out. Note that we normalize to upper
1705                # case.
1706                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
1707                          $sequence .= $1;                          $sequence .= $1;
1708                  }                  }
1709          }          }
1710          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
1711          if ($sequence) {          if ($sequence) {
1712                  $retVal {$id} = $sequence;          $retVal{$id} = uc $sequence;
1713          }          }
1714        # Close the file.
1715        close FASTAFILE;
1716          # Return the hash constructed from the file.          # Return the hash constructed from the file.
1717          return %retVal;          return %retVal;
1718  }  }
# Line 1354  Line 1723 
1723    
1724  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
1725  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
1726  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,
1727    it will not be changed; otherwise, it will be converted. This method can also be used to
1728    perform the reverse task-- insuring that all the locations are in the old format.
1729    
1730  =over 4  =over 4
1731    
# Line 1378  Line 1749 
1749  =back  =back
1750    
1751  =cut  =cut
1752    #: Return Type @;
1753  sub FormatLocations {  sub FormatLocations {
1754          # Get the parameters.          # Get the parameters.
1755          my $self = shift @_;      my ($self, $prefix, $locations, $oldFormat) = @_;
         my ($prefix, $locations, $oldFormat) = @_;  
1756          # Create the return list.          # Create the return list.
1757          my @retVal = ();          my @retVal = ();
1758          # Check to see if any locations were passed in.          # Check to see if any locations were passed in.
1759          if ($locations eq '') {          if ($locations eq '') {
1760              confess "No locations specified.";          Confess("No locations specified.");
1761          } else {          } else {
1762                  # Loop through the locations, converting them to the new format.                  # Loop through the locations, converting them to the new format.
1763                  for my $location (@{$locations}) {                  for my $location (@{$locations}) {
# Line 1422  Line 1792 
1792    
1793  sub DumpData {  sub DumpData {
1794          # Get the parameters.          # Get the parameters.
1795          my $self = shift @_;      my ($self) = @_;
1796          # Get the data directory name.          # Get the data directory name.
1797          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
1798          # Dump the relations.          # Dump the relations.
# Line 1436  Line 1806 
1806  Return the name of this database's XML definition file.  Return the name of this database's XML definition file.
1807    
1808  =cut  =cut
1809    #: Return Type $;
1810  sub XMLFileName {  sub XMLFileName {
1811          my $self = shift @_;      my ($self) = @_;
1812          return $self->{_xmlName};          return $self->{_xmlName};
1813  }  }
1814    
# Line 1458  Line 1828 
1828  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
1829  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>.
1830    
1831  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'}); >>
1832    
1833  =over 4  =over 4
1834    
# Line 1473  Line 1843 
1843  =back  =back
1844    
1845  =cut  =cut
1846    #: Return Type ;
1847  sub Insert {  sub Insert {
1848          # Get the parameters.          # Get the parameters.
1849          my $self = shift @_;      my ($self, $objectType, $fieldHash) = @_;
         my ($objectType, $fieldHash) = @_;  
1850          # Call the underlying method.          # Call the underlying method.
1851          $self->{_erdb}->InsertObject($objectType, $fieldHash);          $self->{_erdb}->InsertObject($objectType, $fieldHash);
1852  }  }
# Line 1515  Line 1884 
1884  =back  =back
1885    
1886  =cut  =cut
1887    #: Return Type $;
1888  sub Annotate {  sub Annotate {
1889          # Get the parameters.          # Get the parameters.
1890          my $self = shift @_;      my ($self, $fid, $timestamp, $user, $text) = @_;
         my ($fid, $timestamp, $user, $text) = @_;  
1891          # Create the annotation ID.          # Create the annotation ID.
1892          my $aid = "$fid:$timestamp";          my $aid = "$fid:$timestamp";
1893          # Insert the Annotation object.          # Insert the Annotation object.
# Line 1539  Line 1907 
1907    
1908  =head3 AssignFunction  =head3 AssignFunction
1909    
1910  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function); >>  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>
1911    
1912  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
1913  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.  
1914    
1915  =over 4  =over 4
1916    
# Line 1553  Line 1920 
1920    
1921  =item user  =item user
1922    
1923  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>.
1924    
1925  =item function  =item function
1926    
1927  Text of the function being assigned.  Text of the function being assigned.
1928    
1929    =item assigningUser (optional)
1930    
1931    Name of the individual user making the assignment. If omitted, defaults to the user group.
1932    
1933  =item RETURN  =item RETURN
1934    
1935  Returns 1 if successful, 0 if an error occurred.  Returns 1 if successful, 0 if an error occurred.
# Line 1566  Line 1937 
1937  =back  =back
1938    
1939  =cut  =cut
1940    #: Return Type $;
1941  sub AssignFunction {  sub AssignFunction {
1942          # Get the parameters.          # Get the parameters.
1943          my $self = shift @_;      my ($self, $featureID, $user, $function, $assigningUser) = @_;
1944          my ($featureID, $user, $function) = @_;      # Default the assigning user.
1945        if (! $assigningUser) {
1946            $assigningUser = $user;
1947        }
1948          # Create an annotation string from the parameters.          # Create an annotation string from the parameters.
1949          my $annotationText = "$user\nset $user function to\n$function";      my $annotationText = "$assigningUser\nset $user function to\n$function";
1950          # Get the current time.          # Get the current time.
1951          my $now = time;          my $now = time;
1952          # Declare the return variable.          # Declare the return variable.
# Line 1614  Line 1988 
1988  =back  =back
1989    
1990  =cut  =cut
1991    #: Return Type @;
1992  sub FeaturesByAlias {  sub FeaturesByAlias {
1993          # Get the parameters.          # Get the parameters.
1994          my $self = shift @_;      my ($self, $alias) = @_;
         my ($alias) = @_;  
1995          # Declare the return variable.          # Declare the return variable.
1996          my @retVal = ();          my @retVal = ();
1997          # Parse the alias.          # Parse the alias.
# Line 1657  Line 2030 
2030  =back  =back
2031    
2032  =cut  =cut
2033    #: Return Type $;
2034  sub Exists {  sub Exists {
2035          # Get the parameters.          # Get the parameters.
2036          my $self = shift @_;      my ($self, $entityName, $entityID) = @_;
         my ($entityName, $entityID) = @_;  
2037          # Check for the entity instance.          # Check for the entity instance.
2038          my $testInstance = $self->GetEntity($entityName, $entityID);          my $testInstance = $self->GetEntity($entityName, $entityID);
2039          # Return an existence indicator.          # Return an existence indicator.
# Line 1688  Line 2060 
2060  =back  =back
2061    
2062  =cut  =cut
2063    #: Return Type $;
2064  sub FeatureTranslation {  sub FeatureTranslation {
2065          # Get the parameters.          # Get the parameters.
2066          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2067          # Get the specified feature's translation.          # Get the specified feature's translation.
2068          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
2069          return $retVal;          return $retVal;
# Line 1721  Line 2092 
2092  =back  =back
2093    
2094  =cut  =cut
2095    #: Return Type @;
2096  sub Taxonomy {  sub Taxonomy {
2097          # Get the parameters.          # Get the parameters.
2098          my $self = shift @_;      my ($self, $genome) = @_;
         my ($genome) = @_;  
2099          # Find the specified genome's taxonomy string.          # Find the specified genome's taxonomy string.
2100          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);
2101          # Declare the return variable.          # Declare the return variable.
# Line 1765  Line 2135 
2135  =back  =back
2136    
2137  =cut  =cut
2138    #: Return Type $;
2139  sub CrudeDistance {  sub CrudeDistance {
2140          # Get the parameters.          # Get the parameters.
2141          my $self = shift @_;      my ($self, $genome1, $genome2) = @_;
         my ($genome1, $genome2) = @_;  
2142          # Insure that the distance is commutative by sorting the genome IDs.          # Insure that the distance is commutative by sorting the genome IDs.
2143          my ($genomeA, $genomeB);          my ($genomeA, $genomeB);
2144          if ($genome2 < $genome2) {          if ($genome2 < $genome2) {
# Line 1813  Line 2182 
2182  =back  =back
2183    
2184  =cut  =cut
2185    #: Return Type $;
2186  sub RoleName {  sub RoleName {
2187          # Get the parameters.          # Get the parameters.
2188          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2189          # Get the specified role's name.          # Get the specified role's name.
2190          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);
2191          # Use the ID if the role has no name.          # Use the ID if the role has no name.
# Line 1847  Line 2215 
2215  =back  =back
2216    
2217  =cut  =cut
2218    #: Return Type @;
2219  sub RoleDiagrams {  sub RoleDiagrams {
2220          # Get the parameters.          # Get the parameters.
2221          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2222          # Query for the diagrams.          # Query for the diagrams.
2223          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2224                                                                  'RoleOccursIn(to-link)');                                                                  'RoleOccursIn(to-link)');
# Line 1859  Line 2226 
2226          return @retVal;          return @retVal;
2227  }  }
2228    
2229    =head3 GetProperties
2230    
2231    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2232    
2233    Return a list of the properties with the specified characteristics.
2234    
2235    Properties are arbitrary key-value pairs associated with a feature. (At some point they
2236    will also be associated with genomes.) A property value is represented by a 4-tuple of
2237    the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2238    
2239    =over 4
2240    
2241    =item fid
2242    
2243    ID of the feature possessing the property.
2244    
2245    =item key
2246    
2247    Name or key of the property.
2248    
2249    =item value
2250    
2251    Value of the property.
2252    
2253    =item url
2254    
2255    URL of the document that indicated the property should have this particular value, or an
2256    empty string if no such document exists.
2257    
2258    =back
2259    
2260    The parameters act as a filter for the desired data. Any non-null parameter will
2261    automatically match all the tuples returned. So, specifying just the I<$fid> will
2262    return all the properties of the specified feature; similarly, specifying the I<$key>
2263    and I<$value> parameters will return all the features having the specified property
2264    value.
2265    
2266    A single property key can have many values, representing different ideas about the
2267    feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2268    virulent, and another may declare that it is not virulent. A query about the virulence of
2269    C<fig|83333.1.peg.10> would be coded as
2270    
2271        my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2272    
2273    Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2274    not to be filtered. The tuples returned would be
2275    
2276        ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2277        ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2278    
2279    =cut
2280    #: Return Type @@;
2281    sub GetProperties {
2282        # Get the parameters.
2283        my ($self, @parms) = @_;
2284        # Declare the return variable.
2285        my @retVal = ();
2286        # Now we need to create a WHERE clause that will get us the data we want. First,
2287        # we create a list of the columns containing the data for each parameter.
2288        my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2289                        'Property(property-value)', 'HasProperty(evidence)');
2290        # Now we build the WHERE clause and the list of parameter values.
2291        my @where = ();
2292        my @values = ();
2293        for (my $i = 0; $i <= $#colNames; $i++) {
2294            my $parm = $parms[$i];
2295            if (defined $parm && ($parm ne '')) {
2296                push @where, "$colNames[$i] = ?";
2297                push @values, $parm;
2298            }
2299        }
2300        # Format the WHERE clause.
2301        my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2302        # Ask for all the propertie values with the desired characteristics.
2303        my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2304        while (my $valueObject = $query->Fetch()) {
2305            my @tuple = $valueObject->Values(\@colNames);
2306            push @retVal, \@tuple;
2307        }
2308        # Return the result.
2309        return @retVal;
2310    }
2311    
2312  =head3 FeatureProperties  =head3 FeatureProperties
2313    
2314  C<< my @properties = $sprout->FeatureProperties($featureID); >>  C<< my @properties = $sprout->FeatureProperties($featureID); >>
# Line 1885  Line 2335 
2335  =back  =back
2336    
2337  =cut  =cut
2338    #: Return Type @@;
2339  sub FeatureProperties {  sub FeatureProperties {
2340          # Get the parameters.          # Get the parameters.
2341          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2342          # Get the properties.          # Get the properties.
2343          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],
2344                                                          ['Property(property-name)', 'Property(property-value)',                                                          ['Property(property-name)', 'Property(property-value)',
# Line 1917  Line 2366 
2366  =back  =back
2367    
2368  =cut  =cut
2369    #: Return Type $;
2370  sub DiagramName {  sub DiagramName {
2371          # Get the parameters.          # Get the parameters.
2372          my $self = shift @_;      my ($self, $diagramID) = @_;
         my ($diagramID) = @_;  
2373          # Get the specified diagram's name and return it.          # Get the specified diagram's name and return it.
2374          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);
2375          return $retVal;          return $retVal;
# Line 1950  Line 2398 
2398  =back  =back
2399    
2400  =cut  =cut
2401    #: Return Type @;
2402  sub MergedAnnotations {  sub MergedAnnotations {
2403          # Get the parameters.          # Get the parameters.
2404          my $self = shift @_;      my ($self, $list) = @_;
         my ($list) = @_;  
2405          # Create a list to hold the annotation tuples found.          # Create a list to hold the annotation tuples found.
2406          my @tuples = ();          my @tuples = ();
2407          # Loop through the features in the input list.          # Loop through the features in the input list.
# Line 1969  Line 2416 
2416          }          }
2417          # Sort the result list by timestamp.          # Sort the result list by timestamp.
2418          my @retVal = sort { $a->[1] <=> $b->[1] } @tuples;          my @retVal = sort { $a->[1] <=> $b->[1] } @tuples;
2419        # Loop through and make the time stamps friendly.
2420        for my $tuple (@retVal) {
2421            $tuple->[1] = FriendlyTimestamp($tuple->[1]);
2422        }
2423          # Return the sorted list.          # Return the sorted list.
2424          return @retVal;          return @retVal;
2425  }  }
# Line 1995  Line 2446 
2446  =back  =back
2447    
2448  =cut  =cut
2449    #: Return Type @;
2450  sub RoleNeighbors {  sub RoleNeighbors {
2451          # Get the parameters.          # Get the parameters.
2452          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2453          # Get all the diagrams containing this role.          # Get all the diagrams containing this role.
2454          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2455                                                                    'RoleOccursIn(to-link)');                                                                    'RoleOccursIn(to-link)');
# Line 2038  Line 2488 
2488  =back  =back
2489    
2490  =cut  =cut
2491    #: Return Type @;
2492  sub FeatureLinks {  sub FeatureLinks {
2493          # Get the parameters.          # Get the parameters.
2494          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2495          # Get the feature's links.          # Get the feature's links.
2496          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);
2497          # Return the feature's links.          # Return the feature's links.
# Line 2069  Line 2518 
2518  =back  =back
2519    
2520  =cut  =cut
2521    #: Return Type %;
2522  sub SubsystemsOf {  sub SubsystemsOf {
2523          # Get the parameters.          # Get the parameters.
2524          my $self = shift @_;      my ($self, $featureID) = @_;
2525          my ($featureID) = @_;      # Get the subsystem list.
         # Use the SSCell to connect features to subsystems.  
2526          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2527                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2528                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
# Line 2088  Line 2536 
2536          return %retVal;          return %retVal;
2537  }  }
2538    
2539    =head3 SubsystemList
2540    
2541    C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2542    
2543    Return a list containing the names of the subsystems in which the specified
2544    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2545    subsystem names, not the roles.
2546    
2547    =over 4
2548    
2549    =item featureID
2550    
2551    ID of the feature whose subsystem names are desired.
2552    
2553    =item RETURN
2554    
2555    Returns a list of the names of the subsystems in which the feature participates.
2556    
2557    =back
2558    
2559    =cut
2560    #: Return Type @;
2561    sub SubsystemList {
2562        # Get the parameters.
2563        my ($self, $featureID) = @_;
2564        # Get the list of names.
2565        my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",
2566                                    [$featureID], 'HasSSCell(from-link)');
2567        # Return the result.
2568        return @retVal;
2569    }
2570    
2571  =head3 RelatedFeatures  =head3 RelatedFeatures
2572    
2573  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2118  Line 2598 
2598  =back  =back
2599    
2600  =cut  =cut
2601    #: Return Type @;
2602  sub RelatedFeatures {  sub RelatedFeatures {
2603          # Get the parameters.          # Get the parameters.
2604          my $self = shift @_;      my ($self, $featureID, $function, $userID) = @_;
         my ($featureID, $function, $userID) = @_;  
2605          # 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.
2606          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],
2607                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],
# Line 2167  Line 2646 
2646  =back  =back
2647    
2648  =cut  =cut
2649    #: Return Type @;
2650  sub TaxonomySort {  sub TaxonomySort {
2651          # Get the parameters.          # Get the parameters.
2652          my $self = shift @_;      my ($self, $featureIDs) = @_;
         my ($featureIDs) = @_;  
2653          # Create the working hash table.          # Create the working hash table.
2654          my %hashBuffer = ();          my %hashBuffer = ();
2655          # Loop through the features.          # Loop through the features.
# Line 2180  Line 2658 
2658                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
2659                                                                                  [$fid], 'Genome(taxonomy)');                                                                                  [$fid], 'Genome(taxonomy)');
2660                  # Add this feature to the hash buffer.                  # Add this feature to the hash buffer.
2661                  if (exists $hashBuffer{$taxonomy}) {          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);
                         push @{$hashBuffer{$taxonomy}}, $fid;  
                 } else {  
                         $hashBuffer{$taxonomy} = [$fid];  
                 }  
2662          }          }
2663          # Sort the keys and get the elements.          # Sort the keys and get the elements.
2664          my @retVal = ();          my @retVal = ();
# Line 2250  Line 2724 
2724  =back  =back
2725    
2726  =cut  =cut
2727    #: Return Type @@;
2728  sub GetAll {  sub GetAll {
2729          # Get the parameters.          # Get the parameters.
2730          my $self = shift @_;      my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
2731          my ($objectNames, $filterClause, $parameterList, $fields, $count) = @_;      # Call the ERDB method.
2732          # Create the query.      my @retVal = $self->{_erdb}->GetAll($objectNames, $filterClause, $parameterList,
2733          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++;  
         }  
2734          # Return the resulting list.          # Return the resulting list.
2735          return @retVal;          return @retVal;
2736  }  }
# Line 2312  Line 2772 
2772  =back  =back
2773    
2774  =cut  =cut
2775    #: Return Type @;
2776  sub GetFlat {  sub GetFlat {
2777          # Get the parameters.          # Get the parameters.
2778          my $self = shift @_;      my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
         my ($objectNames, $filterClause, $parameterList, $field) = @_;  
2779          # Construct the query.          # Construct the query.
2780          my $query = $self->Get($objectNames, $filterClause, $parameterList);          my $query = $self->Get($objectNames, $filterClause, $parameterList);
2781          # Create the result list.          # Create the result list.
# Line 2423  Line 2882 
2882  to load the entire database.  to load the entire database.
2883    
2884  =cut  =cut
2885    #: Return Type @;
2886  sub LoadInfo {  sub LoadInfo {
2887          # Get the parameters.          # Get the parameters.
2888          my $self = shift @_;      my ($self) = @_;
2889          # 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.
2890          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
2891          # Concatenate the table names.          # Concatenate the table names.
# Line 2460  Line 2919 
2919  =back  =back
2920    
2921  =cut  =cut
2922    #: Return Type %;
2923  sub LowBBHs {  sub LowBBHs {
2924          # Get the parsameters.          # Get the parsameters.
2925          my $self = shift @_;      my ($self, $featureID, $cutoff) = @_;
         my ($featureID, $cutoff) = @_;  
2926          # Create the return hash.          # Create the return hash.
2927          my %retVal = ();          my %retVal = ();
2928          # Create a query to get the desired BBHs.          # Create a query to get the desired BBHs.
# Line 2480  Line 2938 
2938          return %retVal;          return %retVal;
2939  }  }
2940    
2941    =head3 GetGroups
2942    
2943    C<< my %groups = $sprout->GetGroups(\@groupList); >>
2944    
2945    Return a hash mapping each group to the IDs of the genomes in the group.
2946    A list of groups may be specified, in which case only those groups will be
2947    shown. Alternatively, if no parameter is supplied, all groups will be
2948    included. Genomes that are not in any group are omitted.
2949    
2950    =cut
2951    #: Return Type %@;
2952    sub GetGroups {
2953        # Get the parameters.
2954        my ($self, $groupList) = @_;
2955        # Declare the return value.
2956        my %retVal = ();
2957        # Determine whether we are getting all the groups or just some.
2958        if (defined $groupList) {
2959            # Here we have a group list. Loop through them individually,
2960            # getting a list of the relevant genomes.
2961            for my $group (@{$groupList}) {
2962                my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",
2963                    [$group], "Genome(id)");
2964                $retVal{$group} = \@genomeIDs;
2965            }
2966        } else {
2967            # Here we need all of the groups. In this case, we run through all
2968            # of the genome records, putting each one found into the appropriate
2969            # group. Note that we use a filter clause to insure that only genomes
2970            # in groups are included in the return set.
2971            my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],
2972                                        ['Genome(id)', 'Genome(group-name)']);
2973            # Loop through the genomes found.
2974            for my $genome (@genomes) {
2975                # Pop this genome's ID off the current list.
2976                my @groups = @{$genome};
2977                my $genomeID = shift @groups;
2978                # Loop through the groups, adding the genome ID to each group's
2979                # list.
2980                for my $group (@groups) {
2981                    Tracer::AddToListMap(\%retVal, $group, $genomeID);
2982                }
2983            }
2984        }
2985        # Return the hash we just built.
2986        return %retVal;
2987    }
2988    
2989    =head3 MyGenomes
2990    
2991    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
2992    
2993    Return a list of the genomes to be included in the Sprout.
2994    
2995    This method is provided for use during the Sprout load. It presumes the Genome load file has
2996    already been created. (It will be in the Sprout data directory and called either C<Genome>
2997    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
2998    IDs.
2999    
3000    =over 4
3001    
3002    =item dataDir
3003    
3004    Directory containing the Sprout load files.
3005    
3006    =back
3007    
3008    =cut
3009    #: Return Type @;
3010    sub MyGenomes {
3011        # Get the parameters.
3012        my ($dataDir) = @_;
3013        # Compute the genome file name.
3014        my $genomeFileName = LoadFileName($dataDir, "Genome");
3015        # Extract the genome IDs from the files.
3016        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3017        # Return the result.
3018        return @retVal;
3019    }
3020    
3021    =head3 LoadFileName
3022    
3023    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3024    
3025    Return the name of the load file for the specified table in the specified data
3026    directory.
3027    
3028    =over 4
3029    
3030    =item dataDir
3031    
3032    Directory containing the Sprout load files.
3033    
3034    =item tableName
3035    
3036    Name of the table whose load file is desired.
3037    
3038    =item RETURN
3039    
3040    Returns the name of the file containing the load data for the specified table, or
3041    C<undef> if no load file is present.
3042    
3043    =back
3044    
3045    =cut
3046    #: Return Type $;
3047    sub LoadFileName {
3048        # Get the parameters.
3049        my ($dataDir, $tableName) = @_;
3050        # Declare the return variable.
3051        my $retVal;
3052        # Check for the various file names.
3053        if (-e "$dataDir/$tableName") {
3054            $retVal = "$dataDir/$tableName";
3055        } elsif (-e "$dataDir/$tableName.dtx") {
3056            $retVal = "$dataDir/$tableName.dtx";
3057        }
3058        # Return the result.
3059        return $retVal;
3060    }
3061    
3062  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3063    
3064  =head3 ParseAssignment  =head3 ParseAssignment
3065    
3066  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,
3067  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
3068  will be returned.  isn't, an empty list will be returned.
3069    
3070    A functional assignment is always of the form
3071    
3072        I<XXXX>C<\nset >I<YYYY>C< function to\n>I<ZZZZZ>
3073    
3074    where I<XXXX> is the B<assigning user>, I<YYYY> is the B<user>, and I<ZZZZ> is the
3075    actual functional role. In most cases, the user and the assigning user will be the
3076    same, but that is not always the case.
3077    
3078  This is a static method.  This is a static method.
3079    
# Line 2505  Line 3092 
3092    
3093  =cut  =cut
3094    
3095  sub ParseAssignment {  sub _ParseAssignment {
3096          # Get the parameters.          # Get the parameters.
3097          my ($text) = @_;          my ($text) = @_;
3098          # Declare the return value.          # Declare the return value.
3099          my @retVal = ();          my @retVal = ();
3100          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3101          my ($user, $type, $function) = split(/\n/, $text);          my ($user, $type, $function) = split(/\n/, $text);
3102          if ($type =~ m/^set $user function to$/i) {      if ($type =~ m/^set ([^ ]+) function to$/i) {
3103                  # 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,
3104                  @retVal = ($user, $function);          # and the assigning user.
3105            @retVal = ($1, $function, $user);
3106          }          }
3107          # Return the result list.          # Return the result list.
3108          return @retVal;          return @retVal;
3109  }  }
3110    
3111    =head3 FriendlyTimestamp
3112    
3113    Convert a time number to a user-friendly time stamp for display.
3114    
3115    This is a static method.
3116    
3117    =over 4
3118    
3119    =item timeValue
3120    
3121    Numeric time value.
3122    
3123    =item RETURN
3124    
3125    Returns a string containing the same time in user-readable format.
3126    
3127    =back
3128    
3129    =cut
3130    
3131    sub FriendlyTimestamp {
3132        my ($timeValue) = @_;
3133        my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));
3134        return $retVal;
3135    }
3136    
3137    =head3 AddProperty
3138    
3139    C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>
3140    
3141    Add a new attribute value (Property) to a feature. In the SEED system, attributes can
3142    be added to almost any object. In Sprout, they can only be added to features. In
3143    Sprout, attributes are implemented using I<properties>. A property represents a key/value
3144    pair. If the particular key/value pair coming in is not already in the database, a new
3145    B<Property> record is created to hold it.
3146    
3147    =over 4
3148    
3149    =item peg
3150    
3151    ID of the feature to which the attribute is to be replied.
3152    
3153    =item key
3154    
3155    Name of the attribute (key).
3156    
3157    =item value
3158    
3159    Value of the attribute.
3160    
3161    =item url
3162    
3163    URL or text citation from which the property was obtained.
3164    
3165    =back
3166    
3167    =cut
3168    #: Return Type ;
3169    sub AddProperty {
3170        # Get the parameters.
3171        my ($self, $featureID, $key, $value, $url) = @_;
3172        # Declare the variable to hold the desired property ID.
3173        my $propID;
3174        # Attempt to find a property record for this key/value pair.
3175        my @properties = $self->GetFlat(['Property'],
3176                                       "Property(property-name) = ? AND Property(property-value) = ?",
3177                                       [$key, $value], 'Property(id)');
3178        if (@properties) {
3179            # Here the property is already in the database. We save its ID.
3180            $propID = $properties[0];
3181            # Here the property value does not exist. We need to generate an ID. It will be set
3182            # to a number one greater than the maximum value in the database. This call to
3183            # GetAll will stop after one record.
3184            my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],
3185                                            1);
3186            $propID = $maxProperty[0]->[0] + 1;
3187            # Insert the new property value.
3188            $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });
3189        }
3190        # Now we connect the incoming feature to the property.
3191        $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3192    }
3193    
3194    
3195    
3196  1;  1;

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3