[Bio] / Sprout / Sprout.pm Repository:
ViewVC logotype

Diff of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.63, Sun Jun 18 07:03:00 2006 UTC revision 1.90, Fri Sep 29 15:10:05 2006 UTC
# Line 12  Line 12 
12      use DBObject;      use DBObject;
13      use Tracer;      use Tracer;
14      use FIGRules;      use FIGRules;
15        use FidCheck;
16      use Stats;      use Stats;
17      use POSIX qw(strftime);      use POSIX qw(strftime);
18        use BasicLocation;
19    
20  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
21    
# Line 91  Line 92 
92  sub new {  sub new {
93      # Get the parameters.      # Get the parameters.
94      my ($class, $dbName, $options) = @_;      my ($class, $dbName, $options) = @_;
95        # Compute the DBD directory.
96        my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
97                                                      $FIG_Config::fig );
98      # Compute the options. We do this by starting with a table of defaults and overwriting with      # Compute the options. We do this by starting with a table of defaults and overwriting with
99      # the incoming data.      # the incoming data.
100      my $optionTable = Tracer::GetOptions({      my $optionTable = Tracer::GetOptions({
# Line 98  Line 102 
102                                                          # database type                                                          # database type
103                         dataDir      => $FIG_Config::sproutData,                         dataDir      => $FIG_Config::sproutData,
104                                                          # data file directory                                                          # data file directory
105                         xmlFileName  => "$FIG_Config::fig/SproutDBD.xml",                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
106                                                          # database definition file name                                                          # database definition file name
107                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
108                                                          # user name and password                                                          # user name and password
109                         port         => $FIG_Config::dbport,                         port         => $FIG_Config::dbport,
110                                                          # database connection port                                                          # database connection port
111                         sock         => $FIG_Config::dbsock,                         sock         => $FIG_Config::dbsock,
112                           host         => $FIG_Config::dbhost,
113                         maxSegmentLength => 4500,        # maximum feature segment length                         maxSegmentLength => 4500,        # maximum feature segment length
114                         maxSequenceLength => 8000,       # maximum contig sequence length                         maxSequenceLength => 8000,       # maximum contig sequence length
115                         noDBOpen     => 0,               # 1 to suppress the database open                         noDBOpen     => 0,               # 1 to suppress the database open
# Line 118  Line 123 
123      my $dbh;      my $dbh;
124      if (! $optionTable->{noDBOpen}) {      if (! $optionTable->{noDBOpen}) {
125          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
126                                  $password, $optionTable->{port}, undef, $optionTable->{sock});                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
127      }      }
128      # Create the ERDB object.      # Create the ERDB object.
129      my $xmlFileName = "$optionTable->{xmlFileName}";      my $xmlFileName = "$optionTable->{xmlFileName}";
# Line 126  Line 131 
131      # Add the option table and XML file name.      # Add the option table and XML file name.
132      $retVal->{_options} = $optionTable;      $retVal->{_options} = $optionTable;
133      $retVal->{_xmlName} = $xmlFileName;      $retVal->{_xmlName} = $xmlFileName;
134        # Set up space for the group file data.
135        $retVal->{groupHash} = undef;
136      # Return it.      # Return it.
137      return $retVal;      return $retVal;
138  }  }
# Line 335  Line 342 
342    
343  =head3 GeneMenu  =head3 GeneMenu
344    
345  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params); >>  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected); >>
346    
347  Return an HTML select menu of genomes. Each genome will be an option in the menu,  Return an HTML select menu of genomes. Each genome will be an option in the menu,
348  and will be displayed by name with the ID and a contig count attached. The selection  and will be displayed by name with the ID and a contig count attached. The selection
# Line 357  Line 364 
364  Reference to a list of values to be substituted in for the parameter marks in  Reference to a list of values to be substituted in for the parameter marks in
365  the filter string.  the filter string.
366    
367    =item selected (optional)
368    
369    ID of the genome to be initially selected.
370    
371    =item fast (optional)
372    
373    If specified and TRUE, the contig counts will be omitted to improve performance.
374    
375  =item RETURN  =item RETURN
376    
377  Returns an HTML select menu with the specified genomes as selectable options.  Returns an HTML select menu with the specified genomes as selectable options.
# Line 367  Line 382 
382    
383  sub GeneMenu {  sub GeneMenu {
384      # Get the parameters.      # Get the parameters.
385      my ($self, $attributes, $filterString, $params) = @_;      my ($self, $attributes, $filterString, $params, $selected, $fast) = @_;
386        my $slowMode = ! $fast;
387        # Default to nothing selected. This prevents an execution warning if "$selected"
388        # is undefined.
389        $selected = "" unless defined $selected;
390        Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3);
391      # Start the menu.      # Start the menu.
392      my $retVal = "<select " .      my $retVal = "<select " .
393          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
# Line 375  Line 395 
395      # Get the genomes.      # Get the genomes.
396      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
397                                                                       'Genome(genus)',                                                                       'Genome(genus)',
398                                                                       'Genome(species)']);                                                                       'Genome(species)',
399                                                                         'Genome(unique-characterization)']);
400      # Sort them by name.      # Sort them by name.
401      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
402      # Loop through the genomes, creating the option tags.      # Loop through the genomes, creating the option tags.
403      for my $genomeData (@sorted) {      for my $genomeData (@sorted) {
404          # Get the data for this genome.          # Get the data for this genome.
405          my ($genomeID, $genus, $species) = @{$genomeData};          my ($genomeID, $genus, $species, $strain) = @{$genomeData};
406          # Get the contig count.          # Get the contig count.
407            my $contigInfo = "";
408            if ($slowMode) {
409          my $count = $self->ContigCount($genomeID);          my $count = $self->ContigCount($genomeID);
410          my $counting = ($count == 1 ? "contig" : "contigs");          my $counting = ($count == 1 ? "contig" : "contigs");
411                $contigInfo = "[$count $counting]";
412            }
413            # Find out if we're selected.
414            my $selectOption = ($selected eq $genomeID ? " selected" : "");
415          # Build the option tag.          # Build the option tag.
416          $retVal .= "<option value=\"$genomeID\">$genus $species ($genomeID) [$count $counting]</option>\n";          $retVal .= "<option value=\"$genomeID\"$selectOption>$genus $species $strain ($genomeID)$contigInfo</option>\n";
417      }      }
418      # Close the SELECT tag.      # Close the SELECT tag.
419      $retVal .= "</select>\n";      $retVal .= "</select>\n";
420      # Return the result.      # Return the result.
421      return $retVal;      return $retVal;
422  }  }
423    
424  =head3 Build  =head3 Build
425    
426  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 627  Line 655 
655      return ($contigID, $start, $dir, $len);      return ($contigID, $start, $dir, $len);
656  }  }
657    
658    
659    
660  =head3 PointLocation  =head3 PointLocation
661    
662  C<< my $found = Sprout::PointLocation($location, $point); >>  C<< my $found = Sprout::PointLocation($location, $point); >>
# Line 836  Line 866 
866    
867  =over 4  =over 4
868    
869  =genomeID  =item genomeID
870    
871  ID of the genome whose feature count is desired.  ID of the genome whose feature count is desired.
872    
# Line 857  Line 887 
887      my ($self, $genomeID, $type) = @_;      my ($self, $genomeID, $type) = @_;
888      # Compute the count.      # Compute the count.
889      my $retVal = $self->GetCount(['HasFeature', 'Feature'],      my $retVal = $self->GetCount(['HasFeature', 'Feature'],
890                                  "HasFeature(from-link) = ? AND Feature(type) = ?",                                  "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
891                                  [$genomeID, $type]);                                  [$genomeID, $type]);
892      # Return the result.      # Return the result.
893      return $retVal;      return $retVal;
# Line 899  Line 929 
929      # Loop through the annotations.      # Loop through the annotations.
930      while (my $data = $query->Fetch) {      while (my $data = $query->Fetch) {
931          # Get the feature ID and annotation text.          # Get the feature ID and annotation text.
932          my ($fid, $annotation) = $data->Values(['HasFeature(from-link)',          my ($fid, $annotation) = $data->Values(['HasFeature(to-link)',
933                                                  'Annotation(text)']);                                                  'Annotation(annotation)']);
934          # Check to see if this is an assignment. Note that the user really          # Check to see if this is an assignment. Note that the user really
935          # doesn't matter to us, other than we use it to determine whether or          # doesn't matter to us, other than we use it to determine whether or
936          # not this is an assignment.          # not this is an assignment.
937          my ($user, $assignment) = $self->_ParseAssignment('fig', $annotation);          my ($user, $assignment) = _ParseAssignment('fig', $annotation);
938          if ($user) {          if ($user) {
939              # Here it's an assignment. We put it in the return hash, overwriting              # Here it's an assignment. We put it in the return hash, overwriting
940              # any older assignment that might be present.              # any older assignment that might be present.
# Line 1469  Line 1499 
1499      my %retVal = ();      my %retVal = ();
1500      # Loop through the incoming features.      # Loop through the incoming features.
1501      for my $featureID (@{$featureList}) {      for my $featureID (@{$featureList}) {
1502          # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1503          my $query = $self->Get(['IsBidirectionalBestHitOf'],          my @bbhData = FIGRules::BBHData($featureID);
                                "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",  
                                [$featureID, $genomeID]);  
1504          # Peel off the BBHs found.          # Peel off the BBHs found.
1505          my @found = ();          my @found = ();
1506          while (my $bbh = $query->Fetch) {          for my $bbh (@bbhData) {
1507              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');              push @found, $bbh->[0];
1508          }          }
1509          $retVal{$featureID} = \@found;          $retVal{$featureID} = \@found;
1510      }      }
# Line 1490  Line 1518 
1518    
1519  Return a list of the similarities to the specified feature.  Return a list of the similarities to the specified feature.
1520    
1521  Sprout does not support real similarities, so this method just returns the bidirectional  This method just returns the bidirectional best hits for performance reasons.
 best hits.  
1522    
1523  =over 4  =over 4
1524    
# Line 1511  Line 1538 
1538      # Get the parameters.      # Get the parameters.
1539      my ($self, $featureID, $count) = @_;      my ($self, $featureID, $count) = @_;
1540      # Ask for the best hits.      # Ask for the best hits.
1541      my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],      my @lists = FIGRules::BBHData($featureID);
                               "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",  
                               [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],  
                               $count);  
1542      # Create the return value.      # Create the return value.
1543      my %retVal = ();      my %retVal = ();
1544      for my $tuple (@lists) {      for my $tuple (@lists) {
# Line 1524  Line 1548 
1548      return %retVal;      return %retVal;
1549  }  }
1550    
   
   
1551  =head3 IsComplete  =head3 IsComplete
1552    
1553  C<< my $flag = $sprout->IsComplete($genomeID); >>  C<< my $flag = $sprout->IsComplete($genomeID); >>
# Line 1653  Line 1675 
1675  sub CoupledFeatures {  sub CoupledFeatures {
1676      # Get the parameters.      # Get the parameters.
1677      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1678        Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1679      # Create a query to retrieve the functionally-coupled features.      # Create a query to retrieve the functionally-coupled features.
1680      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1681                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);
# Line 1665  Line 1688 
1688          # Get the ID and score of the coupling.          # Get the ID and score of the coupling.
1689          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1690                                                          'Coupling(score)']);                                                          'Coupling(score)']);
1691            Trace("$featureID coupled with score $score to ID $couplingID.") if T(coupling => 4);
1692          # Get the other feature that participates in the coupling.          # Get the other feature that participates in the coupling.
1693          my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],          my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],
1694                                             "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",                                             "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",
1695                                             [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');                                             [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');
1696            Trace("$couplingID target feature is $otherFeatureID.") if T(coupling => 4);
1697          # Attach the other feature's score to its ID.          # Attach the other feature's score to its ID.
1698          $retVal{$otherFeatureID} = $score;          $retVal{$otherFeatureID} = $score;
1699          $found = 1;          $found = 1;
# Line 1801  Line 1826 
1826      my ($self, $peg1, $peg2) = @_;      my ($self, $peg1, $peg2) = @_;
1827      # Declare the return values. We'll start with the coupling ID and undefine the      # Declare the return values. We'll start with the coupling ID and undefine the
1828      # flag and score until we have more information.      # flag and score until we have more information.
1829      my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);      my ($retVal, $inverted, $score) = ($self->CouplingID($peg1, $peg2), undef, undef);
1830      # Find the coupling data.      # Find the coupling data.
1831      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1832                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
# Line 1822  Line 1847 
1847      return ($retVal, $inverted, $score);      return ($retVal, $inverted, $score);
1848  }  }
1849    
1850    =head3 GetSynonymGroup
1851    
1852    C<< my $id = $sprout->GetSynonymGroup($fid); >>
1853    
1854    Return the synonym group name for the specified feature.
1855    
1856    =over 4
1857    
1858    =item fid
1859    
1860    ID of the feature whose synonym group is desired.
1861    
1862    =item RETURN
1863    
1864    The name of the synonym group to which the feature belongs. If the feature does
1865    not belong to a synonym group, the feature ID itself is returned.
1866    
1867    =back
1868    
1869    =cut
1870    
1871    sub GetSynonymGroup {
1872        # Get the parameters.
1873        my ($self, $fid) = @_;
1874        # Declare the return variable.
1875        my $retVal;
1876        # Find the synonym group.
1877        my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1878                                       [$fid], 'IsSynonymGroupFor(from-link)');
1879        # Check to see if we found anything.
1880        if (@groups) {
1881            $retVal = $groups[0];
1882        } else {
1883            $retVal = $fid;
1884        }
1885        # Return the result.
1886        return $retVal;
1887    }
1888    
1889    =head3 GetBoundaries
1890    
1891    C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>
1892    
1893    Determine the begin and end boundaries for the locations in a list. All of the
1894    locations must belong to the same contig and have mostly the same direction in
1895    order for this method to produce a meaningful result. The resulting
1896    begin/end pair will contain all of the bases in any of the locations.
1897    
1898    =over 4
1899    
1900    =item locList
1901    
1902    List of locations to process.
1903    
1904    =item RETURN
1905    
1906    Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1907    and the ending boundary. The beginning boundary will be left of the
1908    end for mostly-forward locations and right of the end for mostly-backward
1909    locations.
1910    
1911    =back
1912    
1913    =cut
1914    
1915    sub GetBoundaries {
1916        # Get the parameters.
1917        my ($self, @locList) = @_;
1918        # Set up the counters used to determine the most popular direction.
1919        my %counts = ( '+' => 0, '-' => 0 );
1920        # Get the last location and parse it.
1921        my $locObject = BasicLocation->new(pop @locList);
1922        # Prime the loop with its data.
1923        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
1924        # Count its direction.
1925        $counts{$locObject->Dir}++;
1926        # Loop through the remaining locations. Note that in most situations, this loop
1927        # will not iterate at all, because most of the time we will be dealing with a
1928        # singleton list.
1929        for my $loc (@locList) {
1930            # Create a location object.
1931            my $locObject = BasicLocation->new($loc);
1932            # Count the direction.
1933            $counts{$locObject->Dir}++;
1934            # Get the left end and the right end.
1935            my $left = $locObject->Left;
1936            my $right = $locObject->Right;
1937            # Merge them into the return variables.
1938            if ($left < $beg) {
1939                $beg = $left;
1940            }
1941            if ($right > $end) {
1942                $end = $right;
1943            }
1944        }
1945        # If the most common direction is reverse, flip the begin and end markers.
1946        if ($counts{'-'} > $counts{'+'}) {
1947            ($beg, $end) = ($end, $beg);
1948        }
1949        # Return the result.
1950        return ($contig, $beg, $end);
1951    }
1952    
1953  =head3 CouplingID  =head3 CouplingID
1954    
1955  C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>  C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >>
1956    
1957  Return the coupling ID for a pair of feature IDs.  Return the coupling ID for a pair of feature IDs.
1958    
# Line 1857  Line 1985 
1985  =cut  =cut
1986  #: Return Type $;  #: Return Type $;
1987  sub CouplingID {  sub CouplingID {
1988      return join " ", sort @_;      my ($self, @pegs) = @_;
1989        return $self->DigestKey(join " ", sort @pegs);
1990  }  }
1991    
1992  =head3 ReadFasta  =head3 ReadFasta
# Line 2216  Line 2345 
2345      return @retVal;      return @retVal;
2346  }  }
2347    
 =head3 Exists  
   
 C<< my $found = $sprout->Exists($entityName, $entityID); >>  
   
 Return TRUE if an entity exists, else FALSE.  
   
 =over 4  
   
 =item entityName  
   
 Name of the entity type (e.g. C<Feature>) relevant to the existence check.  
   
 =item entityID  
   
 ID of the entity instance whose existence is to be checked.  
   
 =item RETURN  
   
 Returns TRUE if the entity instance exists, else FALSE.  
   
 =back  
   
 =cut  
 #: Return Type $;  
 sub Exists {  
     # Get the parameters.  
     my ($self, $entityName, $entityID) = @_;  
     # Check for the entity instance.  
     Trace("Checking existence of $entityName with ID=$entityID.") if T(4);  
     my $testInstance = $self->GetEntity($entityName, $entityID);  
     # Return an existence indicator.  
     my $retVal = ($testInstance ? 1 : 0);  
     return $retVal;  
 }  
   
