[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.7, Wed Jan 26 22:26:09 2005 UTC revision 1.57, Sat May 13 03:10:15 2006 UTC
# Line 62  Line 62 
62    
63  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)
64    
65  * B<userData> user name and password, delimited by a slash (default C<root/>)  * B<userData> user name and password, delimited by a slash (default same as SEED)
66    
67  * B<port> connection port (default C<0>)  * B<port> connection port (default C<0>)
68    
69    * B<sock> connection socket (default same as SEED)
70    
71  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
72    
73  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
74    
75    * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
76    
77  =back  =back
78    
79  For example, the following constructor call specifies a database named I<Sprout> and a user name of  For example, the following constructor call specifies a database named I<Sprout> and a user name of
# Line 86  Line 90 
90          # 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
91          # the incoming data.          # the incoming data.
92          my $optionTable = Tracer::GetOptions({          my $optionTable = Tracer::GetOptions({
93                                             dbType               => 'mysql',                     # database type                         dbType       => $FIG_Config::dbms,
94                                             dataDir              => 'Data',                      # data file directory                                                          # database type
95                                             xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
96                                             userData             => 'root/',                     # user name and password                                                          # data file directory
97                                             port                 => 0,                           # database connection port                         xmlFileName  => "$FIG_Config::fig/SproutDBD.xml",
98                                                            # database definition file name
99                           userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
100                                                            # user name and password
101                           port         => $FIG_Config::dbport,
102                                                            # database connection port
103                           sock         => $FIG_Config::dbsock,
104                                             maxSegmentLength => 4500,            # maximum feature segment length                                             maxSegmentLength => 4500,            # maximum feature segment length
105                                             maxSequenceLength => 8000,           # maximum contig sequence length                                             maxSequenceLength => 8000,           # maximum contig sequence length
106                           noDBOpen     => 0,               # 1 to suppress the database open
107                                            }, $options);                                            }, $options);
108          # Get the data directory.          # Get the data directory.
109          my $dataDir = $optionTable->{dataDir};          my $dataDir = $optionTable->{dataDir};
# Line 100  Line 111 
111          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
112          my ($userName, $password) = ($1, $2);          my ($userName, $password) = ($1, $2);
113          # Connect to the database.          # Connect to the database.
114          my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
115        if (! $optionTable->{noDBOpen}) {
116            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
117                                    $password, $optionTable->{port}, undef, $optionTable->{sock});
118        }
119          # Create the ERDB object.          # Create the ERDB object.
120          my $xmlFileName = "$optionTable->{xmlFileName}";          my $xmlFileName = "$optionTable->{xmlFileName}";
121          my $erdb = ERDB->new($dbh, $xmlFileName);          my $erdb = ERDB->new($dbh, $xmlFileName);
# Line 124  Line 139 
139  =cut  =cut
140  #: Return Type $;  #: Return Type $;
141  sub MaxSegment {  sub MaxSegment {
142          my $self = shift @_;      my ($self) = @_;
143          return $self->{_options}->{maxSegmentLength};          return $self->{_options}->{maxSegmentLength};
144  }  }
145    
# Line 139  Line 154 
154  =cut  =cut
155  #: Return Type $;  #: Return Type $;
156  sub MaxSequence {  sub MaxSequence {
157          my $self = shift @_;      my ($self) = @_;
158          return $self->{_options}->{maxSequenceLength};          return $self->{_options}->{maxSequenceLength};
159  }  }
160    
# Line 232  Line 247 
247    
248  sub Get {  sub Get {
249          # Get the parameters.          # Get the parameters.
250          my $self = shift @_;      my ($self, $objectNames, $filterClause, $parameterList) = @_;
         my ($objectNames, $filterClause, $parameterList) = @_;  
251          # 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
252          # 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
253          # 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 269  Line 283 
283    
284  sub GetEntity {  sub GetEntity {
285          # Get the parameters.          # Get the parameters.
286          my $self = shift @_;      my ($self, $entityType, $ID) = @_;
287          my ($entityType, $ID) = @_;      # Call the ERDB method.
288          # 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;  
289  }  }
290    
291  =head3 GetEntityValues  =head3 GetEntityValues
# Line 309  Line 318 
318  #: Return Type @;  #: Return Type @;
319  sub GetEntityValues {  sub GetEntityValues {
320          # Get the parameters.          # Get the parameters.
321          my $self = shift @_;      my ($self, $entityType, $ID, $fields) = @_;
322          my ($entityType, $ID, $fields) = @_;      # Call the ERDB method.
323          # 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;  
324  }  }
325    
326  =head3 ShowMetaData  =head3 ShowMetaData
# Line 341  Line 341 
341    
342  sub ShowMetaData {  sub ShowMetaData {
343          # Get the parameters.          # Get the parameters.
344          my $self = shift @_;      my ($self, $fileName) = @_;
         my ($fileName) = @_;  
345          # Compute the file name.          # Compute the file name.
346          my $options = $self->{_options};          my $options = $self->{_options};
347          # Call the show method on the underlying ERDB object.          # Call the show method on the underlying ERDB object.
# Line 382  Line 381 
381  #: Return Type %;  #: Return Type %;
382  sub Load {  sub Load {
383          # Get the parameters.          # Get the parameters.
384          my $self = shift @_;      my ($self, $rebuild) = @_;
         my ($rebuild) = @_;  
385          # Get the database object.          # Get the database object.
386          my $erdb = $self->{_erdb};          my $erdb = $self->{_erdb};
387          # Load the tables from the data directory.          # Load the tables from the data directory.
# Line 394  Line 392 
392    
393  =head3 LoadUpdate  =head3 LoadUpdate
394    
395  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
396    
397  Load updates to one or more database tables. This method enables the client to make changes to one  Load updates to one or more database tables. This method enables the client to make changes to one
398  or two tables without reloading the whole database. For each table, there must be a corresponding  or two tables without reloading the whole database. For each table, there must be a corresponding
# Line 426  Line 424 
424  #: Return Type $%;  #: Return Type $%;
425  sub LoadUpdate {  sub LoadUpdate {
426          # Get the parameters.          # Get the parameters.
427          my $self = shift @_;      my ($self, $truncateFlag, $tableList) = @_;
         my ($truncateFlag, $tableList) = @_;  
428          # Get the database object.          # Get the database object.
429          my $erdb = $self->{_erdb};          my $erdb = $self->{_erdb};
430          # Declare the return value.          # Declare the return value.
# Line 438  Line 435 
435          # Loop through the incoming table names.          # Loop through the incoming table names.
436          for my $tableName (@{$tableList}) {          for my $tableName (@{$tableList}) {
437                  # Find the table's file.                  # Find the table's file.
438                  my $fileName = "$dataDir/$tableName";          my $fileName = LoadFileName($dataDir, $tableName);
439                  if (! -e $fileName) {          if (! $fileName) {
440                          $fileName = "$fileName.dtx";              Trace("No load file found for $tableName in $dataDir.") if T(0);
441                  }          } else {
442                  # Attempt to load this table.                  # Attempt to load this table.
443                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);
444                  # Accumulate the resulting statistics.                  # Accumulate the resulting statistics.
445                  $retVal->Accumulate($result);                  $retVal->Accumulate($result);
446          }          }
447        }
448          # Return the statistics.          # Return the statistics.
449          return $retVal;          return $retVal;
450  }  }
# Line 463  Line 461 
461  #: Return Type ;  #: Return Type ;
462  sub Build {  sub Build {
463          # Get the parameters.          # Get the parameters.
464          my $self = shift @_;      my ($self) = @_;
465          # Create the tables.          # Create the tables.
466          $self->{_erdb}->CreateTables;          $self->{_erdb}->CreateTables;
467  }  }
# Line 478  Line 476 
476  #: Return Type @;  #: Return Type @;
477  sub Genomes {  sub Genomes {
478          # Get the parameters.          # Get the parameters.
479          my $self = shift @_;      my ($self) = @_;
480          # Get all the genomes.          # Get all the genomes.
481          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');
482          # Return the list of IDs.          # Return the list of IDs.
# Line 508  Line 506 
506  #: Return Type $;  #: Return Type $;
507  sub GenusSpecies {  sub GenusSpecies {
508          # Get the parameters.          # Get the parameters.
509          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
510          # Get the data for the specified genome.          # Get the data for the specified genome.
511          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',
512                                                                                                                            'Genome(unique-characterization)']);                                                                                                                            'Genome(unique-characterization)']);
# Line 545  Line 542 
542  #: Return Type @;  #: Return Type @;
543  sub FeaturesOf {  sub FeaturesOf {
544          # Get the parameters.          # Get the parameters.
545          my $self = shift @_;      my ($self, $genomeID,$ftype) = @_;
         my ($genomeID,$ftype) = @_;  
546          # Get the features we want.          # Get the features we want.
547          my @features;          my @features;
548          if (!$ftype) {          if (!$ftype) {
# Line 590  Line 586 
586  =item RETURN  =item RETURN
587    
588  Returns a list of the feature's contig segments. The locations are returned as a list in a list  Returns a list of the feature's contig segments. The locations are returned as a list in a list
589  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context.
590    
591  =back  =back
592    
# Line 599  Line 595 
595  #: Return Type $;  #: Return Type $;
596  sub FeatureLocation {  sub FeatureLocation {
597          # Get the parameters.          # Get the parameters.
598          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
599          # Create a query for the feature locations.          # Create a query for the feature locations.
600          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",
601                                                     [$featureID]);                                                     [$featureID]);
# Line 618  Line 613 
613                  if ($prevContig eq $contigID && $dir eq $prevDir) {                  if ($prevContig eq $contigID && $dir eq $prevDir) {
614                          # Here the new segment is in the same direction on the same contig. Insure the                          # Here the new segment is in the same direction on the same contig. Insure the
615                          # new segment's beginning is next to the old segment's end.                          # new segment's beginning is next to the old segment's end.
616                          if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||              if ($dir eq "-" && $beg + $len == $prevBeg) {
617                                  ($dir eq "+" && $beg == $prevBeg + $prevLen)) {                  # Here we're merging two backward blocks, so we keep the new begin point
618                                  # Here we need to merge two segments. Adjust the beginning and length values                  # and adjust the length.
619                                  # to include both segments.                  $len += $prevLen;
620                    # Pop the old segment off. The new one will replace it later.
621                    pop @retVal;
622                } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
623                    # Here we need to merge two forward blocks. Adjust the beginning and
624                    # length values to include both segments.
625                                  $beg = $prevBeg;                                  $beg = $prevBeg;
626                                  $len += $prevLen;                                  $len += $prevLen;
627                                  # Pop the old segment off. The new one will replace it later.                                  # Pop the old segment off. The new one will replace it later.
# Line 630  Line 630 
630                  }                  }
631                  # Remember this specifier for the adjacent-segment test the next time through.                  # Remember this specifier for the adjacent-segment test the next time through.
632                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
633            # Compute the initial base pair.
634            my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
635                  # Add the specifier to the list.                  # Add the specifier to the list.
636                  push @retVal, "${contigID}_$beg$dir$len";          push @retVal, "${contigID}_$start$dir$len";
637          }          }
638          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
639          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
640  }  }
641    
642  =head3 ParseLocation  =head3 ParseLocation
# Line 660  Line 662 
662  =cut  =cut
663  #: Return Type @;  #: Return Type @;
664  sub ParseLocation {  sub ParseLocation {
665          # Get the parameter.      # Get the parameter. Note that if we're called as an instance method, we ignore
666        # the first parameter.
667        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
668          my ($location) = @_;          my ($location) = @_;
669          # Parse it into segments.          # Parse it into segments.
670          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
671          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
672          # If the direction is an underscore, convert it to a + or -.          # If the direction is an underscore, convert it to a + or -.
673          if ($dir eq "_") {          if ($dir eq "_") {
# Line 679  Line 683 
683          return ($contigID, $start, $dir, $len);          return ($contigID, $start, $dir, $len);
684  }  }
685    
686    =head3 PointLocation
687    
688    C<< my $found = Sprout::PointLocation($location, $point); >>
689    
690    Return the offset into the specified location of the specified point on the contig. If
691    the specified point is before the location, a negative value will be returned. If it is
692    beyond the location, an undefined value will be returned. It is assumed that the offset
693    is for the location's contig. The location can either be new-style (using a C<+> or C<->
694    and a length) or old-style (using C<_> and start and end positions.
695    
696    =over 4
697    
698    =item location
699    
700    A location specifier (see L</FeatureLocation> for a description).
701    
702    =item point
703    
704    The offset into the contig of the point in which we're interested.
705    
706    =item RETURN
707    
708    Returns the offset inside the specified location of the specified point, a negative
709    number if the point is before the location, or an undefined value if the point is past
710    the location. If the length of the location is 0, this method will B<always> denote
711    that it is outside the location. The offset will always be relative to the left-most
712    position in the location.
713    
714    =back
715    
716    =cut
717    #: Return Type $;
718    sub PointLocation {
719        # Get the parameter. Note that if we're called as an instance method, we ignore
720        # the first parameter.
721        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
722        my ($location, $point) = @_;
723        # Parse out the location elements. Note that this works on both old-style and new-style
724        # locations.
725        my ($contigID, $start, $dir, $len) = ParseLocation($location);
726        # Declare the return variable.
727        my $retVal;
728        # Compute the offset. The computation is dependent on the direction of the location.
729        my $offset = (($dir == '+') ? $point - $start : $point - ($start - $len + 1));
730        # Return the offset if it's valid.
731        if ($offset < $len) {
732            $retVal = $offset;
733        }
734        # Return the offset found.
735        return $retVal;
736    }
737    
738  =head3 DNASeq  =head3 DNASeq
739    
740  C<< my $sequence = $sprout->DNASeq(\@locationList); >>  C<< my $sequence = $sprout->DNASeq(\@locationList); >>
# Line 687  Line 743 
743  should be of the form returned by L</featureLocation> when in a list context. In other words,  should be of the form returned by L</featureLocation> when in a list context. In other words,
744  each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.  each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.
745    
746    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
747    between positions 1401 and 1532, inclusive.
748    
749        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
750    
751  =over 4  =over 4
752    
753  =item locationList  =item locationList
754    
755  List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<end> (see  List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<len> or
756  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
757    
758  =item RETURN  =item RETURN
759    
# Line 704  Line 765 
765  #: Return Type $;  #: Return Type $;
766  sub DNASeq {  sub DNASeq {
767          # Get the parameters.          # Get the parameters.
768          my $self = shift @_;      my ($self, $locationList) = @_;
         my ($locationList) = @_;  
769          # Create the return string.          # Create the return string.
770          my $retVal = "";          my $retVal = "";
771          # Loop through the locations.          # Loop through the locations.
# Line 720  Line 780 
780                  # the start point is the ending. Note that in the latter case we must reverse the DNA string                  # the start point is the ending. Note that in the latter case we must reverse the DNA string
781                  # before putting it in the return value.                  # before putting it in the return value.
782                  my ($start, $stop);                  my ($start, $stop);
783            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
784                  if ($dir eq "+") {                  if ($dir eq "+") {
785                          $start = $beg;                          $start = $beg;
786                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
787                  } else {                  } else {
788                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
789                          $stop = $beg;                          $stop = $beg;
790                  }                  }
791            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
792                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
793                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
794                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 738  Line 800 
800                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
801                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
802                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
803                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
804                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
805                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
806                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
807                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
808                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
809                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
810                  }                  }
811                  # Add this location's data to the return string. Note that we may need to reverse it.                  # Add this location's data to the return string. Note that we may need to reverse it.
812                  if ($dir eq '+') {                  if ($dir eq '+') {
813                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
814                  } else {                  } else {
815                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
816                  }                  }
817          }          }
818          # Return the result.          # Return the result.
# Line 778  Line 841 
841  #: Return Type @;  #: Return Type @;
842  sub AllContigs {  sub AllContigs {
843          # Get the parameters.          # Get the parameters.
844          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
845          # Ask for the genome's Contigs.          # Ask for the genome's Contigs.
846          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],
847                                                                  'HasContig(to-link)');                                                                  'HasContig(to-link)');
# Line 809  Line 871 
871  #: Return Type $;  #: Return Type $;
872  sub ContigLength {  sub ContigLength {
873          # Get the parameters.          # Get the parameters.
874          my $self = shift @_;      my ($self, $contigID) = @_;
         my ($contigID) = @_;  
875          # Get the contig's last sequence.          # Get the contig's last sequence.
876          my $query = $self->Get(['IsMadeUpOf'],          my $query = $self->Get(['IsMadeUpOf'],
877                  "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",                  "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
# Line 821  Line 882 
882          # Set it from the sequence data, if any.          # Set it from the sequence data, if any.
883          if ($sequence) {          if ($sequence) {
884                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
885                  $retVal = $start + $len;          $retVal = $start + $len - 1;
886        }
887        # Return the result.
888        return $retVal;
889    }
890    
891    =head3 ClusterPEGs
892    
893    C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
894    
895    Cluster the PEGs in a list according to the cluster coding scheme of the specified
896    subsystem. In order for this to work properly, the subsystem object must have
897    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
898    This causes the cluster numbers to be pulled into the subsystem's color hash.
899    If a PEG is not found in the color hash, it will not appear in the output
900    sequence.
901    
902    =over 4
903    
904    =item sub
905    
906    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
907    method.
908    
909    =item pegs
910    
911    Reference to the list of PEGs to be clustered.
912    
913    =item RETURN
914    
915    Returns a list of the PEGs, grouped into smaller lists by cluster number.
916    
917    =back
918    
919    =cut
920    #: Return Type $@@;
921    sub ClusterPEGs {
922        # Get the parameters.
923        my ($self, $sub, $pegs) = @_;
924        # Declare the return variable.
925        my $retVal = [];
926        # Loop through the PEGs, creating arrays for each cluster.
927        for my $pegID (@{$pegs}) {
928            my $clusterNumber = $sub->get_cluster_number($pegID);
929            # Only proceed if the PEG is in a cluster.
930            if ($clusterNumber >= 0) {
931                # Push this PEG onto the sub-list for the specified cluster number.
932                push @{$retVal->[$clusterNumber]}, $pegID;
933            }
934          }          }
935          # Return the result.          # Return the result.
936          return $retVal;          return $retVal;
# Line 852  Line 961 
961  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
962  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
963  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
964  the start and stop values.  the start and stop values. The first element (that is, the list of features) is sorted
965    roughly by location.
966    
967  =back  =back
968    
969  =cut  =cut
970  #: Return Type @;  #: Return Type @@;
971  sub GenesInRegion {  sub GenesInRegion {
972          # Get the parameters.          # Get the parameters.
973          my $self = shift @_;      my ($self, $contigID, $start, $stop) = @_;
         my ($contigID, $start, $stop) = @_;  
974          # Get the maximum segment length.          # Get the maximum segment length.
975          my $maximumSegmentLength = $self->MaxSegment;          my $maximumSegmentLength = $self->MaxSegment;
976          # 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
977          # duplicates easily.      # duplicates easily. The hash key will be the feature ID. The value will be a two-element
978        # containing the minimum and maximum offsets. We will use the offsets to sort the results
979        # when we're building the result set.
980          my %featuresFound = ();          my %featuresFound = ();
981          # Prime the values we'll use for the returned beginning and end.          # Prime the values we'll use for the returned beginning and end.
982          my ($min, $max) = ($self->ContigLength($contigID), 0);      my @initialMinMax = ($self->ContigLength($contigID), 0);
983        my ($min, $max) = @initialMinMax;
984          # 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
985          # 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,
986          # 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 898  Line 1010 
1010                                          $found = 1;                                          $found = 1;
1011                                  }                                  }
1012                          } elsif ($dir eq '-') {                          } elsif ($dir eq '-') {
1013                                  $end = $beg - $len;                  # Note we switch things around so that the beginning is to the left of the
1014                                  if ($end <= $stop) {                  # ending.
1015                    ($beg, $end) = ($beg - $len, $beg);
1016                    if ($beg <= $stop) {
1017                                          # Denote we found a useful feature.                                          # Denote we found a useful feature.
1018                                          $found = 1;                                          $found = 1;
1019                                  }                                  }
1020                          }                          }
1021                          if ($found) {                          if ($found) {
1022                                  # 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,
1023                                  $featuresFound{$featureID} = 1;                  # get the current entry for the specified feature.
1024                                  if ($beg < $min) { $min = $beg; }                  my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :
1025                                  if ($end < $min) { $min = $end; }                                       @initialMinMax);
1026                                  if ($beg > $max) { $max = $beg; }                  # Merge the current segment's begin and end into the feature begin and end and the
1027                                  if ($end > $max) { $max = $end; }                  # global min and max.
1028                    if ($beg < $loc1) {
1029                        $loc1 = $beg;
1030                        $min = $beg if $beg < $min;
1031                    }
1032                    if ($end > $loc2) {
1033                        $loc2 = $end;
1034                        $max = $end if $end > $max;
1035                    }
1036                    # Store the entry back into the hash table.
1037                    $featuresFound{$featureID} = [$loc1, $loc2];
1038                          }                          }
1039                  }                  }
1040          }          }
1041          # 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
1042          my @list = (sort (keys %featuresFound));      # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1043        # but the result of the sort will be the same.)
1044        my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;
1045        # Now we sort by midpoint and yank out the feature IDs.
1046        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1047          # Return it along with the min and max.          # Return it along with the min and max.
1048          return (\@list, $min, $max);      return (\@retVal, $min, $max);
1049  }  }
1050    
1051  =head3 FType  =head3 FType
# Line 943  Line 1071 
1071  #: Return Type $;  #: Return Type $;
1072  sub FType {  sub FType {
1073          # Get the parameters.          # Get the parameters.
1074          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1075          # Get the specified feature's type.          # Get the specified feature's type.
1076          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
1077          # Return the result.          # Return the result.
# Line 953  Line 1080 
1080    
1081  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1082    
1083  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1084    
1085  Return the annotations of a feature.  Return the annotations of a feature.
1086    
# Line 963  Line 1090 
1090    
1091  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1092    
1093    =item rawFlag
1094    
1095    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1096    will be returned in human-readable form.
1097    
1098  =item RETURN  =item RETURN
1099    
1100  Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.  Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.
1101    
1102  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1103    
1104  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1105    
1106  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1107    
# Line 981  Line 1113 
1113  #: Return Type @%;  #: Return Type @%;
1114  sub FeatureAnnotations {  sub FeatureAnnotations {
1115          # Get the parameters.          # Get the parameters.
1116          my $self = shift @_;      my ($self, $featureID, $rawFlag) = @_;
         my ($featureID) = @_;  
1117          # 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.
1118          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1119                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 995  Line 1126 
1126                          $annotation->Values(['IsTargetOfAnnotation(from-link)',                          $annotation->Values(['IsTargetOfAnnotation(from-link)',
1127                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1128                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1129            # Convert the time, if necessary.
1130            if (! $rawFlag) {
1131                $timeStamp = FriendlyTimestamp($timeStamp);
1132            }
1133                  # Assemble them into a hash.                  # Assemble them into a hash.
1134          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1135                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1136                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1137                  # Add it to the return list.                  # Add it to the return list.
1138                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1011  Line 1146 
1146  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>
1147    
1148  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
1149  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,
1150  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
1151  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,
1152  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.
1153  features only have a small number of annotations. Finally, if a single user has multiple  Finally, if a single user has multiple functional assignments, we will only keep the most
1154  functional assignments, we will only keep the most recent one.  recent one.
1155    
1156  =over 4  =over 4
1157    
# Line 1026  Line 1161 
1161    
1162  =item RETURN  =item RETURN
1163    
1164  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1165    
1166  =back  =back
1167    
# Line 1034  Line 1169 
1169  #: Return Type %;  #: Return Type %;
1170  sub AllFunctionsOf {  sub AllFunctionsOf {
1171          # Get the parameters.          # Get the parameters.
1172          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1173          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1174      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1175                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1176                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1177                                               'MadeAnnotation(from-link)']);
1178          # Declare the return hash.          # Declare the return hash.
1179          my %retVal;          my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1180      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1181      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1182          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1183      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1184          # Get the annotation fields.          # Get the annotation fields.
1185          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1186                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1187                  my ($user, $function) = ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1188          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1189              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1190              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1191              # return hash.              # return hash.
1192                          $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1193                  }                  }
1194          }          }
1195          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1073  Line 1204 
1204    
1205  The functional assignment is handled differently depending on the type of feature. If  The functional assignment is handled differently depending on the type of feature. If
1206  the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional  the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1207  assignment is a type of annotation. It has the format "XXXX\nset XXXX function to\nYYYYY". In this  assignment is a type of annotation. The format of an assignment is described in
1208  instance, XXXX is the user ID and YYYYY is the functional assignment text. Its worth noting that  L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1209  we cannot filter on the content of the annotation itself because it's a text field; however, this  annotation itself because it's a text field; however, this is not a big problem because
1210  is not a big problem because most features only have a small number of annotations.  most features only have a small number of annotations.
1211    
1212  Each user has an associated list of trusted users. The assignment returned will be the most  Each user has an associated list of trusted users. The assignment returned will be the most
1213  recent one by at least one of the trusted users. If no trusted user list is available, then  recent one by at least one of the trusted users. If no trusted user list is available, then
# Line 1108  Line 1239 
1239  #: Return Type $;  #: Return Type $;
1240  sub FunctionOf {  sub FunctionOf {
1241          # Get the parameters.          # Get the parameters.
1242          my $self = shift @_;      my ($self, $featureID, $userID) = @_;
         my ($featureID, $userID) = @_;  
1243      # Declare the return value.      # Declare the return value.
1244      my $retVal;      my $retVal;
1245      # Determine the ID type.      # Determine the ID type.
# Line 1137  Line 1267 
1267              }              }
1268          }          }
1269          # Build a query for all of the feature's annotations, sorted by date.          # Build a query for all of the feature's annotations, sorted by date.
1270          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1271                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1272                                 [$featureID]);                                 [$featureID]);
1273          my $timeSelected = 0;          my $timeSelected = 0;
1274          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1275          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1276              # Get the annotation text.              # Get the annotation text.
1277              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);              my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1278                                                         'Annotation(time)', 'MadeAnnotation(from-link)']);
1279              # Check to see if this is a functional assignment for a trusted user.              # Check to see if this is a functional assignment for a trusted user.
1280              my ($user, $type, $function) = split(/\n/, $text);              my ($actualUser, $function) = _ParseAssignment($user, $text);
1281              if ($type =~ m/^set $user function to$/i) {              Trace("Assignment user is $actualUser, text is $function.") if T(4);
1282                if ($actualUser) {
1283                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1284                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1285                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                  if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1286                      $retVal = $function;                      $retVal = $function;
1287                      $timeSelected = $time;                      $timeSelected = $time;
1288                  }                  }
# Line 1166  Line 1298 
1298          return $retVal;          return $retVal;
1299  }  }
1300    
1301    =head3 FunctionsOf
1302    
1303    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1304    
1305    Return the functional assignments of a particular feature.
1306    
1307    The functional assignment is handled differently depending on the type of feature. If
1308    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1309    assignment is a type of annotation. The format of an assignment is described in
1310    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1311    annotation itself because it's a text field; however, this is not a big problem because
1312    most features only have a small number of annotations.
1313    
1314    If the feature is B<not> identified by a FIG ID, then the functional assignment
1315    information is taken from the B<ExternalAliasFunc> table. If the table does
1316    not contain an entry for the feature, an empty list is returned.
1317    
1318    =over 4
1319    
1320    =item featureID
1321    
1322    ID of the feature whose functional assignments are desired.
1323    
1324    =item RETURN
1325    
1326    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1327    that user.
1328    
1329    =back
1330    
1331    =cut
1332    #: Return Type @@;
1333    sub FunctionsOf {
1334        # Get the parameters.
1335        my ($self, $featureID) = @_;
1336        # Declare the return value.
1337        my @retVal = ();
1338        # Determine the ID type.
1339        if ($featureID =~ m/^fig\|/) {
1340            # Here we have a FIG feature ID. We must build the list of trusted
1341            # users.
1342            my %trusteeTable = ();
1343            # Build a query for all of the feature's annotations, sorted by date.
1344            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1345                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1346                                   [$featureID]);
1347            my $timeSelected = 0;
1348            # Loop until we run out of annotations.
1349            while (my $annotation = $query->Fetch()) {
1350                # Get the annotation text.
1351                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1352                                                                'Annotation(time)',
1353                                                                'MadeAnnotation(user)']);
1354                # Check to see if this is a functional assignment for a trusted user.
1355                my ($actualUser, $function) = _ParseAssignment($user, $text);
1356                if ($actualUser) {
1357                    # Here it is a functional assignment.
1358                    push @retVal, [$actualUser, $function];
1359                }
1360            }
1361        } else {
1362            # Here we have a non-FIG feature ID. In this case the user ID does not
1363            # matter. We simply get the information from the External Alias Function
1364            # table.
1365            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1366                                                     ['ExternalAliasFunc(func)']);
1367            push @retVal, map { ['master', $_] } @assignments;
1368        }
1369        # Return the assignments found.
1370        return @retVal;
1371    }
1372    
1373  =head3 BBHList  =head3 BBHList
1374    
1375  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1185  Line 1389 
1389    
1390  =item RETURN  =item RETURN
1391    
1392  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
1393  their best hits.  on the target genome.
1394    
1395  =back  =back
1396    
# Line 1194  Line 1398 
1398  #: Return Type %;  #: Return Type %;
1399  sub BBHList {  sub BBHList {
1400          # Get the parameters.          # Get the parameters.
1401          my $self = shift @_;      my ($self, $genomeID, $featureList) = @_;
         my ($genomeID, $featureList) = @_;  
1402          # Create the return structure.          # Create the return structure.
1403          my %retVal = ();          my %retVal = ();
1404          # Loop through the incoming features.          # Loop through the incoming features.
# Line 1204  Line 1407 
1407                  my $query = $self->Get(['IsBidirectionalBestHitOf'],                  my $query = $self->Get(['IsBidirectionalBestHitOf'],
1408                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",
1409                                                             [$featureID, $genomeID]);                                                             [$featureID, $genomeID]);
1410                  # Look for the best hit.          # Peel off the BBHs found.
1411                  my $bbh = $query->Fetch;          my @found = ();
1412                  if ($bbh) {          while (my $bbh = $query->Fetch) {
1413                          my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');
                         $retVal{$featureID} = $targetFeature;  
1414                  }                  }
1415            $retVal{$featureID} = \@found;
1416          }          }
1417          # Return the mapping.          # Return the mapping.
1418          return \%retVal;          return \%retVal;
1419  }  }
1420    
1421    =head3 SimList
1422    
1423    C<< my %similarities = $sprout->SimList($featureID, $count); >>
1424    
1425    Return a list of the similarities to the specified feature.
1426    
1427    Sprout does not support real similarities, so this method just returns the bidirectional
1428    best hits.
1429    
1430    =over 4
1431    
1432    =item featureID
1433    
1434    ID of the feature whose similarities are desired.
1435    
1436    =item count
1437    
1438    Maximum number of similar features to be returned, or C<0> to return them all.
1439    
1440    =back
1441    
1442    =cut
1443    #: Return Type %;
1444    sub SimList {
1445        # Get the parameters.
1446        my ($self, $featureID, $count) = @_;
1447        # Ask for the best hits.
1448        my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],
1449                                  "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",
1450                                  [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],
1451                                  $count);
1452        # Create the return value.
1453        my %retVal = ();
1454        for my $tuple (@lists) {
1455            $retVal{$tuple->[0]} = $tuple->[1];
1456        }
1457        # Return the result.
1458        return %retVal;
1459    }
1460    
1461    
1462    
1463    =head3 IsComplete
1464    
1465    C<< my $flag = $sprout->IsComplete($genomeID); >>
1466    
1467    Return TRUE if the specified genome is complete, else FALSE.
1468    
1469    =over 4
1470    
1471    =item genomeID
1472    
1473    ID of the genome whose completeness status is desired.
1474    
1475    =item RETURN
1476    
1477    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1478    not found.
1479    
1480    =back
1481    
1482    =cut
1483    #: Return Type $;
1484    sub IsComplete {
1485        # Get the parameters.
1486        my ($self, $genomeID) = @_;
1487        # Declare the return variable.
1488        my $retVal;
1489        # Get the genome's data.
1490        my $genomeData = $self->GetEntity('Genome', $genomeID);
1491        if ($genomeData) {
1492            # The genome exists, so get the completeness flag.
1493            ($retVal) = $genomeData->Value('Genome(complete)');
1494        }
1495        # Return the result.
1496        return $retVal;
1497    }
1498    
1499  =head3 FeatureAliases  =head3 FeatureAliases
1500    
1501  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
# Line 1238  Line 1519 
1519  #: Return Type @;  #: Return Type @;
1520  sub FeatureAliases {  sub FeatureAliases {
1521          # Get the parameters.          # Get the parameters.
1522          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1523          # Get the desired feature's aliases          # Get the desired feature's aliases
1524          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);
1525          # Return the result.          # Return the result.
# Line 1250  Line 1530 
1530    
1531  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1532    
1533  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1534    
1535  =over 4  =over 4
1536    
1537  =item featureID  =item featureID
1538    
1539  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1540    
1541  =item RETURN  =item RETURN
1542    
1543  Returns the ID of the genome for the specified feature. If the feature is not found, returns  Returns the ID of the genome for the specified feature or contig. If the feature or contig is not
1544  an undefined value.  found, returns an undefined value.
1545    
1546  =back  =back
1547    
# Line 1269  Line 1549 
1549  #: Return Type $;  #: Return Type $;
1550  sub GenomeOf {  sub GenomeOf {
1551          # Get the parameters.          # Get the parameters.
1552          my $self = shift @_;      my ($self, $featureID) = @_;
1553          my ($featureID) = @_;      # Create a query to find the genome associated with the incoming ID.
1554          # Create a query to find the genome associated with the feature.      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1555          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);                             [$featureID, $featureID]);
1556          # Declare the return value.          # Declare the return value.
1557          my $retVal;          my $retVal;
1558          # Get the genome ID.          # Get the genome ID.
# Line 1306  Line 1586 
1586  #: Return Type %;  #: Return Type %;
1587  sub CoupledFeatures {  sub CoupledFeatures {
1588          # Get the parameters.          # Get the parameters.
1589          my $self = shift @_;      my ($self, $featureID) = @_;
1590          my ($featureID) = @_;      # Create a query to retrieve the functionally-coupled features.
1591          # Create a query to retrieve the functionally-coupled features. Note that we depend on the      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1592          # 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]);  
1593          # 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.
1594          my $found = 0;          my $found = 0;
1595          # Create the return hash.          # Create the return hash.
1596          my %retVal = ();          my %retVal = ();
1597          # Retrieve the relationship records and store them in the hash.          # Retrieve the relationship records and store them in the hash.
1598          while (my $clustering = $query->Fetch()) {          while (my $clustering = $query->Fetch()) {
1599                  my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',          # Get the ID and score of the coupling.
1600                                                                      'IsClusteredOnChromosomeWith(score)']);          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1601                                                            'Coupling(score)']);
1602            # The coupling ID contains the two feature IDs separated by a space. We use
1603            # this information to find the ID of the other feature.
1604            my ($fid1, $fid2) = split / /, $couplingID;
1605            my $otherFeatureID = ($featureID eq $fid1 ? $fid2 : $fid1);
1606            # Attach the other feature's score to its ID.
1607                  $retVal{$otherFeatureID} = $score;                  $retVal{$otherFeatureID} = $score;
1608                  $found = 1;                  $found = 1;
1609          }          }
# Line 1333  Line 1616 
1616          return %retVal;          return %retVal;
1617  }  }
1618    
1619    =head3 CouplingEvidence
1620    
1621    C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1622    
1623    Return the evidence for a functional coupling.
1624    
1625    A pair of features is considered evidence of a coupling between two other
1626    features if they occur close together on a contig and both are similar to
1627    the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1628    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1629    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1630    similar to B<A2>.
1631    
1632    The score of a coupling is determined by the number of pieces of evidence
1633    that are considered I<representative>. If several evidence items belong to
1634    a group of genomes that are close to each other, only one of those items
1635    is considered representative. The other evidence items are presumed to be
1636    there because of the relationship between the genomes rather than because
1637    the two proteins generated by the features have a related functionality.
1638    
1639    Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1640    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1641    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1642    and FALSE otherwise.
1643    
1644    =over 4
1645    
1646    =item peg1
1647    
1648    ID of the feature of interest.
1649    
1650    =item peg2
1651    
1652    ID of a feature functionally coupled to the feature of interest.
1653    
1654    =item RETURN
1655    
1656    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1657    of interest, a feature similar to the functionally coupled feature, and a flag
1658    that is TRUE for a representative piece of evidence and FALSE otherwise.
1659    
1660    =back
1661    
1662    =cut
1663    #: Return Type @@;
1664    sub CouplingEvidence {
1665        # Get the parameters.
1666        my ($self, $peg1, $peg2) = @_;
1667        # Declare the return variable.
1668        my @retVal = ();
1669        # Our first task is to find out the nature of the coupling: whether or not
1670        # it exists, its score, and whether the features are stored in the same
1671        # order as the ones coming in.
1672        my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1673        # Only proceed if a coupling exists.
1674        if ($couplingID) {
1675            # Determine the ordering to place on the evidence items. If we're
1676            # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1677            # we want feature 1 before feature 2 (normal).
1678            Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);
1679            my $ordering = ($inverted ? "DESC" : "");
1680            # Get the coupling evidence.
1681            my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
1682                                              "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",
1683                                              [$couplingID],
1684                                              ['PCH(used)', 'UsesAsEvidence(to-link)']);
1685            # Loop through the evidence items. Each piece of evidence is represented by two
1686            # positions in the evidence list, one for each feature on the other side of the
1687            # evidence link. If at some point we want to generalize to couplings with
1688            # more than two positions, this section of code will need to be re-done.
1689            while (@evidenceList > 0) {
1690                my $peg1Data = shift @evidenceList;
1691                my $peg2Data = shift @evidenceList;
1692                Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1693                push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1694            }
1695            Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1696        }
1697        # Return the result.
1698        return @retVal;
1699    }
1700    
1701    =head3 GetCoupling
1702    
1703    C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>
1704    
1705    Return the coupling (if any) for the specified pair of PEGs. If a coupling
1706    exists, we return the coupling ID along with an indicator of whether the
1707    coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.
1708    In the second case, we say the coupling is I<inverted>. The importance of an
1709    inverted coupling is that the PEGs in the evidence will appear in reverse order.
1710    
1711    =over 4
1712    
1713    =item peg1
1714    
1715    ID of the feature of interest.
1716    
1717    =item peg2
1718    
1719    ID of the potentially coupled feature.
1720    
1721    =item RETURN
1722    
1723    Returns a three-element list. The first element contains the database ID of
1724    the coupling. The second element is FALSE if the coupling is stored in the
1725    database in the caller specified order and TRUE if it is stored in the
1726    inverted order. The third element is the coupling's score. If the coupling
1727    does not exist, all three list elements will be C<undef>.
1728    
1729    =back
1730    
1731    =cut
1732    #: Return Type $%@;
1733    sub GetCoupling {
1734        # Get the parameters.
1735        my ($self, $peg1, $peg2) = @_;
1736        # Declare the return values. We'll start with the coupling ID and undefine the
1737        # flag and score until we have more information.
1738        my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);
1739        # Find the coupling data.
1740        my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1741                                     "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1742                                     [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1743        # Check to see if we found anything.
1744        if (!@pegs) {
1745            Trace("No coupling found.") if T(Coupling => 4);
1746            # No coupling, so undefine the return value.
1747            $retVal = undef;
1748        } else {
1749            # We have a coupling! Get the score and check for inversion.
1750            $score = $pegs[0]->[1];
1751            my $firstFound = $pegs[0]->[0];
1752            $inverted = ($firstFound ne $peg1);
1753            Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1754        }
1755        # Return the result.
1756        return ($retVal, $inverted, $score);
1757    }
1758    
1759    =head3 CouplingID
1760    
1761    C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>
1762    
1763    Return the coupling ID for a pair of feature IDs.
1764    
1765    The coupling ID is currently computed by joining the feature IDs in
1766    sorted order with a space. Client modules (that is, modules which
1767    use Sprout) should not, however, count on this always being the
1768    case. This method provides a way for abstracting the concept of a
1769    coupling ID. All that we know for sure about it is that it can be
1770    generated easily from the feature IDs and the order of the IDs
1771    in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>
1772    will have the same value as C<CouplingID("b1", "a1")>.
1773    
1774    =over 4
1775    
1776    =item peg1
1777    
1778    First feature of interest.
1779    
1780    =item peg2
1781    
1782    Second feature of interest.
1783    
1784    =item RETURN
1785    
1786    Returns the ID that would be used to represent a functional coupling of
1787    the two specified PEGs.
1788    
1789    =back
1790    
1791    =cut
1792    #: Return Type $;
1793    sub CouplingID {
1794        return join " ", sort @_;
1795    }
1796    
1797  =head3 GetEntityTypes  =head3 GetEntityTypes
1798    
1799  C<< my @entityList = $sprout->GetEntityTypes(); >>  C<< my @entityList = $sprout->GetEntityTypes(); >>
# Line 1343  Line 1804 
1804  #: Return Type @;  #: Return Type @;
1805  sub GetEntityTypes {  sub GetEntityTypes {
1806          # Get the parameters.          # Get the parameters.
1807          my $self = shift @_;      my ($self) = @_;
1808          # Get the underlying database object.          # Get the underlying database object.
1809          my $erdb = $self->{_erdb};          my $erdb = $self->{_erdb};
1810          # Get its entity type list.          # Get its entity type list.
# Line 1394  Line 1855 
1855                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1856                          # 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.
1857                          if ($id) {                          if ($id) {
1858                                  $retVal{$id} = $sequence;                  $retVal{$id} = lc $sequence;
1859                          }                          }
1860                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
1861                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
1862                  } else {                  } else {
1863                          # 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.
1864                          # First, we get the actual data out.              # First, we get the actual data out. Note that we normalize to lower
1865                # case.
1866                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
1867                          $sequence .= $1;                          $sequence .= $1;
1868                  }                  }
1869          }          }
1870          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
1871          if ($sequence) {          if ($sequence) {
1872                  $retVal {$id} = $sequence;          $retVal{$id} = lc $sequence;
1873          }          }
1874        # Close the file.
1875        close FASTAFILE;
1876          # Return the hash constructed from the file.          # Return the hash constructed from the file.
1877          return %retVal;          return %retVal;
1878  }  }
# Line 1419  Line 1883 
1883    
1884  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
1885  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
1886  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,
1887    it will not be changed; otherwise, it will be converted. This method can also be used to
1888    perform the reverse task-- insuring that all the locations are in the old format.
1889    
1890  =over 4  =over 4
1891    
# Line 1446  Line 1912 
1912  #: Return Type @;  #: Return Type @;
1913  sub FormatLocations {  sub FormatLocations {
1914          # Get the parameters.          # Get the parameters.
1915          my $self = shift @_;      my ($self, $prefix, $locations, $oldFormat) = @_;
         my ($prefix, $locations, $oldFormat) = @_;  
1916          # Create the return list.          # Create the return list.
1917          my @retVal = ();          my @retVal = ();
1918          # Check to see if any locations were passed in.          # Check to see if any locations were passed in.
1919          if ($locations eq '') {          if ($locations eq '') {
1920              confess "No locations specified.";          Confess("No locations specified.");
1921          } else {          } else {
1922                  # Loop through the locations, converting them to the new format.                  # Loop through the locations, converting them to the new format.
1923                  for my $location (@{$locations}) {                  for my $location (@{$locations}) {
# Line 1487  Line 1952 
1952    
1953  sub DumpData {  sub DumpData {
1954          # Get the parameters.          # Get the parameters.
1955          my $self = shift @_;      my ($self) = @_;
1956          # Get the data directory name.          # Get the data directory name.
1957          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
1958          # Dump the relations.          # Dump the relations.
# Line 1503  Line 1968 
1968  =cut  =cut
1969  #: Return Type $;  #: Return Type $;
1970  sub XMLFileName {  sub XMLFileName {
1971          my $self = shift @_;      my ($self) = @_;
1972          return $self->{_xmlName};          return $self->{_xmlName};
1973  }  }
1974    
# Line 1523  Line 1988 
1988  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
1989  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>.
1990    
1991  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'}); >>
1992    
1993  =over 4  =over 4
1994    
# Line 1541  Line 2006 
2006  #: Return Type ;  #: Return Type ;
2007  sub Insert {  sub Insert {
2008          # Get the parameters.          # Get the parameters.
2009          my $self = shift @_;      my ($self, $objectType, $fieldHash) = @_;
         my ($objectType, $fieldHash) = @_;  
2010          # Call the underlying method.          # Call the underlying method.
2011          $self->{_erdb}->InsertObject($objectType, $fieldHash);          $self->{_erdb}->InsertObject($objectType, $fieldHash);
2012  }  }
# Line 1583  Line 2047 
2047  #: Return Type $;  #: Return Type $;
2048  sub Annotate {  sub Annotate {
2049          # Get the parameters.          # Get the parameters.
2050          my $self = shift @_;      my ($self, $fid, $timestamp, $user, $text) = @_;
         my ($fid, $timestamp, $user, $text) = @_;  
2051          # Create the annotation ID.          # Create the annotation ID.
2052          my $aid = "$fid:$timestamp";          my $aid = "$fid:$timestamp";
2053          # Insert the Annotation object.          # Insert the Annotation object.
# Line 1604  Line 2067 
2067    
2068  =head3 AssignFunction  =head3 AssignFunction
2069    
2070  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function); >>  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>
2071    
2072  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
2073  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.  
2074    
2075  =over 4  =over 4
2076    
# Line 1618  Line 2080 
2080    
2081  =item user  =item user
2082    
2083  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>.
2084    
2085  =item function  =item function
2086    
2087  Text of the function being assigned.  Text of the function being assigned.
2088    
2089    =item assigningUser (optional)
2090    
2091    Name of the individual user making the assignment. If omitted, defaults to the user group.
2092    
2093  =item RETURN  =item RETURN
2094    
2095  Returns 1 if successful, 0 if an error occurred.  Returns 1 if successful, 0 if an error occurred.
# Line 1634  Line 2100 
2100  #: Return Type $;  #: Return Type $;
2101  sub AssignFunction {  sub AssignFunction {
2102          # Get the parameters.          # Get the parameters.
2103          my $self = shift @_;      my ($self, $featureID, $user, $function, $assigningUser) = @_;
2104          my ($featureID, $user, $function) = @_;      # Default the assigning user.
2105        if (! $assigningUser) {
2106            $assigningUser = $user;
2107        }
2108          # Create an annotation string from the parameters.          # Create an annotation string from the parameters.
2109          my $annotationText = "$user\nset $user function to\n$function";      my $annotationText = "$assigningUser\nset $user function to\n$function";
2110          # Get the current time.          # Get the current time.
2111          my $now = time;          my $now = time;
2112          # Declare the return variable.          # Declare the return variable.
# Line 1682  Line 2151 
2151  #: Return Type @;  #: Return Type @;
2152  sub FeaturesByAlias {  sub FeaturesByAlias {
2153          # Get the parameters.          # Get the parameters.
2154          my $self = shift @_;      my ($self, $alias) = @_;
         my ($alias) = @_;  
2155          # Declare the return variable.          # Declare the return variable.
2156          my @retVal = ();          my @retVal = ();
2157          # Parse the alias.          # Parse the alias.
# Line 1725  Line 2193 
2193  #: Return Type $;  #: Return Type $;
2194  sub Exists {  sub Exists {
2195          # Get the parameters.          # Get the parameters.
2196          my $self = shift @_;      my ($self, $entityName, $entityID) = @_;
         my ($entityName, $entityID) = @_;  
2197          # Check for the entity instance.          # Check for the entity instance.
2198        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
2199          my $testInstance = $self->GetEntity($entityName, $entityID);          my $testInstance = $self->GetEntity($entityName, $entityID);
2200          # Return an existence indicator.          # Return an existence indicator.
2201          my $retVal = ($testInstance ? 1 : 0);          my $retVal = ($testInstance ? 1 : 0);
# Line 1756  Line 2224 
2224  #: Return Type $;  #: Return Type $;
2225  sub FeatureTranslation {  sub FeatureTranslation {
2226          # Get the parameters.          # Get the parameters.
2227          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2228          # Get the specified feature's translation.          # Get the specified feature's translation.
2229          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
2230          return $retVal;          return $retVal;
# Line 1789  Line 2256 
2256  #: Return Type @;  #: Return Type @;
2257  sub Taxonomy {  sub Taxonomy {
2258          # Get the parameters.          # Get the parameters.
2259          my $self = shift @_;      my ($self, $genome) = @_;
         my ($genome) = @_;  
2260          # Find the specified genome's taxonomy string.          # Find the specified genome's taxonomy string.
2261          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);
2262          # Declare the return variable.          # Declare the return variable.
# Line 1833  Line 2299 
2299  #: Return Type $;  #: Return Type $;
2300  sub CrudeDistance {  sub CrudeDistance {
2301          # Get the parameters.          # Get the parameters.
2302          my $self = shift @_;      my ($self, $genome1, $genome2) = @_;
         my ($genome1, $genome2) = @_;  
2303          # Insure that the distance is commutative by sorting the genome IDs.          # Insure that the distance is commutative by sorting the genome IDs.
2304          my ($genomeA, $genomeB);          my ($genomeA, $genomeB);
2305          if ($genome2 < $genome2) {          if ($genome2 < $genome2) {
# Line 1881  Line 2346 
2346  #: Return Type $;  #: Return Type $;
2347  sub RoleName {  sub RoleName {
2348          # Get the parameters.          # Get the parameters.
2349          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2350          # Get the specified role's name.          # Get the specified role's name.
2351          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);
2352          # Use the ID if the role has no name.          # Use the ID if the role has no name.
# Line 1915  Line 2379 
2379  #: Return Type @;  #: Return Type @;
2380  sub RoleDiagrams {  sub RoleDiagrams {
2381          # Get the parameters.          # Get the parameters.
2382          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2383          # Query for the diagrams.          # Query for the diagrams.
2384          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2385                                                                  'RoleOccursIn(to-link)');                                                                  'RoleOccursIn(to-link)');
# Line 1924  Line 2387 
2387          return @retVal;          return @retVal;
2388  }  }
2389    
2390    =head3 GetProperties
2391    
2392    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2393    
2394    Return a list of the properties with the specified characteristics.
2395    
2396    Properties are arbitrary key-value pairs associated with a feature. (At some point they
2397    will also be associated with genomes.) A property value is represented by a 4-tuple of
2398    the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2399    
2400    =over 4
2401    
2402    =item fid
2403    
2404    ID of the feature possessing the property.
2405    
2406    =item key
2407    
2408    Name or key of the property.
2409    
2410    =item value
2411    
2412    Value of the property.
2413    
2414    =item url
2415    
2416    URL of the document that indicated the property should have this particular value, or an
2417    empty string if no such document exists.
2418    
2419    =back
2420    
2421    The parameters act as a filter for the desired data. Any non-null parameter will
2422    automatically match all the tuples returned. So, specifying just the I<$fid> will
2423    return all the properties of the specified feature; similarly, specifying the I<$key>
2424    and I<$value> parameters will return all the features having the specified property
2425    value.
2426    
2427    A single property key can have many values, representing different ideas about the
2428    feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2429    virulent, and another may declare that it is not virulent. A query about the virulence of
2430    C<fig|83333.1.peg.10> would be coded as
2431    
2432        my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2433    
2434    Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2435    not to be filtered. The tuples returned would be
2436    
2437        ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2438        ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2439    
2440    =cut
2441    #: Return Type @@;
2442    sub GetProperties {
2443        # Get the parameters.
2444        my ($self, @parms) = @_;
2445        # Declare the return variable.
2446        my @retVal = ();
2447        # Now we need to create a WHERE clause that will get us the data we want. First,
2448        # we create a list of the columns containing the data for each parameter.
2449        my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2450                        'Property(property-value)', 'HasProperty(evidence)');
2451        # Now we build the WHERE clause and the list of parameter values.
2452        my @where = ();
2453        my @values = ();
2454        for (my $i = 0; $i <= $#colNames; $i++) {
2455            my $parm = $parms[$i];
2456            if (defined $parm && ($parm ne '')) {
2457                push @where, "$colNames[$i] = ?";
2458                push @values, $parm;
2459            }
2460        }
2461        # Format the WHERE clause.
2462        my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2463        # Ask for all the propertie values with the desired characteristics.
2464        my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2465        while (my $valueObject = $query->Fetch()) {
2466            my @tuple = $valueObject->Values(\@colNames);
2467            push @retVal, \@tuple;
2468        }
2469        # Return the result.
2470        return @retVal;
2471    }
2472    
2473  =head3 FeatureProperties  =head3 FeatureProperties
2474    
2475  C<< my @properties = $sprout->FeatureProperties($featureID); >>  C<< my @properties = $sprout->FeatureProperties($featureID); >>
# Line 1953  Line 2499 
2499  #: Return Type @@;  #: Return Type @@;
2500  sub FeatureProperties {  sub FeatureProperties {
2501          # Get the parameters.          # Get the parameters.
2502          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2503          # Get the properties.          # Get the properties.
2504          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],
2505                                                          ['Property(property-name)', 'Property(property-value)',                                                          ['Property(property-name)', 'Property(property-value)',
# Line 1985  Line 2530 
2530  #: Return Type $;  #: Return Type $;
2531  sub DiagramName {  sub DiagramName {
2532          # Get the parameters.          # Get the parameters.
2533          my $self = shift @_;      my ($self, $diagramID) = @_;
         my ($diagramID) = @_;  
2534          # Get the specified diagram's name and return it.          # Get the specified diagram's name and return it.
2535          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);
2536          return $retVal;          return $retVal;
# Line 2018  Line 2562 
2562  #: Return Type @;  #: Return Type @;
2563  sub MergedAnnotations {  sub MergedAnnotations {
2564          # Get the parameters.          # Get the parameters.
2565          my $self = shift @_;      my ($self, $list) = @_;
         my ($list) = @_;  
2566          # Create a list to hold the annotation tuples found.          # Create a list to hold the annotation tuples found.
2567          my @tuples = ();          my @tuples = ();
2568          # Loop through the features in the input list.          # Loop through the features in the input list.
# Line 2067  Line 2610 
2610  #: Return Type @;  #: Return Type @;
2611  sub RoleNeighbors {  sub RoleNeighbors {
2612          # Get the parameters.          # Get the parameters.
2613          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2614          # Get all the diagrams containing this role.          # Get all the diagrams containing this role.
2615          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2616                                                                    'RoleOccursIn(to-link)');                                                                    'RoleOccursIn(to-link)');
# Line 2110  Line 2652 
2652  #: Return Type @;  #: Return Type @;
2653  sub FeatureLinks {  sub FeatureLinks {
2654          # Get the parameters.          # Get the parameters.
2655          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2656          # Get the feature's links.          # Get the feature's links.
2657          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);
2658          # Return the feature's links.          # Return the feature's links.
# Line 2123  Line 2664 
2664  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2665    
2666  Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped  Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped
2667  to the role the feature performs.  to the roles the feature performs.
2668    
2669  =over 4  =over 4
2670    
# Line 2133  Line 2674 
2674    
2675  =item RETURN  =item RETURN
2676    
2677  Returns a hash mapping all the feature's subsystems to the feature's role.  Returns a hash mapping all the feature's subsystems to a list of the feature's roles.
2678    
2679  =back  =back
2680    
2681  =cut  =cut
2682  #: Return Type %;  #: Return Type %@;
2683  sub SubsystemsOf {  sub SubsystemsOf {
2684          # Get the parameters.          # Get the parameters.
2685          my $self = shift @_;      my ($self, $featureID) = @_;
2686          my ($featureID) = @_;      # Get the subsystem list.
         # Use the SSCell to connect features to subsystems.  
2687          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2688                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2689                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2690          # Create the return value.          # Create the return value.
2691          my %retVal = ();          my %retVal = ();
2692        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2693        # in two spreadsheet cells.
2694        my %dupHash = ();
2695          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
2696          for my $record (@subsystems) {          for my $record (@subsystems) {
2697                  $retVal{$record->[0]} = $record->[1];          # Get this subsystem and role.
2698            my ($subsys, $role) = @{$record};
2699            # Insure it's the first time for both.
2700            my $dupKey = "$subsys\n$role";
2701            if (! exists $dupHash{"$subsys\n$role"}) {
2702                $dupHash{$dupKey} = 1;
2703                push @{$retVal{$subsys}}, $role;
2704            }
2705          }          }
2706          # Return the hash.          # Return the hash.
2707          return %retVal;          return %retVal;
2708  }  }
2709    
2710    =head3 SubsystemList
2711    
2712    C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2713    
2714    Return a list containing the names of the subsystems in which the specified
2715    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2716    subsystem names, not the roles.
2717    
2718    =over 4
2719    
2720    =item featureID
2721    
2722    ID of the feature whose subsystem names are desired.
2723    
2724    =item RETURN
2725    
2726    Returns a list of the names of the subsystems in which the feature participates.
2727    
2728    =back
2729    
2730    =cut
2731    #: Return Type @;
2732    sub SubsystemList {
2733        # Get the parameters.
2734        my ($self, $featureID) = @_;
2735        # Get the list of names.
2736        my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",
2737                                    [$featureID], 'HasSSCell(from-link)');
2738        # Return the result.
2739        return @retVal;
2740    }
2741    
2742    
2743    
2744  =head3 RelatedFeatures  =head3 RelatedFeatures
2745    
2746  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2190  Line 2774 
2774  #: Return Type @;  #: Return Type @;
2775  sub RelatedFeatures {  sub RelatedFeatures {
2776          # Get the parameters.          # Get the parameters.
2777          my $self = shift @_;      my ($self, $featureID, $function, $userID) = @_;
         my ($featureID, $function, $userID) = @_;  
2778          # 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.
2779          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],
2780                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],
# Line 2239  Line 2822 
2822  #: Return Type @;  #: Return Type @;
2823  sub TaxonomySort {  sub TaxonomySort {
2824          # Get the parameters.          # Get the parameters.
2825          my $self = shift @_;      my ($self, $featureIDs) = @_;
         my ($featureIDs) = @_;  
2826          # Create the working hash table.          # Create the working hash table.
2827          my %hashBuffer = ();          my %hashBuffer = ();
2828          # Loop through the features.          # Loop through the features.
# Line 2249  Line 2831 
2831                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
2832                                                                                  [$fid], 'Genome(taxonomy)');                                                                                  [$fid], 'Genome(taxonomy)');
2833                  # Add this feature to the hash buffer.                  # Add this feature to the hash buffer.
2834                  if (exists $hashBuffer{$taxonomy}) {          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);
                         push @{$hashBuffer{$taxonomy}}, $fid;  
                 } else {  
                         $hashBuffer{$taxonomy} = [$fid];  
                 }  
2835          }          }
2836          # Sort the keys and get the elements.          # Sort the keys and get the elements.
2837          my @retVal = ();          my @retVal = ();
# Line 2322  Line 2900 
2900  #: Return Type @@;  #: Return Type @@;
2901  sub GetAll {  sub GetAll {
2902          # Get the parameters.          # Get the parameters.
2903          my $self = shift @_;      my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
2904          my ($objectNames, $filterClause, $parameterList, $fields, $count) = @_;      # Call the ERDB method.
2905          # Create the query.      my @retVal = $self->{_erdb}->GetAll($objectNames, $filterClause, $parameterList,
2906          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++;  
         }  
2907          # Return the resulting list.          # Return the resulting list.
2908          return @retVal;          return @retVal;
2909  }  }
# Line 2384  Line 2948 
2948  #: Return Type @;  #: Return Type @;
2949  sub GetFlat {  sub GetFlat {
2950          # Get the parameters.          # Get the parameters.
2951          my $self = shift @_;      my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
         my ($objectNames, $filterClause, $parameterList, $field) = @_;  
2952          # Construct the query.          # Construct the query.
2953          my $query = $self->Get($objectNames, $filterClause, $parameterList);          my $query = $self->Get($objectNames, $filterClause, $parameterList);
2954          # Create the result list.          # Create the result list.
# Line 2495  Line 3058 
3058  #: Return Type @;  #: Return Type @;
3059  sub LoadInfo {  sub LoadInfo {
3060          # Get the parameters.          # Get the parameters.
3061          my $self = shift @_;      my ($self) = @_;
3062          # 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.
3063          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
3064          # Concatenate the table names.          # Concatenate the table names.
# Line 2532  Line 3095 
3095  #: Return Type %;  #: Return Type %;
3096  sub LowBBHs {  sub LowBBHs {
3097          # Get the parsameters.          # Get the parsameters.
3098          my $self = shift @_;      my ($self, $featureID, $cutoff) = @_;
         my ($featureID, $cutoff) = @_;  
3099          # Create the return hash.          # Create the return hash.
3100          my %retVal = ();          my %retVal = ();
3101          # Create a query to get the desired BBHs.          # Create a query to get the desired BBHs.
# Line 2551  Line 3113 
3113    
3114  =head3 GetGroups  =head3 GetGroups
3115    
3116    C<< my %groups = $sprout->GetGroups(\@groupList); >>
3117    
3118    Return a hash mapping each group to the IDs of the genomes in the group.
3119    A list of groups may be specified, in which case only those groups will be
3120    shown. Alternatively, if no parameter is supplied, all groups will be
3121    included. Genomes that are not in any group are omitted.
3122    
3123  =cut  =cut
3124  #: Return Type %@;  #: Return Type %@;
3125  sub GetGroups {  sub GetGroups {
3126        # Get the parameters.
3127        my ($self, $groupList) = @_;
3128        # Declare the return value.
3129        my %retVal = ();
3130        # Determine whether we are getting all the groups or just some.
3131        if (defined $groupList) {
3132            # Here we have a group list. Loop through them individually,
3133            # getting a list of the relevant genomes.
3134            for my $group (@{$groupList}) {
3135                my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",
3136                    [$group], "Genome(id)");
3137                $retVal{$group} = \@genomeIDs;
3138            }
3139        } else {
3140            # Here we need all of the groups. In this case, we run through all
3141            # of the genome records, putting each one found into the appropriate
3142            # group. Note that we use a filter clause to insure that only genomes
3143            # in groups are included in the return set.
3144            my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],
3145                                        ['Genome(id)', 'Genome(group-name)']);
3146            # Loop through the genomes found.
3147            for my $genome (@genomes) {
3148                # Pop this genome's ID off the current list.
3149                my @groups = @{$genome};
3150                my $genomeID = shift @groups;
3151                # Loop through the groups, adding the genome ID to each group's
3152                # list.
3153                for my $group (@groups) {
3154                    Tracer::AddToListMap(\%retVal, $group, $genomeID);
3155                }
3156            }
3157        }
3158        # Return the hash we just built.
3159        return %retVal;
3160    }
3161    
3162    =head3 MyGenomes
3163    
3164    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
3165    
3166    Return a list of the genomes to be included in the Sprout.
3167    
3168    This method is provided for use during the Sprout load. It presumes the Genome load file has
3169    already been created. (It will be in the Sprout data directory and called either C<Genome>
3170    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3171    IDs.
3172    
3173    =over 4
3174    
3175    =item dataDir
3176    
3177    Directory containing the Sprout load files.
3178    
3179    =back
3180    
3181    =cut
3182    #: Return Type @;
3183    sub MyGenomes {
3184        # Get the parameters.
3185        my ($dataDir) = @_;
3186        # Compute the genome file name.
3187        my $genomeFileName = LoadFileName($dataDir, "Genome");
3188        # Extract the genome IDs from the files.
3189        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3190        # Return the result.
3191        return @retVal;
3192    }
3193    
3194    =head3 LoadFileName
3195    
3196    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3197    
3198    Return the name of the load file for the specified table in the specified data
3199    directory.
3200    
3201    =over 4
3202    
3203    =item dataDir
3204    
3205    Directory containing the Sprout load files.
3206    
3207    =item tableName
3208    
3209    Name of the table whose load file is desired.
3210    
3211    =item RETURN
3212    
3213    Returns the name of the file containing the load data for the specified table, or
3214    C<undef> if no load file is present.
3215    
3216    =back
3217    
3218    =cut
3219    #: Return Type $;
3220    sub LoadFileName {
3221        # Get the parameters.
3222        my ($dataDir, $tableName) = @_;
3223        # Declare the return variable.
3224        my $retVal;
3225        # Check for the various file names.
3226        if (-e "$dataDir/$tableName") {
3227            $retVal = "$dataDir/$tableName";
3228        } elsif (-e "$dataDir/$tableName.dtx") {
3229            $retVal = "$dataDir/$tableName.dtx";
3230        }
3231        # Return the result.
3232        return $retVal;
3233    }
3234    
3235    =head3 DeleteGenome
3236    
3237    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3238    
3239    Delete a genome from the database.
3240    
3241    =over 4
3242    
3243    =item genomeID
3244    
3245    ID of the genome to delete
3246    
3247    =item testFlag
3248    
3249    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3250    
3251    =item RETURN
3252    
3253    Returns a statistics object describing the rows deleted.
3254    
3255    =back
3256    
3257    =cut
3258    #: Return Type $%;
3259    sub DeleteGenome {
3260        # Get the parameters.
3261        my ($self, $genomeID, $testFlag) = @_;
3262        # Perform the delete for the genome's features.
3263        my $retVal = $self->{_erdb}->Delete('Feature', "fig|$genomeID.%", $testFlag);
3264        # Perform the delete for the primary genome data.
3265        my $stats = $self->{_erdb}->Delete('Genome', $genomeID, $testFlag);
3266        $retVal->Accumulate($stats);
3267        # Return the result.
3268        return $retVal;
3269  }  }
3270    
3271  =head2 Internal Utility Methods  =head2 Internal Utility Methods
# Line 2561  Line 3273 
3273  =head3 ParseAssignment  =head3 ParseAssignment
3274    
3275  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,
3276  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
3277  will be returned.  isn't, an empty list will be returned.
3278    
3279    A functional assignment is always of the form
3280    
3281        C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3282    
3283    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3284    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3285    not always the case.
3286    
3287    In addition, the functional role may contain extra data that is stripped, such as
3288    terminating spaces or a comment separated from the rest of the text by a tab.
3289    
3290  This is a static method.  This is a static method.
3291    
3292  =over 4  =over 4
3293    
3294    =item user
3295    
3296    Name of the assigning user.
3297    
3298  =item text  =item text
3299    
3300  Text of the annotation.  Text of the annotation.
# Line 2581  Line 3308 
3308    
3309  =cut  =cut
3310    
3311  sub ParseAssignment {  sub _ParseAssignment {
3312          # Get the parameters.          # Get the parameters.
3313          my ($text) = @_;      my ($user, $text) = @_;
3314          # Declare the return value.          # Declare the return value.
3315          my @retVal = ();          my @retVal = ();
3316          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3317          my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3318          if ($type =~ m/^set $user function to$/i) {      if ($type =~ m/^set function to$/i) {
3319                  # Here it is, so we return the user name and function text.          # Here we have an assignment without a user, so we use the incoming user ID.
3320                  @retVal = ($user, $function);                  @retVal = ($user, $function);
3321        } elsif ($type =~ m/^set (\S+) function to$/i) {
3322            # Here we have an assignment with a user that is passed back to the caller.
3323            @retVal = ($1, $function);
3324        }
3325        # If we have an assignment, we need to clean the function text. There may be
3326        # extra junk at the end added as a note from the user.
3327        if (@retVal) {
3328            $retVal[1] =~ s/(\t\S)?\s*$//;
3329          }          }
3330          # Return the result list.          # Return the result list.
3331          return @retVal;          return @retVal;
# Line 2618  Line 3353 
3353    
3354  sub FriendlyTimestamp {  sub FriendlyTimestamp {
3355      my ($timeValue) = @_;      my ($timeValue) = @_;
3356      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
3357      return $retVal;      return $retVal;
3358  }  }
3359    
3360    =head3 AddProperty
3361    
3362    C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>
3363    
3364    Add a new attribute value (Property) to a feature. In the SEED system, attributes can
3365    be added to almost any object. In Sprout, they can only be added to features. In
3366    Sprout, attributes are implemented using I<properties>. A property represents a key/value
3367    pair. If the particular key/value pair coming in is not already in the database, a new
3368    B<Property> record is created to hold it.
3369    
3370    =over 4
3371    
3372    =item peg
3373    
3374    ID of the feature to which the attribute is to be replied.
3375    
3376    =item key
3377    
3378    Name of the attribute (key).
3379    
3380    =item value
3381    
3382    Value of the attribute.
3383    
3384    =item url
3385    
3386    URL or text citation from which the property was obtained.
3387    
3388    =back
3389    
3390    =cut
3391    #: Return Type ;
3392    sub AddProperty {
3393        # Get the parameters.
3394        my ($self, $featureID, $key, $value, $url) = @_;
3395        # Declare the variable to hold the desired property ID.
3396        my $propID;
3397        # Attempt to find a property record for this key/value pair.
3398        my @properties = $self->GetFlat(['Property'],
3399                                       "Property(property-name) = ? AND Property(property-value) = ?",
3400                                       [$key, $value], 'Property(id)');
3401        if (@properties) {
3402            # Here the property is already in the database. We save its ID.
3403            $propID = $properties[0];
3404            # Here the property value does not exist. We need to generate an ID. It will be set
3405            # to a number one greater than the maximum value in the database. This call to
3406            # GetAll will stop after one record.
3407            my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],
3408                                            1);
3409            $propID = $maxProperty[0]->[0] + 1;
3410            # Insert the new property value.
3411            $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });
3412        }
3413        # Now we connect the incoming feature to the property.
3414        $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3415    }
3416    
3417    
3418  1;  1;

Legend:
Removed from v.1.7  
changed lines
  Added in v.1.57

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3