--- Sprout.pm 2006/01/28 08:59:17 1.53 +++ Sprout.pm 2007/04/27 22:21:46 1.99 @@ -1,18 +1,22 @@ package Sprout; + require Exporter; + use ERDB; + @ISA = qw(Exporter ERDB); use Data::Dumper; use strict; - use Carp; use DBKernel; use XML::Simple; use DBQuery; - use DBObject; - use ERDB; + use ERDBObject; use Tracer; use FIGRules; + use FidCheck; use Stats; use POSIX qw(strftime); - + use BasicLocation; + use CustomAttributes; + use RemoteCustomAttributes; =head1 Sprout Database Manipulation Object @@ -32,6 +36,8 @@ 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(); @@ -62,10 +68,12 @@ * B name of the XML file containing the database definition (default C) -* B user name and password, delimited by a slash (default C) +* B user name and password, delimited by a slash (default same as SEED) * B connection port (default C<0>) +* B connection socket (default same as SEED) + * B maximum number of residues per feature segment, (default C<4500>) * B maximum number of residues per sequence, (default C<8000>) @@ -85,6 +93,9 @@ sub new { # Get the parameters. my ($class, $dbName, $options) = @_; + # Compute the DBD directory. + my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir : + $FIG_Config::fig ); # Compute the options. We do this by starting with a table of defaults and overwriting with # the incoming data. my $optionTable = Tracer::GetOptions({ @@ -92,12 +103,14 @@ # database type dataDir => $FIG_Config::sproutData, # data file directory - xmlFileName => "$FIG_Config::sproutData/SproutDBD.xml", + xmlFileName => "$dbd_dir/SproutDBD.xml", # database definition file name userData => "$FIG_Config::dbuser/$FIG_Config::dbpass", # user name and password port => $FIG_Config::dbport, # database connection port + sock => $FIG_Config::dbsock, + host => $FIG_Config::dbhost, maxSegmentLength => 4500, # maximum feature segment length maxSequenceLength => 8000, # maximum contig sequence length noDBOpen => 0, # 1 to suppress the database open @@ -111,16 +124,27 @@ my $dbh; if (! $optionTable->{noDBOpen}) { $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, - $password, $optionTable->{port}); + $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock}); } # Create the ERDB object. my $xmlFileName = "$optionTable->{xmlFileName}"; - my $erdb = ERDB->new($dbh, $xmlFileName); - # Create this object. - my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName }; - # Bless and return it. - bless $self; - return $self; + my $retVal = ERDB::new($class, $dbh, $xmlFileName); + # 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; + # 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); + } + # Return it. + return $retVal; } =head3 MaxSegment @@ -155,196 +179,6 @@ return $self->{_options}->{maxSequenceLength}; } -=head3 Get - -C<< my $query = $sprout->Get(\@objectNames, $filterClause, \@parameterList); >> - -This method allows a general query against the Sprout data using a specified filter clause. - -The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each -field name represented in the form B(I)>. For example, the -following call requests all B objects for the genus specified in the variable -$genus. - -C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ?", [$genus]); >> - -The WHERE clause contains a single question mark, so there is a single additional -parameter representing the parameter value. It would also be possible to code - -C<< $query = $sprout->Get(['Genome'], "Genome(genus) = \'$genus\'"); >> - -however, this version of the call would generate a syntax error if there were any quote -characters inside the variable C<$genus>. - -The use of the strange parenthesized notation for field names enables us to distinguish -hyphens contained within field names from minus signs that participate in the computation -of the WHERE clause. All of the methods that manipulate fields will use this same notation. - -It is possible to specify multiple entity and relationship names in order to retrieve more than -one object's data at the same time, which allows highly complex joined queries. For example, - -C<< $query = $sprout->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >> - -This query returns all the genomes for a particular genus and allows access to the -sources from which they came. The join clauses to go from Genome to Source are generated -automatically. - -Finally, the filter clause can contain sort information. To do this, simply put an C -clause at the end of the filter. Field references in the ORDER BY section follow the same rules -as they do in the filter itself; in other words, each one must be of the form B(I)>. -For example, the following filter string gets all genomes for a particular genus and sorts -them by species name. - -C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ? ORDER BY Genome(species)", [$genus]); >> - -It is also permissible to specify I an ORDER BY clause. For example, the following invocation gets -all genomes ordered by genus and species. - -C<< $query = $sprout->Get(['Genome'], "ORDER BY Genome(genus), Genome(species)"); >> - -Odd things may happen if one of the ORDER BY fields is in a secondary relation. So, for example, an -attempt to order Bs by alias may (depending on the underlying database engine used) cause -a single feature to appear more than once. - -If multiple names are specified, then the query processor will automatically determine a -join path between the entities and relationships. The algorithm used is very simplistic. -In particular, you can't specify any entity or relationship more than once, and if a -relationship is recursive, the path is determined by the order in which the entity -and the relationship appear. For example, consider a recursive relationship B -which relates B objects to other B objects. If the join path is -coded as C<['People', 'IsParentOf']>, then the people returned will be parents. If, however, -the join path is C<['IsParentOf', 'People']>, then the people returned will be children. - -=over 4 - -=item objectNames - -List containing the names of the entity and relationship objects to be retrieved. - -=item filterClause - -WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can -be parameterized with parameter markers (C). Each field used must be specified in the standard form -B(I)>. Any parameters specified in the filter clause should be added to the -parameter list as additional parameters. The fields in a filter clause can come from primary -entity relations, relationship relations, or secondary entity relations; however, all of the -entities and relationships involved must be included in the list of object names. - -=item parameterList - -List of the parameters to be substituted in for the parameters marks in the filter clause. - -=item RETURN - -Returns a B that can be used to iterate through all of the results. - -=back - -=cut - -sub Get { - # Get the parameters. - my ($self, $objectNames, $filterClause, $parameterList) = @_; - # We differ from the ERDB Get method in that the parameter list is passed in as a list reference - # rather than a list of parameters. The next step is to convert the parameters from a reference - # to a real list. We can only do this if the parameters have been specified. - my @parameters; - if ($parameterList) { @parameters = @{$parameterList}; } - return $self->{_erdb}->Get($objectNames, $filterClause, @parameters); -} - -=head3 GetEntity - -C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >> - -Return an object describing the entity instance with a specified ID. - -=over 4 - -=item entityType - -Entity type name. - -=item ID - -ID of the desired entity. - -=item RETURN - -Returns a B representing the desired entity instance, or an undefined value if no -instance is found with the specified key. - -=back - -=cut - -sub GetEntity { - # Get the parameters. - my ($self, $entityType, $ID) = @_; - # Call the ERDB method. - return $self->{_erdb}->GetEntity($entityType, $ID); -} - -=head3 GetEntityValues - -C<< my @values = GetEntityValues($entityType, $ID, \@fields); >> - -Return a list of values from a specified entity instance. - -=over 4 - -=item entityType - -Entity type name. - -=item ID - -ID of the desired entity. - -=item fields - -List of field names, each of the form IC<(>IC<)>. - -=item RETURN - -Returns a flattened list of the values of the specified fields for the specified entity. - -=back - -=cut -#: Return Type @; -sub GetEntityValues { - # Get the parameters. - my ($self, $entityType, $ID, $fields) = @_; - # Call the ERDB method. - return $self->{_erdb}->GetEntityValues($entityType, $ID, $fields); -} - -=head3 ShowMetaData - -C<< $sprout->ShowMetaData($fileName); >> - -This method outputs a description of the database to an HTML file in the data directory. - -=over 4 - -=item fileName - -Fully-qualified name to give to the output file. - -=back - -=cut - -sub ShowMetaData { - # Get the parameters. - my ($self, $fileName) = @_; - # Compute the file name. - my $options = $self->{_options}; - # Call the show method on the underlying ERDB object. - $self->{_erdb}->ShowMetaData($fileName); -} - =head3 Load C<< $sprout->Load($rebuild); >>; @@ -379,10 +213,8 @@ sub Load { # Get the parameters. my ($self, $rebuild) = @_; - # Get the database object. - my $erdb = $self->{_erdb}; # Load the tables from the data directory. - my $retVal = $erdb->LoadTables($self->{_options}->{dataDir}, $rebuild); + my $retVal = $self->LoadTables($self->{_options}->{dataDir}, $rebuild); # Return the statistics. return $retVal; } @@ -422,8 +254,6 @@ sub LoadUpdate { # Get the parameters. my ($self, $truncateFlag, $tableList) = @_; - # Get the database object. - my $erdb = $self->{_erdb}; # Declare the return value. my $retVal = Stats->new(); # Get the data directory. @@ -437,7 +267,7 @@ Trace("No load file found for $tableName in $dataDir.") if T(0); } else { # Attempt to load this table. - my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag); + my $result = $self->LoadTable($fileName, $tableName, $truncateFlag); # Accumulate the resulting statistics. $retVal->Accumulate($result); } @@ -446,6 +276,161 @@ return $retVal; } +=head3 GenomeCounts + +C<< 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. + +=over 4 + +=item complete + +TRUE if only complete genomes are to be counted, FALSE if all genomes are to be +counted + +=item RETURN + +A six-element list containing the number of genomes in each of six categories-- +Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively. + +=back + +=cut + +sub GenomeCounts { + # Get the parameters. + my ($self, $complete) = @_; + # Set the filter based on the completeness flag. + my $filter = ($complete ? "Genome(complete) = 1" : ""); + # Get all the genomes and the related taxonomy information. + my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']); + # Clear the counters. + my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0); + # Loop through, counting the domains. + for my $genome (@genomes) { + if ($genome->[1] =~ /^archaea/i) { ++$arch } + elsif ($genome->[1] =~ /^bacter/i) { ++$bact } + elsif ($genome->[1] =~ /^eukar/i) { ++$euk } + elsif ($genome->[1] =~ /^vir/i) { ++$vir } + elsif ($genome->[1] =~ /^env/i) { ++$env } + else { ++$unk } + } + # Return the counts. + return ($arch, $bact, $euk, $vir, $env, $unk); +} + +=head3 ContigCount + +C<< my $count = $sprout->ContigCount($genomeID); >> + +Return the number of contigs for the specified genome ID. + +=over 4 + +=item genomeID + +ID of the genome whose contig count is desired. + +=item RETURN + +Returns the number of contigs for the specified genome. + +=back + +=cut + +sub ContigCount { + # Get the parameters. + my ($self, $genomeID) = @_; + # Get the contig count. + my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]); + # Return the result. + return $retVal; +} + +=head3 GeneMenu + +C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected); >> + +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. + +=over 4 + +=item attributes + +Reference to a hash mapping attributes to values for the SELECT tag generated. + +=item filterString + +A filter string for use in selecting the genomes. The filter string must conform +to the rules for the C<< ERDB->Get >> method. + +=item params + +Reference to a list of values to be substituted in for the parameter marks in +the filter string. + +=item selected (optional) + +ID of the genome to be initially selected. + +=item fast (optional) + +If specified and TRUE, the contig counts will be omitted to improve performance. + +=item RETURN + +Returns an HTML select menu with the specified genomes as selectable options. + +=back + +=cut + +sub GeneMenu { + # 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 = "\n"; + # Return the result. + return $retVal; +} + =head3 Build C<< $sprout->Build(); >> @@ -460,7 +445,7 @@ # Get the parameters. my ($self) = @_; # Create the tables. - $self->{_erdb}->CreateTables; + $self->CreateTables(); } =head3 Genomes @@ -680,6 +665,8 @@ return ($contigID, $start, $dir, $len); } + + =head3 PointLocation C<< my $found = Sprout::PointLocation($location, $point); >> @@ -740,12 +727,17 @@ should be of the form returned by L when in a list context. In other words, each location is of the form IC<_>III. +For example, the following would return the DNA sequence for contig C<83333.1:NC_000913> +between positions 1401 and 1532, inclusive. + + my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532'); + =over 4 =item locationList -List of location specifiers, each in the form IC<_>III (see -L for more about this format). +List of location specifiers, each in the form IC<_>III or +IC<_>IC<_>I (see L for more about this format). =item RETURN @@ -841,6 +833,119 @@ return @retVal; } +=head3 GenomeLength + +C<< my $length = $sprout->GenomeLength($genomeID); >> + +Return the length of the specified genome in base pairs. + +=over 4 + +=item genomeID + +ID of the genome whose base pair count is desired. + +=item RETURN + +Returns the number of base pairs in all the contigs of the specified +genome. + +=back + +=cut + +sub GenomeLength { + # Get the parameters. + 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; + # Return the result. + return $retVal; +} + +=head3 FeatureCount + +C<< my $count = $sprout->FeatureCount($genomeID, $type); >> + +Return the number of features of the specified type in the specified genome. + +=over 4 + +=item genomeID + +ID of the genome whose feature count is desired. + +=item type + +Type of feature to count (eg. C, C, etc.). + +=item RETURN + +Returns the number of features of the specified type for the specified genome. + +=back + +=cut + +sub FeatureCount { + # Get the parameters. + my ($self, $genomeID, $type) = @_; + # Compute the count. + my $retVal = $self->GetCount(['HasFeature', 'Feature'], + "HasFeature(from-link) = ? AND Feature(feature-type) = ?", + [$genomeID, $type]); + # Return the result. + return $retVal; +} + +=head3 GenomeAssignments + +C<< 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 +assignment. + +=over 4 + +=item genomeID + +ID of the genome whose functional assignments are desired. + +=item RETURN + +Returns a reference to a hash which maps each feature to its most recent +functional assignment. + +=back + +=cut + +sub GenomeAssignments { + # Get the parameters. + my ($self, $genomeID) = @_; + # Declare the return variable. + my $retVal = {}; + # Query the genome's features. + my $query = $self->Get(['HasFeature', 'Feature'], "HasFeature(from-link) = ?", + [$genomeID]); + # Loop through the features. + while (my $data = $query->Fetch) { + # Get the feature ID and assignment. + my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']); + if ($assignment) { + $retVal->{$fid} = $assignment; + } + } + # Return the result. + return $retVal; +} + =head3 ContigLength C<< my $length = $sprout->ContigLength($contigID); >> @@ -1195,11 +1300,8 @@ Return the most recently-determined functional assignment of a particular feature. The functional assignment is handled differently depending on the type of feature. If -the feature is identified by a FIG ID (begins with the string C), then a functional -assignment is a type of annotation. The format of an assignment is described in -L. 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. +the feature is identified by a FIG ID (begins with the string C), then the functional +assignment is taken from the B or C table, depending. Each user has an associated list of trusted users. The assignment returned will be the most recent one by at least one of the trusted users. If no trusted user list is available, then @@ -1218,8 +1320,8 @@ =item userID (optional) -ID of the user whose function determination is desired. If omitted, only the latest -C assignment will be returned. +ID of the user whose function determination is desired. If omitted, the primary +functional assignment in the B table will be returned. =item RETURN @@ -1236,47 +1338,52 @@ my $retVal; # Determine the ID type. if ($featureID =~ m/^fig\|/) { - # Here we have a FIG feature ID. We must build the list of trusted - # users. - my %trusteeTable = (); - # Check the user ID. + # Here we have a FIG feature ID. if (!$userID) { - # No user ID, so only FIG is trusted. - $trusteeTable{FIG} = 1; + # Use the primary assignment. + ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']); } else { - # Add this user's ID. - $trusteeTable{$userID} = 1; - # Look for the trusted users in the database. - my @trustees = $self->GetFlat(['IsTrustedBy'], 'IsTrustedBy(from-link) = ?', [$userID], 'IsTrustedBy(to-link)'); - if (! @trustees) { - # None were found, so build a default list. + # We must build the list of trusted users. + my %trusteeTable = (); + # Check the user ID. + if (!$userID) { + # No user ID, so only FIG is trusted. $trusteeTable{FIG} = 1; } else { - # Otherwise, put all the trustees in. - for my $trustee (@trustees) { - $trusteeTable{$trustee} = 1; - } - } - } - # 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]); - my $timeSelected = 0; - # Loop until we run out of annotations. - while (my $annotation = $query->Fetch()) { - # Get the annotation text. - my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)', - 'Annotation(time)', 'MadeAnnotation(from-link)']); - # Check to see if this is a functional assignment for a trusted user. - my ($actualUser, $function) = _ParseAssignment($user, $text); - Trace("Assignment user is $actualUser, text is $function.") if T(4); - if ($actualUser) { - # Here it is a functional assignment. Check the time and the user - # name. The time must be recent and the user must be trusted. - if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) { - $retVal = $function; - $timeSelected = $time; + # Add this user's ID. + $trusteeTable{$userID} = 1; + # Look for the trusted users in the database. + my @trustees = $self->GetFlat(['IsTrustedBy'], 'IsTrustedBy(from-link) = ?', [$userID], 'IsTrustedBy(to-link)'); + if (! @trustees) { + # None were found, so build a default list. + $trusteeTable{FIG} = 1; + } else { + # Otherwise, put all the trustees in. + for my $trustee (@trustees) { + $trusteeTable{$trustee} = 1; + } + } + } + # 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]); + my $timeSelected = 0; + # Loop until we run out of annotations. + while (my $annotation = $query->Fetch()) { + # Get the annotation text. + my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)', + 'Annotation(time)', 'MadeAnnotation(from-link)']); + # Check to see if this is a functional assignment for a trusted user. + my ($actualUser, $function) = _ParseAssignment($user, $text); + Trace("Assignment user is $actualUser, text is $function.") if T(4); + if ($actualUser) { + # Here it is a functional assignment. Check the time and the user + # name. The time must be recent and the user must be trusted. + if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) { + $retVal = $function; + $timeSelected = $time; + } } } } @@ -1395,14 +1502,16 @@ my %retVal = (); # Loop through the incoming features. for my $featureID (@{$featureList}) { - # Create a query to get the feature's best hit. - my $query = $self->Get(['IsBidirectionalBestHitOf'], - "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?", - [$featureID, $genomeID]); + # Ask the server for the feature's best hit. + my @bbhData = FIGRules::BBHData($featureID); # Peel off the BBHs found. my @found = (); - while (my $bbh = $query->Fetch) { - push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)'); + for my $bbh (@bbhData) { + my $fid = $bbh->[0]; + my $bbGenome = $self->GenomeOf($fid); + if ($bbGenome eq $genomeID) { + push @found, $fid; + } } $retVal{$featureID} = \@found; } @@ -1416,8 +1525,7 @@ Return a list of the similarities to the specified feature. -Sprout does not support real similarities, so this method just returns the bidirectional -best hits. +This method just returns the bidirectional best hits for performance reasons. =over 4 @@ -1437,10 +1545,7 @@ # Get the parameters. my ($self, $featureID, $count) = @_; # Ask for the best hits. - my @lists = $self->GetAll(['IsBidirectionalBestHitOf'], - "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC", - [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'], - $count); + my @lists = FIGRules::BBHData($featureID); # Create the return value. my %retVal = (); for my $tuple (@lists) { @@ -1450,8 +1555,6 @@ return %retVal; } - - =head3 IsComplete C<< my $flag = $sprout->IsComplete($genomeID); >> @@ -1522,18 +1625,18 @@ C<< my $genomeID = $sprout->GenomeOf($featureID); >> -Return the genome that contains a specified feature. +Return the genome that contains a specified feature or contig. =over 4 =item featureID -ID of the feature whose genome is desired. +ID of the feature or contig whose genome is desired. =item RETURN -Returns the ID of the genome for the specified feature. If the feature is not found, returns -an undefined value. +Returns the ID of the genome for the specified feature or contig. If the feature or contig is not +found, returns an undefined value. =back @@ -1542,8 +1645,9 @@ sub GenomeOf { # Get the parameters. my ($self, $featureID) = @_; - # Create a query to find the genome associated with the feature. - my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]); + # Create a query to find the genome associated with the incoming ID. + my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?", + [$featureID, $featureID]); # Declare the return value. my $retVal; # Get the genome ID. @@ -1578,6 +1682,7 @@ sub CoupledFeatures { # Get the parameters. my ($self, $featureID) = @_; + Trace("Looking for features coupled to $featureID.") if T(coupling => 3); # Create a query to retrieve the functionally-coupled features. my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'], "ParticipatesInCoupling(from-link) = ?", [$featureID]); @@ -1590,10 +1695,12 @@ # Get the ID and score of the coupling. my ($couplingID, $score) = $clustering->Values(['Coupling(id)', 'Coupling(score)']); - # The coupling ID contains the two feature IDs separated by a space. We use - # this information to find the ID of the other feature. - my ($fid1, $fid2) = split / /, $couplingID; - my $otherFeatureID = ($featureID eq $fid1 ? $fid2 : $fid1); + Trace("$featureID coupled with score $score to ID $couplingID.") if T(coupling => 4); + # Get the other feature that participates in the coupling. + my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'], + "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?", + [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)'); + Trace("$couplingID target feature is $otherFeatureID.") if T(coupling => 4); # Attach the other feature's score to its ID. $retVal{$otherFeatureID} = $score; $found = 1; @@ -1726,7 +1833,7 @@ my ($self, $peg1, $peg2) = @_; # Declare the return values. We'll start with the coupling ID and undefine the # flag and score until we have more information. - my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef); + my ($retVal, $inverted, $score) = ($self->CouplingID($peg1, $peg2), undef, undef); # Find the coupling data. my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'], "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)", @@ -1747,9 +1854,112 @@ return ($retVal, $inverted, $score); } +=head3 GetSynonymGroup + +C<< my $id = $sprout->GetSynonymGroup($fid); >> + +Return the synonym group name for the specified feature. + +=over 4 + +=item fid + +ID of the feature whose synonym group is desired. + +=item RETURN + +The name of the synonym group to which the feature belongs. If the feature does +not belong to a synonym group, the feature ID itself is returned. + +=back + +=cut + +sub GetSynonymGroup { + # Get the parameters. + my ($self, $fid) = @_; + # Declare the return variable. + my $retVal; + # Find the synonym group. + my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?", + [$fid], 'IsSynonymGroupFor(from-link)'); + # Check to see if we found anything. + if (@groups) { + $retVal = $groups[0]; + } else { + $retVal = $fid; + } + # Return the result. + return $retVal; +} + +=head3 GetBoundaries + +C<< 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 +order for this method to produce a meaningful result. The resulting +begin/end pair will contain all of the bases in any of the locations. + +=over 4 + +=item locList + +List of locations to process. + +=item RETURN + +Returns a 3-tuple consisting of the contig ID, the beginning boundary, +and the ending boundary. The beginning boundary will be left of the +end for mostly-forward locations and right of the end for mostly-backward +locations. + +=back + +=cut + +sub GetBoundaries { + # Get the parameters. + my ($self, @locList) = @_; + # Set up the counters used to determine the most popular direction. + my %counts = ( '+' => 0, '-' => 0 ); + # Get the last location and parse it. + my $locObject = BasicLocation->new(pop @locList); + # Prime the loop with its data. + my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right); + # Count its direction. + $counts{$locObject->Dir}++; + # Loop through the remaining locations. Note that in most situations, this loop + # will not iterate at all, because most of the time we will be dealing with a + # singleton list. + for my $loc (@locList) { + # Create a location object. + my $locObject = BasicLocation->new($loc); + # Count the direction. + $counts{$locObject->Dir}++; + # Get the left end and the right end. + my $left = $locObject->Left; + my $right = $locObject->Right; + # Merge them into the return variables. + if ($left < $beg) { + $beg = $left; + } + if ($right > $end) { + $end = $right; + } + } + # If the most common direction is reverse, flip the begin and end markers. + if ($counts{'-'} > $counts{'+'}) { + ($beg, $end) = ($end, $beg); + } + # Return the result. + return ($contig, $beg, $end); +} + =head3 CouplingID -C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >> +C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >> Return the coupling ID for a pair of feature IDs. @@ -1782,24 +1992,8 @@ =cut #: Return Type $; sub CouplingID { - return join " ", sort @_; -} - -=head3 GetEntityTypes - -C<< my @entityList = $sprout->GetEntityTypes(); >> - -Return the list of supported entity types. - -=cut -#: Return Type @; -sub GetEntityTypes { - # Get the parameters. - my ($self) = @_; - # Get the underlying database object. - my $erdb = $self->{_erdb}; - # Get its entity type list. - my @retVal = $erdb->GetEntityTypes(); + my ($self, @pegs) = @_; + return $self->DigestKey(join " ", sort @pegs); } =head3 ReadFasta @@ -1947,7 +2141,7 @@ # Get the data directory name. my $outputDirectory = $self->{_options}->{dataDir}; # Dump the relations. - $self->{_erdb}->DumpRelations($outputDirectory); + $self->DumpRelations($outputDirectory); } =head3 XMLFileName @@ -1999,7 +2193,7 @@ # Get the parameters. my ($self, $objectType, $fieldHash) = @_; # Call the underlying method. - $self->{_erdb}->InsertObject($objectType, $fieldHash); + $self->InsertObject($objectType, $fieldHash); } =head3 Annotate @@ -2158,41 +2352,6 @@ return @retVal; } -=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) 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; -} - =head3 FeatureTranslation C<< my $translation = $sprout->FeatureTranslation($featureID); >> @@ -2384,79 +2543,82 @@ Return a list of the properties with the specified characteristics. -Properties are arbitrary key-value pairs associated with a feature. (At some point they -will also be associated with genomes.) A property value is represented by a 4-tuple of -the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter +Properties are the Sprout analog of the FIG attributes. The call is +passed directly to the CustomAttributes or RemoteCustomAttributes object +contained in this object. -=over 4 +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, -=item fid + my @attributeList = $sprout->GetProperties('fig|100226.1.peg.1004', 'structure%', 1, 2); -ID of the feature possessing the property. +would return something like -=item key + ['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] -Name or key of the property. +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, -=item value + my @attributeList = $sprout->GetProperties(['100226.1', 'fig|100226.1.%'], 'PUBMED'); -Value of the property. +would get the PUBMED attribute data for Streptomyces coelicolor A3(2) and all its +features. -=item url +In addition to values in multiple sections, a single attribute key can have multiple +values, so even -URL of the document that indicated the property should have this particular value, or an -empty string if no such document exists. + my @attributeList = $sprout->GetProperties($peg, 'virulent'); -=back +which has no wildcard in the key or the object ID, may return multiple tuples. + +=over 4 -The parameters act as a filter for the desired data. Any non-null parameter will -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. +=item objectID -A single property key can have many values, representing different ideas about the -feature in question. For example, one paper may declare that a feature C is -virulent, and another may declare that it is not virulent. A query about the virulence of -C would be coded as +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. - my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', ''); +=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. -Here the I<$value> and I<$url> fields are left blank, indicating that those fields are -not to be filtered. The tuples returned would be +=item RETURN - ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf') - ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf') +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 -#: Return Type @@; + sub GetProperties { # Get the parameters. my ($self, @parms) = @_; # Declare the return variable. - my @retVal = (); - # 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; - } + my @retVal = $self->{_ca}->GetAttributes(@parms); # Return the result. return @retVal; } @@ -2469,9 +2631,7 @@ that specify special characteristics of the feature. For example, a property could indicate that a feature is essential to the survival of the organism or that it has benign influence on the activities of a pathogen. Each property is returned as a triple of the form -C<($key,$value,$url)>, where C<$key> is the property name, C<$value> is its value (commonly -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. +C<($key,@values)>, where C<$key> is the property name and C<@values> are its values. =over 4 @@ -2481,8 +2641,7 @@ =item RETURN -Returns a list of triples, each triple containing the property name, its value, and a URL or -citation. +Returns a list of tuples, each tuple containing the property name and its values. =back @@ -2492,9 +2651,13 @@ # Get the parameters. my ($self, $featureID) = @_; # Get the properties. - my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID], - ['Property(property-name)', 'Property(property-value)', - 'HasProperty(evidence)']); + my @attributes = $self->{_ca}->GetAttributes($featureID); + # Strip the feature ID off each tuple. + my @retVal = (); + for my $attributeRow (@attributes) { + shift @{$attributeRow}; + push @retVal, $attributeRow; + } # Return the resulting list. return @retVal; } @@ -2527,6 +2690,43 @@ return $retVal; } +=head3 PropertyID + +C<< 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 +Sprout properties, mostly for use in search optimization. + +=over 4 + +=item propName + +Name of the desired property. + +=item propValue + +Value expected for the desired property. + +=item RETURN + +Returns the ID of the name/value pair, or C if the pair does not exist. + +=back + +=cut + +sub PropertyID { + # Get the parameters. + my ($self, $propName, $propValue) = @_; + # Try to find the ID. + my ($retVal) = $self->GetFlat(['Property'], + "Property(property-name) = ? AND Property(property-value) = ?", + [$propName, $propValue], 'Property(id)'); + # Return the result. + return $retVal; +} + =head3 MergedAnnotations C<< my @annotationList = $sprout->MergedAnnotations(\@list); >> @@ -2724,10 +2924,70 @@ # Get the parameters. my ($self, $featureID) = @_; # Get the list of names. - my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?", - [$featureID], 'HasSSCell(from-link)'); + my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?", + [$featureID], 'HasRoleInSubsystem(to-link)'); + # Return the result, sorted. + return sort @retVal; +} + +=head3 GenomeSubsystemData + +C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >> + +Return a hash mapping genome features to their subsystem roles. + +=over 4 + +=item genomeID + +ID of the genome whose subsystem feature map is desired. + +=item RETURN + +Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb +2-tuple contains a subsystem name followed by a role ID. + +=back + +=cut + +sub GenomeSubsystemData { + # Get the parameters. + my ($self, $genomeID) = @_; + # 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. + 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) { + # Insure this feature has an entry in the return hash. + if (! exists $retVal{$fid}) { $retVal{$fid} = []; } + # Merge in this new data. + push @{$retVal{$fid}}, [$subsys, $role]; + } + } # Return the result. - return @retVal; + return %retVal; } =head3 RelatedFeatures @@ -2765,9 +3025,7 @@ # Get the parameters. my ($self, $featureID, $function, $userID) = @_; # Get a list of the features that are BBHs of the incoming feature. - my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'], - "IsBidirectionalBestHitOf(from-link) = ?", [$featureID], - 'IsBidirectionalBestHitOf(to-link)'); + my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID); # Now we loop through the features, pulling out the ones that have the correct # functional assignment. my @retVal = (); @@ -2831,125 +3089,6 @@ return @retVal; } -=head3 GetAll - -C<< my @list = $sprout->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >> - -Return a list of values taken from the objects returned by a query. The first three -parameters correspond to the parameters of the L method. The final parameter is -a list of the fields desired from each record found by the query. The field name -syntax is the standard syntax used for fields in the B system-- -B(I)>-- where I is the name of the relevant entity -or relationship and I is the name of the field. - -The list returned will be a list of lists. Each element of the list will contain -the values returned for the fields specified in the fourth parameter. If one of the -fields specified returns multiple values, they are flattened in with the rest. For -example, the following call will return a list of the features in a particular -spreadsheet cell, and each feature will be represented by a list containing the -feature ID followed by all of its aliases. - -C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >> - -=over 4 - -=item objectNames - -List containing the names of the entity and relationship objects to be retrieved. - -=item filterClause - -WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can -be parameterized with parameter markers (C). Each field used must be specified in the standard form -B(I)>. Any parameters specified in the filter clause should be added to the -parameter list as additional parameters. The fields in a filter clause can come from primary -entity relations, relationship relations, or secondary entity relations; however, all of the -entities and relationships involved must be included in the list of object names. - -=item parameterList - -List of the parameters to be substituted in for the parameters marks in the filter clause. - -=item fields - -List of the fields to be returned in each element of the list returned. - -=item count - -Maximum number of records to return. If omitted or 0, all available records will be returned. - -=item RETURN - -Returns a list of list references. Each element of the return list contains the values for the -fields specified in the B parameter. - -=back - -=cut -#: Return Type @@; -sub GetAll { - # Get the parameters. - my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_; - # Call the ERDB method. - my @retVal = $self->{_erdb}->GetAll($objectNames, $filterClause, $parameterList, - $fields, $count); - # Return the resulting list. - return @retVal; -} - -=head3 GetFlat - -C<< my @list = $sprout->GetFlat(\@objectNames, $filterClause, $parameterList, $field); >> - -This is a variation of L that asks for only a single field per record and -returns a single flattened list. - -=over 4 - -=item objectNames - -List containing the names of the entity and relationship objects to be retrieved. - -=item filterClause - -WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can -be parameterized with parameter markers (C). Each field used must be specified in the standard form -B(I)>. Any parameters specified in the filter clause should be added to the -parameter list as additional parameters. The fields in a filter clause can come from primary -entity relations, relationship relations, or secondary entity relations; however, all of the -entities and relationships involved must be included in the list of object names. - -=item parameterList - -List of the parameters to be substituted in for the parameters marks in the filter clause. - -=item field - -Name of the field to be used to get the elements of the list returned. - -=item RETURN - -Returns a list of values. - -=back - -=cut -#: Return Type @; -sub GetFlat { - # Get the parameters. - my ($self, $objectNames, $filterClause, $parameterList, $field) = @_; - # Construct the query. - my $query = $self->Get($objectNames, $filterClause, $parameterList); - # Create the result list. - my @retVal = (); - # Loop through the records, adding the field values found to the result list. - while (my $row = $query->Fetch()) { - push @retVal, $row->Value($field); - } - # Return the list created. - return @retVal; -} - =head3 Protein C<< my $protein = Sprout::Protein($sequence, $table); >> @@ -3022,8 +3161,9 @@ # Loop through the input triples. my $n = length $sequence; for (my $i = 0; $i < $n; $i += 3) { - # Get the current triple from the sequence. - my $triple = substr($sequence, $i, 3); + # Get the current triple from the sequence. Note we convert to + # upper case to insure a match. + my $triple = uc substr($sequence, $i, 3); # Translate it using the table. my $protein = "X"; if (exists $table->{$triple}) { $protein = $table->{$triple}; } @@ -3051,14 +3191,138 @@ # Create the return list, priming it with the name of the data directory. my @retVal = ($self->{_options}->{dataDir}); # Concatenate the table names. - push @retVal, $self->{_erdb}->GetTableNames(); + push @retVal, $self->GetTableNames(); # Return the result. return @retVal; } +=head3 BBHMatrix + +C<< 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 +features in the original genome to their bidirectional best hits in the +target genomes. + +=over 4 + +=item genomeID + +ID of the genome whose features are to be examined for bidirectional best hits. + +=item cutoff + +A cutoff value. Only hits with a score lower than the cutoff will be returned. + +=item targets + +List of target genomes. Only pairs originating in the original +genome and landing in one of the target genomes will be returned. + +=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. + +=back + +=cut + +sub BBHMatrix { + # Get the parameters. + my ($self, $genomeID, $cutoff, @targets) = @_; + # Declare the return variable. + my %retVal = (); + # Ask for the BBHs. + my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets); + # 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}; + if (! exists $retVal{$peg1}) { + $retVal{$peg1} = { $peg2 => $score }; + } else { + $retVal{$peg1}->{$peg2} = $score; + } + } + # Return the result. + return %retVal; +} + + +=head3 SimMatrix + +C<< 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 +features in the original genome to their similarites in the +target genomes. + +=over 4 + +=item genomeID + +ID of the genome whose features are to be examined for similarities. + +=item cutoff + +A cutoff value. Only hits with a score lower than the cutoff will be returned. + +=item targets + +List of target genomes. Only pairs originating in the original +genome and landing in one of the target genomes will be returned. + +=item RETURN + +Returns a hash mapping each feature in the original genome to a hash mapping its +similar pegs in the target genomes to their scores. + +=back + +=cut + +sub SimMatrix { + # Get the parameters. + my ($self, $genomeID, $cutoff, @targets) = @_; + # Declare the return variable. + my %retVal = (); + # Get the list of features in the source organism. + my @fids = $self->FeaturesOf($genomeID); + # Ask for the sims. We only want similarities to fig features. + my $simList = FIGRules::GetNetworkSims($self, \@fids, {}, 1000, $cutoff, "fig"); + if (! defined $simList) { + Confess("Unable to retrieve similarities from server."); + } else { + Trace("Processing sims.") if T(3); + # We now have a set of sims that we need to convert into a hash of hashes. First, we + # Create a hash for the target genomes. + my %targetHash = map { $_ => 1 } @targets; + for my $simData (@{$simList}) { + # Get the PEGs and the score. + my ($peg1, $peg2, $score) = ($simData->id1, $simData->id2, $simData->psc); + # Insure the second ID is in the target list. + my ($genome2) = FIGRules::ParseFeatureID($peg2); + if (exists $targetHash{$genome2}) { + # Here it is. Now we need to add it to the return hash. How we do that depends + # on whether or not $peg1 is new to us. + if (! exists $retVal{$peg1}) { + $retVal{$peg1} = { $peg2 => $score }; + } else { + $retVal{$peg1}->{$peg2} = $score; + } + } + } + } + # Return the result. + return %retVal; +} + + =head3 LowBBHs -C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >> +C<< 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 @@ -3087,19 +3351,133 @@ my ($self, $featureID, $cutoff) = @_; # Create the return hash. my %retVal = (); - # Create a query to get the desired BBHs. - my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'], - 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?', - [$cutoff, $featureID], - ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']); + # Query for the desired BBHs. + my @bbhList = FIGRules::BBHData($featureID, $cutoff); # Form the results into the return hash. for my $pair (@bbhList) { - $retVal{$pair->[0]} = $pair->[1]; + my $fid = $pair->[0]; + if ($self->Exists('Feature', $fid)) { + $retVal{$fid} = $pair->[1]; + } } # Return the result. return %retVal; } +=head3 Sims + +C<< 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 +returned as B objects. A Sim object is actually a list reference that has been blessed +so that its elements can be accessed by name. + +Similarities can be either raw or expanded. The raw similarities are basic +hits between features with similar DNA. Expanding a raw similarity drags in any +features considered substantially identical. So, for example, if features B, +B, and B are all substantially identical to B, then a raw similarity +B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>. + +=over 4 + +=item fid + +ID of the feature whose similarities are desired. + +=item maxN + +Maximum number of similarities to return. + +=item maxP + +Minumum allowable similarity score. + +=item select + +Selection criterion: C means only raw similarities are returned; C +means only similarities to FIG features are returned; C means all expanded +similarities are returned; and C means similarities are expanded until the +number of FIG features equals the maximum. + +=item max_expand + +The maximum number of features to expand. + +=item filters + +Reference to a hash containing filter information, or a subroutine that can be +used to filter the sims. + +=item RETURN + +Returns a reference to a list of similarity objects, or C if an error +occurred. + +=back + +=cut + +sub Sims { + # Get the parameters. + my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_; + # Create the shim object to test for deleted FIDs. + my $shim = FidCheck->new($self); + # Ask the network for sims. + my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters); + # Return the result. + return $retVal; +} + +=head3 IsAllGenomes + +C<< 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 +compared to a list of all the genomes. + +=over 4 + +=item list + +Reference to the list to be compared to the second list. + +=item checkList (optional) + +Reference to the comparison target list. Every genome ID in this list must occur at +least once in the first list. If this parameter is omitted, a list of all the genomes +is used. + +=item RETURN + +Returns TRUE if every item in the second list appears at least once in the +first list, else FALSE. + +=back + +=cut + +sub IsAllGenomes { + # Get the parameters. + my ($self, $list, $checkList) = @_; + # Supply the checklist if it was omitted. + $checkList = [$self->Genomes()] if ! defined($checkList); + # Create a hash of the original list. + my %testList = map { $_ => 1 } @{$list}; + # Declare the return variable. We assume that the representation + # is complete and stop at the first failure. + my $retVal = 1; + my $n = scalar @{$checkList}; + for (my $i = 0; $retVal && $i < $n; $i++) { + if (! $testList{$checkList->[$i]}) { + $retVal = 0; + } + } + # Return the result. + return $retVal; +} + =head3 GetGroups C<< my %groups = $sprout->GetGroups(\@groupList); >> @@ -3121,7 +3499,7 @@ # Here we have a group list. Loop through them individually, # getting a list of the relevant genomes. for my $group (@{$groupList}) { - my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?", + my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?", [$group], "Genome(id)"); $retVal{$group} = \@genomeIDs; } @@ -3129,9 +3507,9 @@ # Here we need all of the groups. In this case, we run through all # of the genome records, putting each one found into the appropriate # group. Note that we use a filter clause to insure that only genomes - # in groups are included in the return set. - my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [], - ['Genome(id)', 'Genome(group-name)']); + # in real NMPDR groups are included in the return set. + my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?", + [$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. @@ -3249,14 +3627,236 @@ # Get the parameters. my ($self, $genomeID, $testFlag) = @_; # Perform the delete for the genome's features. - my $retVal = $self->{_erdb}->Delete('Feature', "fig|$genomeID.%", $testFlag); + my $retVal = $self->Delete('Feature', "fig|$genomeID.%", testMode => $testFlag); # Perform the delete for the primary genome data. - my $stats = $self->{_erdb}->Delete('Genome', $genomeID, $testFlag); + my $stats = $self->Delete('Genome', $genomeID, testMode => $testFlag); $retVal->Accumulate($stats); # Return the result. return $retVal; } +=head3 Fix + +C<< 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. + +=over 4 + +=item groupHash + +Hash to be fixed up. + +=item RETURN + +Returns a fixed-up version of the hash. + +=back + +=cut + +sub Fix { + # Get the parameters. + my (%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}}); + } + # Return the result hash. + return %retVal; +} + +=head3 GroupPageName + +C<< my $name = $sprout->GroupPageName($group); >> + +Return the name of the page for the specified NMPDR group. + +=over 4 + +=item group + +Name of the relevant group. + +=item RETURN + +Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in +memory it will be read in. + +=back + +=cut + +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; + } + # 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]; + # 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 + +=item species + +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. + +=back + +The parameters to this method are as follows + +=over 4 + +=item groupFile + +Name of the file containing the group data. + +=item RETURN + +Returns a hash keyed on group name. The value of each hash + +=back + +=cut + +sub ReadGroupFile { + # 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; +} + +=head3 AddProperty + +C<< my = $sprout->AddProperty($featureID, $key, @values); >> + +Add a new attribute value (Property) to a feature. + +=over 4 + +=item peg + +ID of the feature to which the attribute is to be added. + +=item key + +Name of the attribute (key). + +=item values + +Values of the attribute. + +=back + +=cut +#: Return Type ; +sub AddProperty { + # Get the parameters. + my ($self, $featureID, $key, @values) = @_; + # Add the property using the attached attributes object. + $self->{_ca}->AddAttribute($featureID, $key, @values); +} + +=head2 Virtual Methods + +=head3 CleanKeywords + +C<< 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, +a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic +characters. In addition, any extra spaces are removed. + +=over 4 + +=item searchExpression + +Search expression or keyword list to clean. Note that a search expression may +contain boolean operators which need to be preserved. This includes leading +minus signs. + +=item RETURN + +Cleaned expression or keyword list. + +=back + +=cut + +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; + # Return the result. + return $retVal; +} + =head2 Internal Utility Methods =head3 ParseAssignment @@ -3313,7 +3913,7 @@ } # If we have an assignment, we need to clean the function text. There may be # extra junk at the end added as a note from the user. - if (@retVal) { + if (defined( $retVal[1] )) { $retVal[1] =~ s/(\t\S)?\s*$//; } # Return the result list. @@ -3346,62 +3946,5 @@ return $retVal; } -=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. A property represents a key/value -pair. If the particular key/value pair coming in is not already in the database, a new -B 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 }); -} - -1; \ No newline at end of file +1;