[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.63, Sun Jun 18 07:03:00 2006 UTC revision 1.99, Fri Apr 27 22:21:46 2007 UTC
# Line 5  Line 5 
5      @ISA = qw(Exporter ERDB);      @ISA = qw(Exporter ERDB);
6      use Data::Dumper;      use Data::Dumper;
7      use strict;      use strict;
     use Carp;  
8      use DBKernel;      use DBKernel;
9      use XML::Simple;      use XML::Simple;
10      use DBQuery;      use DBQuery;
11      use DBObject;      use ERDBObject;
12      use Tracer;      use Tracer;
13      use FIGRules;      use FIGRules;
14        use FidCheck;
15      use Stats;      use Stats;
16      use POSIX qw(strftime);      use POSIX qw(strftime);
17        use BasicLocation;
18        use CustomAttributes;
19        use RemoteCustomAttributes;
20    
21  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
22    
# Line 91  Line 93 
93  sub new {  sub new {
94      # Get the parameters.      # Get the parameters.
95      my ($class, $dbName, $options) = @_;      my ($class, $dbName, $options) = @_;
96        # Compute the DBD directory.
97        my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
98                                                      $FIG_Config::fig );
99      # 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
100      # the incoming data.      # the incoming data.
101      my $optionTable = Tracer::GetOptions({      my $optionTable = Tracer::GetOptions({
# Line 98  Line 103 
103                                                          # database type                                                          # database type
104                         dataDir      => $FIG_Config::sproutData,                         dataDir      => $FIG_Config::sproutData,
105                                                          # data file directory                                                          # data file directory
106                         xmlFileName  => "$FIG_Config::fig/SproutDBD.xml",                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
107                                                          # database definition file name                                                          # database definition file name
108                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
109                                                          # user name and password                                                          # user name and password
110                         port         => $FIG_Config::dbport,                         port         => $FIG_Config::dbport,
111                                                          # database connection port                                                          # database connection port
112                         sock         => $FIG_Config::dbsock,                         sock         => $FIG_Config::dbsock,
113                           host         => $FIG_Config::dbhost,
114                         maxSegmentLength => 4500,        # maximum feature segment length                         maxSegmentLength => 4500,        # maximum feature segment length
115                         maxSequenceLength => 8000,       # maximum contig sequence length                         maxSequenceLength => 8000,       # maximum contig sequence length
116                         noDBOpen     => 0,               # 1 to suppress the database open                         noDBOpen     => 0,               # 1 to suppress the database open
# Line 118  Line 124 
124      my $dbh;      my $dbh;
125      if (! $optionTable->{noDBOpen}) {      if (! $optionTable->{noDBOpen}) {
126          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
127                                  $password, $optionTable->{port}, undef, $optionTable->{sock});                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
128      }      }
129      # Create the ERDB object.      # Create the ERDB object.
130      my $xmlFileName = "$optionTable->{xmlFileName}";      my $xmlFileName = "$optionTable->{xmlFileName}";
# Line 126  Line 132 
132      # Add the option table and XML file name.      # Add the option table and XML file name.
133      $retVal->{_options} = $optionTable;      $retVal->{_options} = $optionTable;
134      $retVal->{_xmlName} = $xmlFileName;      $retVal->{_xmlName} = $xmlFileName;
135        # Set up space for the group file data.
136        $retVal->{groupHash} = undef;
137        # Connect to the attributes.
138        if ($FIG_Config::attrURL) {
139            Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);
140            $retVal->{_ca} = RemoteCustomAttributes->new($FIG_Config::attrURL);
141        } elsif ($FIG_Config::attrDbName) {
142            Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);
143            my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));
144            $retVal->{_ca} = CustomAttributes->new(user => $user);
145        }
146      # Return it.      # Return it.
147      return $retVal;      return $retVal;
148  }  }
# Line 335  Line 352 
352    
353  =head3 GeneMenu  =head3 GeneMenu
354    
355  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params); >>  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected); >>
356    
357  Return an HTML select menu of genomes. Each genome will be an option in the menu,  Return an HTML select menu of genomes. Each genome will be an option in the menu,
358  and will be displayed by name with the ID and a contig count attached. The selection  and will be displayed by name with the ID and a contig count attached. The selection
# Line 357  Line 374 
374  Reference to a list of values to be substituted in for the parameter marks in  Reference to a list of values to be substituted in for the parameter marks in
375  the filter string.  the filter string.
376    
377    =item selected (optional)
378    
379    ID of the genome to be initially selected.
380    
381    =item fast (optional)
382    
383    If specified and TRUE, the contig counts will be omitted to improve performance.
384    
385  =item RETURN  =item RETURN
386    
387  Returns an HTML select menu with the specified genomes as selectable options.  Returns an HTML select menu with the specified genomes as selectable options.
# Line 367  Line 392 
392    
393  sub GeneMenu {  sub GeneMenu {
394      # Get the parameters.      # Get the parameters.
395      my ($self, $attributes, $filterString, $params) = @_;      my ($self, $attributes, $filterString, $params, $selected, $fast) = @_;
396        my $slowMode = ! $fast;
397        # Default to nothing selected. This prevents an execution warning if "$selected"
398        # is undefined.
399        $selected = "" unless defined $selected;
400        Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3);
401      # Start the menu.      # Start the menu.
402      my $retVal = "<select " .      my $retVal = "<select " .
403          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
# Line 375  Line 405 
405      # Get the genomes.      # Get the genomes.
406      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
407                                                                       'Genome(genus)',                                                                       'Genome(genus)',
408                                                                       'Genome(species)']);                                                                       'Genome(species)',
409                                                                         'Genome(unique-characterization)']);
410      # Sort them by name.      # Sort them by name.
411      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
412      # Loop through the genomes, creating the option tags.      # Loop through the genomes, creating the option tags.
413      for my $genomeData (@sorted) {      for my $genomeData (@sorted) {
414          # Get the data for this genome.          # Get the data for this genome.
415          my ($genomeID, $genus, $species) = @{$genomeData};          my ($genomeID, $genus, $species, $strain) = @{$genomeData};
416          # Get the contig count.          # Get the contig count.
417            my $contigInfo = "";
418            if ($slowMode) {
419          my $count = $self->ContigCount($genomeID);          my $count = $self->ContigCount($genomeID);
420          my $counting = ($count == 1 ? "contig" : "contigs");          my $counting = ($count == 1 ? "contig" : "contigs");
421                $contigInfo = "[$count $counting]";
422            }
423            # Find out if we're selected.
424            my $selectOption = ($selected eq $genomeID ? " selected" : "");
425          # Build the option tag.          # Build the option tag.
426          $retVal .= "<option value=\"$genomeID\">$genus $species ($genomeID) [$count $counting]</option>\n";          $retVal .= "<option value=\"$genomeID\"$selectOption>$genus $species $strain ($genomeID)$contigInfo</option>\n";
427      }      }
428      # Close the SELECT tag.      # Close the SELECT tag.
429      $retVal .= "</select>\n";      $retVal .= "</select>\n";
430      # Return the result.      # Return the result.
431      return $retVal;      return $retVal;
432  }  }
433    
434  =head3 Build  =head3 Build
435    
436  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 627  Line 665 
665      return ($contigID, $start, $dir, $len);      return ($contigID, $start, $dir, $len);
666  }  }
667    
668    
669    
670  =head3 PointLocation  =head3 PointLocation
671    
672  C<< my $found = Sprout::PointLocation($location, $point); >>  C<< my $found = Sprout::PointLocation($location, $point); >>
# Line 836  Line 876 
876    
877  =over 4  =over 4
878    
879  =genomeID  =item genomeID
880    
881  ID of the genome whose feature count is desired.  ID of the genome whose feature count is desired.
882    
# Line 857  Line 897 
897      my ($self, $genomeID, $type) = @_;      my ($self, $genomeID, $type) = @_;
898      # Compute the count.      # Compute the count.
899      my $retVal = $self->GetCount(['HasFeature', 'Feature'],      my $retVal = $self->GetCount(['HasFeature', 'Feature'],
900                                  "HasFeature(from-link) = ? AND Feature(type) = ?",                                  "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
901                                  [$genomeID, $type]);                                  [$genomeID, $type]);
902      # Return the result.      # Return the result.
903      return $retVal;      return $retVal;
# Line 891  Line 931 
931      my ($self, $genomeID) = @_;      my ($self, $genomeID) = @_;
932      # Declare the return variable.      # Declare the return variable.
933      my $retVal = {};      my $retVal = {};
934      # Query the genome's features and annotations. We'll put the oldest annotations      # Query the genome's features.
935      # first so that the last assignment to go into the hash will be the correct one.      my $query = $self->Get(['HasFeature', 'Feature'], "HasFeature(from-link) = ?",
     my $query = $self->Get(['HasFeature', 'IsTargetOfAnnotation', 'Annotation'],  
                            "HasFeature(from-link) = ? ORDER BY Annotation(time)",  
936                             [$genomeID]);                             [$genomeID]);
937      # Loop through the annotations.      # Loop through the features.
938      while (my $data = $query->Fetch) {      while (my $data = $query->Fetch) {
939          # Get the feature ID and annotation text.          # Get the feature ID and assignment.
940          my ($fid, $annotation) = $data->Values(['HasFeature(from-link)',          my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']);
941                                                  'Annotation(text)']);          if ($assignment) {
         # Check to see if this is an assignment. Note that the user really  
         # doesn't matter to us, other than we use it to determine whether or  
         # not this is an assignment.  
         my ($user, $assignment) = $self->_ParseAssignment('fig', $annotation);  
         if ($user) {  
             # Here it's an assignment. We put it in the return hash, overwriting  
             # any older assignment that might be present.  
942              $retVal->{$fid} = $assignment;              $retVal->{$fid} = $assignment;
943          }          }
944      }      }
# Line 1269  Line 1300 
1300  Return the most recently-determined functional assignment of a particular feature.  Return the most recently-determined functional assignment of a particular feature.
1301    
1302  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
1303  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 the functional
1304  assignment is a type of annotation. The format of an assignment is described in  assignment is taken from the B<Feature> or C<Annotation> table, depending.
 L</ParseAssignment>. Its worth noting that we cannot filter on the content of the  
 annotation itself because it's a text field; however, this is not a big problem because  
 most features only have a small number of annotations.  
