--- Sprout.pm 2007/08/20 23:29:24 1.101 +++ Sprout.pm 2009/05/04 18:49:49 1.127 @@ -1,13 +1,10 @@ package Sprout; - require Exporter; - use ERDB; - @ISA = qw(Exporter ERDB); use Data::Dumper; use strict; use DBKernel; use XML::Simple; - use DBQuery; + use ERDBQuery; use ERDBObject; use Tracer; use FIGRules; @@ -17,6 +14,10 @@ use BasicLocation; use CustomAttributes; use RemoteCustomAttributes; + use CGI qw(-nosticky); + use WikiTools; + use BioWords; + use base qw(ERDB); =head1 Sprout Database Manipulation Object @@ -29,45 +30,46 @@ on the constructor. For example, the following invocation specifies a PostgreSQL database named I whose definition and data files are in a co-directory named F. -C<< my $sprout = Sprout->new('GenDB', { dbType => 'pg', dataDir => '../Data', xmlFileName => '../Data/SproutDBD.xml' }); >> + my $sprout = Sprout->new('GenDB', { dbType => 'pg', dataDir => '../Data', xmlFileName => '../Data/SproutDBD.xml' }); Once you have a sprout object, you may use it to re-create the database, load the tables from tab-delimited flat files and perform queries. Several special methods are provided for common -query tasks. For example, L lists the IDs of all the genomes in the database and -L returns the DNA sequence for a specified genome location. +query tasks. For example, L lists the IDs of all the genomes in the database and +L returns the DNA sequence for a specified genome location. The Sprout object is a subclass of the ERDB object and inherits all its properties and methods. =cut -#: Constructor SFXlate->new_sprout_only(); - =head2 Public Methods =head3 new -C<< my $sprout = Sprout->new($dbName, \%options); >> + my $sprout = Sprout->new(%parms) This is the constructor for a sprout object. It connects to the database and loads the -database definition into memory. The positional first parameter specifies the name of the -database. +database definition into memory. The incoming parameter hash has the following permissible +members (others will be ignored without error. =over 4 +=item DBD + +Name of the XML file containing the database definition (default C in +the DBD directory). + =item dbName -Name of the database. +Name of the database. If omitted, the default Sprout database name is used. =item options -Table of options. +Sub-hash of special options. * B type of database (currently C for MySQL and C for PostgreSQL) (default C) * B directory containing the database definition file and the flat files used to load the data (default C) -* B name of the XML file containing the database definition (default C) - * B user name and password, delimited by a slash (default same as SEED) * B connection port (default C<0>) @@ -80,19 +82,31 @@ * B suppresses the connection to the database if TRUE, else FALSE +* B name of the database host + =back For example, the following constructor call specifies a database named I and a user name of I with a password of I. The database load files are in the directory F. -C<< my $sprout = Sprout->new('Sprout', { userData =>; 'fig/admin', dataDir => '/usr/fig/SproutData' }); >> + my $sprout = Sprout->new(dbName => 'Sprout', options => { userData => 'fig/admin', dataDir => '/usr/fig/SproutData' }); + +The odd constructor signature is a result of Sprout's status as the first ERDB database, +and the need to make it compatible with the needs of its younger siblings. =cut sub new { # Get the parameters. - my ($class, $dbName, $options) = @_; + my ($class, %parms) = @_; + # Look for an options hash. + my $options = $parms{options} || {}; + # Plug in the DBD and name parameters. + if ($parms{DBD}) { + $options->{xmlFileName} = $parms{DBD}; + } + my $dbName = $parms{dbName} || $FIG_Config::sproutDB; # Compute the DBD directory. my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir : $FIG_Config::fig ); @@ -105,15 +119,16 @@ # data file directory xmlFileName => "$dbd_dir/SproutDBD.xml", # database definition file name - userData => "$FIG_Config::dbuser/$FIG_Config::dbpass", + userData => "$FIG_Config::sproutUser/$FIG_Config::sproutPass", # user name and password - port => $FIG_Config::dbport, + port => $FIG_Config::sproutPort, # database connection port - sock => $FIG_Config::dbsock, - host => $FIG_Config::dbhost, + sock => $FIG_Config::sproutSock, + host => $FIG_Config::sprout_host, maxSegmentLength => 4500, # maximum feature segment length maxSequenceLength => 8000, # maximum contig sequence length noDBOpen => 0, # 1 to suppress the database open + demandDriven => 0, # 1 for forward-only queries }, $options); # Get the data directory. my $dataDir = $optionTable->{dataDir}; @@ -123,35 +138,170 @@ # Connect to the database. my $dbh; if (! $optionTable->{noDBOpen}) { + Trace("Connect data: host = $optionTable->{host}, port = $optionTable->{port}.") if T(3); $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock}); } # Create the ERDB object. my $xmlFileName = "$optionTable->{xmlFileName}"; - my $retVal = ERDB::new($class, $dbh, $xmlFileName); + my $retVal = ERDB::new($class, $dbh, $xmlFileName, %$optionTable); # Add the option table and XML file name. $retVal->{_options} = $optionTable; $retVal->{_xmlName} = $xmlFileName; # Set up space for the group file data. $retVal->{groupHash} = undef; - # Set up space for the genome hash. We use this to identify NMPDR genomes. - $retVal->{genomeHash} = undef; - # Connect to the attributes. - if ($FIG_Config::attrURL) { - Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3); - $retVal->{_ca} = RemoteCustomAttributes->new($FIG_Config::attrURL); - } elsif ($FIG_Config::attrDbName) { - Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3); - my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent())); - $retVal->{_ca} = CustomAttributes->new(user => $user); - } + # Set up space for the genome hash. We use this to identify NMPDR genomes + # and remember genome data. + $retVal->{genomeHash} = {}; + $retVal->{genomeHashFilled} = 0; + # Remember the data directory name. + $retVal->{dataDir} = $dataDir; # Return it. return $retVal; } +=head3 ca + + my $ca = $sprout->ca():; + +Return the [[CustomAttributesPm]] object for retrieving object +properties. + +=cut + +sub ca { + # Get the parameters. + my ($self) = @_; + # Do we already have an attribute object? + my $retVal = $self->{_ca}; + if (! defined $retVal) { + # No, create one. How we do it depends on the configuration. + if ($FIG_Config::attrURL) { + Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3); + $retVal = RemoteCustomAttributes->new($FIG_Config::attrURL); + } elsif ($FIG_Config::attrDbName) { + Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3); + my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent())); + $retVal = CustomAttributes->new(user => $user); + } + # Save it for next time. + $self->{_ca} = $retVal; + } + # Return the result. + return $retVal; +} + +=head3 CoreGenomes + + my @genomes = $sprout->CoreGenomes($scope); + +Return the IDs of NMPDR genomes in the specified scope. + +=over 4 + +=item scope + +Scope of the desired genomes. C covers the original core genomes, +C covers all genomes in NMPDR groups, and C covers all +genomes in the system. + +=item RETURN + +Returns a list of the IDs for the genomes in the specified scope. + +=back + +=cut + +sub CoreGenomes { + # Get the parameters. + my ($self, $scope) = @_; + # Declare the return variable. + my @retVal = (); + # If we want all genomes, then this is easy. + if ($scope eq 'all') { + @retVal = $self->Genomes(); + } else { + # Here we're dealing with groups. Get the hash of all the + # genome groups. + my %groups = $self->GetGroups(); + # Loop through the groups, keeping the ones that we want. + for my $group (keys %groups) { + # Decide if we want to keep this group. + my $keepGroup = 0; + if ($scope eq 'nmpdr') { + # NMPDR mode: keep all groups. + $keepGroup = 1; + } elsif ($scope eq 'core') { + # CORE mode. Only keep real core groups. + if (grep { $group =~ /$_/ } @{$FIG_Config::realCoreGroups}) { + $keepGroup = 1; + } + } + # Add this group if we're keeping it. + if ($keepGroup) { + push @retVal, @{$groups{$group}}; + } + } + } + # Return the result. + return @retVal; +} + +=head3 SuperGroup + + my $superGroup = $sprout->SuperGroup($groupName); + +Return the name of the super-group containing the specified NMPDR genome +group. If no appropriate super-group can be found, an error will be +thrown. + +=over 4 + +=item groupName + +Name of the group whose super-group is desired. + +=item RETURN + +Returns the name of the super-group containing the incoming group. + +=back + +=cut + +sub SuperGroup { + # Get the parameters. + my ($self, $groupName) = @_; + # Declare the return variable. + my $retVal; + # Get the group hash. + my %groupHash = $self->CheckGroupFile(); + # Find the super-group genus. + $groupName =~ /([A-Z]\w+)/; + my $nameThing = $1; + # See if it's directly in the group hash. + if (exists $groupHash{$nameThing}) { + # Yes, then it's our result. + $retVal = $nameThing; + } else { + # No, so we have to search. + for my $superGroup (keys %groupHash) { + # Get this super-group's item list. + my $list = $groupHash{$superGroup}->{contents}; + # Search it. + if (grep { $_->[0] eq $nameThing } @{$list}) { + $retVal = $superGroup; + } + } + } + # Return the result. + return $retVal; +} + =head3 MaxSegment -C<< my $length = $sprout->MaxSegment(); >> + my $length = $sprout->MaxSegment(); This method returns the maximum permissible length of a feature segment. The length is important because it enables us to make reasonable guesses at how to find features inside a particular @@ -168,7 +318,7 @@ =head3 MaxSequence -C<< my $length = $sprout->MaxSequence(); >> + my $length = $sprout->MaxSequence(); This method returns the maximum permissible length of a contig sequence. A contig is broken into sequences in order to save memory resources. In particular, when manipulating features, @@ -183,7 +333,7 @@ =head3 Load -C<< $sprout->Load($rebuild); >>; + $sprout->Load($rebuild);; Load the database from files in the data directory, optionally re-creating the tables. @@ -195,7 +345,7 @@ The files are loaded based on the presumption that each line of the file is a record in the relation, and the individual fields are delimited by tabs. Tab and new-line characters inside fields must be represented by the escape sequences C<\t> and C<\n>, respectively. The fields must -be presented in the order given in the relation tables produced by the L method. +be presented in the order given in the relation tables produced by the database documentation. =over 4 @@ -223,7 +373,7 @@ =head3 LoadUpdate -C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >> + my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); Load updates to one or more database tables. This method enables the client to make changes to one or two tables without reloading the whole database. For each table, there must be a corresponding @@ -269,7 +419,7 @@ Trace("No load file found for $tableName in $dataDir.") if T(0); } else { # Attempt to load this table. - my $result = $self->LoadTable($fileName, $tableName, $truncateFlag); + my $result = $self->LoadTable($fileName, $tableName, truncate => $truncateFlag); # Accumulate the resulting statistics. $retVal->Accumulate($result); } @@ -280,7 +430,7 @@ =head3 GenomeCounts -C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >> + my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); Count the number of genomes in each domain. If I<$complete> is TRUE, only complete genomes will be included in the counts. @@ -325,7 +475,7 @@ =head3 ContigCount -C<< my $count = $sprout->ContigCount($genomeID); >> + my $count = $sprout->ContigCount($genomeID); Return the number of contigs for the specified genome ID. @@ -352,90 +502,315 @@ return $retVal; } -=head3 GeneMenu +=head3 GenomeMenu -C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected); >> + my $html = $sprout->GenomeMenu(%options); -Return an HTML select menu of genomes. Each genome will be an option in the menu, -and will be displayed by name with the ID and a contig count attached. The selection -value will be the genome ID. The genomes will be sorted by genus/species name. +Generate a genome selection control with the specified name and options. +This control is almost but not quite the same as the genome control in the +B class. Eventually, the two will be combined. =over 4 -=item attributes +=item options + +Optional parameters for the control (see below). + +=item RETURN + +Returns the HTML for a genome selection control on a form (sometimes called a popup menu). -Reference to a hash mapping attributes to values for the SELECT tag generated. +=back -=item filterString +The valid options are as follows. -A filter string for use in selecting the genomes. The filter string must conform -to the rules for the C<< ERDB->Get >> method. +=over 4 -=item params +=item name -Reference to a list of values to be substituted in for the parameter marks in -the filter string. +Name to give this control for use in passing it to the form. The default is C. +Terrible things will happen if you have two controls with the same name on the same page. -=item selected (optional) +=item filter -ID of the genome to be initially selected. +If specified, a filter for the list of genomes to display. The filter should be in the form of a +list reference, a string, or a hash reference. If it is a list reference, the first element +of the list should be the filter string, and the remaining elements the filter parameters. If it is a +string, it will be split into a list at each included tab. If it is a hash reference, it should be +a hash that maps genomes which should be included to a TRUE value. -=item fast (optional) +=item multiSelect -If specified and TRUE, the contig counts will be omitted to improve performance. +If TRUE, then the user can select multiple genomes. If FALSE, the user can only select one genome. -=item RETURN +=item size + +Number of rows to display in the control. The default is C<10> + +=item id -Returns an HTML select menu with the specified genomes as selectable options. +ID to give this control. The default is the value of the C option. Nothing will work correctly +unless this ID is unique. + +=item selected + +A comma-delimited list of selected genomes, or a reference to a list of selected genomes. The +default is none. + +=item class + +If specified, a style class to assign to the genome control. =back =cut -sub GeneMenu { +sub GenomeMenu { # Get the parameters. - my ($self, $attributes, $filterString, $params, $selected, $fast) = @_; - my $slowMode = ! $fast; - # Default to nothing selected. This prevents an execution warning if "$selected" - # is undefined. - $selected = "" unless defined $selected; - Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3); - # Start the menu. - my $retVal = "); + # Loop through the groups. + for my $group (@groups) { + # Get the genomes in the group. + for my $genome (@{$gHash{$group}}) { + # If this is an NMPDR organism, we add an extra style and count it. + my $nmpdrStyle = ""; + if ($nmpdrGroupCount > 0) { + $nmpdrCount++; + $nmpdrStyle = " Core"; + } + # Get the organism ID, name, contig count, and domain. + my ($genomeID, $name, $contigCount, $domain) = @{$genome}; + # See if we're pre-selected. + my $selectTag = ($selected{$genomeID} ? " SELECTED" : ""); + # Compute the display name. + my $nameString = "$name ($genomeID$contigCount)"; + # Generate the option tag. + my $optionTag = ""; + push @lines, " $optionTag"; + } + # Record this group in the nmpdrGroup count. When that gets to 0, we've finished the NMPDR + # groups. + $nmpdrGroupCount--; } # Close the SELECT tag. - $retVal .= "\n"; + push @lines, ""; + if ($rows > 1) { + # We're in a non-compact mode, so we need to add some selection helpers. First is + # the search box. This allows the user to type text and change which genomes are + # displayed. For multiple-select mode, we include a button that selects the displayed + # genes. For single-select mode, we use a plain label instead. + my $searchThingName = "${menuID}_SearchThing"; + my $searchThingLabel = "Type to narrow selection"; + my $searchThingButton = ""; + if ($multiSelect) { + $searchThingButton = qq(); + } + push @lines, "
$searchThingLabel " . + qq() . + $searchThingButton . + Hint("GenomeControl", 28) . "
"; + # For multi-select mode, we also have buttons to set and clear selections. + if ($multiSelect) { + push @lines, qq(); + push @lines, qq(); + push @lines, qq(); + } + # Add a hidden field we can use to generate organism page hyperlinks. + push @lines, qq(); + # Add the status display. This tells the user what's selected no matter where the list is scrolled. + push @lines, qq(
); + } + # Assemble all the lines into a string. + my $retVal = join("\n", @lines, ""); + # Return the result. + return $retVal; +} + +=head3 Cleanup + + $sprout->Cleanup(); + +Release the internal cache structures to free up memory. + +=cut + +sub Cleanup { + # Get the parameters. + my ($self) = @_; + # Delete the stemmer. + delete $self->{stemmer}; + # Delete the attribute database. + delete $self->{_ca}; + # Delete the group hash. + delete $self->{groupHash}; + # Is there a FIG object? + if (defined $self->{fig}) { + # Yes, clear its subsystem cache. + $self->{fig}->clear_subsystem_cache(); + } +} + + +=head3 Stem + + my $stem = $sprout->Stem($word); + +Return the stem of the specified word, or C if the word is not +stemmable. Note that even if the word is stemmable, the stem may be +the same as the original word. + +=over 4 + +=item word + +Word to convert into a stem. + +=item RETURN + +Returns a stem of the word (which may be the word itself), or C if +the word is not stemmable. + +=back + +=cut + +sub Stem { + # Get the parameters. + my ($self, $word) = @_; + # Get the stemmer object. + my $stemmer = $self->{stemmer}; + if (! defined $stemmer) { + # We don't have one pre-built, so we build and save it now. + $stemmer = BioWords->new(exceptions => "$FIG_Config::sproutData/Exceptions.txt", + stops => "$FIG_Config::sproutData/StopWords.txt", + cache => 0); + $self->{stemmer} = $stemmer; + } + # Try to stem the word. + my $retVal = $stemmer->Process($word); # Return the result. return $retVal; } + =head3 Build -C<< $sprout->Build(); >> + $sprout->Build(); Build the database. The database will be cleared and the tables re-created from the metadata. This method is useful when a database is brand new or when the database definition has @@ -452,7 +827,7 @@ =head3 Genomes -C<< my @genomes = $sprout->Genomes(); >> + my @genomes = $sprout->Genomes(); Return a list of all the genome IDs. @@ -469,7 +844,7 @@ =head3 GenusSpecies -C<< my $infoString = $sprout->GenusSpecies($genomeID); >> + my $infoString = $sprout->GenusSpecies($genomeID); Return the genus, species, and unique characterization for a genome. @@ -491,17 +866,21 @@ sub GenusSpecies { # Get the parameters. my ($self, $genomeID) = @_; - # Get the data for the specified genome. - my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)', - 'Genome(unique-characterization)']); - # Format the result and return it. - my $retVal = join(' ', @values); + # Declare the return value. + my $retVal; + # Get the genome data. + my $genomeData = $self->_GenomeData($genomeID); + # Only proceed if we found the genome. + if (defined $genomeData) { + $retVal = $genomeData->PrimaryValue('Genome(scientific-name)'); + } + # Return it. return $retVal; } =head3 FeaturesOf -C<< my @features = $sprout->FeaturesOf($genomeID, $ftype); >> + my @features = $sprout->FeaturesOf($genomeID, $ftype); Return a list of the features relevant to a specified genome. @@ -546,7 +925,7 @@ =head3 FeatureLocation -C<< my @locations = $sprout->FeatureLocation($featureID); >> + my @locations = $sprout->FeatureLocation($featureID); Return the location of a feature in its genome's contig segments. In a list context, this method will return a list of the locations. In a scalar context, it will return the locations as a space- @@ -570,7 +949,8 @@ =item RETURN Returns a list of the feature's contig segments. The locations are returned as a list in a list -context and as a comma-delimited string in a scalar context. +context and as a comma-delimited string in a scalar context. An empty list means the feature +wasn't found. =back @@ -579,20 +959,24 @@ sub FeatureLocation { # Get the parameters. my ($self, $featureID) = @_; + # Declare the return variable. + my @retVal = (); # Get the feature record. my $object = $self->GetEntity('Feature', $featureID); - Confess("Feature $featureID not found.") if ! defined($object); - # Get the location string. - my $locString = $object->PrimaryValue('Feature(location-string)'); - # Create the return list. - my @retVal = split /\s*,\s*/, $locString; + # Only proceed if we found it. + if (defined $object) { + # Get the location string. + my $locString = $object->PrimaryValue('Feature(location-string)'); + # Create the return list. + @retVal = split /\s*,\s*/, $locString; + } # Return the list in the format indicated by the context. return (wantarray ? @retVal : join(',', @retVal)); } =head3 ParseLocation -C<< my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location); >> + my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location); Split a location specifier into the contig ID, the starting point, the direction, and the length. @@ -635,10 +1019,9 @@ } - =head3 PointLocation -C<< my $found = Sprout::PointLocation($location, $point); >> + my $found = Sprout::PointLocation($location, $point); Return the offset into the specified location of the specified point on the contig. If the specified point is before the location, a negative value will be returned. If it is @@ -690,7 +1073,7 @@ =head3 DNASeq -C<< my $sequence = $sprout->DNASeq(\@locationList); >> + my $sequence = $sprout->DNASeq(\@locationList); This method returns the DNA sequence represented by a list of locations. The list of locations should be of the form returned by L when in a list context. In other words, @@ -774,7 +1157,7 @@ =head3 AllContigs -C<< my @idList = $sprout->AllContigs($genomeID); >> + my @idList = $sprout->AllContigs($genomeID); Return a list of all the contigs for a genome. @@ -804,7 +1187,7 @@ =head3 GenomeLength -C<< my $length = $sprout->GenomeLength($genomeID); >> + my $length = $sprout->GenomeLength($genomeID); Return the length of the specified genome in base pairs. @@ -828,18 +1211,19 @@ my ($self, $genomeID) = @_; # Declare the return variable. my $retVal = 0; - # Get the genome's contig sequence lengths. - my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?', - [$genomeID], 'IsMadeUpOf(len)'); - # Sum the lengths. - map { $retVal += $_ } @lens; + # Get the genome data. + my $genomeData = $self->_GenomeData($genomeID); + # Only proceed if it exists. + if (defined $genomeData) { + $retVal = $genomeData->PrimaryValue('Genome(dna-size)'); + } # Return the result. return $retVal; } =head3 FeatureCount -C<< my $count = $sprout->FeatureCount($genomeID, $type); >> + my $count = $sprout->FeatureCount($genomeID, $type); Return the number of features of the specified type in the specified genome. @@ -874,7 +1258,7 @@ =head3 GenomeAssignments -C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >> + my $fidHash = $sprout->GenomeAssignments($genomeID); Return a list of a genome's assigned features. The return hash will contain each assigned feature of the genome mapped to the text of its most recent functional @@ -917,7 +1301,7 @@ =head3 ContigLength -C<< my $length = $sprout->ContigLength($contigID); >> + my $length = $sprout->ContigLength($contigID); Compute the length of a contig. @@ -956,14 +1340,14 @@ =head3 ClusterPEGs -C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >> + my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); Cluster the PEGs in a list according to the cluster coding scheme of the specified subsystem. In order for this to work properly, the subsystem object must have -been used recently to retrieve the PEGs using the B method. -This causes the cluster numbers to be pulled into the subsystem's color hash. -If a PEG is not found in the color hash, it will not appear in the output -sequence. +been used recently to retrieve the PEGs using the B or +B methods. This causes the cluster numbers to be pulled into the +subsystem's color hash. If a PEG is not found in the color hash, it will not +appear in the output sequence. =over 4 @@ -1004,7 +1388,7 @@ =head3 GenesInRegion -C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >> + my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); List the features which overlap a specified region in a contig. @@ -1085,7 +1469,7 @@ =head3 GeneDataInRegion -C<< my @featureList = $sprout->GenesInRegion($contigID, $start, $stop); >> + my @featureList = $sprout->GenesInRegion($contigID, $start, $stop); List the features which overlap a specified region in a contig. @@ -1136,7 +1520,7 @@ # Loop through the feature segments found. while (my $segment = $query->Fetch) { # Get the data about this segment. - my ($featureID, $contig, $dir, $beg, $len) = $segment->Values([qw(IsLocatedIn(from-link) + my ($featureID, $contig, $dir, $beg, $len) = $segment->Values([qw(IsLocatedIn(from-link) IsLocatedIn(to-link) IsLocatedIn(dir) IsLocatedIn(beg) IsLocatedIn(len))]); # Determine if this feature segment actually overlaps the region. The query insures that # this will be the case if the segment is the maximum length, so to fine-tune @@ -1156,7 +1540,7 @@ =head3 FType -C<< my $ftype = $sprout->FType($featureID); >> + my $ftype = $sprout->FType($featureID); Return the type of a feature. @@ -1186,7 +1570,7 @@ =head3 FeatureAnnotations -C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >> + my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); Return the annotations of a feature. @@ -1249,7 +1633,7 @@ =head3 AllFunctionsOf -C<< my %functions = $sprout->AllFunctionsOf($featureID); >> + my %functions = $sprout->AllFunctionsOf($featureID); Return all of the functional assignments for a particular feature. The data is returned as a hash of functional assignments to user IDs. A functional assignment is a type of annotation, @@ -1304,7 +1688,7 @@ =head3 FunctionOf -C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >> + my $functionText = $sprout->FunctionOf($featureID, $userID); Return the most recently-determined functional assignment of a particular feature. @@ -1317,9 +1701,8 @@ the specified user and FIG are considered trusted. If the user ID is omitted, only FIG is trusted. -If the feature is B identified by a FIG ID, then the functional assignment -information is taken from the B table. If the table does -not contain an entry for the feature, an undefined value is returned. +If the feature is B identified by a FIG ID, then we search the aliases for it. +If no matching alias is found, we return an undefined value. =over 4 @@ -1345,12 +1728,14 @@ my ($self, $featureID, $userID) = @_; # Declare the return value. my $retVal; - # Determine the ID type. - if ($featureID =~ m/^fig\|/) { + # Find a FIG ID for this feature. + my ($fid) = $self->FeaturesByAlias($featureID); + # Only proceed if we have an ID. + if ($fid) { # Here we have a FIG feature ID. if (!$userID) { # Use the primary assignment. - ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']); + ($retVal) = $self->GetEntityValues('Feature', $fid, ['Feature(assignment)']); } else { # We must build the list of trusted users. my %trusteeTable = (); @@ -1376,7 +1761,7 @@ # Build a query for all of the feature's annotations, sorted by date. my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'], "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC", - [$featureID]); + [$fid]); my $timeSelected = 0; # Loop until we run out of annotations. while (my $annotation = $query->Fetch()) { @@ -1396,11 +1781,6 @@ } } } - } else { - # Here we have a non-FIG feature ID. In this case the user ID does not - # matter. We simply get the information from the External Alias Function - # table. - ($retVal) = $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']); } # Return the assignment found. return $retVal; @@ -1408,7 +1788,7 @@ =head3 FunctionsOf -C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >> + my @functionList = $sprout->FunctionOf($featureID, $userID); Return the functional assignments of a particular feature. @@ -1419,10 +1799,6 @@ 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. -If the feature is B identified by a FIG ID, then the functional assignment -information is taken from the B table. If the table does -not contain an entry for the feature, an empty list is returned. - =over 4 =item featureID @@ -1443,15 +1819,17 @@ my ($self, $featureID) = @_; # Declare the return value. my @retVal = (); - # Determine the ID type. - if ($featureID =~ m/^fig\|/) { + # Convert to a FIG ID. + my ($fid) = $self->FeaturesByAlias($featureID); + # Only proceed if we found one. + if ($fid) { # Here we have a FIG feature ID. We must build the list of trusted # users. my %trusteeTable = (); # Build a query for all of the feature's annotations, sorted by date. my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'], "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC", - [$featureID]); + [$fid]); my $timeSelected = 0; # Loop until we run out of annotations. while (my $annotation = $query->Fetch()) { @@ -1466,13 +1844,6 @@ push @retVal, [$actualUser, $function]; } } - } else { - # Here we have a non-FIG feature ID. In this case the user ID does not - # matter. We simply get the information from the External Alias Function - # table. - my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID, - ['ExternalAliasFunc(func)']); - push @retVal, map { ['master', $_] } @assignments; } # Return the assignments found. return @retVal; @@ -1480,7 +1851,7 @@ =head3 BBHList -C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >> + my $bbhHash = $sprout->BBHList($genomeID, \@featureList); Return a hash mapping the features in a specified list to their bidirectional best hits on a specified target genome. @@ -1512,10 +1883,10 @@ # Loop through the incoming features. for my $featureID (@{$featureList}) { # Ask the server for the feature's best hit. - my @bbhData = FIGRules::BBHData($featureID); + my $bbhData = FIGRules::BBHData($featureID); # Peel off the BBHs found. my @found = (); - for my $bbh (@bbhData) { + for my $bbh (@$bbhData) { my $fid = $bbh->[0]; my $bbGenome = $self->GenomeOf($fid); if ($bbGenome eq $genomeID) { @@ -1530,7 +1901,7 @@ =head3 SimList -C<< my %similarities = $sprout->SimList($featureID, $count); >> + my %similarities = $sprout->SimList($featureID, $count); Return a list of the similarities to the specified feature. @@ -1554,10 +1925,10 @@ # Get the parameters. my ($self, $featureID, $count) = @_; # Ask for the best hits. - my @lists = FIGRules::BBHData($featureID); + my $lists = FIGRules::BBHData($featureID); # Create the return value. my %retVal = (); - for my $tuple (@lists) { + for my $tuple (@$lists) { $retVal{$tuple->[0]} = $tuple->[1]; } # Return the result. @@ -1566,7 +1937,7 @@ =head3 IsComplete -C<< my $flag = $sprout->IsComplete($genomeID); >> + my $flag = $sprout->IsComplete($genomeID); Return TRUE if the specified genome is complete, else FALSE. @@ -1591,8 +1962,9 @@ # Declare the return variable. my $retVal; # Get the genome's data. - my $genomeData = $self->GetEntity('Genome', $genomeID); - if ($genomeData) { + my $genomeData = $self->_GenomeData($genomeID); + # Only proceed if it exists. + if (defined $genomeData) { # The genome exists, so get the completeness flag. $retVal = $genomeData->PrimaryValue('Genome(complete)'); } @@ -1602,7 +1974,7 @@ =head3 FeatureAliases -C<< my @aliasList = $sprout->FeatureAliases($featureID); >> + my @aliasList = $sprout->FeatureAliases($featureID); Return a list of the aliases for a specified feature. @@ -1632,7 +2004,7 @@ =head3 GenomeOf -C<< my $genomeID = $sprout->GenomeOf($featureID); >> + my $genomeID = $sprout->GenomeOf($featureID); Return the genome that contains a specified feature or contig. @@ -1660,7 +2032,11 @@ if ($featureID =~ /^fig\|(\d+\.\d+)/) { $retVal = $1; } else { - Confess("Invalid feature ID $featureID."); + # Find the feature by alias. + my ($realFeatureID) = $self->FeaturesByAlias($featureID); + if ($realFeatureID && $realFeatureID =~ /^fig\|(\d+\.\d+)/) { + $retVal = $1; + } } # Return the value found. return $retVal; @@ -1668,7 +2044,7 @@ =head3 CoupledFeatures -C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >> + my %coupleHash = $sprout->CoupledFeatures($featureID); Return the features functionally coupled with a specified feature. Features are considered functionally coupled if they tend to be clustered on the same chromosome. @@ -1704,18 +2080,13 @@ $retVal{$featureID2} = $score; } } - # Functional coupling is reflexive. If we found at least one coupled feature, we must add - # the incoming feature as well. - if (keys %retVal) { - $retVal{$featureID} = 9999; - } # Return the hash. return %retVal; } =head3 CouplingEvidence -C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >> + my @evidence = $sprout->CouplingEvidence($peg1, $peg2); Return the evidence for a functional coupling. @@ -1777,7 +2148,7 @@ =head3 GetSynonymGroup -C<< my $id = $sprout->GetSynonymGroup($fid); >> + my $id = $sprout->GetSynonymGroup($fid); Return the synonym group name for the specified feature. @@ -1816,7 +2187,7 @@ =head3 GetBoundaries -C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >> + my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); Determine the begin and end boundaries for the locations in a list. All of the locations must belong to the same contig and have mostly the same direction in @@ -1880,7 +2251,7 @@ =head3 ReadFasta -C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >> + my %sequenceData = Sprout::ReadFasta($fileName, $prefix); Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by one or more lines of data. The first line begins with a > character and contains an ID. @@ -1946,7 +2317,7 @@ =head3 FormatLocations -C<< my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat); >> + my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat); Insure that a list of feature locations is in the Sprout format. The Sprout feature location format is I_I where I<*> is C<+> for a forward gene and C<-> for a backward @@ -2011,7 +2382,7 @@ =head3 DumpData -C<< $sprout->DumpData(); >> + $sprout->DumpData(); Dump all the tables to tab-delimited DTX files. The files will be stored in the data directory. @@ -2028,7 +2399,7 @@ =head3 XMLFileName -C<< my $fileName = $sprout->XMLFileName(); >> + my $fileName = $sprout->XMLFileName(); Return the name of this database's XML definition file. @@ -2039,9 +2410,97 @@ return $self->{_xmlName}; } +=head3 GetGenomeNameData + + my ($genus, $species, $strain) = $sprout->GenomeNameData($genomeID); + +Return the genus, species, and unique characterization for a genome. This +is similar to L, with the exception that it returns the +values in three seperate fields. + +=over 4 + +=item genomeID + +ID of the genome whose name data is desired. + +=item RETURN + +Returns a three-element list, consisting of the genus, species, and strain +of the specified genome. If the genome is not found, an error occurs. + +=back + +=cut + +sub GetGenomeNameData { + # Get the parameters. + my ($self, $genomeID) = @_; + # Declare the return variables. + my ($genus, $species, $strain); + # Get the genome's data. + my $genomeData = $self->_GenomeData($genomeID); + # Only proceed if the genome exists. + if (defined $genomeData) { + # Get the desired values. + ($genus, $species, $strain) = $genomeData->Values(['Genome(genus)', + 'Genome(species)', + 'Genome(unique-characterization)']); + } else { + # Throw an error because they were not found. + Confess("Genome $genomeID not found in database."); + } + # Return the results. + return ($genus, $species, $strain); +} + +=head3 GetGenomeByNameData + + my @genomes = $sprout->GetGenomeByNameData($genus, $species, $strain); + +Return a list of the IDs of the genomes with the specified genus, +species, and strain. In almost every case, there will be either zero or +one IDs returned; however, two or more IDs could be returned if there are +multiple versions of the genome in the database. + +=over 4 + +=item genus + +Genus of the desired genome. + +=item species + +Species of the desired genome. + +=item strain + +Strain (unique characterization) of the desired genome. This may be an empty +string, in which case it is presumed that the desired genome has no strain +specified. + +=item RETURN + +Returns a list of the IDs of the genomes having the specified genus, species, and +strain. + +=back + +=cut + +sub GetGenomeByNameData { + # Get the parameters. + my ($self, $genus, $species, $strain) = @_; + # Try to find the genomes. + my @retVal = $self->GetFlat(['Genome'], "Genome(genus) = ? AND Genome(species) = ? AND Genome(unique-characterization) = ?", + [$genus, $species, $strain], 'Genome(id)'); + # Return the result. + return @retVal; +} + =head3 Insert -C<< $sprout->Insert($objectType, \%fieldHash); >> + $sprout->Insert($objectType, \%fieldHash); Insert an entity or relationship instance into the database. The entity or relationship of interest is defined by a type name and then a hash of field names to values. Field values in the primary @@ -2050,12 +2509,12 @@ list references. For example, the following line inserts an inactive PEG feature named C with aliases C and C. -C<< $sprout->Insert('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >> + $sprout->Insert('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); The next statement inserts a C relationship between feature C and property C<4> with an evidence URL of C. -C<< $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >> + $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); =over 4 @@ -2080,7 +2539,7 @@ =head3 Annotate -C<< my $ok = $sprout->Annotate($fid, $timestamp, $user, $text); >> + my $ok = $sprout->Annotate($fid, $timestamp, $user, $text); Annotate a feature. This inserts an Annotation record into the database and links it to the specified feature and user. @@ -2134,7 +2593,7 @@ =head3 AssignFunction -C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >> + my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); This method assigns a function to a feature. Functions are a special type of annotation. The general format is described in L. @@ -2194,7 +2653,7 @@ =head3 FeaturesByAlias -C<< my @features = $sprout->FeaturesByAlias($alias); >> + my @features = $sprout->FeaturesByAlias($alias); Returns a list of features with the specified alias. The alias is parsed to determine the type of the alias. A string of digits is a GenBack ID and a string of exactly 6 @@ -2236,7 +2695,7 @@ =head3 FeatureTranslation -C<< my $translation = $sprout->FeatureTranslation($featureID); >> + my $translation = $sprout->FeatureTranslation($featureID); Return the translation of a feature. @@ -2264,13 +2723,13 @@ =head3 Taxonomy -C<< my @taxonomyList = $sprout->Taxonomy($genome); >> + my @taxonomyList = $sprout->Taxonomy($genome); Return the taxonomy of the specified genome. This will be in the form of a list containing the various classifications in order from domain (eg. C, C, or C) to sub-species. For example, -C<< (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12) >> + (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12) =over 4 @@ -2289,14 +2748,16 @@ sub Taxonomy { # Get the parameters. my ($self, $genome) = @_; - # Find the specified genome's taxonomy string. - my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']); # Declare the return variable. my @retVal = (); - # If we found the genome, return its taxonomy string. - if ($list) { - @retVal = split /\s*;\s*/, $list; + # Get the genome data. + my $genomeData = $self->_GenomeData($genome); + # Only proceed if it exists. + if (defined $genomeData) { + # Create the taxonomy from the taxonomy string. + @retVal = split /\s*;\s*/, $genomeData->PrimaryValue('Genome(taxonomy)'); } else { + # Genome doesn't exist, so emit a warning. Trace("Genome \"$genome\" does not have a taxonomy in the database.\n") if T(0); } # Return the value found. @@ -2305,7 +2766,7 @@ =head3 CrudeDistance -C<< my $distance = $sprout->CrudeDistance($genome1, $genome2); >> + my $distance = $sprout->CrudeDistance($genome1, $genome2); Returns a crude estimate of the distance between two genomes. The distance is construed so that it will be 0 for genomes with identical taxonomies and 1 for genomes from different domains. @@ -2341,23 +2802,14 @@ } my @taxA = $self->Taxonomy($genomeA); my @taxB = $self->Taxonomy($genomeB); - # Initialize the distance to 1. We'll reduce it each time we find a match between the - # taxonomies. - my $retVal = 1.0; - # Initialize the subtraction amount. This amount determines the distance reduction caused - # by a mismatch at the current level. - my $v = 0.5; - # Loop through the taxonomies. - for (my $i = 0; ($i < @taxA) && ($i < @taxB) && ($taxA[$i] eq $taxB[$i]); $i++) { - $retVal -= $v; - $v /= 2; - } + # Compute the distance. + my $retVal = FIGRules::CrudeDistanceFormula(\@taxA, \@taxB); return $retVal; } =head3 RoleName -C<< my $roleName = $sprout->RoleName($roleID); >> + my $roleName = $sprout->RoleName($roleID); Return the descriptive name of the role with the specified ID. In general, a role will only have a descriptive name if it is coded as an EC number. @@ -2391,7 +2843,7 @@ =head3 RoleDiagrams -C<< my @diagrams = $sprout->RoleDiagrams($roleID); >> + my @diagrams = $sprout->RoleDiagrams($roleID); Return a list of the diagrams containing a specified functional role. @@ -2419,95 +2871,9 @@ return @retVal; } -=head3 GetProperties - -C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >> - -Return a list of the properties with the specified characteristics. - -Properties are the Sprout analog of the FIG attributes. The call is -passed directly to the CustomAttributes or RemoteCustomAttributes object -contained in this object. - -This method returns a series of tuples that match the specified criteria. Each tuple -will contain an object ID, a key, and one or more values. The parameters to this -method therefore correspond structurally to the values expected in each tuple. In -addition, you can ask for a generic search by suffixing a percent sign (C<%>) to any -of the parameters. So, for example, - - my @attributeList = $sprout->GetProperties('fig|100226.1.peg.1004', 'structure%', 1, 2); - -would return something like - - ['fig}100226.1.peg.1004', 'structure', 1, 2] - ['fig}100226.1.peg.1004', 'structure1', 1, 2] - ['fig}100226.1.peg.1004', 'structure2', 1, 2] - ['fig}100226.1.peg.1004', 'structureA', 1, 2] - -Use of C in any position acts as a wild card (all values). You can also specify -a list reference in the ID column. Thus, - - my @attributeList = $sprout->GetProperties(['100226.1', 'fig|100226.1.%'], 'PUBMED'); - -would get the PUBMED attribute data for Streptomyces coelicolor A3(2) and all its -features. - -In addition to values in multiple sections, a single attribute key can have multiple -values, so even - - my @attributeList = $sprout->GetProperties($peg, 'virulent'); - -which has no wildcard in the key or the object ID, may return multiple tuples. - -=over 4 - -=item objectID - -ID of object whose attributes are desired. If the attributes are desired for multiple -objects, this parameter can be specified as a list reference. If the attributes are -desired for all objects, specify C or an empty string. Finally, you can specify -attributes for a range of object IDs by putting a percent sign (C<%>) at the end. - -=item key - -Attribute key name. A value of C or an empty string will match all -attribute keys. If the values are desired for multiple keys, this parameter can be -specified as a list reference. Finally, you can specify attributes for a range of -keys by putting a percent sign (C<%>) at the end. - -=item values - -List of the desired attribute values, section by section. If C -or an empty string is specified, all values in that section will match. A -generic match can be requested by placing a percent sign (C<%>) at the end. -In that case, all values that match up to and not including the percent sign -will match. You may also specify a regular expression enclosed -in slashes. All values that match the regular expression will be returned. For -performance reasons, only values have this extra capability. - -=item RETURN - -Returns a list of tuples. The first element in the tuple is an object ID, the -second is an attribute key, and the remaining elements are the sections of -the attribute value. All of the tuples will match the criteria set forth in -the parameter list. - -=back - -=cut - -sub GetProperties { - # Get the parameters. - my ($self, @parms) = @_; - # Declare the return variable. - my @retVal = $self->{_ca}->GetAttributes(@parms); - # Return the result. - return @retVal; -} - =head3 FeatureProperties -C<< my @properties = $sprout->FeatureProperties($featureID); >> + my @properties = $sprout->FeatureProperties($featureID); Return a list of the properties for the specified feature. Properties are key-value pairs that specify special characteristics of the feature. For example, a property could indicate @@ -2533,7 +2899,7 @@ # Get the parameters. my ($self, $featureID) = @_; # Get the properties. - my @attributes = $self->{_ca}->GetAttributes($featureID); + my @attributes = $self->ca->GetAttributes($featureID); # Strip the feature ID off each tuple. my @retVal = (); for my $attributeRow (@attributes) { @@ -2546,7 +2912,7 @@ =head3 DiagramName -C<< my $diagramName = $sprout->DiagramName($diagramID); >> + my $diagramName = $sprout->DiagramName($diagramID); Return the descriptive name of a diagram. @@ -2574,7 +2940,7 @@ =head3 PropertyID -C<< my $id = $sprout->PropertyID($propName, $propValue); >> + my $id = $sprout->PropertyID($propName, $propValue); Return the ID of the specified property name and value pair, if the pair exists. Only a small subset of the FIG attributes are stored as @@ -2611,7 +2977,7 @@ =head3 MergedAnnotations -C<< my @annotationList = $sprout->MergedAnnotations(\@list); >> + my @annotationList = $sprout->MergedAnnotations(\@list); Returns a merged list of the annotations for the features in a list. Each annotation is represented by a 4-tuple of the form C<($fid, $timestamp, $userID, $annotation)>, where @@ -2660,7 +3026,7 @@ =head3 RoleNeighbors -C<< my @roleList = $sprout->RoleNeighbors($roleID); >> + my @roleList = $sprout->RoleNeighbors($roleID); Returns a list of the roles that occur in the same diagram as the specified role. Because diagrams and roles are in a many-to-many relationship with each other, the list is @@ -2703,7 +3069,7 @@ =head3 FeatureLinks -C<< my @links = $sprout->FeatureLinks($featureID); >> + my @links = $sprout->FeatureLinks($featureID); Return a list of the web hyperlinks associated with a feature. The web hyperlinks are to external websites describing either the feature itself or the organism containing it @@ -2734,7 +3100,7 @@ =head3 SubsystemsOf -C<< my %subsystems = $sprout->SubsystemsOf($featureID); >> + my %subsystems = $sprout->SubsystemsOf($featureID); Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped to the roles the feature performs. @@ -2782,7 +3148,7 @@ =head3 SubsystemList -C<< my @subsystems = $sprout->SubsystemList($featureID); >> + my @subsystems = $sprout->SubsystemList($featureID); Return a list containing the names of the subsystems in which the specified feature participates. Unlike L, this method only returns the @@ -2805,8 +3171,9 @@ sub SubsystemList { # Get the parameters. my ($self, $featureID) = @_; - # Get the list of names. - my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?", + # Get the list of names. We do a join to the Subsystem table because we have missing subsystems in + # the Sprout database! + my @retVal = $self->GetFlat(['HasRoleInSubsystem', 'Subsystem'], "HasRoleInSubsystem(from-link) = ?", [$featureID], 'HasRoleInSubsystem(to-link)'); # Return the result, sorted. return sort @retVal; @@ -2814,7 +3181,7 @@ =head3 GenomeSubsystemData -C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >> + my %featureData = $sprout->GenomeSubsystemData($genomeID); Return a hash mapping genome features to their subsystem roles. @@ -2839,29 +3206,23 @@ # Declare the return variable. my %retVal = (); # Get a list of the genome features that participate in subsystems. For each - # feature we get its spreadsheet cells and the corresponding roles. - my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'], - "HasFeature(from-link) = ?", [$genomeID], - ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']); - # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems - # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the - # list. We use it at the beginning to get all the spreadsheet cells for the genome and - # again at the end to filter out participation in subsystems with a negative variant code. - my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'], - "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?", - [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']); - # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features. - # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We - # link these two lists together to create the result. First, we want a hash mapping - # spreadsheet cells to subsystem names. - my %subHash = map { $_->[0] => $_->[1] } @cellData; - # We loop through @cellData to build the hash. + # feature we get its subsystem ID and the corresponding roles. + my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf', 'HasSSCell'], + "HasFeature(from-link) = ?", [$genomeID], + ['HasFeature(to-link)', 'IsRoleOf(from-link)', 'HasSSCell(from-link)']); + # Now we get a list of valid subsystems. These are the subsystems connected to the genome with + # a non-negative variant code. + my %subs = map { $_ => 1 } $self->GetFlat(['ParticipatesIn'], + "ParticipatesIn(from-link) = ? AND ParticipatesIn(variant-code) >= 0", + [$genomeID], 'ParticipatesIn(to-link)'); + # We loop through @roleData to build the hash. for my $roleEntry (@roleData) { # Get the data for this feature and cell. - my ($fid, $cellID, $role) = @{$roleEntry}; - # Check for a subsystem name. - my $subsys = $subHash{$cellID}; - if ($subsys) { + my ($fid, $role, $subsys) = @{$roleEntry}; + Trace("Subsystem for $fid is $subsys.") if T(4); + # Check the subsystem; + if ($subs{$subsys}) { + Trace("Subsystem found.") if T(4); # Insure this feature has an entry in the return hash. if (! exists $retVal{$fid}) { $retVal{$fid} = []; } # Merge in this new data. @@ -2874,7 +3235,7 @@ =head3 RelatedFeatures -C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >> + my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); Return a list of the features which are bi-directional best hits of the specified feature and have been assigned the specified function by the specified user. If no such features exists, @@ -2907,7 +3268,8 @@ # Get the parameters. my ($self, $featureID, $function, $userID) = @_; # Get a list of the features that are BBHs of the incoming feature. - my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID); + my $bbhData = FIGRules::BBHData($featureID); + my @bbhFeatures = map { $_->[0] } @$bbhData; # Now we loop through the features, pulling out the ones that have the correct # functional assignment. my @retVal = (); @@ -2925,7 +3287,7 @@ =head3 TaxonomySort -C<< my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs); >> + my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs); Return a list formed by sorting the specified features by the taxonomy of the containing genome. This will cause genomes from similar organisms to float close to each other. @@ -2960,7 +3322,7 @@ my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?", [$fid], 'Genome(taxonomy)'); # Add this feature to the hash buffer. - Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid); + push @{$hashBuffer{$taxonomy}}, $fid; } # Sort the keys and get the elements. my @retVal = (); @@ -2973,7 +3335,7 @@ =head3 Protein -C<< my $protein = Sprout::Protein($sequence, $table); >> + my $protein = Sprout::Protein($sequence, $table); Translate a DNA sequence into a protein sequence. @@ -3059,7 +3421,7 @@ =head3 LoadInfo -C<< my ($dirName, @relNames) = $sprout->LoadInfo(); >> + my ($dirName, @relNames) = $sprout->LoadInfo(); Return the name of the directory from which data is to be loaded and a list of the relation names. This information is useful when trying to analyze what needs to be put where in order @@ -3080,7 +3442,7 @@ =head3 BBHMatrix -C<< my %bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets); >> + my $bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets); Find all the bidirectional best hits for the features of a genome in a specified list of target genomes. The return value will be a hash mapping @@ -3104,8 +3466,8 @@ =item RETURN -Returns a hash mapping each feature in the original genome to a hash mapping its -BBH pegs in the target genomes to their scores. +Returns a reference to a hash mapping each feature in the original genome +to a sub-hash mapping its BBH pegs in the target genomes to their scores. =back @@ -3118,6 +3480,7 @@ my %retVal = (); # Ask for the BBHs. my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets); + Trace("Retrieved " . scalar(@bbhList) . " BBH results.") if T(3); # We now have a set of 4-tuples that we need to convert into a hash of hashes. for my $bbhData (@bbhList) { my ($peg1, $peg2, $score) = @{$bbhData}; @@ -3128,13 +3491,13 @@ } } # Return the result. - return %retVal; + return \%retVal; } =head3 SimMatrix -C<< my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets); >> + my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets); Find all the similarities for the features of a genome in a specified list of target genomes. The return value will be a hash mapping @@ -3204,7 +3567,7 @@ =head3 LowBBHs -C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >> + my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); Return the bidirectional best hits of a feature whose score is no greater than a specified cutoff value. A higher cutoff value will allow inclusion of hits with @@ -3234,9 +3597,9 @@ # Create the return hash. my %retVal = (); # Query for the desired BBHs. - my @bbhList = FIGRules::BBHData($featureID, $cutoff); + my $bbhList = FIGRules::BBHData($featureID, $cutoff); # Form the results into the return hash. - for my $pair (@bbhList) { + for my $pair (@$bbhList) { my $fid = $pair->[0]; if ($self->Exists('Feature', $fid)) { $retVal{$fid} = $pair->[1]; @@ -3248,7 +3611,7 @@ =head3 Sims -C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >> + my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); Get a list of similarities for a specified feature. Similarity information is not kept in the Sprout database; rather, they are retrieved from a network server. The similarities are @@ -3314,7 +3677,7 @@ =head3 IsAllGenomes -C<< my $flag = $sprout->IsAllGenomes(\@list, \@checkList); >> + my $flag = $sprout->IsAllGenomes(\@list, \@checkList); Return TRUE if all genomes in the second list are represented in the first list at least one. Otherwise, return FALSE. If the second list is omitted, the first list is @@ -3363,7 +3726,7 @@ =head3 GetGroups -C<< my %groups = $sprout->GetGroups(\@groupList); >> + my %groups = $sprout->GetGroups(\@groupList); Return a hash mapping each group to the IDs of the genomes in the group. A list of groups may be specified, in which case only those groups will be @@ -3395,14 +3758,9 @@ [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']); # Loop through the genomes found. for my $genome (@genomes) { - # Pop this genome's ID off the current list. - my @groups = @{$genome}; - my $genomeID = shift @groups; - # Loop through the groups, adding the genome ID to each group's - # list. - for my $group (@groups) { - Tracer::AddToListMap(\%retVal, $group, $genomeID); - } + # Get the genome ID and group, and add this genome to the group's list. + my ($genomeID, $group) = @{$genome}; + push @{$retVal{$group}}, $genomeID; } } # Return the hash we just built. @@ -3411,7 +3769,7 @@ =head3 MyGenomes -C<< my @genomes = Sprout::MyGenomes($dataDir); >> + my @genomes = Sprout::MyGenomes($dataDir); Return a list of the genomes to be included in the Sprout. @@ -3443,7 +3801,7 @@ =head3 LoadFileName -C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >> + my $fileName = Sprout::LoadFileName($dataDir, $tableName); Return the name of the load file for the specified table in the specified data directory. @@ -3484,7 +3842,7 @@ =head3 DeleteGenome -C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >> + my $stats = $sprout->DeleteGenome($genomeID, $testFlag); Delete a genome from the database. @@ -3520,11 +3878,10 @@ =head3 Fix -C<< my %fixedHash = Sprout::Fix(%groupHash); >> + my %fixedHash = $sprout->Fix(%groupHash); Prepare a genome group hash (like that returned by L) for processing. -Groups with the same primary name will be combined. The primary name is the -first capitalized word in the group name. +The groups will be combined into the appropriate super-groups. =over 4 @@ -3542,19 +3899,16 @@ sub Fix { # Get the parameters. - my (%groupHash) = @_; + my ($self, %groupHash) = @_; # Create the result hash. my %retVal = (); # Copy over the genomes. for my $groupID (keys %groupHash) { - # Make a safety copy of the group ID. - my $realGroupID = $groupID; - # Yank the primary name. - if ($groupID =~ /([A-Z]\w+)/) { - $realGroupID = $1; - } - # Append this group's genomes into the result hash. - Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}}); + # Get the super-group name. + my $realGroupID = $self->SuperGroup($groupID); + # Append this group's genomes into the result hash + # using the super-group name. + push @{$retVal{$realGroupID}}, @{$groupHash{$groupID}}; } # Return the result hash. return %retVal; @@ -3562,7 +3916,7 @@ =head3 GroupPageName -C<< my $name = $sprout->GroupPageName($group); >> + my $name = $sprout->GroupPageName($group); Return the name of the page for the specified NMPDR group. @@ -3584,123 +3938,107 @@ sub GroupPageName { # Get the parameters. my ($self, $group) = @_; - # Declare the return variable. - my $retVal; # Check for the group file data. - if (! defined $self->{groupHash}) { - # Read the group file. - my %groupData = Sprout::ReadGroupFile($self->{_options}->{dataDir} . "/groups.tbl"); - # Store it in our object. - $self->{groupHash} = \%groupData; - } + my %superTable = $self->CheckGroupFile(); # Compute the real group name. - my $realGroup = $group; - if ($group =~ /([A-Z]\w+)/) { - $realGroup = $1; - } - # Return the page name. - $retVal = "../content/" . $self->{groupHash}->{$realGroup}->[1]; + my $realGroup = $self->SuperGroup($group); + # Get the associated page name. + my $retVal = "../content/$superTable{$realGroup}->{page}"; # Return the result. return $retVal; } -=head3 ReadGroupFile - -C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >> - -Read in the data from the specified group file. The group file contains information -about each of the NMPDR groups. - -=over 4 - -=item name - -Name of the group. - -=item page - -Name of the group's page on the web site (e.g. C for -Campylobacter) - -=item genus -Genus of the group +=head3 AddProperty -=item species + $sprout->AddProperty($featureID, $key, @values); -Species of the group, or an empty string if the group is for an entire -genus. If the group contains more than one species, the species names -should be separated by commas. +Add a new attribute value (Property) to a feature. -=back +=over 4 -The parameters to this method are as follows +=item peg -=over 4 +ID of the feature to which the attribute is to be added. -=item groupFile +=item key -Name of the file containing the group data. +Name of the attribute (key). -=item RETURN +=item values -Returns a hash keyed on group name. The value of each hash +Values of the attribute. =back =cut - -sub ReadGroupFile { +#: Return Type ; +sub AddProperty { # Get the parameters. - my ($groupFileName) = @_; - # Declare the return variable. - my %retVal; - # Read the group file. - my @groupLines = Tracer::GetFile($groupFileName); - for my $groupLine (@groupLines) { - my ($name, $page, $genus, $species) = split(/\t/, $groupLine); - $retVal{$name} = [$page, $genus, $species]; - } - # Return the result. - return %retVal; + my ($self, $featureID, $key, @values) = @_; + # Add the property using the attached attributes object. + $self->ca->AddAttribute($featureID, $key, @values); } -=head3 AddProperty +=head3 CheckGroupFile -C<< my = $sprout->AddProperty($featureID, $key, @values); >> + my %groupData = $sprout->CheckGroupFile(); -Add a new attribute value (Property) to a feature. - -=over 4 +Get the group file hash. The group file hash describes the relationship +between a group and the super-group to which it belongs for purposes of +display. The super-group name is computed from the first capitalized word +in the actual group name. For each super-group, the group file contains +the page name and a list of the species expected to be in the group. +Each species is specified by a genus and a species name. A species name +of C<0> implies an entire genus. -=item peg +This method returns a hash from super-group names to a hash reference. Each +resulting hash reference contains the following fields. -ID of the feature to which the attribute is to be added. +=over 4 -=item key +=item specials -Name of the attribute (key). +Reference to a hash whose keys are the names of special species. -=item values +=item contents -Values of the attribute. +A list of 2-tuples, each containing a genus name followed by a species name +(or 0, indicating all species). This list indicates which organisms belong +in the super-group. =back =cut -#: Return Type ; -sub AddProperty { + +sub CheckGroupFile { # Get the parameters. - my ($self, $featureID, $key, @values) = @_; - # Add the property using the attached attributes object. - $self->{_ca}->AddAttribute($featureID, $key, @values); + my ($self) = @_; + # Check to see if we already have this hash. + if (! defined $self->{groupHash}) { + # We don't, so we need to read it in. + my %groupHash; + # Read the group file. + my @groupLines = Tracer::GetFile("$FIG_Config::sproutData/groups.tbl"); + # Loop through the list of sort-of groups. + for my $groupLine (@groupLines) { + my ($name, $specials, @contents) = split /\t/, $groupLine; + $groupHash{$name} = { specials => { map { $_ => 1 } split /\s*,\s*/, $specials }, + contents => [ map { [ split /\s*,\s*/, $_ ] } @contents ] + }; + } + # Save the hash. + $self->{groupHash} = \%groupHash; + } + # Return the result. + return %{$self->{groupHash}}; } =head2 Virtual Methods =head3 CleanKeywords -C<< my $cleanedString = $sprout->CleanKeywords($searchExpression); >> + my $cleanedString = $sprout->CleanKeywords($searchExpression); Clean up a search expression or keyword list. This involves converting the periods in EC numbers to underscores, converting non-leading minus signs to underscores, @@ -3726,22 +4064,165 @@ sub CleanKeywords { # Get the parameters. my ($self, $searchExpression) = @_; - # Perform the standard cleanup. - my $retVal = $self->ERDB::CleanKeywords($searchExpression); - # Fix the periods in EC and TC numbers. - $retVal =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g; - # Fix non-trailing periods. - $retVal =~ s/\.(\w)/_$1/g; - # Fix non-leading minus signs. - $retVal =~ s/(\w)[\-]/$1_/g; - # Fix the vertical bars and colons - $retVal =~ s/(\w)[|:](\w)/$1'$2/g; + # Get the stemmer. + my $stemmer = $self->GetStemmer(); + # Convert the search expression using the stemmer. + my $retVal = $stemmer->PrepareSearchExpression($searchExpression); + Trace("Cleaned keyword list for \"$searchExpression\" is \"$retVal\".") if T(3); # Return the result. return $retVal; } +=head3 GetSourceObject + + my $source = $erdb->GetSourceObject(); + +Return the object to be used in creating load files for this database. + +=cut + +sub GetSourceObject { + # Get the parameters. + my ($self) = @_; + # Do we already have one? + my $retVal = $self->{fig}; + if (! defined $retVal) { + # Create the object. + require FIG; + $retVal = FIG->new(); + Trace("FIG source object created for process $$.") if T(ERDBLoadGroup => 3); + # Set up retries to prevent the lost-connection error when harvesting + # the feature data. + my $dbh = $retVal->db_handle(); + $dbh->set_retries(5); + # Save it for other times. + $self->{fig} = $retVal; + } + # Return the object. + return $retVal; +} + +=head3 SectionList + + my @sections = $erdb->SectionList($fig); + +Return a list of the names for the different data sections used when loading this database. +The default is a single string, in which case there is only one section representing the +entire database. + +=cut + +sub SectionList { + # Get the parameters. + my ($self, $source) = @_; + # Ask the BaseSproutLoader for a section list. + require BaseSproutLoader; + my @retVal = BaseSproutLoader::GetSectionList($self, $source); + # Return the list. + return @retVal; +} + +=head3 Loader + + my $groupLoader = $erdb->Loader($groupName, $options); + +Return an [[ERDBLoadGroupPm]] object for the specified load group. This method is used +by [[ERDBGeneratorPl]] to create the load group objects. If you are not using +[[ERDBGeneratorPl]], you don't need to override this method. + +=over 4 + +=item groupName + +Name of the load group whose object is to be returned. The group name is +guaranteed to be a single word with only the first letter capitalized. + +=item options + +Reference to a hash of command-line options. + +=item RETURN + +Returns an [[ERDBLoadGroupPm]] object that can be used to process the specified load group +for this database. + +=back + +=cut + +sub Loader { + # Get the parameters. + my ($self, $groupName, $options) = @_; + # Compute the loader name. + my $loaderClass = "${groupName}SproutLoader"; + # Pull in its definition. + require "$loaderClass.pm"; + # Create an object for it. + my $retVal = eval("$loaderClass->new(\$self, \$options)"); + # Insure it worked. + Confess("Could not create $loaderClass object: $@") if $@; + # Return it to the caller. + return $retVal; +} + + +=head3 LoadGroupList + + my @groups = $erdb->LoadGroupList(); + +Returns a list of the names for this database's load groups. This method is used +by [[ERDBGeneratorPl]] when the user wishes to load all table groups. The default +is a single group called 'All' that loads everything. + +=cut + +sub LoadGroupList { + # Return the list. + return qw(Feature Subsystem Genome Annotation Property Source Reaction Synonym Drug); +} + +=head3 LoadDirectory + + my $dirName = $erdb->LoadDirectory(); + +Return the name of the directory in which load files are kept. The default is +the FIG temporary directory, which is a really bad choice, but it's always there. + +=cut + +sub LoadDirectory { + # Get the parameters. + my ($self) = @_; + # Return the directory name. + return $self->{dataDir}; +} + =head2 Internal Utility Methods +=head3 GetStemmer + + my $stermmer = $sprout->GetStemmer(); + +Return the stemmer object for this database. + +=cut + +sub GetStemmer { + # Get the parameters. + my ($self) = @_; + # Declare the return variable. + my $retVal = $self->{stemmer}; + if (! defined $retVal) { + # We don't have one pre-built, so we build and save it now. + $retVal = BioWords->new(exceptions => "$FIG_Config::sproutData/Exceptions.txt", + stops => "$FIG_Config::sproutData/StopWords.txt", + cache => 0); + $self->{stemmer} = $retVal; + } + # Return the result. + return $retVal; +} + =head3 ParseAssignment Parse annotation text to determine whether or not it is a functional assignment. If it is, @@ -3750,7 +4231,8 @@ A functional assignment is always of the form - CIC< function to\n>I + set YYYY function to + ZZZZ where I is the B, and I is the actual functional role. In most cases, the user and the assigning user (from MadeAnnotation) will be the same, but that is @@ -3805,7 +4287,7 @@ =head3 _CheckFeature -C<< my $flag = $sprout->_CheckFeature($fid); >> + my $flag = $sprout->_CheckFeature($fid); Return TRUE if the specified FID is probably an NMPDR feature ID, else FALSE. @@ -3827,10 +4309,7 @@ # Get the parameters. my ($self, $fid) = @_; # Insure we have a genome hash. - if (! defined $self->{genomeHash}) { - my %genomeHash = map { $_ => 1 } $self->GetFlat(['Genome'], "", [], 'Genome(id)'); - $self->{genomeHash} = \%genomeHash; - } + my $genomes = $self->_GenomeHash(); # Get the feature's genome ID. my ($genomeID) = FIGRules::ParseFeatureID($fid); # Return an indicator of whether or not the genome ID is in the hash. @@ -3864,4 +4343,155 @@ } -1; +=head3 Hint + + my $htmlText = Sprout::Hint($wikiPage, $hintID); + +Return the HTML for a help link that displays the specified hint text when it is clicked. +This HTML can be put in forms to provide a useful hinting mechanism. + +=over 4 + +=item wikiPage + +Name of the wiki page to be popped up when the hint mark is clicked. + +=item hintID + +ID of the text to display for the hint. This should correspond to a tip number +in the Wiki. + +=item RETURN + +Returns the html for the hint facility. The resulting html shows the word "help" and +uses the standard FIG popup technology. + +=back + +=cut + +sub Hint { + # Get the parameters. + my ($wikiPage, $hintID) = @_; + # Declare the return variable. + my $retVal; + # Convert the wiki page name to a URL. + my $wikiURL; + if ($wikiPage =~ m#/#) { + # Here it's a URL of some sort. + $wikiURL = $wikiPage; + } else { + # Here it's a wiki page. + my $page = join("", map { ucfirst $_ } split /\s+/, $wikiPage); + if ($page =~ /^(.+?)\.(.+)$/) { + $page = "$1/$2"; + } else { + $page = "FIG/$page"; + } + $wikiURL = "$FIG_Config::cgi_url/wiki/view.cgi/$page"; + } + # Is there hint text? + if (! $hintID) { + # No. Create a new-page hint. + $retVal = qq( (help)); + } else { + # With hint text, we create a popup window hint. We need to compute the hint URL. + my $tipURL = "$FIG_Config::cgi_url/wiki/view.cgi/FIG/TWikiCustomTip" . + Tracer::Pad($hintID, 3, 1, "0"); + # Create a hint pop-up link. + $retVal = qq( (help)); + } + # Return the HTML. + return $retVal; +} + +=head3 _GenomeHash + + my $gHash = $sprout->_GenomeHash(); + +Return a hash mapping all NMPDR genome IDs to [[ERDBObjectPm]] genome objects. + +=cut + +sub _GenomeHash { + # Get the parameters. + my ($self) = @_; + # Do we already have a filled hash? + if (! $self->{genomeHashFilled}) { + # No, create it. + my %gHash = map { $_->PrimaryValue('id') => $_ } $self->GetList("Genome", "", []); + $self->{genomeHash} = \%gHash; + # Denote we have it. + $self->{genomeHashFilled} = 1; + } + # Return the hash. + return $self->{genomeHash}; +} + +=head3 _GenomeData + + my $genomeData = $sprout->_GenomeData($genomeID); + +Return an [[ERDBObjectPm]] object for the specified genome, or an undefined +value if the genome does not exist. + +=over 4 + +=item genomeID + +ID of the desired genome. + +=item RETURN + +Returns either an [[ERDBObjectPm]] containing the genome, or an undefined value. +If the genome exists, it will have been read into the genome cache. + +=back + +=cut + +sub _GenomeData { + # Get the parameters. + my ($self, $genomeID) = @_; + # Are we in the genome hash? + if (! exists $self->{genomeHash}->{$genomeID} && ! $self->{genomeHashFilled}) { + # The genome isn't in the hash, and the hash is not complete, so we try to + # read it. + $self->{genomeHash}->{$genomeID} = $self->GetEntity(Genome => $genomeID); + } + # Return the result. + return $self->{genomeHash}->{$genomeID}; +} + +=head3 _CacheGenome + + $sprout->_CacheGenome($genomeID, $genomeData); + +Store the specified genome object in the genome cache if it is already there. + +=over 4 + +=item genomeID + +ID of the genome to store in the cache. + +=item genomeData + +An [[ERDBObjectPm]] containing at least the data for the specified genome. +Note that the Genome may not be the primary object in it, so a fully-qualified +field name has to be used to retrieve data from it. + +=back + +=cut + +sub _CacheGenome { + # Get the parameters. + my ($self, $genomeID, $genomeData) = @_; + # Only proceed if we don't already have the genome. + if (! exists $self->{genomeHash}->{$genomeID}) { + $self->{genomeHash}->{$genomeID} = $genomeData; + } +} + +1; \ No newline at end of file