2348  =head3 FeatureTranslation  =head3 FeatureTranslation
2349    
2350  C<< my $translation = $sprout->FeatureTranslation($featureID); >>  C<< my $translation = $sprout->FeatureTranslation($featureID); >>
# Line 2585  Line 2679 
2679      return $retVal;      return $retVal;
2680  }  }
2681    
2682    =head3 PropertyID
2683    
2684    C<< my $id = $sprout->PropertyID($propName, $propValue); >>
2685    
2686    Return the ID of the specified property name and value pair, if the
2687    pair exists.
2688    
2689    =over 4
2690    
2691    =item propName
2692    
2693    Name of the desired property.
2694    
2695    =item propValue
2696    
2697    Value expected for the desired property.
2698    
2699    =item RETURN
2700    
2701    Returns the ID of the name/value pair, or C<undef> if the pair does not exist.
2702    
2703    =back
2704    
2705    =cut
2706    
2707    sub PropertyID {
2708        # Get the parameters.
2709        my ($self, $propName, $propValue) = @_;
2710        # Try to find the ID.
2711        my ($retVal) = $self->GetFlat(['Property'],
2712                                      "Property(property-name) = ? AND Property(property-value) = ?",
2713                                      [$propName, $propValue], 'Property(id)');
2714        # Return the result.
2715        return $retVal;
2716    }
2717    
2718  =head3 MergedAnnotations  =head3 MergedAnnotations
2719    
2720  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>
# Line 2782  Line 2912 
2912      # Get the parameters.      # Get the parameters.
2913      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2914      # Get the list of names.      # Get the list of names.
2915      my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",      my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?",
2916                                  [$featureID], 'HasSSCell(from-link)');                                  [$featureID], 'HasRoleInSubsystem(to-link)');
2917      # Return the result.      # Return the result, sorted.
2918      return @retVal;      return sort @retVal;
2919  }  }
2920    
2921    =head3 GenomeSubsystemData
2922    
2923    C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>
2924    
2925    Return a hash mapping genome features to their subsystem roles.
2926    
2927    =over 4
2928    
2929    =item genomeID
2930    
2931    ID of the genome whose subsystem feature map is desired.
2932    
2933    =item RETURN
2934    
2935    Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb
2936    2-tuple contains a subsystem name followed by a role ID.
2937    
2938    =back
2939    
2940    =cut
2941    
2942    sub GenomeSubsystemData {
2943        # Get the parameters.
2944        my ($self, $genomeID) = @_;
2945        # Declare the return variable.
2946        my %retVal = ();
2947        # Get a list of the genome features that participate in subsystems. For each
2948        # feature we get its spreadsheet cells and the corresponding roles.
2949        my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],
2950                                 "HasFeature(from-link) = ?", [$genomeID],
2951                                 ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);
2952        # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems
2953        # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the
2954        # list. We use it at the beginning to get all the spreadsheet cells for the genome and
2955        # again at the end to filter out participation in subsystems with a negative variant code.
2956        my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],
2957                                     "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?",
2958                                     [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']);
2959        # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features.
2960        # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We
2961        # link these two lists together to create the result. First, we want a hash mapping
2962        # spreadsheet cells to subsystem names.
2963        my %subHash = map { $_->[0] => $_->[1] } @cellData;
2964        # We loop through @cellData to build the hash.
2965        for my $roleEntry (@roleData) {
2966            # Get the data for this feature and cell.
2967            my ($fid, $cellID, $role) = @{$roleEntry};
2968            # Check for a subsystem name.
2969            my $subsys = $subHash{$cellID};
2970            if ($subsys) {
2971                # Insure this feature has an entry in the return hash.
2972                if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
2973                # Merge in this new data.
2974                push @{$retVal{$fid}}, [$subsys, $role];
2975            }
2976        }
2977        # Return the result.
2978        return %retVal;
2979    }
2980    
2981  =head3 RelatedFeatures  =head3 RelatedFeatures
2982    
# Line 2825  Line 3013 
3013      # Get the parameters.      # Get the parameters.
3014      my ($self, $featureID, $function, $userID) = @_;      my ($self, $featureID, $function, $userID) = @_;
3015      # Get a list of the features that are BBHs of the incoming feature.      # Get a list of the features that are BBHs of the incoming feature.
3016      my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
                                      "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],  
                                      'IsBidirectionalBestHitOf(to-link)');  