1305    
1306  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
1307  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 1292  Line 1320 
1320    
1321  =item userID (optional)  =item userID (optional)
1322    
1323  ID of the user whose function determination is desired. If omitted, only the latest  ID of the user whose function determination is desired. If omitted, the primary
1324  C<FIG> assignment will be returned.  functional assignment in the B<Feature> table will be returned.
1325    
1326  =item RETURN  =item RETURN
1327    
# Line 1310  Line 1338 
1338      my $retVal;      my $retVal;
1339      # Determine the ID type.      # Determine the ID type.
1340      if ($featureID =~ m/^fig\|/) {      if ($featureID =~ m/^fig\|/) {
1341          # Here we have a FIG feature ID. We must build the list of trusted          # Here we have a FIG feature ID.
1342          # users.          if (!$userID) {
1343                # Use the primary assignment.
1344                ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']);
1345            } else {
1346                # We must build the list of trusted users.
1347          my %trusteeTable = ();          my %trusteeTable = ();
1348          # Check the user ID.          # Check the user ID.
1349          if (!$userID) {          if (!$userID) {
# Line 1354  Line 1386 
1386                  }                  }
1387              }              }
1388          }          }
1389            }
1390      } else {      } else {
1391          # Here we have a non-FIG feature ID. In this case the user ID does not          # Here we have a non-FIG feature ID. In this case the user ID does not
1392          # matter. We simply get the information from the External Alias Function          # matter. We simply get the information from the External Alias Function
# Line 1469  Line 1502 
1502      my %retVal = ();      my %retVal = ();
1503      # Loop through the incoming features.      # Loop through the incoming features.
1504      for my $featureID (@{$featureList}) {      for my $featureID (@{$featureList}) {
1505          # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1506          my $query = $self->Get(['IsBidirectionalBestHitOf'],          my @bbhData = FIGRules::BBHData($featureID);
                                "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",  
                                [$featureID, $genomeID]);  
1507          # Peel off the BBHs found.          # Peel off the BBHs found.
1508          my @found = ();          my @found = ();
1509          while (my $bbh = $query->Fetch) {          for my $bbh (@bbhData) {
1510              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');              my $fid = $bbh->[0];
1511                my $bbGenome = $self->GenomeOf($fid);
1512                if ($bbGenome eq $genomeID) {
1513                    push @found, $fid;
1514                }
1515          }          }
1516          $retVal{$featureID} = \@found;          $retVal{$featureID} = \@found;
1517      }      }
# Line 1490  Line 1525 
1525    
1526  Return a list of the similarities to the specified feature.  Return a list of the similarities to the specified feature.
1527    
1528  Sprout does not support real similarities, so this method just returns the bidirectional  This method just returns the bidirectional best hits for performance reasons.
 best hits.  
