--- Sprout.pm 2006/06/25 07:34:46 1.74 +++ Sprout.pm 2007/08/20 23:29:24 1.101 @@ -5,17 +5,18 @@ @ISA = qw(Exporter ERDB); use Data::Dumper; use strict; - use Carp; use DBKernel; use XML::Simple; use DBQuery; - use DBObject; + 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 @@ -92,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({ @@ -99,13 +103,14 @@ # database type dataDir => $FIG_Config::sproutData, # data file directory - xmlFileName => "$FIG_Config::fig/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 @@ -119,7 +124,7 @@ my $dbh; if (! $optionTable->{noDBOpen}) { $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, - $password, $optionTable->{port}, undef, $optionTable->{sock}); + $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock}); } # Create the ERDB object. my $xmlFileName = "$optionTable->{xmlFileName}"; @@ -127,6 +132,19 @@ # 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); + } # Return it. return $retVal; } @@ -336,7 +354,7 @@ =head3 GeneMenu -C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params); >> +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 @@ -358,6 +376,14 @@ 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. @@ -368,7 +394,12 @@ sub GeneMenu { # Get the parameters. - my ($self, $attributes, $filterString, $params) = @_; + 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(); >> @@ -538,50 +575,17 @@ =back =cut -#: Return Type @; -#: Return Type $; + sub FeatureLocation { # Get the parameters. my ($self, $featureID) = @_; - # Create a query for the feature locations. - my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)", - [$featureID]); + # 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 = (); - # Set up the variables used to determine if we have adjacent segments. This initial setup will - # not match anything. - my ($prevContig, $prevBeg, $prevDir, $prevLen) = ("", 0, "0", 0); - # Loop through the query results, creating location specifiers. - while (my $location = $query->Fetch()) { - # Get the location parameters. - my ($contigID, $beg, $dir, $len) = $location->Values(['IsLocatedIn(to-link)', - 'IsLocatedIn(beg)', 'IsLocatedIn(dir)', 'IsLocatedIn(len)']); - # Check to see if we are adjacent to the previous segment. - if ($prevContig eq $contigID && $dir eq $prevDir) { - # Here the new segment is in the same direction on the same contig. Insure the - # new segment's beginning is next to the old segment's end. - if ($dir eq "-" && $beg + $len == $prevBeg) { - # Here we're merging two backward blocks, so we keep the new begin point - # and adjust the length. - $len += $prevLen; - # Pop the old segment off. The new one will replace it later. - pop @retVal; - } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) { - # Here we need to merge two forward blocks. Adjust the beginning and - # length values to include both segments. - $beg = $prevBeg; - $len += $prevLen; - # Pop the old segment off. The new one will replace it later. - pop @retVal; - } - } - # Remember this specifier for the adjacent-segment test the next time through. - ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len); - # Compute the initial base pair. - my $start = ($dir eq "+" ? $beg : $beg + $len - 1); - # Add the specifier to the list. - push @retVal, "${contigID}_$start$dir$len"; - } + my @retVal = split /\s*,\s*/, $locString; # Return the list in the format indicated by the context. return (wantarray ? @retVal : join(',', @retVal)); } @@ -607,7 +611,7 @@ =back =cut -#: Return Type @; + sub ParseLocation { # Get the parameter. Note that if we're called as an instance method, we ignore # the first parameter. @@ -630,6 +634,8 @@ return ($contigID, $start, $dir, $len); } + + =head3 PointLocation C<< my $found = Sprout::PointLocation($location, $point); >> @@ -661,7 +667,7 @@ =back =cut -#: Return Type $; + sub PointLocation { # Get the parameter. Note that if we're called as an instance method, we ignore # the first parameter. @@ -894,23 +900,14 @@ my ($self, $genomeID) = @_; # Declare the return variable. my $retVal = {}; - # Query the genome's features and annotations. We'll put the oldest annotations - # first so that the last assignment to go into the hash will be the correct one. - my $query = $self->Get(['HasFeature', 'IsTargetOfAnnotation', 'Annotation'], - "HasFeature(from-link) = ? ORDER BY Annotation(time)", + # Query the genome's features. + my $query = $self->Get(['HasFeature', 'Feature'], "HasFeature(from-link) = ?", [$genomeID]); - # Loop through the annotations. + # Loop through the features. while (my $data = $query->Fetch) { - # Get the feature ID and annotation text. - my ($fid, $annotation) = $data->Values(['HasFeature(to-link)', - 'Annotation(annotation)']); - # Check to see if this is an assignment. Note that the user really - # doesn't matter to us, other than we use it to determine whether or - # not this is an assignment. - my ($user, $assignment) = _ParseAssignment('fig', $annotation); - if ($user) { - # Here it's an assignment. We put it in the return hash, overwriting - # any older assignment that might be present. + # Get the feature ID and assignment. + my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']); + if ($assignment) { $retVal->{$fid} = $assignment; } } @@ -1036,21 +1033,95 @@ =back =cut -#: Return Type @@; + sub GenesInRegion { # Get the parameters. my ($self, $contigID, $start, $stop) = @_; # Get the maximum segment length. my $maximumSegmentLength = $self->MaxSegment; - # Create a hash to receive the feature list. We use a hash so that we can eliminate - # duplicates easily. The hash key will be the feature ID. The value will be a two-element - # containing the minimum and maximum offsets. We will use the offsets to sort the results - # when we're building the result set. - my %featuresFound = (); # Prime the values we'll use for the returned beginning and end. my @initialMinMax = ($self->ContigLength($contigID), 0); my ($min, $max) = @initialMinMax; - # Create a table of parameters for each query. Each query looks for features travelling in + # Get the overlapping features. + my @featureObjects = $self->GeneDataInRegion($contigID, $start, $stop); + # We'l use this hash to help us track the feature IDs and sort them. The key is the + # feature ID and the value is a [$left,$right] pair indicating the maximum extent + # of the feature's locations. + my %featureMap = (); + # Loop through them to do the begin/end analysis. + for my $featureObject (@featureObjects) { + # Get the feature's location string. This may contain multiple actual locations. + my ($locations, $fid) = $featureObject->Values([qw(Feature(location-string) Feature(id))]); + my @locationSegments = split /\s*,\s*/, $locations; + # Loop through the locations. + for my $locationSegment (@locationSegments) { + # Construct an object for the location. + my $locationObject = BasicLocation->new($locationSegment); + # Merge the current segment's begin and end into the min and max. + my ($left, $right) = ($locationObject->Left, $locationObject->Right); + my ($beg, $end); + if (exists $featureMap{$fid}) { + ($beg, $end) = @{$featureMap{$fid}}; + $beg = $left if $left < $beg; + $end = $right if $right > $end; + } else { + ($beg, $end) = ($left, $right); + } + $min = $beg if $beg < $min; + $max = $end if $end > $max; + # Store the feature's new extent back into the hash table. + $featureMap{$fid} = [$beg, $end]; + } + } + # Now we must compute the list of the IDs for the features found. We start with a list + # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint, + # but the result of the sort will be the same.) + my @list = map { [$featureMap{$_}->[0] + $featureMap{$_}->[1], $_] } keys %featureMap; + # Now we sort by midpoint and yank out the feature IDs. + my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list; + # Return it along with the min and max. + return (\@retVal, $min, $max); +} + +=head3 GeneDataInRegion + +C<< my @featureList = $sprout->GenesInRegion($contigID, $start, $stop); >> + +List the features which overlap a specified region in a contig. + +=over 4 + +=item contigID + +ID of the contig containing the region of interest. + +=item start + +Offset of the first residue in the region of interest. + +=item stop + +Offset of the last residue in the region of interest. + +=item RETURN + +Returns a list of B for the desired features. Each object will +contain a B record. + +=back + +=cut + +sub GeneDataInRegion { + # Get the parameters. + my ($self, $contigID, $start, $stop) = @_; + # Get the maximum segment length. + my $maximumSegmentLength = $self->MaxSegment; + # Create a hash to receive the feature list. We use a hash so that we can eliminate + # duplicates easily. The hash key will be the feature ID. The value will be the feature's + # ERDBObject from the query. + my %featuresFound = (); + # Create a table of parameters for the queries. Each query looks for features travelling in # a particular direction. The query parameters include the contig ID, the feature direction, # the lowest possible start position, and the highest possible start position. This works # because each feature segment length must be no greater than the maximum segment length. @@ -1059,62 +1130,28 @@ # Loop through the query parameters. for my $parms (values %queryParms) { # Create the query. - my $query = $self->Get(['IsLocatedIn'], + my $query = $self->Get([qw(Feature IsLocatedIn)], "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?", $parms); # Loop through the feature segments found. while (my $segment = $query->Fetch) { # Get the data about this segment. - my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)', - 'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']); - # Determine if this feature actually overlaps the region. The query insures that + 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 # the results we insure that the inequality from the query holds using the actual # length. - my ($found, $end) = (0, 0); - if ($dir eq '+') { - $end = $beg + $len; - if ($end >= $start) { - # Denote we found a useful feature. - $found = 1; - } - } elsif ($dir eq '-') { - # Note we switch things around so that the beginning is to the left of the - # ending. - ($beg, $end) = ($beg - $len, $beg); - if ($beg <= $stop) { - # Denote we found a useful feature. - $found = 1; - } - } + my $loc = BasicLocation->new($contig, $beg, $dir, $len); + my $found = $loc->Overlap($start, $stop); if ($found) { - # Here we need to record the feature and update the minima and maxima. First, - # get the current entry for the specified feature. - my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} : - @initialMinMax); - # Merge the current segment's begin and end into the feature begin and end and the - # global min and max. - if ($beg < $loc1) { - $loc1 = $beg; - $min = $beg if $beg < $min; - } - if ($end > $loc2) { - $loc2 = $end; - $max = $end if $end > $max; - } - # Store the entry back into the hash table. - $featuresFound{$featureID} = [$loc1, $loc2]; + # Save this feature in the result list. + $featuresFound{$featureID} = $segment; } } } - # Now we must compute the list of the IDs for the features found. We start with a list - # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint, - # but the result of the sort will be the same.) - my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound; - # Now we sort by midpoint and yank out the feature IDs. - my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list; - # Return it along with the min and max. - return (\@retVal, $min, $max); + # Return the ERDB objects for the features found. + return values %featuresFound; } =head3 FType @@ -1272,11 +1309,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 @@ -1295,8 +1329,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 @@ -1313,47 +1347,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; + # 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; + # 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; + } } } } @@ -1472,14 +1511,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; } @@ -1493,8 +1534,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 @@ -1514,10 +1554,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) { @@ -1527,8 +1564,6 @@ return %retVal; } - - =head3 IsComplete C<< my $flag = $sprout->IsComplete($genomeID); >> @@ -1559,7 +1594,7 @@ my $genomeData = $self->GetEntity('Genome', $genomeID); if ($genomeData) { # The genome exists, so get the completeness flag. - ($retVal) = $genomeData->Value('Genome(complete)'); + $retVal = $genomeData->PrimaryValue('Genome(complete)'); } # Return the result. return $retVal; @@ -1590,7 +1625,7 @@ # Get the parameters. my ($self, $featureID) = @_; # Get the desired feature's aliases - my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']); + my @retVal = $self->GetFlat(['IsAliasOf'], "IsAliasOf(to-link) = ?", [$featureID], 'IsAliasOf(from-link)'); # Return the result. return @retVal; } @@ -1619,14 +1654,13 @@ sub GenomeOf { # Get the parameters. my ($self, $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. - if (my $relationship = $query->Fetch()) { - ($retVal) = $relationship->Value('HasContig(from-link)'); + # Parse the genome ID from the feature ID. + if ($featureID =~ /^fig\|(\d+\.\d+)/) { + $retVal = $1; + } else { + Confess("Invalid feature ID $featureID."); } # Return the value found. return $retVal; @@ -1656,29 +1690,23 @@ sub CoupledFeatures { # Get the parameters. my ($self, $featureID) = @_; - # Create a query to retrieve the functionally-coupled features. - my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'], - "ParticipatesInCoupling(from-link) = ?", [$featureID]); - # This value will be set to TRUE if we find at least one coupled feature. - my $found = 0; - # Create the return hash. + # Ask the coupling server for the data. + Trace("Looking for features coupled to $featureID.") if T(coupling => 3); + my @rawPairs = FIGRules::NetCouplingData('coupled_to', id1 => $featureID); + Trace(scalar(@rawPairs) . " couplings returned.") if T(coupling => 3); + # Form them into a hash. my %retVal = (); - # Retrieve the relationship records and store them in the hash. - while (my $clustering = $query->Fetch()) { - # Get the ID and score of the coupling. - my ($couplingID, $score) = $clustering->Values(['Coupling(id)', - 'Coupling(score)']); - # 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)'); - # Attach the other feature's score to its ID. - $retVal{$otherFeatureID} = $score; - $found = 1; + for my $pair (@rawPairs) { + # Get the feature ID and score. + my ($featureID2, $score) = @{$pair}; + # Only proceed if the feature is in NMPDR. + if ($self->_CheckFeature($featureID2)) { + $retVal{$featureID2} = $score; + } } # Functional coupling is reflexive. If we found at least one coupled feature, we must add # the incoming feature as well. - if ($found) { + if (keys %retVal) { $retVal{$featureID} = 9999; } # Return the hash. @@ -1735,96 +1763,18 @@ my ($self, $peg1, $peg2) = @_; # Declare the return variable. my @retVal = (); - # Our first task is to find out the nature of the coupling: whether or not - # it exists, its score, and whether the features are stored in the same - # order as the ones coming in. - my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2); - # Only proceed if a coupling exists. - if ($couplingID) { - # Determine the ordering to place on the evidence items. If we're - # inverted, we want to see feature 2 before feature 1 (descending); otherwise, - # we want feature 1 before feature 2 (normal). - Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4); - my $ordering = ($inverted ? "DESC" : ""); - # Get the coupling evidence. - my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'], - "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering", - [$couplingID], - ['PCH(used)', 'UsesAsEvidence(to-link)']); - # Loop through the evidence items. Each piece of evidence is represented by two - # positions in the evidence list, one for each feature on the other side of the - # evidence link. If at some point we want to generalize to couplings with - # more than two positions, this section of code will need to be re-done. - while (@evidenceList > 0) { - my $peg1Data = shift @evidenceList; - my $peg2Data = shift @evidenceList; - Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4); - push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]]; + # Get the coupling and evidence data. + my @rawData = FIGRules::NetCouplingData('coupling_evidence', id1 => $peg1, id2 => $peg2); + # Loop through the raw data, saving the ones that are in NMPDR genomes. + for my $rawTuple (@rawData) { + if ($self->_CheckFeature($rawTuple->[0]) && $self->_CheckFeature($rawTuple->[1])) { + push @retVal, $rawTuple; } - Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4); } # Return the result. return @retVal; } -=head3 GetCoupling - -C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >> - -Return the coupling (if any) for the specified pair of PEGs. If a coupling -exists, we return the coupling ID along with an indicator of whether the -coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>. -In the second case, we say the coupling is I. The importance of an -inverted coupling is that the PEGs in the evidence will appear in reverse order. - -=over 4 - -=item peg1 - -ID of the feature of interest. - -=item peg2 - -ID of the potentially coupled feature. - -=item RETURN - -Returns a three-element list. The first element contains the database ID of -the coupling. The second element is FALSE if the coupling is stored in the -database in the caller specified order and TRUE if it is stored in the -inverted order. The third element is the coupling's score. If the coupling -does not exist, all three list elements will be C. - -=back - -=cut -#: Return Type $%@; -sub GetCoupling { - # Get the parameters. - 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) = ($self->CouplingID($peg1, $peg2), undef, undef); - # Find the coupling data. - my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'], - "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)", - [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]); - # Check to see if we found anything. - if (!@pegs) { - Trace("No coupling found.") if T(Coupling => 4); - # No coupling, so undefine the return value. - $retVal = undef; - } else { - # We have a coupling! Get the score and check for inversion. - $score = $pegs[0]->[1]; - my $firstFound = $pegs[0]->[0]; - $inverted = ($firstFound ne $peg1); - Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4); - } - # Return the result. - return ($retVal, $inverted, $score); -} - =head3 GetSynonymGroup C<< my $id = $sprout->GetSynonymGroup($fid); >> @@ -1864,43 +1814,68 @@ return $retVal; } -=head3 CouplingID - -C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >> +=head3 GetBoundaries -Return the coupling ID for a pair of feature IDs. +C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >> -The coupling ID is currently computed by joining the feature IDs in -sorted order with a space. Client modules (that is, modules which -use Sprout) should not, however, count on this always being the -case. This method provides a way for abstracting the concept of a -coupling ID. All that we know for sure about it is that it can be -generated easily from the feature IDs and the order of the IDs -in the parameter list does not matter (i.e. C -will have the same value as C. +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 peg1 - -First feature of interest. - -=item peg2 +=item locList -Second feature of interest. +List of locations to process. =item RETURN -Returns the ID that would be used to represent a functional coupling of -the two specified PEGs. +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 -#: Return Type $; -sub CouplingID { - my ($self, @pegs) = @_; - return $self->DigestKey(join " ", sort @pegs); + +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 ReadFasta @@ -2253,7 +2228,7 @@ push @retVal, $mappedAlias; } else { # Here we have a non-FIG alias. Get the features with the normalized alias. - @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)'); + @retVal = $self->GetFlat(['IsAliasOf'], 'IsAliasOf(from-link) = ?', [$mappedAlias], 'IsAliasOf(to-link)'); } # Return the result. return @retVal; @@ -2450,79 +2425,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. -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. +=over 4 + +=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 -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 +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. - ('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') +=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 -#: 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; } @@ -2535,9 +2513,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 @@ -2547,8 +2523,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 @@ -2558,9 +2533,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; } @@ -2593,6 +2572,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); >> @@ -2790,10 +2806,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 @@ -2831,9 +2907,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 = (); @@ -2969,8 +3043,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}; } @@ -3003,6 +3078,130 @@ 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->LowBBHs($featureID, $cutoff); >> @@ -3034,14 +3233,14 @@ 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; @@ -3059,14 +3258,15 @@ 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 substatially identical to B, then a raw similarity +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. +ID of the feature whose similarities are desired, or reference to a list of IDs +of features whose similarities are desired. =item maxN @@ -3112,6 +3312,55 @@ 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); >> @@ -3133,7 +3382,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; } @@ -3141,9 +3390,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. @@ -3261,14 +3510,236 @@ # Get the parameters. my ($self, $genomeID, $testFlag) = @_; # Perform the delete for the genome's features. - my $retVal = $self->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->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 @@ -3325,95 +3796,72 @@ } # 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. return @retVal; } -=head3 FriendlyTimestamp +=head3 _CheckFeature -Convert a time number to a user-friendly time stamp for display. +C<< my $flag = $sprout->_CheckFeature($fid); >> -This is a static method. +Return TRUE if the specified FID is probably an NMPDR feature ID, else FALSE. =over 4 -=item timeValue +=item fid -Numeric time value. +Feature ID to check. =item RETURN -Returns a string containing the same time in user-readable format. +Returns TRUE if the FID is for one of the NMPDR genomes, else FALSE. =back =cut -sub FriendlyTimestamp { - my ($timeValue) = @_; - my $retVal = localtime($timeValue); - return $retVal; +sub _CheckFeature { + # 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; + } + # 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. + return ($self->{genomeHash}->{$genomeID} ? 1 : 0); } -=head3 AddProperty +=head3 FriendlyTimestamp -C<< my = $sprout->AddProperty($featureID, $key, $value, $url); >> +Convert a time number to a user-friendly time stamp for display. -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. +This is a static method. =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 +=item timeValue -Value of the attribute. +Numeric time value. -=item url +=item RETURN -URL or text citation from which the property was obtained. +Returns a string containing the same time in user-readable format. =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 }); + +sub FriendlyTimestamp { + my ($timeValue) = @_; + my $retVal = localtime($timeValue); + return $retVal; } -1; \ No newline at end of file +1;