3017      # Now we loop through the features, pulling out the ones that have the correct      # Now we loop through the features, pulling out the ones that have the correct
3018      # functional assignment.      # functional assignment.
3019      my @retVal = ();      my @retVal = ();
# Line 3028  Line 3214 
3214      my ($self, $featureID, $cutoff) = @_;      my ($self, $featureID, $cutoff) = @_;
3215      # Create the return hash.      # Create the return hash.
3216      my %retVal = ();      my %retVal = ();
3217      # Create a query to get the desired BBHs.      # Query for the desired BBHs.
3218      my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BBHData($featureID, $cutoff);
                                 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',  
                                 [$cutoff, $featureID],  
                                 ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);  
3219      # Form the results into the return hash.      # Form the results into the return hash.
3220      for my $pair (@bbhList) {      for my $pair (@bbhList) {
3221          $retVal{$pair->[0]} = $pair->[1];          $retVal{$pair->[0]} = $pair->[1];
# Line 3041  Line 3224 
3224      return %retVal;      return %retVal;
3225  }  }
3226    
3227    =head3 Sims
3228    
3229    C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>
3230    
3231    Get a list of similarities for a specified feature. Similarity information is not kept in the
3232    Sprout database; rather, they are retrieved from a network server. The similarities are
3233    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3234    so that its elements can be accessed by name.
3235    
3236    Similarities can be either raw or expanded. The raw similarities are basic
3237    hits between features with similar DNA. Expanding a raw similarity drags in any
3238    features considered substantially identical. So, for example, if features B<A1>,
3239    B<A2>, and B<A3> are all substatially identical to B<A>, then a raw similarity
3240    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3241    
3242    =over 4
3243    
3244    =item fid
3245    
3246    ID of the feature whose similarities are desired.
3247    
3248    =item maxN
3249    
3250    Maximum number of similarities to return.
3251    
3252    =item maxP
3253    
3254    Minumum allowable similarity score.
3255    
3256    =item select
3257    
3258    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3259    means only similarities to FIG features are returned; C<all> means all expanded
3260    similarities are returned; and C<figx> means similarities are expanded until the
3261    number of FIG features equals the maximum.
3262    
3263    =item max_expand
3264    
3265    The maximum number of features to expand.
3266    
3267    =item filters
3268    
3269    Reference to a hash containing filter information, or a subroutine that can be
3270    used to filter the sims.
3271    
3272    =item RETURN
3273    
3274    Returns a reference to a list of similarity objects, or C<undef> if an error
3275    occurred.
3276    
3277    =back
3278    
3279    =cut
3280    
3281    sub Sims {
3282        # Get the parameters.
3283        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3284        # Create the shim object to test for deleted FIDs.
3285        my $shim = FidCheck->new($self);
3286        # Ask the network for sims.
3287        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3288        # Return the result.
3289        return $retVal;
3290    }
3291    
3292    =head3 IsAllGenomes
3293    
3294    C<< my $flag = $sprout->IsAllGenomes(\@list, \@checkList); >>
3295    
3296    Return TRUE if all genomes in the second list are represented in the first list at
3297    least one. Otherwise, return FALSE. If the second list is omitted, the first list is
3298    compared to a list of all the genomes.
3299    
3300    =over 4
3301    
3302    =item list
3303    
3304    Reference to the list to be compared to the second list.
3305    
3306    =item checkList (optional)
3307    
3308    Reference to the comparison target list. Every genome ID in this list must occur at
3309    least once in the first list. If this parameter is omitted, a list of all the genomes
3310    is used.
3311    
3312    =item RETURN
3313    
3314    Returns TRUE if every item in the second list appears at least once in the
3315    first list, else FALSE.
3316    
3317    =back
3318    
3319    =cut
3320    
3321    sub IsAllGenomes {
3322        # Get the parameters.
3323        my ($self, $list, $checkList) = @_;
3324        # Supply the checklist if it was omitted.
3325        $checkList = [$self->Genomes()] if ! defined($checkList);
3326        # Create a hash of the original list.
3327        my %testList = map { $_ => 1 } @{$list};
3328        # Declare the return variable. We assume that the representation
3329        # is complete and stop at the first failure.
3330        my $retVal = 1;
3331        my $n = scalar @{$checkList};
3332        for (my $i = 0; $retVal && $i < $n; $i++) {
3333            if (! $testList{$checkList->[$i]}) {
3334                $retVal = 0;
3335            }
3336        }
3337        # Return the result.
3338        return $retVal;
3339    }
3340    
3341  =head3 GetGroups  =head3 GetGroups
3342    
3343  C<< my %groups = $sprout->GetGroups(\@groupList); >>  C<< my %groups = $sprout->GetGroups(\@groupList); >>
# Line 3062  Line 3359 
3359          # Here we have a group list. Loop through them individually,          # Here we have a group list. Loop through them individually,
3360          # getting a list of the relevant genomes.          # getting a list of the relevant genomes.
3361          for my $group (@{$groupList}) {          for my $group (@{$groupList}) {
3362              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3363                  [$group], "Genome(id)");                  [$group], "Genome(id)");
3364              $retVal{$group} = \@genomeIDs;              $retVal{$group} = \@genomeIDs;
3365          }          }
# Line 3070  Line 3367 
3367          # Here we need all of the groups. In this case, we run through all          # Here we need all of the groups. In this case, we run through all
3368          # of the genome records, putting each one found into the appropriate          # of the genome records, putting each one found into the appropriate
3369          # group. Note that we use a filter clause to insure that only genomes          # group. Note that we use a filter clause to insure that only genomes
3370          # in groups are included in the return set.          # in real NMPDR groups are included in the return set.
3371          my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],          my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3372                                      ['Genome(id)', 'Genome(group-name)']);                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3373          # Loop through the genomes found.          # Loop through the genomes found.
3374          for my $genome (@genomes) {          for my $genome (@genomes) {
3375              # Pop this genome's ID off the current list.              # Pop this genome's ID off the current list.
# Line 3198  Line 3495 
3495      return $retVal;      return $retVal;
3496  }  }
3497    
3498  =head2 Internal Utility Methods  =head3 Fix
3499    
3500  =head3 ParseAssignment  C<< my %fixedHash = Sprout::Fix(%groupHash); >>
3501    
3502  Parse annotation text to determine whether or not it is a functional assignment. If it is,  Prepare a genome group hash (like that returned by L</GetGroups> for processing.
3503  the user, function text, and assigning user will be returned as a 3-element list. If it  Groups with the same primary name will be combined. The primary name is the
3504  isn't, an empty list will be returned.  first capitalized word in the group name.
3505    
3506  A functional assignment is always of the form  =over 4
3507    
3508      C<set >I<YYYY>C< function to\n>I<ZZZZZ>  =item groupHash
3509    
3510  where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,  Hash to be fixed up.
 the user and the assigning user (from MadeAnnotation) will be the same, but that is  
 not always the case.  
3511    
3512  In addition, the functional role may contain extra data that is stripped, such as  =item RETURN
 terminating spaces or a comment separated from the rest of the text by a tab.  
3513    
3514  This is a static method.  Returns a fixed-up version of the hash.
3515    
3516  =over 4  =back
3517    
3518  =item user  =cut
3519    
3520  Name of the assigning user.  sub Fix {
3521        # Get the parameters.
3522        my (%groupHash) = @_;
3523        # Create the result hash.
3524        my %retVal = ();
3525        # Copy over the genomes.
3526        for my $groupID (keys %groupHash) {
3527            # Make a safety copy of the group ID.
3528            my $realGroupID = $groupID;
3529            # Yank the primary name.
3530            if ($groupID =~ /([A-Z]\w+)/) {
3531                $realGroupID = $1;
3532            }
3533            # Append this group's genomes into the result hash.
3534            Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}});
3535        }
3536        # Return the result hash.
3537        return %retVal;
3538    }
3539    
3540  =item text  =head3 GroupPageName
3541    
3542  Text of the annotation.  C<< my $name = $sprout->GroupPageName($group); >>
3543    
3544    Return the name of the page for the specified NMPDR group.
3545    
3546    =over 4
3547    
3548    =item group
3549    
3550    Name of the relevant group.
3551    
3552  =item RETURN  =item RETURN
3553    
3554  Returns an empty list if the annotation is not a functional assignment; otherwise, returns  Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3555  a two-element list containing the user name and the function text.  memory it will be read in.
3556    
3557  =back  =back
3558    
3559  =cut  =cut
3560    
3561  sub _ParseAssignment {  sub GroupPageName {
3562      # Get the parameters.      # Get the parameters.
3563      my ($user, $text) = @_;      my ($self, $group) = @_;
3564      # Declare the return value.      # Declare the return variable.
3565      my @retVal = ();      my $retVal;
3566      # Check to see if this is a functional assignment.      # Check for the group file data.
3567      my ($type, $function) = split(/\n/, $text);      if (! defined $self->{groupHash}) {
3568      if ($type =~ m/^set function to$/i) {          # Read the group file.
3569          # Here we have an assignment without a user, so we use the incoming user ID.          my %groupData = Sprout::ReadGroupFile($self->{_options}->{dataDir} . "/groups.tbl");
3570          @retVal = ($user, $function);          # Store it in our object.
3571      } elsif ($type =~ m/^set (\S+) function to$/i) {          $self->{groupHash} = \%groupData;
         # Here we have an assignment with a user that is passed back to the caller.  
         @retVal = ($1, $function);  
3572      }      }
3573      # If we have an assignment, we need to clean the function text. There may be      # Compute the real group name.
3574      # extra junk at the end added as a note from the user.      my $realGroup = $group;
3575      if (@retVal) {      if ($group =~ /([A-Z]\w+)/) {
3576          $retVal[1] =~ s/(\t\S)?\s*$//;          $realGroup = $1;
3577      }      }
3578      # Return the result list.      # Return the page name.
3579      return @retVal;      $retVal = "../content/" . $self->{groupHash}->{$realGroup}->[1];
3580        # Return the result.
3581        return $retVal;
3582  }  }
3583    
3584  =head3 FriendlyTimestamp  =head3 ReadGroupFile
3585    
3586  Convert a time number to a user-friendly time stamp for display.  C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >>
3587    
3588  This is a static method.  Read in the data from the specified group file. The group file contains information
3589    about each of the NMPDR groups.
3590    
3591  =over 4  =over 4
3592    
3593  =item timeValue  =item name
3594    
3595  Numeric time value.  Name of the group.
3596    
3597    =item page
3598    
3599    Name of the group's page on the web site (e.g. C<campy.php> for
3600    Campylobacter)
3601    
3602    =item genus
3603    
3604    Genus of the group
3605    
3606    =item species
3607    
3608    Species of the group, or an empty string if the group is for an entire
3609    genus. If the group contains more than one species, the species names
3610    should be separated by commas.
3611    
3612    =back
3613    
3614    The parameters to this method are as follows
3615    
3616    =over 4
3617    
3618    =item groupFile
3619    
3620    Name of the file containing the group data.
3621    
3622  =item RETURN  =item RETURN
3623    
3624  Returns a string containing the same time in user-readable format.  Returns a hash keyed on group name. The value of each hash
3625    
3626  =back  =back
3627    
3628  =cut  =cut
3629    
3630  sub FriendlyTimestamp {  sub ReadGroupFile {
3631      my ($timeValue) = @_;      # Get the parameters.
3632      my $retVal = localtime($timeValue);      my ($groupFileName) = @_;
3633      return $retVal;      # Declare the return variable.
3634        my %retVal;
3635        # Read the group file.
3636        my @groupLines = Tracer::GetFile($groupFileName);
3637        for my $groupLine (@groupLines) {
3638            my ($name, $page, $genus, $species) = split(/\t/, $groupLine);
3639            $retVal{$name} = [$page, $genus, $species];
3640        }
3641        # Return the result.
3642        return %retVal;
3643  }  }
3644    
3645  =head3 AddProperty  =head3 AddProperty
# Line 3344  Line 3699 
3699      $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });      $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3700  }  }
3701    
3702    =head2 Internal Utility Methods
3703    
3704    =head3 ParseAssignment
3705    
3706    Parse annotation text to determine whether or not it is a functional assignment. If it is,
3707    the user, function text, and assigning user will be returned as a 3-element list. If it
3708    isn't, an empty list will be returned.
3709    
3710    A functional assignment is always of the form
3711    
3712        C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3713    
3714    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3715    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3716    not always the case.
3717    
3718    In addition, the functional role may contain extra data that is stripped, such as
3719    terminating spaces or a comment separated from the rest of the text by a tab.
3720    
3721    This is a static method.
3722    
3723    =over 4
3724    
3725    =item user
3726    
3727    Name of the assigning user.
3728    
3729    =item text
3730    
3731    Text of the annotation.
3732    
3733    =item RETURN
3734    
3735    Returns an empty list if the annotation is not a functional assignment; otherwise, returns
3736    a two-element list containing the user name and the function text.
3737    
3738    =back
3739    
3740    =cut
3741    
3742    sub _ParseAssignment {
3743        # Get the parameters.
3744        my ($user, $text) = @_;
3745        # Declare the return value.
3746        my @retVal = ();
3747        # Check to see if this is a functional assignment.
3748        my ($type, $function) = split(/\n/, $text);
3749        if ($type =~ m/^set function to$/i) {
3750            # Here we have an assignment without a user, so we use the incoming user ID.
3751            @retVal = ($user, $function);
3752        } elsif ($type =~ m/^set (\S+) function to$/i) {
3753            # Here we have an assignment with a user that is passed back to the caller.
3754            @retVal = ($1, $function);
3755        }
3756        # If we have an assignment, we need to clean the function text. There may be
3757        # extra junk at the end added as a note from the user.
3758        if (defined( $retVal[1] )) {
3759            $retVal[1] =~ s/(\t\S)?\s*$//;
3760        }
3761        # Return the result list.
3762        return @retVal;
3763    }
3764    
3765    =head3 FriendlyTimestamp
3766    
3767    Convert a time number to a user-friendly time stamp for display.
3768    
3769    This is a static method.
3770    
3771    =over 4
3772    
3773    =item timeValue
3774    
3775    Numeric time value.
3776    
3777    =item RETURN
3778    
3779    Returns a string containing the same time in user-readable format.
3780    
3781    =back
3782    
3783    =cut
3784    
3785    sub FriendlyTimestamp {
3786        my ($timeValue) = @_;
3787        my $retVal = localtime($timeValue);
3788        return $retVal;
3789    }
3790    
3791    
3792  1;  1;

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3