1529    
1530  =over 4  =over 4
1531    
# Line 1511  Line 1545 
1545      # Get the parameters.      # Get the parameters.
1546      my ($self, $featureID, $count) = @_;      my ($self, $featureID, $count) = @_;
1547      # Ask for the best hits.      # Ask for the best hits.
1548      my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],      my @lists = FIGRules::BBHData($featureID);
                               "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",  
                               [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],  
                               $count);  
1549      # Create the return value.      # Create the return value.
1550      my %retVal = ();      my %retVal = ();
1551      for my $tuple (@lists) {      for my $tuple (@lists) {
# Line 1524  Line 1555 
1555      return %retVal;      return %retVal;
1556  }  }
1557    
   
   
1558  =head3 IsComplete  =head3 IsComplete
1559    
1560  C<< my $flag = $sprout->IsComplete($genomeID); >>  C<< my $flag = $sprout->IsComplete($genomeID); >>
# Line 1653  Line 1682 
1682  sub CoupledFeatures {  sub CoupledFeatures {
1683      # Get the parameters.      # Get the parameters.
1684      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1685        Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1686      # Create a query to retrieve the functionally-coupled features.      # Create a query to retrieve the functionally-coupled features.
1687      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1688                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);
# Line 1665  Line 1695 
1695          # Get the ID and score of the coupling.          # Get the ID and score of the coupling.
1696          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1697                                                          'Coupling(score)']);                                                          'Coupling(score)']);
1698            Trace("$featureID coupled with score $score to ID $couplingID.") if T(coupling => 4);
1699          # Get the other feature that participates in the coupling.          # Get the other feature that participates in the coupling.
1700          my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],          my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],
1701                                             "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",                                             "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",
1702                                             [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');                                             [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');
1703            Trace("$couplingID target feature is $otherFeatureID.") if T(coupling => 4);
1704          # Attach the other feature's score to its ID.          # Attach the other feature's score to its ID.
1705          $retVal{$otherFeatureID} = $score;          $retVal{$otherFeatureID} = $score;
1706          $found = 1;          $found = 1;
# Line 1801  Line 1833 
1833      my ($self, $peg1, $peg2) = @_;      my ($self, $peg1, $peg2) = @_;
1834      # Declare the return values. We'll start with the coupling ID and undefine the      # Declare the return values. We'll start with the coupling ID and undefine the
1835      # flag and score until we have more information.      # flag and score until we have more information.
1836      my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);      my ($retVal, $inverted, $score) = ($self->CouplingID($peg1, $peg2), undef, undef);
1837      # Find the coupling data.      # Find the coupling data.
1838      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1839                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
# Line 1822  Line 1854 
1854      return ($retVal, $inverted, $score);      return ($retVal, $inverted, $score);
1855  }  }
1856    
1857    =head3 GetSynonymGroup
1858    
1859    C<< my $id = $sprout->GetSynonymGroup($fid); >>
1860    
1861    Return the synonym group name for the specified feature.
1862    
1863    =over 4
1864    
1865    =item fid
1866    
1867    ID of the feature whose synonym group is desired.
1868    
1869    =item RETURN
1870    
1871    The name of the synonym group to which the feature belongs. If the feature does
1872    not belong to a synonym group, the feature ID itself is returned.
1873    
1874    =back
1875    
1876    =cut
1877    
1878    sub GetSynonymGroup {
1879        # Get the parameters.
1880        my ($self, $fid) = @_;
1881        # Declare the return variable.
1882        my $retVal;
1883        # Find the synonym group.
1884        my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1885                                       [$fid], 'IsSynonymGroupFor(from-link)');
1886        # Check to see if we found anything.
1887        if (@groups) {
1888            $retVal = $groups[0];
1889        } else {
1890            $retVal = $fid;
1891        }
1892        # Return the result.
1893        return $retVal;
1894    }
1895    
1896    =head3 GetBoundaries
1897    
1898    C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>
1899    
1900    Determine the begin and end boundaries for the locations in a list. All of the
1901    locations must belong to the same contig and have mostly the same direction in
1902    order for this method to produce a meaningful result. The resulting
1903    begin/end pair will contain all of the bases in any of the locations.
1904    
1905    =over 4
1906    
1907    =item locList
1908    
1909    List of locations to process.
1910    
1911    =item RETURN
1912    
1913    Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1914    and the ending boundary. The beginning boundary will be left of the
1915    end for mostly-forward locations and right of the end for mostly-backward
1916    locations.
1917    
1918    =back
1919    
1920    =cut
1921    
1922    sub GetBoundaries {
1923        # Get the parameters.
1924        my ($self, @locList) = @_;
1925        # Set up the counters used to determine the most popular direction.
1926        my %counts = ( '+' => 0, '-' => 0 );
1927        # Get the last location and parse it.
1928        my $locObject = BasicLocation->new(pop @locList);
1929        # Prime the loop with its data.
1930        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
1931        # Count its direction.
1932        $counts{$locObject->Dir}++;
1933        # Loop through the remaining locations. Note that in most situations, this loop
1934        # will not iterate at all, because most of the time we will be dealing with a
1935        # singleton list.
1936        for my $loc (@locList) {
1937            # Create a location object.
1938            my $locObject = BasicLocation->new($loc);
1939            # Count the direction.
1940            $counts{$locObject->Dir}++;
1941            # Get the left end and the right end.
1942            my $left = $locObject->Left;
1943            my $right = $locObject->Right;
1944            # Merge them into the return variables.
1945            if ($left < $beg) {
1946                $beg = $left;
1947            }
1948            if ($right > $end) {
1949                $end = $right;
1950            }
1951        }
1952        # If the most common direction is reverse, flip the begin and end markers.
1953        if ($counts{'-'} > $counts{'+'}) {
1954            ($beg, $end) = ($end, $beg);
1955        }
1956        # Return the result.
1957        return ($contig, $beg, $end);
1958    }
1959    
1960  =head3 CouplingID  =head3 CouplingID
1961    
1962  C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>  C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >>
1963    
1964  Return the coupling ID for a pair of feature IDs.  Return the coupling ID for a pair of feature IDs.
1965    
# Line 1857  Line 1992 
1992  =cut  =cut
1993  #: Return Type $;  #: Return Type $;
1994  sub CouplingID {  sub CouplingID {
1995      return join " ", sort @_;      my ($self, @pegs) = @_;
1996        return $self->DigestKey(join " ", sort @pegs);
1997  }  }
1998    
1999  =head3 ReadFasta  =head3 ReadFasta
# Line 2216  Line 2352 
2352      return @retVal;      return @retVal;
2353  }  }
2354    
 =head3 Exists  
   
 C<< my $found = $sprout->Exists($entityName, $entityID); >>  
   
 Return TRUE if an entity exists, else FALSE.  
   
 =over 4  
   
 =item entityName  
   
 Name of the entity type (e.g. C<Feature>) relevant to the existence check.  
   
 =item entityID  
   
 ID of the entity instance whose existence is to be checked.  
   
 =item RETURN  
   
 Returns TRUE if the entity instance exists, else FALSE.  
   
 =back  
   
 =cut  
 #: Return Type $;  
 sub Exists {  
     # Get the parameters.  
     my ($self, $entityName, $entityID) = @_;  
     # Check for the entity instance.  
     Trace("Checking existence of $entityName with ID=$entityID.") if T(4);  
     my $testInstance = $self->GetEntity($entityName, $entityID);  
     # Return an existence indicator.  
     my $retVal = ($testInstance ? 1 : 0);  
     return $retVal;  
 }  
   
2355  =head3 FeatureTranslation  =head3 FeatureTranslation
2356    
2357  C<< my $translation = $sprout->FeatureTranslation($featureID); >>  C<< my $translation = $sprout->FeatureTranslation($featureID); >>
# Line 2442  Line 2543 
2543    
2544  Return a list of the properties with the specified characteristics.  Return a list of the properties with the specified characteristics.
2545    
2546  Properties are arbitrary key-value pairs associated with a feature. (At some point they  Properties are the Sprout analog of the FIG attributes. The call is
2547  will also be associated with genomes.) A property value is represented by a 4-tuple of  passed directly to the CustomAttributes or RemoteCustomAttributes object
2548  the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter  contained in this object.
2549    
2550  =over 4  This method returns a series of tuples that match the specified criteria. Each tuple
2551    will contain an object ID, a key, and one or more values. The parameters to this
2552    method therefore correspond structurally to the values expected in each tuple. In
2553    addition, you can ask for a generic search by suffixing a percent sign (C<%>) to any
2554    of the parameters. So, for example,
2555    
2556  =item fid      my @attributeList = $sprout->GetProperties('fig|100226.1.peg.1004', 'structure%', 1, 2);
2557    
2558  ID of the feature possessing the property.  would return something like
2559    
2560  =item key      ['fig}100226.1.peg.1004', 'structure', 1, 2]
2561        ['fig}100226.1.peg.1004', 'structure1', 1, 2]
2562        ['fig}100226.1.peg.1004', 'structure2', 1, 2]
2563        ['fig}100226.1.peg.1004', 'structureA', 1, 2]
2564    
2565  Name or key of the property.  Use of C<undef> in any position acts as a wild card (all values). You can also specify
2566    a list reference in the ID column. Thus,
2567    
2568  =item value      my @attributeList = $sprout->GetProperties(['100226.1', 'fig|100226.1.%'], 'PUBMED');
2569    
2570  Value of the property.  would get the PUBMED attribute data for Streptomyces coelicolor A3(2) and all its
2571    features.
2572    
2573  =item url  In addition to values in multiple sections, a single attribute key can have multiple
2574    values, so even
2575    
2576  URL of the document that indicated the property should have this particular value, or an      my @attributeList = $sprout->GetProperties($peg, 'virulent');
 empty string if no such document exists.  
2577    
2578  =back  which has no wildcard in the key or the object ID, may return multiple tuples.
2579    
2580  The parameters act as a filter for the desired data. Any non-null parameter will  =over 4
 automatically match all the tuples returned. So, specifying just the I<$fid> will  
 return all the properties of the specified feature; similarly, specifying the I<$key>  
 and I<$value> parameters will return all the features having the specified property  
 value.  
2581    
2582  A single property key can have many values, representing different ideas about the  =item objectID
 feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is  
 virulent, and another may declare that it is not virulent. A query about the virulence of  
 C<fig|83333.1.peg.10> would be coded as  
2583    
2584      my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');  ID of object whose attributes are desired. If the attributes are desired for multiple
2585    objects, this parameter can be specified as a list reference. If the attributes are
2586    desired for all objects, specify C<undef> or an empty string. Finally, you can specify
2587    attributes for a range of object IDs by putting a percent sign (C<%>) at the end.
2588    
2589  Here the I<$value> and I<$url> fields are left blank, indicating that those fields are  =item key
2590  not to be filtered. The tuples returned would be  
2591    Attribute key name. A value of C<undef> or an empty string will match all
2592    attribute keys. If the values are desired for multiple keys, this parameter can be
2593    specified as a list reference. Finally, you can specify attributes for a range of
2594    keys by putting a percent sign (C<%>) at the end.
2595    
2596    =item values
2597    
2598    List of the desired attribute values, section by section. If C<undef>
2599    or an empty string is specified, all values in that section will match. A
2600    generic match can be requested by placing a percent sign (C<%>) at the end.
2601    In that case, all values that match up to and not including the percent sign
2602    will match. You may also specify a regular expression enclosed
2603    in slashes. All values that match the regular expression will be returned. For
2604    performance reasons, only values have this extra capability.
2605    
2606      ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')  =item RETURN
2607      ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')  
2608    Returns a list of tuples. The first element in the tuple is an object ID, the
2609    second is an attribute key, and the remaining elements are the sections of
2610    the attribute value. All of the tuples will match the criteria set forth in
2611    the parameter list.
2612    
2613    =back
2614    
2615  =cut  =cut
2616  #: Return Type @@;  
2617  sub GetProperties {  sub GetProperties {
2618      # Get the parameters.      # Get the parameters.
2619      my ($self, @parms) = @_;      my ($self, @parms) = @_;
2620      # Declare the return variable.      # Declare the return variable.
2621      my @retVal = ();      my @retVal = $self->{_ca}->GetAttributes(@parms);
     # Now we need to create a WHERE clause that will get us the data we want. First,  
     # we create a list of the columns containing the data for each parameter.  
     my @colNames = ('HasProperty(from-link)', 'Property(property-name)',  
                     'Property(property-value)', 'HasProperty(evidence)');  
     # Now we build the WHERE clause and the list of parameter values.  
     my @where = ();  
     my @values = ();  
     for (my $i = 0; $i <= $#colNames; $i++) {  
         my $parm = $parms[$i];  
         if (defined $parm && ($parm ne '')) {  
             push @where, "$colNames[$i] = ?";  
             push @values, $parm;  
         }  
     }  
     # Format the WHERE clause.  
     my $filter = (@values > 0 ? (join " AND ", @where) : undef);  
     # Ask for all the propertie values with the desired characteristics.  
     my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);  
     while (my $valueObject = $query->Fetch()) {  
         my @tuple = $valueObject->Values(\@colNames);  
         push @retVal, \@tuple;  
     }  
2622      # Return the result.      # Return the result.
2623      return @retVal;      return @retVal;
2624  }  }
# Line 2527  Line 2631 
2631  that specify special characteristics of the feature. For example, a property could indicate  that specify special characteristics of the feature. For example, a property could indicate
2632  that a feature is essential to the survival of the organism or that it has benign influence  that a feature is essential to the survival of the organism or that it has benign influence
2633  on the activities of a pathogen. Each property is returned as a triple of the form  on the activities of a pathogen. Each property is returned as a triple of the form
2634  C<($key,$value,$url)>, where C<$key> is the property name, C<$value> is its value (commonly  C<($key,@values)>, where C<$key> is the property name and  C<@values> are its values.
 a 1 or a 0, but possibly a string or a floating-point value), and C<$url> is a string describing  
 the web address or citation in which the property's value for the feature was identified.  
2635    
2636  =over 4  =over 4
2637    
# Line 2539  Line 2641 
2641    
2642  =item RETURN  =item RETURN
2643    
2644  Returns a list of triples, each triple containing the property name, its value, and a URL or  Returns a list of tuples, each tuple containing the property name and its values.
 citation.  
2645    
2646  =back  =back
2647    
# Line 2550  Line 2651 
2651      # Get the parameters.      # Get the parameters.
2652      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2653      # Get the properties.      # Get the properties.
2654      my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],      my @attributes = $self->{_ca}->GetAttributes($featureID);
2655                              ['Property(property-name)', 'Property(property-value)',      # Strip the feature ID off each tuple.
2656                               'HasProperty(evidence)']);      my @retVal = ();
2657        for my $attributeRow (@attributes) {
2658            shift @{$attributeRow};
2659            push @retVal, $attributeRow;
2660        }
2661      # Return the resulting list.      # Return the resulting list.
2662      return @retVal;      return @retVal;
2663  }  }
# Line 2585  Line 2690 
2690      return $retVal;      return $retVal;
2691  }  }
2692    
2693    =head3 PropertyID
2694    
2695    C<< my $id = $sprout->PropertyID($propName, $propValue); >>
2696    
2697    Return the ID of the specified property name and value pair, if the
2698    pair exists. Only a small subset of the FIG attributes are stored as
2699    Sprout properties, mostly for use in search optimization.
2700    
2701    =over 4
2702    
2703    =item propName
2704    
2705    Name of the desired property.
2706    
2707    =item propValue
2708    
2709    Value expected for the desired property.
2710    
2711    =item RETURN
2712    
2713    Returns the ID of the name/value pair, or C<undef> if the pair does not exist.
2714    
2715    =back
2716    
2717    =cut
2718    
2719    sub PropertyID {
2720        # Get the parameters.
2721        my ($self, $propName, $propValue) = @_;
2722        # Try to find the ID.
2723        my ($retVal) = $self->GetFlat(['Property'],
2724                                      "Property(property-name) = ? AND Property(property-value) = ?",
2725                                      [$propName, $propValue], 'Property(id)');
2726        # Return the result.
2727        return $retVal;
2728    }
2729    
2730  =head3 MergedAnnotations  =head3 MergedAnnotations
2731    
2732  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>
# Line 2782  Line 2924 
2924      # Get the parameters.      # Get the parameters.
2925      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2926      # Get the list of names.      # Get the list of names.
2927      my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",      my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?",
2928                                  [$featureID], 'HasSSCell(from-link)');                                  [$featureID], 'HasRoleInSubsystem(to-link)');
2929      # Return the result.      # Return the result, sorted.
2930      return @retVal;      return sort @retVal;
2931  }  }
2932    
2933    =head3 GenomeSubsystemData
2934    
2935    C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>
2936    
2937    Return a hash mapping genome features to their subsystem roles.
2938    
2939    =over 4
2940    
2941    =item genomeID
2942    
2943    ID of the genome whose subsystem feature map is desired.
2944    
2945    =item RETURN
2946    
2947    Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb
2948    2-tuple contains a subsystem name followed by a role ID.
2949    
2950    =back
2951    
2952    =cut
2953    
2954    sub GenomeSubsystemData {
2955        # Get the parameters.
2956        my ($self, $genomeID) = @_;
2957        # Declare the return variable.
2958        my %retVal = ();
2959        # Get a list of the genome features that participate in subsystems. For each
2960        # feature we get its spreadsheet cells and the corresponding roles.
2961        my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],
2962                                 "HasFeature(from-link) = ?", [$genomeID],
2963                                 ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);
2964        # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems
2965        # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the
2966        # list. We use it at the beginning to get all the spreadsheet cells for the genome and
2967        # again at the end to filter out participation in subsystems with a negative variant code.
2968        my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],
2969                                     "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?",
2970                                     [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']);
2971        # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features.
2972        # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We
2973        # link these two lists together to create the result. First, we want a hash mapping
2974        # spreadsheet cells to subsystem names.
2975        my %subHash = map { $_->[0] => $_->[1] } @cellData;
2976        # We loop through @cellData to build the hash.
2977        for my $roleEntry (@roleData) {
2978            # Get the data for this feature and cell.
2979            my ($fid, $cellID, $role) = @{$roleEntry};
2980            # Check for a subsystem name.
2981            my $subsys = $subHash{$cellID};
2982            if ($subsys) {
2983                # Insure this feature has an entry in the return hash.
2984                if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
2985                # Merge in this new data.
2986                push @{$retVal{$fid}}, [$subsys, $role];
2987            }
2988        }
2989        # Return the result.
2990        return %retVal;
2991    }
2992    
2993  =head3 RelatedFeatures  =head3 RelatedFeatures
2994    
# Line 2825  Line 3025 
3025      # Get the parameters.      # Get the parameters.
3026      my ($self, $featureID, $function, $userID) = @_;      my ($self, $featureID, $function, $userID) = @_;
3027      # 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.
3028      my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
                                      "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],  
                                      'IsBidirectionalBestHitOf(to-link)');  
3029      # Now we loop through the features, pulling out the ones that have the correct      # Now we loop through the features, pulling out the ones that have the correct
3030      # functional assignment.      # functional assignment.
3031      my @retVal = ();      my @retVal = ();
# Line 2963  Line 3161 
3161      # Loop through the input triples.      # Loop through the input triples.
3162      my $n = length $sequence;      my $n = length $sequence;
3163      for (my $i = 0; $i < $n; $i += 3) {      for (my $i = 0; $i < $n; $i += 3) {
3164          # Get the current triple from the sequence.          # Get the current triple from the sequence. Note we convert to
3165          my $triple = substr($sequence, $i, 3);          # upper case to insure a match.
3166            my $triple = uc substr($sequence, $i, 3);
3167          # Translate it using the table.          # Translate it using the table.
3168          my $protein = "X";          my $protein = "X";
3169          if (exists $table->{$triple}) { $protein = $table->{$triple}; }          if (exists $table->{$triple}) { $protein = $table->{$triple}; }
# Line 2997  Line 3196 
3196      return @retVal;      return @retVal;
3197  }  }
3198    
3199    =head3 BBHMatrix
3200    
3201    C<< my %bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets); >>
3202    
3203    Find all the bidirectional best hits for the features of a genome in a
3204    specified list of target genomes. The return value will be a hash mapping
3205    features in the original genome to their bidirectional best hits in the
3206    target genomes.
3207    
3208    =over 4
3209    
3210    =item genomeID
3211    
3212    ID of the genome whose features are to be examined for bidirectional best hits.
3213    
3214    =item cutoff
3215    
3216    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3217    
3218    =item targets
3219    
3220    List of target genomes. Only pairs originating in the original
3221    genome and landing in one of the target genomes will be returned.
3222    
3223    =item RETURN
3224    
3225    Returns a hash mapping each feature in the original genome to a hash mapping its
3226    BBH pegs in the target genomes to their scores.
3227    
3228    =back
3229    
3230    =cut
3231    
3232    sub BBHMatrix {
3233        # Get the parameters.
3234        my ($self, $genomeID, $cutoff, @targets) = @_;
3235        # Declare the return variable.
3236        my %retVal = ();
3237        # Ask for the BBHs.
3238        my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets);
3239        # We now have a set of 4-tuples that we need to convert into a hash of hashes.
3240        for my $bbhData (@bbhList) {
3241            my ($peg1, $peg2, $score) = @{$bbhData};
3242            if (! exists $retVal{$peg1}) {
3243                $retVal{$peg1} = { $peg2 => $score };
3244            } else {
3245                $retVal{$peg1}->{$peg2} = $score;
3246            }
3247        }
3248        # Return the result.
3249        return %retVal;
3250    }
3251    
3252    
3253    =head3 SimMatrix
3254    
3255    C<< my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets); >>
3256    
3257    Find all the similarities for the features of a genome in a
3258    specified list of target genomes. The return value will be a hash mapping
3259    features in the original genome to their similarites in the
3260    target genomes.
3261    
3262    =over 4
3263    
3264    =item genomeID
3265    
3266    ID of the genome whose features are to be examined for similarities.
3267    
3268    =item cutoff
3269    
3270    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3271    
3272    =item targets
3273    
3274    List of target genomes. Only pairs originating in the original
3275    genome and landing in one of the target genomes will be returned.
3276    
3277    =item RETURN
3278    
3279    Returns a hash mapping each feature in the original genome to a hash mapping its
3280    similar pegs in the target genomes to their scores.
3281    
3282    =back
3283    
3284    =cut
3285    
3286    sub SimMatrix {
3287        # Get the parameters.
3288        my ($self, $genomeID, $cutoff, @targets) = @_;
3289        # Declare the return variable.
3290        my %retVal = ();
3291        # Get the list of features in the source organism.
3292        my @fids = $self->FeaturesOf($genomeID);
3293        # Ask for the sims. We only want similarities to fig features.
3294        my $simList = FIGRules::GetNetworkSims($self, \@fids, {}, 1000, $cutoff, "fig");
3295        if (! defined $simList) {
3296            Confess("Unable to retrieve similarities from server.");
3297        } else {
3298            Trace("Processing sims.") if T(3);
3299            # We now have a set of sims that we need to convert into a hash of hashes. First, we
3300            # Create a hash for the target genomes.
3301            my %targetHash = map { $_ => 1 } @targets;
3302            for my $simData (@{$simList}) {
3303                # Get the PEGs and the score.
3304                my ($peg1, $peg2, $score) = ($simData->id1, $simData->id2, $simData->psc);
3305                # Insure the second ID is in the target list.
3306                my ($genome2) = FIGRules::ParseFeatureID($peg2);
3307                if (exists $targetHash{$genome2}) {
3308                    # Here it is. Now we need to add it to the return hash. How we do that depends
3309                    # on whether or not $peg1 is new to us.
3310                    if (! exists $retVal{$peg1}) {
3311                        $retVal{$peg1} = { $peg2 => $score };
3312                    } else {
3313                        $retVal{$peg1}->{$peg2} = $score;
3314                    }
3315                }
3316            }
3317        }
3318        # Return the result.
3319        return %retVal;
3320    }
3321    
3322    
3323  =head3 LowBBHs  =head3 LowBBHs
3324    
3325  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
# Line 3028  Line 3351 
3351      my ($self, $featureID, $cutoff) = @_;      my ($self, $featureID, $cutoff) = @_;
3352      # Create the return hash.      # Create the return hash.
3353      my %retVal = ();      my %retVal = ();
3354      # Create a query to get the desired BBHs.      # Query for the desired BBHs.
3355      my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BBHData($featureID, $cutoff);
                                 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',  
                                 [$cutoff, $featureID],  
                                 ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);  
3356      # Form the results into the return hash.      # Form the results into the return hash.
3357      for my $pair (@bbhList) {      for my $pair (@bbhList) {
3358          $retVal{$pair->[0]} = $pair->[1];          my $fid = $pair->[0];
3359            if ($self->Exists('Feature', $fid)) {
3360                $retVal{$fid} = $pair->[1];
3361            }
3362      }      }
3363      # Return the result.      # Return the result.
3364      return %retVal;      return %retVal;
3365  }  }
3366    
3367    =head3 Sims
3368    
3369    C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>
3370    
3371    Get a list of similarities for a specified feature. Similarity information is not kept in the
3372    Sprout database; rather, they are retrieved from a network server. The similarities are
3373    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3374    so that its elements can be accessed by name.
3375    
3376    Similarities can be either raw or expanded. The raw similarities are basic
3377    hits between features with similar DNA. Expanding a raw similarity drags in any
3378    features considered substantially identical. So, for example, if features B<A1>,
3379    B<A2>, and B<A3> are all substantially identical to B<A>, then a raw similarity
3380    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3381    
3382    =over 4
3383    
3384    =item fid
3385    
3386    ID of the feature whose similarities are desired.
3387    
3388    =item maxN
3389    
3390    Maximum number of similarities to return.
3391    
3392    =item maxP
3393    
3394    Minumum allowable similarity score.
3395    
3396    =item select
3397    
3398    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3399    means only similarities to FIG features are returned; C<all> means all expanded
3400    similarities are returned; and C<figx> means similarities are expanded until the
3401    number of FIG features equals the maximum.
3402    
3403    =item max_expand
3404    
3405    The maximum number of features to expand.
3406    
3407    =item filters
3408    
3409    Reference to a hash containing filter information, or a subroutine that can be
3410    used to filter the sims.
3411    
3412    =item RETURN
3413    
3414    Returns a reference to a list of similarity objects, or C<undef> if an error
3415    occurred.
3416    
3417    =back
3418    
3419    =cut
3420    
3421    sub Sims {
3422        # Get the parameters.
3423        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3424        # Create the shim object to test for deleted FIDs.
3425        my $shim = FidCheck->new($self);
3426        # Ask the network for sims.
3427        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3428        # Return the result.
3429        return $retVal;
3430    }
3431    
3432    =head3 IsAllGenomes
3433    
3434    C<< my $flag = $sprout->IsAllGenomes(\@list, \@checkList); >>
3435    
3436    Return TRUE if all genomes in the second list are represented in the first list at
3437    least one. Otherwise, return FALSE. If the second list is omitted, the first list is
3438    compared to a list of all the genomes.
3439    
3440    =over 4
3441    
3442    =item list
3443    
3444    Reference to the list to be compared to the second list.
3445    
3446    =item checkList (optional)
3447    
3448    Reference to the comparison target list. Every genome ID in this list must occur at
3449    least once in the first list. If this parameter is omitted, a list of all the genomes
3450    is used.
3451    
3452    =item RETURN
3453    
3454    Returns TRUE if every item in the second list appears at least once in the
3455    first list, else FALSE.
3456    
3457    =back
3458    
3459    =cut
3460    
3461    sub IsAllGenomes {
3462        # Get the parameters.
3463        my ($self, $list, $checkList) = @_;
3464        # Supply the checklist if it was omitted.
3465        $checkList = [$self->Genomes()] if ! defined($checkList);
3466        # Create a hash of the original list.
3467        my %testList = map { $_ => 1 } @{$list};
3468        # Declare the return variable. We assume that the representation
3469        # is complete and stop at the first failure.
3470        my $retVal = 1;
3471        my $n = scalar @{$checkList};
3472        for (my $i = 0; $retVal && $i < $n; $i++) {
3473            if (! $testList{$checkList->[$i]}) {
3474                $retVal = 0;
3475            }
3476        }
3477        # Return the result.
3478        return $retVal;
3479    }
3480    
3481  =head3 GetGroups  =head3 GetGroups
3482    
3483  C<< my %groups = $sprout->GetGroups(\@groupList); >>  C<< my %groups = $sprout->GetGroups(\@groupList); >>
# Line 3062  Line 3499 
3499          # Here we have a group list. Loop through them individually,          # Here we have a group list. Loop through them individually,
3500          # getting a list of the relevant genomes.          # getting a list of the relevant genomes.
3501          for my $group (@{$groupList}) {          for my $group (@{$groupList}) {
3502              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3503                  [$group], "Genome(id)");                  [$group], "Genome(id)");
3504              $retVal{$group} = \@genomeIDs;              $retVal{$group} = \@genomeIDs;
3505          }          }
# Line 3070  Line 3507 
3507          # Here we need all of the groups. In this case, we run through all          # Here we need all of the groups. In this case, we run through all
3508          # of the genome records, putting each one found into the appropriate          # of the genome records, putting each one found into the appropriate
3509          # group. Note that we use a filter clause to insure that only genomes          # group. Note that we use a filter clause to insure that only genomes
3510          # in groups are included in the return set.          # in real NMPDR groups are included in the return set.
3511          my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],          my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3512                                      ['Genome(id)', 'Genome(group-name)']);                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3513          # Loop through the genomes found.          # Loop through the genomes found.
3514          for my $genome (@genomes) {          for my $genome (@genomes) {
3515              # Pop this genome's ID off the current list.              # Pop this genome's ID off the current list.
# Line 3190  Line 3627 
3627      # Get the parameters.      # Get the parameters.
3628      my ($self, $genomeID, $testFlag) = @_;      my ($self, $genomeID, $testFlag) = @_;
3629      # Perform the delete for the genome's features.      # Perform the delete for the genome's features.
3630      my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);      my $retVal = $self->Delete('Feature', "fig|$genomeID.%", testMode => $testFlag);
3631      # Perform the delete for the primary genome data.      # Perform the delete for the primary genome data.
3632      my $stats = $self->Delete('Genome', $genomeID, $testFlag);      my $stats = $self->Delete('Genome', $genomeID, testMode => $testFlag);
3633      $retVal->Accumulate($stats);      $retVal->Accumulate($stats);
3634      # Return the result.      # Return the result.
3635      return $retVal;      return $retVal;
3636  }  }
3637    
3638    =head3 Fix
3639    
3640    C<< my %fixedHash = Sprout::Fix(%groupHash); >>
3641    
3642    Prepare a genome group hash (like that returned by L</GetGroups> for processing.
3643    Groups with the same primary name will be combined. The primary name is the
3644    first capitalized word in the group name.
3645    
3646    =over 4
3647    
3648    =item groupHash
3649    
3650    Hash to be fixed up.
3651    
3652    =item RETURN
3653    
3654    Returns a fixed-up version of the hash.
3655    
3656    =back
3657    
3658    =cut
3659    
3660    sub Fix {
3661        # Get the parameters.
3662        my (%groupHash) = @_;
3663        # Create the result hash.
3664        my %retVal = ();
3665        # Copy over the genomes.
3666        for my $groupID (keys %groupHash) {
3667            # Make a safety copy of the group ID.
3668            my $realGroupID = $groupID;
3669            # Yank the primary name.
3670            if ($groupID =~ /([A-Z]\w+)/) {
3671                $realGroupID = $1;
3672            }
3673            # Append this group's genomes into the result hash.
3674            Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}});
3675        }
3676        # Return the result hash.
3677        return %retVal;
3678    }
3679    
3680    =head3 GroupPageName
3681    
3682    C<< my $name = $sprout->GroupPageName($group); >>
3683    
3684    Return the name of the page for the specified NMPDR group.
3685    
3686    =over 4
3687    
3688    =item group
3689    
3690    Name of the relevant group.
3691    
3692    =item RETURN
3693    
3694    Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3695    memory it will be read in.
3696    
3697    =back
3698    
3699    =cut
3700    
3701    sub GroupPageName {
3702        # Get the parameters.
3703        my ($self, $group) = @_;
3704        # Declare the return variable.
3705        my $retVal;
3706        # Check for the group file data.
3707        if (! defined $self->{groupHash}) {
3708            # Read the group file.
3709            my %groupData = Sprout::ReadGroupFile($self->{_options}->{dataDir} . "/groups.tbl");
3710            # Store it in our object.
3711            $self->{groupHash} = \%groupData;
3712        }
3713        # Compute the real group name.
3714        my $realGroup = $group;
3715        if ($group =~ /([A-Z]\w+)/) {
3716            $realGroup = $1;
3717        }
3718        # Return the page name.
3719        $retVal = "../content/" . $self->{groupHash}->{$realGroup}->[1];
3720        # Return the result.
3721        return $retVal;
3722    }
3723    
3724    =head3 ReadGroupFile
3725    
3726    C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >>
3727    
3728    Read in the data from the specified group file. The group file contains information
3729    about each of the NMPDR groups.
3730    
3731    =over 4
3732    
3733    =item name
3734    
3735    Name of the group.
3736    
3737    =item page
3738    
3739    Name of the group's page on the web site (e.g. C<campy.php> for
3740    Campylobacter)
3741    
3742    =item genus
3743    
3744    Genus of the group
3745    
3746    =item species
3747    
3748    Species of the group, or an empty string if the group is for an entire
3749    genus. If the group contains more than one species, the species names
3750    should be separated by commas.
3751    
3752    =back
3753    
3754    The parameters to this method are as follows
3755    
3756    =over 4
3757    
3758    =item groupFile
3759    
3760    Name of the file containing the group data.
3761    
3762    =item RETURN
3763    
3764    Returns a hash keyed on group name. The value of each hash
3765    
3766    =back
3767    
3768    =cut
3769    
3770    sub ReadGroupFile {
3771        # Get the parameters.
3772        my ($groupFileName) = @_;
3773        # Declare the return variable.
3774        my %retVal;
3775        # Read the group file.
3776        my @groupLines = Tracer::GetFile($groupFileName);
3777        for my $groupLine (@groupLines) {
3778            my ($name, $page, $genus, $species) = split(/\t/, $groupLine);
3779            $retVal{$name} = [$page, $genus, $species];
3780        }
3781        # Return the result.
3782        return %retVal;
3783    }
3784    
3785    =head3 AddProperty
3786    
3787    C<< my  = $sprout->AddProperty($featureID, $key, @values); >>
3788    
3789    Add a new attribute value (Property) to a feature.
3790    
3791    =over 4
3792    
3793    =item peg
3794    
3795    ID of the feature to which the attribute is to be added.
3796    
3797    =item key
3798    
3799    Name of the attribute (key).
3800    
3801    =item values
3802    
3803    Values of the attribute.
3804    
3805    =back
3806    
3807    =cut
3808    #: Return Type ;
3809    sub AddProperty {
3810        # Get the parameters.
3811        my ($self, $featureID, $key, @values) = @_;
3812        # Add the property using the attached attributes object.
3813        $self->{_ca}->AddAttribute($featureID, $key, @values);
3814    }
3815    
3816    =head2 Virtual Methods
3817    
3818    =head3 CleanKeywords
3819    
3820    C<< my $cleanedString = $sprout->CleanKeywords($searchExpression); >>
3821    
3822    Clean up a search expression or keyword list. This involves converting the periods
3823    in EC numbers to underscores, converting non-leading minus signs to underscores,
3824    a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
3825    characters. In addition, any extra spaces are removed.
3826    
3827    =over 4
3828    
3829    =item searchExpression
3830    
3831    Search expression or keyword list to clean. Note that a search expression may
3832    contain boolean operators which need to be preserved. This includes leading
3833    minus signs.
3834    
3835    =item RETURN
3836    
3837    Cleaned expression or keyword list.
3838    
3839    =back
3840    
3841    =cut
3842    
3843    sub CleanKeywords {
3844        # Get the parameters.
3845        my ($self, $searchExpression) = @_;
3846        # Perform the standard cleanup.
3847        my $retVal = $self->ERDB::CleanKeywords($searchExpression);
3848        # Fix the periods in EC and TC numbers.
3849        $retVal =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g;
3850        # Fix non-trailing periods.
3851        $retVal =~ s/\.(\w)/_$1/g;
3852        # Fix non-leading minus signs.
3853        $retVal =~ s/(\w)[\-]/$1_/g;
3854        # Fix the vertical bars and colons
3855        $retVal =~ s/(\w)[|:](\w)/$1'$2/g;
3856        # Return the result.
3857        return $retVal;
3858    }
3859    
3860  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3861    
3862  =head3 ParseAssignment  =head3 ParseAssignment
# Line 3254  Line 3913 
3913      }      }
3914      # If we have an assignment, we need to clean the function text. There may be      # If we have an assignment, we need to clean the function text. There may be
3915      # extra junk at the end added as a note from the user.      # extra junk at the end added as a note from the user.
3916      if (@retVal) {      if (defined( $retVal[1] )) {
3917          $retVal[1] =~ s/(\t\S)?\s*$//;          $retVal[1] =~ s/(\t\S)?\s*$//;
3918      }      }
3919      # Return the result list.      # Return the result list.
# Line 3287  Line 3946 
3946      return $retVal;      return $retVal;
3947  }  }
3948    
 =head3 AddProperty  
   
 C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>  
   
 Add a new attribute value (Property) to a feature. In the SEED system, attributes can  
 be added to almost any object. In Sprout, they can only be added to features. In  
 Sprout, attributes are implemented using I<properties>. A property represents a key/value  
 pair. If the particular key/value pair coming in is not already in the database, a new  
 B<Property> record is created to hold it.  
   
 =over 4  
   
 =item peg  
   
 ID of the feature to which the attribute is to be replied.  
   
 =item key  
   
 Name of the attribute (key).  
   
 =item value  
   
 Value of the attribute.  
   
 =item url  
   
 URL or text citation from which the property was obtained.  
   
 =back  
   
 =cut  
 #: Return Type ;  
 sub AddProperty {  
     # Get the parameters.  
     my ($self, $featureID, $key, $value, $url) = @_;  
     # Declare the variable to hold the desired property ID.  
     my $propID;  
     # Attempt to find a property record for this key/value pair.  
     my @properties = $self->GetFlat(['Property'],  
                                    "Property(property-name) = ? AND Property(property-value) = ?",  
                                    [$key, $value], 'Property(id)');  
     if (@properties) {  
         # Here the property is already in the database. We save its ID.  
         $propID = $properties[0];  
         # Here the property value does not exist. We need to generate an ID. It will be set  
         # to a number one greater than the maximum value in the database. This call to  
         # GetAll will stop after one record.  
         my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],  
                                         1);  
         $propID = $maxProperty[0]->[0] + 1;  
         # Insert the new property value.  
         $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });  
     }  
     # Now we connect the incoming feature to the property.  
     $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });  
 }  
   
3949    
3950  1;  1;

Legend:
Removed from v.1.63  
changed lines
  Added in v.1.99

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3