[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.58, Tue Jun 6 05:07:15 2006 UTC revision 1.100, Mon Jul 16 19:59:50 2007 UTC
# Line 5  Line 5 
5      @ISA = qw(Exporter ERDB);      @ISA = qw(Exporter ERDB);
6      use Data::Dumper;      use Data::Dumper;
7      use strict;      use strict;
     use Carp;  
8      use DBKernel;      use DBKernel;
9      use XML::Simple;      use XML::Simple;
10      use DBQuery;      use DBQuery;
11      use DBObject;      use ERDBObject;
12      use Tracer;      use Tracer;
13      use FIGRules;      use FIGRules;
14        use FidCheck;
15      use Stats;      use Stats;
16      use POSIX qw(strftime);      use POSIX qw(strftime);
17        use BasicLocation;
18        use CustomAttributes;
19        use RemoteCustomAttributes;
20    
21  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
22    
# Line 91  Line 93 
93  sub new {  sub new {
94      # Get the parameters.      # Get the parameters.
95      my ($class, $dbName, $options) = @_;      my ($class, $dbName, $options) = @_;
96        # Compute the DBD directory.
97        my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
98                                                      $FIG_Config::fig );
99      # Compute the options. We do this by starting with a table of defaults and overwriting with      # Compute the options. We do this by starting with a table of defaults and overwriting with
100      # the incoming data.      # the incoming data.
101      my $optionTable = Tracer::GetOptions({      my $optionTable = Tracer::GetOptions({
# Line 98  Line 103 
103                                                          # database type                                                          # database type
104                         dataDir      => $FIG_Config::sproutData,                         dataDir      => $FIG_Config::sproutData,
105                                                          # data file directory                                                          # data file directory
106                         xmlFileName  => "$FIG_Config::fig/SproutDBD.xml",                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
107                                                          # database definition file name                                                          # database definition file name
108                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
109                                                          # user name and password                                                          # user name and password
110                         port         => $FIG_Config::dbport,                         port         => $FIG_Config::dbport,
111                                                          # database connection port                                                          # database connection port
112                         sock         => $FIG_Config::dbsock,                         sock         => $FIG_Config::dbsock,
113                           host         => $FIG_Config::dbhost,
114                         maxSegmentLength => 4500,        # maximum feature segment length                         maxSegmentLength => 4500,        # maximum feature segment length
115                         maxSequenceLength => 8000,       # maximum contig sequence length                         maxSequenceLength => 8000,       # maximum contig sequence length
116                         noDBOpen     => 0,               # 1 to suppress the database open                         noDBOpen     => 0,               # 1 to suppress the database open
# Line 118  Line 124 
124      my $dbh;      my $dbh;
125      if (! $optionTable->{noDBOpen}) {      if (! $optionTable->{noDBOpen}) {
126          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
127                                  $password, $optionTable->{port}, undef, $optionTable->{sock});                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
128      }      }
129      # Create the ERDB object.      # Create the ERDB object.
130      my $xmlFileName = "$optionTable->{xmlFileName}";      my $xmlFileName = "$optionTable->{xmlFileName}";
# Line 126  Line 132 
132      # Add the option table and XML file name.      # Add the option table and XML file name.
133      $retVal->{_options} = $optionTable;      $retVal->{_options} = $optionTable;
134      $retVal->{_xmlName} = $xmlFileName;      $retVal->{_xmlName} = $xmlFileName;
135        # Set up space for the group file data.
136        $retVal->{groupHash} = undef;
137        # Set up space for the genome hash. We use this to identify NMPDR genomes.
138        $retVal->{genomeHash} = undef;
139        # Connect to the attributes.
140        if ($FIG_Config::attrURL) {
141            Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);
142            $retVal->{_ca} = RemoteCustomAttributes->new($FIG_Config::attrURL);
143        } elsif ($FIG_Config::attrDbName) {
144            Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);
145            my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));
146            $retVal->{_ca} = CustomAttributes->new(user => $user);
147        }
148      # Return it.      # Return it.
149      return $retVal;      return $retVal;
150  }  }
# Line 304  Line 323 
323      return ($arch, $bact, $euk, $vir, $env, $unk);      return ($arch, $bact, $euk, $vir, $env, $unk);
324  }  }
325    
326    =head3 ContigCount
327    
328    C<< my $count = $sprout->ContigCount($genomeID); >>
329    
330    Return the number of contigs for the specified genome ID.
331    
332    =over 4
333    
334    =item genomeID
335    
336    ID of the genome whose contig count is desired.
337    
338    =item RETURN
339    
340    Returns the number of contigs for the specified genome.
341    
342    =back
343    
344    =cut
345    
346    sub ContigCount {
347        # Get the parameters.
348        my ($self, $genomeID) = @_;
349        # Get the contig count.
350        my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
351        # Return the result.
352        return $retVal;
353    }
354    
355    =head3 GeneMenu
356    
357    C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected); >>
358    
359    Return an HTML select menu of genomes. Each genome will be an option in the menu,
360    and will be displayed by name with the ID and a contig count attached. The selection
361    value will be the genome ID. The genomes will be sorted by genus/species name.
362    
363    =over 4
364    
365    =item attributes
366    
367    Reference to a hash mapping attributes to values for the SELECT tag generated.
368    
369    =item filterString
370    
371    A filter string for use in selecting the genomes. The filter string must conform
372    to the rules for the C<< ERDB->Get >> method.
373    
374    =item params
375    
376    Reference to a list of values to be substituted in for the parameter marks in
377    the filter string.
378    
379    =item selected (optional)
380    
381    ID of the genome to be initially selected.
382    
383    =item fast (optional)
384    
385    If specified and TRUE, the contig counts will be omitted to improve performance.
386    
387    =item RETURN
388    
389    Returns an HTML select menu with the specified genomes as selectable options.
390    
391    =back
392    
393    =cut
394    
395    sub GeneMenu {
396        # Get the parameters.
397        my ($self, $attributes, $filterString, $params, $selected, $fast) = @_;
398        my $slowMode = ! $fast;
399        # Default to nothing selected. This prevents an execution warning if "$selected"
400        # is undefined.
401        $selected = "" unless defined $selected;
402        Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3);
403        # Start the menu.
404        my $retVal = "<select " .
405            join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
406            ">\n";
407        # Get the genomes.
408        my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
409                                                                         'Genome(genus)',
410                                                                         'Genome(species)',
411                                                                         'Genome(unique-characterization)']);
412        # Sort them by name.
413        my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
414        # Loop through the genomes, creating the option tags.
415        for my $genomeData (@sorted) {
416            # Get the data for this genome.
417            my ($genomeID, $genus, $species, $strain) = @{$genomeData};
418            # Get the contig count.
419            my $contigInfo = "";
420            if ($slowMode) {
421                my $count = $self->ContigCount($genomeID);
422                my $counting = ($count == 1 ? "contig" : "contigs");
423                $contigInfo = "[$count $counting]";
424            }
425            # Find out if we're selected.
426            my $selectOption = ($selected eq $genomeID ? " selected" : "");
427            # Build the option tag.
428            $retVal .= "<option value=\"$genomeID\"$selectOption>$genus $species $strain ($genomeID)$contigInfo</option>\n";
429        }
430        # Close the SELECT tag.
431        $retVal .= "</select>\n";
432        # Return the result.
433        return $retVal;
434    }
435    
436  =head3 Build  =head3 Build
437    
438  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 446  Line 575 
575  =back  =back
576    
577  =cut  =cut
578  #: Return Type @;  
 #: Return Type $;  
579  sub FeatureLocation {  sub FeatureLocation {
580      # Get the parameters.      # Get the parameters.
581      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
582      # Create a query for the feature locations.      # Get the feature record.
583      my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",      my $object = $self->GetEntity('Feature', $featureID);
584                             [$featureID]);      Confess("Feature $featureID not found.") if ! defined($object);
585        # Get the location string.
586        my $locString = $object->PrimaryValue('Feature(location-string)');
587      # Create the return list.      # Create the return list.
588      my @retVal = ();      my @retVal = split /\s*,\s*/, $locString;
     # 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";  
     }  
589      # Return the list in the format indicated by the context.      # Return the list in the format indicated by the context.
590      return (wantarray ? @retVal : join(',', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
591  }  }
# Line 515  Line 611 
611  =back  =back
612    
613  =cut  =cut
614  #: Return Type @;  
615  sub ParseLocation {  sub ParseLocation {
616      # Get the parameter. Note that if we're called as an instance method, we ignore      # Get the parameter. Note that if we're called as an instance method, we ignore
617      # the first parameter.      # the first parameter.
# Line 538  Line 634 
634      return ($contigID, $start, $dir, $len);      return ($contigID, $start, $dir, $len);
635  }  }
636    
637    
638    
639  =head3 PointLocation  =head3 PointLocation
640    
641  C<< my $found = Sprout::PointLocation($location, $point); >>  C<< my $found = Sprout::PointLocation($location, $point); >>
# Line 569  Line 667 
667  =back  =back
668    
669  =cut  =cut
670  #: Return Type $;  
671  sub PointLocation {  sub PointLocation {
672      # Get the parameter. Note that if we're called as an instance method, we ignore      # Get the parameter. Note that if we're called as an instance method, we ignore
673      # the first parameter.      # the first parameter.
# Line 704  Line 802 
802      return @retVal;      return @retVal;
803  }  }
804    
805    =head3 GenomeLength
806    
807    C<< my $length = $sprout->GenomeLength($genomeID); >>
808    
809    Return the length of the specified genome in base pairs.
810    
811    =over 4
812    
813    =item genomeID
814    
815    ID of the genome whose base pair count is desired.
816    
817    =item RETURN
818    
819    Returns the number of base pairs in all the contigs of the specified
820    genome.
821    
822    =back
823    
824    =cut
825    
826    sub GenomeLength {
827        # Get the parameters.
828        my ($self, $genomeID) = @_;
829        # Declare the return variable.
830        my $retVal = 0;
831        # Get the genome's contig sequence lengths.
832        my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
833                           [$genomeID], 'IsMadeUpOf(len)');
834        # Sum the lengths.
835        map { $retVal += $_ } @lens;
836        # Return the result.
837        return $retVal;
838    }
839    
840    =head3 FeatureCount
841    
842    C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
843    
844    Return the number of features of the specified type in the specified genome.
845    
846    =over 4
847    
848    =item genomeID
849    
850    ID of the genome whose feature count is desired.
851    
852    =item type
853    
854    Type of feature to count (eg. C<peg>, C<rna>, etc.).
855    
856    =item RETURN
857    
858    Returns the number of features of the specified type for the specified genome.
859    
860    =back
861    
862    =cut
863    
864    sub FeatureCount {
865        # Get the parameters.
866        my ($self, $genomeID, $type) = @_;
867        # Compute the count.
868        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
869                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
870                                    [$genomeID, $type]);
871        # Return the result.
872        return $retVal;
873    }
874    
875    =head3 GenomeAssignments
876    
877    C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
878    
879    Return a list of a genome's assigned features. The return hash will contain each
880    assigned feature of the genome mapped to the text of its most recent functional
881    assignment.
882    
883    =over 4
884    
885    =item genomeID
886    
887    ID of the genome whose functional assignments are desired.
888    
889    =item RETURN
890    
891    Returns a reference to a hash which maps each feature to its most recent
892    functional assignment.
893    
894    =back
895    
896    =cut
897    
898    sub GenomeAssignments {
899        # Get the parameters.
900        my ($self, $genomeID) = @_;
901        # Declare the return variable.
902        my $retVal = {};
903        # Query the genome's features.
904        my $query = $self->Get(['HasFeature', 'Feature'], "HasFeature(from-link) = ?",
905                               [$genomeID]);
906        # Loop through the features.
907        while (my $data = $query->Fetch) {
908            # Get the feature ID and assignment.
909            my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']);
910            if ($assignment) {
911                $retVal->{$fid} = $assignment;
912            }
913        }
914        # Return the result.
915        return $retVal;
916    }
917    
918  =head3 ContigLength  =head3 ContigLength
919    
920  C<< my $length = $sprout->ContigLength($contigID); >>  C<< my $length = $sprout->ContigLength($contigID); >>
# Line 822  Line 1033 
1033  =back  =back
1034    
1035  =cut  =cut
1036  #: Return Type @@;  
1037  sub GenesInRegion {  sub GenesInRegion {
1038      # Get the parameters.      # Get the parameters.
1039      my ($self, $contigID, $start, $stop) = @_;      my ($self, $contigID, $start, $stop) = @_;
1040      # Get the maximum segment length.      # Get the maximum segment length.
1041      my $maximumSegmentLength = $self->MaxSegment;      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 = ();  
1042      # Prime the values we'll use for the returned beginning and end.      # Prime the values we'll use for the returned beginning and end.
1043      my @initialMinMax = ($self->ContigLength($contigID), 0);      my @initialMinMax = ($self->ContigLength($contigID), 0);
1044      my ($min, $max) = @initialMinMax;      my ($min, $max) = @initialMinMax;
1045      # Create a table of parameters for each query. Each query looks for features travelling in      # Get the overlapping features.
1046        my @featureObjects = $self->GeneDataInRegion($contigID, $start, $stop);
1047        # We'l use this hash to help us track the feature IDs and sort them. The key is the
1048        # feature ID and the value is a [$left,$right] pair indicating the maximum extent
1049        # of the feature's locations.
1050        my %featureMap = ();
1051        # Loop through them to do the begin/end analysis.
1052        for my $featureObject (@featureObjects) {
1053            # Get the feature's location string. This may contain multiple actual locations.
1054            my ($locations, $fid) = $featureObject->Values([qw(Feature(location-string) Feature(id))]);
1055            my @locationSegments = split /\s*,\s*/, $locations;
1056            # Loop through the locations.
1057            for my $locationSegment (@locationSegments) {
1058                # Construct an object for the location.
1059                my $locationObject = BasicLocation->new($locationSegment);
1060                # Merge the current segment's begin and end into the min and max.
1061                my ($left, $right) = ($locationObject->Left, $locationObject->Right);
1062                my ($beg, $end);
1063                if (exists $featureMap{$fid}) {
1064                    ($beg, $end) = @{$featureMap{$fid}};
1065                    $beg = $left if $left < $beg;
1066                    $end = $right if $right > $end;
1067                } else {
1068                    ($beg, $end) = ($left, $right);
1069                }
1070                $min = $beg if $beg < $min;
1071                $max = $end if $end > $max;
1072                # Store the feature's new extent back into the hash table.
1073                $featureMap{$fid} = [$beg, $end];
1074            }
1075        }
1076        # Now we must compute the list of the IDs for the features found. We start with a list
1077        # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1078        # but the result of the sort will be the same.)
1079        my @list = map { [$featureMap{$_}->[0] + $featureMap{$_}->[1], $_] } keys %featureMap;
1080        # Now we sort by midpoint and yank out the feature IDs.
1081        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1082        # Return it along with the min and max.
1083        return (\@retVal, $min, $max);
1084    }
1085    
1086    =head3 GeneDataInRegion
1087    
1088    C<< my @featureList = $sprout->GenesInRegion($contigID, $start, $stop); >>
1089    
1090    List the features which overlap a specified region in a contig.
1091    
1092    =over 4
1093    
1094    =item contigID
1095    
1096    ID of the contig containing the region of interest.
1097    
1098    =item start
1099    
1100    Offset of the first residue in the region of interest.
1101    
1102    =item stop
1103    
1104    Offset of the last residue in the region of interest.
1105    
1106    =item RETURN
1107    
1108    Returns a list of B<ERDBObjects> for the desired features. Each object will
1109    contain a B<Feature> record.
1110    
1111    =back
1112    
1113    =cut
1114    
1115    sub GeneDataInRegion {
1116        # Get the parameters.
1117        my ($self, $contigID, $start, $stop) = @_;
1118        # Get the maximum segment length.
1119        my $maximumSegmentLength = $self->MaxSegment;
1120        # Create a hash to receive the feature list. We use a hash so that we can eliminate
1121        # duplicates easily. The hash key will be the feature ID. The value will be the feature's
1122        # ERDBObject from the query.
1123        my %featuresFound = ();
1124        # Create a table of parameters for the queries. Each query looks for features travelling in
1125      # a particular direction. The query parameters include the contig ID, the feature direction,      # a particular direction. The query parameters include the contig ID, the feature direction,
1126      # the lowest possible start position, and the highest possible start position. This works      # the lowest possible start position, and the highest possible start position. This works
1127      # because each feature segment length must be no greater than the maximum segment length.      # because each feature segment length must be no greater than the maximum segment length.
# Line 845  Line 1130 
1130      # Loop through the query parameters.      # Loop through the query parameters.
1131      for my $parms (values %queryParms) {      for my $parms (values %queryParms) {
1132          # Create the query.          # Create the query.
1133          my $query = $self->Get(['IsLocatedIn'],          my $query = $self->Get([qw(Feature IsLocatedIn)],
1134              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
1135              $parms);              $parms);
1136          # Loop through the feature segments found.          # Loop through the feature segments found.
1137          while (my $segment = $query->Fetch) {          while (my $segment = $query->Fetch) {
1138              # Get the data about this segment.              # Get the data about this segment.
1139              my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',              my ($featureID, $contig, $dir, $beg, $len) = $segment->Values([qw(IsLocatedIn(from-link)
1140                  'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);                  IsLocatedIn(to-link) IsLocatedIn(dir) IsLocatedIn(beg) IsLocatedIn(len))]);
1141              # Determine if this feature actually overlaps the region. The query insures that              # Determine if this feature segment actually overlaps the region. The query insures that
1142              # this will be the case if the segment is the maximum length, so to fine-tune              # this will be the case if the segment is the maximum length, so to fine-tune
1143              # the results we insure that the inequality from the query holds using the actual              # the results we insure that the inequality from the query holds using the actual
1144              # length.              # length.
1145              my ($found, $end) = (0, 0);              my $loc = BasicLocation->new($contig, $beg, $dir, $len);
1146              if ($dir eq '+') {              my $found = $loc->Overlap($start, $stop);
                 $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;  
                 }  
             }  
1147              if ($found) {              if ($found) {
1148                  # Here we need to record the feature and update the minima and maxima. First,                  # Save this feature in the result list.
1149                  # get the current entry for the specified feature.                  $featuresFound{$featureID} = $segment;
                 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];  
1150              }              }
1151          }          }
1152      }      }
1153      # Now we must compute the list of the IDs for the features found. We start with a list      # Return the ERDB objects for the features found.
1154      # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,      return values %featuresFound;
     # 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);  
1155  }  }
1156    
1157  =head3 FType  =head3 FType
# Line 1058  Line 1309 
1309  Return the most recently-determined functional assignment of a particular feature.  Return the most recently-determined functional assignment of a particular feature.
1310    
1311  The functional assignment is handled differently depending on the type of feature. If  The functional assignment is handled differently depending on the type of feature. If
1312  the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional  the feature is identified by a FIG ID (begins with the string C<fig|>), then the functional
1313  assignment is a type of annotation. The format of an assignment is described in  assignment is taken from the B<Feature> or C<Annotation> table, depending.
 L</ParseAssignment>. Its worth noting that we cannot filter on the content of the  
 annotation itself because it's a text field; however, this is not a big problem because  
 most features only have a small number of annotations.  
1314    
1315  Each user has an associated list of trusted users. The assignment returned will be the most  Each user has an associated list of trusted users. The assignment returned will be the most
1316  recent one by at least one of the trusted users. If no trusted user list is available, then  recent one by at least one of the trusted users. If no trusted user list is available, then
# Line 1081  Line 1329 
1329    
1330  =item userID (optional)  =item userID (optional)
1331    
1332  ID of the user whose function determination is desired. If omitted, only the latest  ID of the user whose function determination is desired. If omitted, the primary
1333  C<FIG> assignment will be returned.  functional assignment in the B<Feature> table will be returned.
1334    
1335  =item RETURN  =item RETURN
1336    
# Line 1099  Line 1347 
1347      my $retVal;      my $retVal;
1348      # Determine the ID type.      # Determine the ID type.
1349      if ($featureID =~ m/^fig\|/) {      if ($featureID =~ m/^fig\|/) {
1350          # Here we have a FIG feature ID. We must build the list of trusted          # Here we have a FIG feature ID.
1351          # users.          if (!$userID) {
1352                # Use the primary assignment.
1353                ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']);
1354            } else {
1355                # We must build the list of trusted users.
1356          my %trusteeTable = ();          my %trusteeTable = ();
1357          # Check the user ID.          # Check the user ID.
1358          if (!$userID) {          if (!$userID) {
# Line 1143  Line 1395 
1395                  }                  }
1396              }              }
1397          }          }
1398            }
1399      } else {      } else {
1400          # Here we have a non-FIG feature ID. In this case the user ID does not          # Here we have a non-FIG feature ID. In this case the user ID does not
1401          # matter. We simply get the information from the External Alias Function          # matter. We simply get the information from the External Alias Function
# Line 1258  Line 1511 
1511      my %retVal = ();      my %retVal = ();
1512      # Loop through the incoming features.      # Loop through the incoming features.
1513      for my $featureID (@{$featureList}) {      for my $featureID (@{$featureList}) {
1514          # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1515          my $query = $self->Get(['IsBidirectionalBestHitOf'],          my @bbhData = FIGRules::BBHData($featureID);
                                "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",  
                                [$featureID, $genomeID]);  
1516          # Peel off the BBHs found.          # Peel off the BBHs found.
1517          my @found = ();          my @found = ();
1518          while (my $bbh = $query->Fetch) {          for my $bbh (@bbhData) {
1519              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');              my $fid = $bbh->[0];
1520                my $bbGenome = $self->GenomeOf($fid);
1521                if ($bbGenome eq $genomeID) {
1522                    push @found, $fid;
1523                }
1524          }          }
1525          $retVal{$featureID} = \@found;          $retVal{$featureID} = \@found;
1526      }      }
# Line 1279  Line 1534 
1534    
1535  Return a list of the similarities to the specified feature.  Return a list of the similarities to the specified feature.
1536    
1537  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.  
1538    
1539  =over 4  =over 4
1540    
# Line 1300  Line 1554 
1554      # Get the parameters.      # Get the parameters.
1555      my ($self, $featureID, $count) = @_;      my ($self, $featureID, $count) = @_;
1556      # Ask for the best hits.      # Ask for the best hits.
1557      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);  
1558      # Create the return value.      # Create the return value.
1559      my %retVal = ();      my %retVal = ();
1560      for my $tuple (@lists) {      for my $tuple (@lists) {
# Line 1313  Line 1564 
1564      return %retVal;      return %retVal;
1565  }  }
1566    
   
   
1567  =head3 IsComplete  =head3 IsComplete
1568    
1569  C<< my $flag = $sprout->IsComplete($genomeID); >>  C<< my $flag = $sprout->IsComplete($genomeID); >>
# Line 1345  Line 1594 
1594      my $genomeData = $self->GetEntity('Genome', $genomeID);      my $genomeData = $self->GetEntity('Genome', $genomeID);
1595      if ($genomeData) {      if ($genomeData) {
1596          # The genome exists, so get the completeness flag.          # The genome exists, so get the completeness flag.
1597          ($retVal) = $genomeData->Value('Genome(complete)');          $retVal = $genomeData->PrimaryValue('Genome(complete)');
1598      }      }
1599      # Return the result.      # Return the result.
1600      return $retVal;      return $retVal;
# Line 1376  Line 1625 
1625      # Get the parameters.      # Get the parameters.
1626      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1627      # Get the desired feature's aliases      # Get the desired feature's aliases
1628      my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);      my @retVal = $self->GetFlat(['IsAliasOf'], "IsAliasOf(to-link) = ?", [$featureID], 'IsAliasOf(from-link)');
1629      # Return the result.      # Return the result.
1630      return @retVal;      return @retVal;
1631  }  }
# Line 1405  Line 1654 
1654  sub GenomeOf {  sub GenomeOf {
1655      # Get the parameters.      # Get the parameters.
1656      my ($self, $featureID) = @_;      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]);  
1657      # Declare the return value.      # Declare the return value.
1658      my $retVal;      my $retVal;
1659      # Get the genome ID.      # Parse the genome ID from the feature ID.
1660      if (my $relationship = $query->Fetch()) {      if ($featureID =~ /^fig\|(\d+\.\d+)/) {
1661          ($retVal) = $relationship->Value('HasContig(from-link)');          $retVal = $1;
1662        } else {
1663            Confess("Invalid feature ID $featureID.");
1664      }      }
1665      # Return the value found.      # Return the value found.
1666      return $retVal;      return $retVal;
# Line 1442  Line 1690 
1690  sub CoupledFeatures {  sub CoupledFeatures {
1691      # Get the parameters.      # Get the parameters.
1692      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1693      # Create a query to retrieve the functionally-coupled features.      # Ask the coupling server for the data.
1694      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1695                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);      my @rawPairs = FIGRules::NetCouplingData('coupled_to', id1 => $featureID);
1696      # This value will be set to TRUE if we find at least one coupled feature.      Trace(scalar(@rawPairs) . " couplings returned.") if T(coupling => 3);
1697      my $found = 0;      # Form them into a hash.
     # Create the return hash.  
1698      my %retVal = ();      my %retVal = ();
1699      # Retrieve the relationship records and store them in the hash.      for my $pair (@rawPairs) {
1700      while (my $clustering = $query->Fetch()) {          # Get the feature ID and score.
1701          # Get the ID and score of the coupling.          my ($featureID2, $score) = @{$pair};
1702          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          # Only proceed if the feature is in NMPDR.
1703                                                          'Coupling(score)']);          if ($self->_CheckFeature($featureID2)) {
1704          # The coupling ID contains the two feature IDs separated by a space. We use              $retVal{$featureID2} = $score;
1705          # this information to find the ID of the other feature.          }
         my ($fid1, $fid2) = split / /, $couplingID;  
         my $otherFeatureID = ($featureID eq $fid1 ? $fid2 : $fid1);  
         # Attach the other feature's score to its ID.  
         $retVal{$otherFeatureID} = $score;  
         $found = 1;  
1706      }      }
1707      # Functional coupling is reflexive. If we found at least one coupled feature, we must add      # Functional coupling is reflexive. If we found at least one coupled feature, we must add
1708      # the incoming feature as well.      # the incoming feature as well.
1709      if ($found) {      if (keys %retVal) {
1710          $retVal{$featureID} = 9999;          $retVal{$featureID} = 9999;
1711      }      }
1712      # Return the hash.      # Return the hash.
# Line 1521  Line 1763 
1763      my ($self, $peg1, $peg2) = @_;      my ($self, $peg1, $peg2) = @_;
1764      # Declare the return variable.      # Declare the return variable.
1765      my @retVal = ();      my @retVal = ();
1766      # Our first task is to find out the nature of the coupling: whether or not      # Get the coupling and evidence data.
1767      # it exists, its score, and whether the features are stored in the same      my @rawData = FIGRules::NetCouplingData('coupling_evidence', id1 => $peg1, id2 => $peg2);
1768      # order as the ones coming in.      # Loop through the raw data, saving the ones that are in NMPDR genomes.
1769      my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);      for my $rawTuple (@rawData) {
1770      # Only proceed if a coupling exists.          if ($self->_CheckFeature($rawTuple->[0]) && $self->_CheckFeature($rawTuple->[1])) {
1771      if ($couplingID) {              push @retVal, $rawTuple;
         # 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]];  
1772          }          }
         Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);  
1773      }      }
1774      # Return the result.      # Return the result.
1775      return @retVal;      return @retVal;
1776  }  }
1777    
1778  =head3 GetCoupling  =head3 GetSynonymGroup
1779    
1780  C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>  C<< my $id = $sprout->GetSynonymGroup($fid); >>
1781    
1782  Return the coupling (if any) for the specified pair of PEGs. If a coupling  Return the synonym group name for the specified feature.
 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<inverted>. The importance of an  
 inverted coupling is that the PEGs in the evidence will appear in reverse order.  
1783    
1784  =over 4  =over 4
1785    
1786  =item peg1  =item fid
   
 ID of the feature of interest.  
   
 =item peg2  
1787    
1788  ID of the potentially coupled feature.  ID of the feature whose synonym group is desired.
1789    
1790  =item RETURN  =item RETURN
1791    
1792  Returns a three-element list. The first element contains the database ID of  The name of the synonym group to which the feature belongs. If the feature does
1793  the coupling. The second element is FALSE if the coupling is stored in the  not belong to a synonym group, the feature ID itself is returned.
 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<undef>.  
1794    
1795  =back  =back
1796    
1797  =cut  =cut
1798  #: Return Type $%@;  
1799  sub GetCoupling {  sub GetSynonymGroup {
1800      # Get the parameters.      # Get the parameters.
1801      my ($self, $peg1, $peg2) = @_;      my ($self, $fid) = @_;
1802      # Declare the return values. We'll start with the coupling ID and undefine the      # Declare the return variable.
1803      # flag and score until we have more information.      my $retVal;
1804      my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);      # Find the synonym group.
1805      # Find the coupling data.      my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1806      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],                                     [$fid], 'IsSynonymGroupFor(from-link)');
                                  "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",  
                                  [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);  
1807      # Check to see if we found anything.      # Check to see if we found anything.
1808      if (!@pegs) {      if (@groups) {
1809          Trace("No coupling found.") if T(Coupling => 4);          $retVal = $groups[0];
         # No coupling, so undefine the return value.  
         $retVal = undef;  
1810      } else {      } else {
1811          # We have a coupling! Get the score and check for inversion.          $retVal = $fid;
         $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);  
1812      }      }
1813      # Return the result.      # Return the result.
1814      return ($retVal, $inverted, $score);      return $retVal;
1815  }  }
1816    
1817  =head3 CouplingID  =head3 GetBoundaries
   
 C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>  
1818    
1819  Return the coupling ID for a pair of feature IDs.  C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>
1820    
1821  The coupling ID is currently computed by joining the feature IDs in  Determine the begin and end boundaries for the locations in a list. All of the
1822  sorted order with a space. Client modules (that is, modules which  locations must belong to the same contig and have mostly the same direction in
1823  use Sprout) should not, however, count on this always being the  order for this method to produce a meaningful result. The resulting
1824  case. This method provides a way for abstracting the concept of a  begin/end pair will contain all of the bases in any of the locations.
 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<CouplingID("a1", "b1")>  
 will have the same value as C<CouplingID("b1", "a1")>.  
1825    
1826  =over 4  =over 4
1827    
1828  =item peg1  =item locList
   
 First feature of interest.  
   
 =item peg2  
1829    
1830  Second feature of interest.  List of locations to process.
1831    
1832  =item RETURN  =item RETURN
1833    
1834  Returns the ID that would be used to represent a functional coupling of  Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1835  the two specified PEGs.  and the ending boundary. The beginning boundary will be left of the
1836    end for mostly-forward locations and right of the end for mostly-backward
1837    locations.
1838    
1839  =back  =back
1840    
1841  =cut  =cut
1842  #: Return Type $;  
1843  sub CouplingID {  sub GetBoundaries {
1844      return join " ", sort @_;      # Get the parameters.
1845        my ($self, @locList) = @_;
1846        # Set up the counters used to determine the most popular direction.
1847        my %counts = ( '+' => 0, '-' => 0 );
1848        # Get the last location and parse it.
1849        my $locObject = BasicLocation->new(pop @locList);
1850        # Prime the loop with its data.
1851        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
1852        # Count its direction.
1853        $counts{$locObject->Dir}++;
1854        # Loop through the remaining locations. Note that in most situations, this loop
1855        # will not iterate at all, because most of the time we will be dealing with a
1856        # singleton list.
1857        for my $loc (@locList) {
1858            # Create a location object.
1859            my $locObject = BasicLocation->new($loc);
1860            # Count the direction.
1861            $counts{$locObject->Dir}++;
1862            # Get the left end and the right end.
1863            my $left = $locObject->Left;
1864            my $right = $locObject->Right;
1865            # Merge them into the return variables.
1866            if ($left < $beg) {
1867                $beg = $left;
1868            }
1869            if ($right > $end) {
1870                $end = $right;
1871            }
1872        }
1873        # If the most common direction is reverse, flip the begin and end markers.
1874        if ($counts{'-'} > $counts{'+'}) {
1875            ($beg, $end) = ($end, $beg);
1876        }
1877        # Return the result.
1878        return ($contig, $beg, $end);
1879  }  }
1880    
1881  =head3 ReadFasta  =head3 ReadFasta
# Line 1999  Line 2228 
2228          push @retVal, $mappedAlias;          push @retVal, $mappedAlias;
2229      } else {      } else {
2230          # Here we have a non-FIG alias. Get the features with the normalized alias.          # Here we have a non-FIG alias. Get the features with the normalized alias.
2231          @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');          @retVal = $self->GetFlat(['IsAliasOf'], 'IsAliasOf(from-link) = ?', [$mappedAlias], 'IsAliasOf(to-link)');
2232      }      }
2233      # Return the result.      # Return the result.
2234      return @retVal;      return @retVal;
2235  }  }
2236    
2237  =head3 Exists  =head3 FeatureTranslation
2238    
2239  C<< my $found = $sprout->Exists($entityName, $entityID); >>  C<< my $translation = $sprout->FeatureTranslation($featureID); >>
2240    
2241  Return TRUE if an entity exists, else FALSE.  Return the translation of a feature.
2242    
2243  =over 4  =over 4
2244    
2245  =item entityName  =item featureID
   
 Name of the entity type (e.g. C<Feature>) relevant to the existence check.  
   
 =item entityID  
2246    
2247  ID of the entity instance whose existence is to be checked.  ID of the feature whose translation is desired
2248    
2249  =item RETURN  =item RETURN
2250    
2251  Returns TRUE if the entity instance exists, else FALSE.  Returns the translation of the specified feature.
2252    
2253  =back  =back
2254    
2255  =cut  =cut
2256  #: Return Type $;  #: Return Type $;
2257  sub Exists {  sub FeatureTranslation {
2258      # Get the parameters.      # Get the parameters.
2259      my ($self, $entityName, $entityID) = @_;      my ($self, $featureID) = @_;
2260      # Check for the entity instance.      # Get the specified feature's translation.
2261      Trace("Checking existence of $entityName with ID=$entityID.") if T(4);      my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
     my $testInstance = $self->GetEntity($entityName, $entityID);  
     # Return an existence indicator.  
     my $retVal = ($testInstance ? 1 : 0);  
2262      return $retVal;      return $retVal;
2263  }  }
2264    
2265  =head3 FeatureTranslation  =head3 Taxonomy
2266    
2267  C<< my $translation = $sprout->FeatureTranslation($featureID); >>  C<< my @taxonomyList = $sprout->Taxonomy($genome); >>
   
 Return the translation of a feature.  
   
 =over 4  
   
 =item featureID  
   
 ID of the feature whose translation is desired  
   
 =item RETURN  
   
 Returns the translation of the specified feature.  
   
 =back  
   
 =cut  
 #: Return Type $;  
 sub FeatureTranslation {  
     # Get the parameters.  
     my ($self, $featureID) = @_;  
     # Get the specified feature's translation.  
     my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);  
     return $retVal;  
 }  
   
 =head3 Taxonomy  
   
 C<< my @taxonomyList = $sprout->Taxonomy($genome); >>  
2268    
2269  Return the taxonomy of the specified genome. This will be in the form of a list  Return the taxonomy of the specified genome. This will be in the form of a list
2270  containing the various classifications in order from domain (eg. C<Bacteria>, C<Archaea>,  containing the various classifications in order from domain (eg. C<Bacteria>, C<Archaea>,
# Line 2231  Line 2425 
2425    
2426  Return a list of the properties with the specified characteristics.  Return a list of the properties with the specified characteristics.
2427    
2428  Properties are arbitrary key-value pairs associated with a feature. (At some point they  Properties are the Sprout analog of the FIG attributes. The call is
2429  will also be associated with genomes.) A property value is represented by a 4-tuple of  passed directly to the CustomAttributes or RemoteCustomAttributes object
2430  the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter  contained in this object.
2431    
2432  =over 4  This method returns a series of tuples that match the specified criteria. Each tuple
2433    will contain an object ID, a key, and one or more values. The parameters to this
2434    method therefore correspond structurally to the values expected in each tuple. In
2435    addition, you can ask for a generic search by suffixing a percent sign (C<%>) to any
2436    of the parameters. So, for example,
2437    
2438  =item fid      my @attributeList = $sprout->GetProperties('fig|100226.1.peg.1004', 'structure%', 1, 2);
2439    
2440  ID of the feature possessing the property.  would return something like
2441    
2442  =item key      ['fig}100226.1.peg.1004', 'structure', 1, 2]
2443        ['fig}100226.1.peg.1004', 'structure1', 1, 2]
2444        ['fig}100226.1.peg.1004', 'structure2', 1, 2]
2445        ['fig}100226.1.peg.1004', 'structureA', 1, 2]
2446    
2447  Name or key of the property.  Use of C<undef> in any position acts as a wild card (all values). You can also specify
2448    a list reference in the ID column. Thus,
2449    
2450  =item value      my @attributeList = $sprout->GetProperties(['100226.1', 'fig|100226.1.%'], 'PUBMED');
2451    
2452  Value of the property.  would get the PUBMED attribute data for Streptomyces coelicolor A3(2) and all its
2453    features.
2454    
2455  =item url  In addition to values in multiple sections, a single attribute key can have multiple
2456    values, so even
2457    
2458  URL of the document that indicated the property should have this particular value, or an      my @attributeList = $sprout->GetProperties($peg, 'virulent');
 empty string if no such document exists.  
2459    
2460  =back  which has no wildcard in the key or the object ID, may return multiple tuples.
2461    
2462    =over 4
2463    
2464  The parameters act as a filter for the desired data. Any non-null parameter will  =item objectID
 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.  
2465    
2466  A single property key can have many values, representing different ideas about the  ID of object whose attributes are desired. If the attributes are desired for multiple
2467  feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is  objects, this parameter can be specified as a list reference. If the attributes are
2468  virulent, and another may declare that it is not virulent. A query about the virulence of  desired for all objects, specify C<undef> or an empty string. Finally, you can specify
2469  C<fig|83333.1.peg.10> would be coded as  attributes for a range of object IDs by putting a percent sign (C<%>) at the end.
2470    
2471      my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');  =item key
2472    
2473  Here the I<$value> and I<$url> fields are left blank, indicating that those fields are  Attribute key name. A value of C<undef> or an empty string will match all
2474  not to be filtered. The tuples returned would be  attribute keys. If the values are desired for multiple keys, this parameter can be
2475    specified as a list reference. Finally, you can specify attributes for a range of
2476    keys by putting a percent sign (C<%>) at the end.
2477    
2478    =item values
2479    
2480    List of the desired attribute values, section by section. If C<undef>
2481    or an empty string is specified, all values in that section will match. A
2482    generic match can be requested by placing a percent sign (C<%>) at the end.
2483    In that case, all values that match up to and not including the percent sign
2484    will match. You may also specify a regular expression enclosed
2485    in slashes. All values that match the regular expression will be returned. For
2486    performance reasons, only values have this extra capability.
2487    
2488      ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')  =item RETURN
2489      ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')  
2490    Returns a list of tuples. The first element in the tuple is an object ID, the
2491    second is an attribute key, and the remaining elements are the sections of
2492    the attribute value. All of the tuples will match the criteria set forth in
2493    the parameter list.
2494    
2495    =back
2496    
2497  =cut  =cut
2498  #: Return Type @@;  
2499  sub GetProperties {  sub GetProperties {
2500      # Get the parameters.      # Get the parameters.
2501      my ($self, @parms) = @_;      my ($self, @parms) = @_;
2502      # Declare the return variable.      # Declare the return variable.
2503      my @retVal = ();      my @retVal = $self->{_ca}->GetAttributes(@parms);
     # Now we need to create a WHERE clause that will get us the data we want. First,  
     # we create a list of the columns containing the data for each parameter.  
     my @colNames = ('HasProperty(from-link)', 'Property(property-name)',  
                     'Property(property-value)', 'HasProperty(evidence)');  
     # Now we build the WHERE clause and the list of parameter values.  
     my @where = ();  
     my @values = ();  
     for (my $i = 0; $i <= $#colNames; $i++) {  
         my $parm = $parms[$i];  
         if (defined $parm && ($parm ne '')) {  
             push @where, "$colNames[$i] = ?";  
             push @values, $parm;  
         }  
     }  
     # Format the WHERE clause.  
     my $filter = (@values > 0 ? (join " AND ", @where) : undef);  
     # Ask for all the propertie values with the desired characteristics.  
     my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);  
     while (my $valueObject = $query->Fetch()) {  
         my @tuple = $valueObject->Values(\@colNames);  
         push @retVal, \@tuple;  
     }  
2504      # Return the result.      # Return the result.
2505      return @retVal;      return @retVal;
2506  }  }
# Line 2316  Line 2513 
2513  that specify special characteristics of the feature. For example, a property could indicate  that specify special characteristics of the feature. For example, a property could indicate
2514  that a feature is essential to the survival of the organism or that it has benign influence  that a feature is essential to the survival of the organism or that it has benign influence
2515  on the activities of a pathogen. Each property is returned as a triple of the form  on the activities of a pathogen. Each property is returned as a triple of the form
2516  C<($key,$value,$url)>, where C<$key> is the property name, C<$value> is its value (commonly  C<($key,@values)>, where C<$key> is the property name and  C<@values> are its values.
 a 1 or a 0, but possibly a string or a floating-point value), and C<$url> is a string describing  
 the web address or citation in which the property's value for the feature was identified.  
2517    
2518  =over 4  =over 4
2519    
# Line 2328  Line 2523 
2523    
2524  =item RETURN  =item RETURN
2525    
2526  Returns a list of triples, each triple containing the property name, its value, and a URL or  Returns a list of tuples, each tuple containing the property name and its values.
 citation.  
2527    
2528  =back  =back
2529    
# Line 2339  Line 2533 
2533      # Get the parameters.      # Get the parameters.
2534      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2535      # Get the properties.      # Get the properties.
2536      my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],      my @attributes = $self->{_ca}->GetAttributes($featureID);
2537                              ['Property(property-name)', 'Property(property-value)',      # Strip the feature ID off each tuple.
2538                               'HasProperty(evidence)']);      my @retVal = ();
2539        for my $attributeRow (@attributes) {
2540            shift @{$attributeRow};
2541            push @retVal, $attributeRow;
2542        }
2543      # Return the resulting list.      # Return the resulting list.
2544      return @retVal;      return @retVal;
2545  }  }
# Line 2374  Line 2572 
2572      return $retVal;      return $retVal;
2573  }  }
2574    
2575    =head3 PropertyID
2576    
2577    C<< my $id = $sprout->PropertyID($propName, $propValue); >>
2578    
2579    Return the ID of the specified property name and value pair, if the
2580    pair exists. Only a small subset of the FIG attributes are stored as
2581    Sprout properties, mostly for use in search optimization.
2582    
2583    =over 4
2584    
2585    =item propName
2586    
2587    Name of the desired property.
2588    
2589    =item propValue
2590    
2591    Value expected for the desired property.
2592    
2593    =item RETURN
2594    
2595    Returns the ID of the name/value pair, or C<undef> if the pair does not exist.
2596    
2597    =back
2598    
2599    =cut
2600    
2601    sub PropertyID {
2602        # Get the parameters.
2603        my ($self, $propName, $propValue) = @_;
2604        # Try to find the ID.
2605        my ($retVal) = $self->GetFlat(['Property'],
2606                                      "Property(property-name) = ? AND Property(property-value) = ?",
2607                                      [$propName, $propValue], 'Property(id)');
2608        # Return the result.
2609        return $retVal;
2610    }
2611    
2612  =head3 MergedAnnotations  =head3 MergedAnnotations
2613    
2614  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>
# Line 2571  Line 2806 
2806      # Get the parameters.      # Get the parameters.
2807      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2808      # Get the list of names.      # Get the list of names.
2809      my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",      my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?",
2810                                  [$featureID], 'HasSSCell(from-link)');                                  [$featureID], 'HasRoleInSubsystem(to-link)');
2811      # Return the result.      # Return the result, sorted.
2812      return @retVal;      return sort @retVal;
2813  }  }
2814    
2815    =head3 GenomeSubsystemData
2816    
2817    C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>
2818    
2819    Return a hash mapping genome features to their subsystem roles.
2820    
2821    =over 4
2822    
2823    =item genomeID
2824    
2825    ID of the genome whose subsystem feature map is desired.
2826    
2827    =item RETURN
2828    
2829    Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb
2830    2-tuple contains a subsystem name followed by a role ID.
2831    
2832    =back
2833    
2834    =cut
2835    
2836    sub GenomeSubsystemData {
2837        # Get the parameters.
2838        my ($self, $genomeID) = @_;
2839        # Declare the return variable.
2840        my %retVal = ();
2841        # Get a list of the genome features that participate in subsystems. For each
2842        # feature we get its spreadsheet cells and the corresponding roles.
2843        my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],
2844                                 "HasFeature(from-link) = ?", [$genomeID],
2845                                 ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);
2846        # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems
2847        # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the
2848        # list. We use it at the beginning to get all the spreadsheet cells for the genome and
2849        # again at the end to filter out participation in subsystems with a negative variant code.
2850        my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],
2851                                     "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?",
2852                                     [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']);
2853        # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features.
2854        # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We
2855        # link these two lists together to create the result. First, we want a hash mapping
2856        # spreadsheet cells to subsystem names.
2857        my %subHash = map { $_->[0] => $_->[1] } @cellData;
2858        # We loop through @cellData to build the hash.
2859        for my $roleEntry (@roleData) {
2860            # Get the data for this feature and cell.
2861            my ($fid, $cellID, $role) = @{$roleEntry};
2862            # Check for a subsystem name.
2863            my $subsys = $subHash{$cellID};
2864            if ($subsys) {
2865                # Insure this feature has an entry in the return hash.
2866                if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
2867                # Merge in this new data.
2868                push @{$retVal{$fid}}, [$subsys, $role];
2869            }
2870        }
2871        # Return the result.
2872        return %retVal;
2873    }
2874    
2875  =head3 RelatedFeatures  =head3 RelatedFeatures
2876    
# Line 2614  Line 2907 
2907      # Get the parameters.      # Get the parameters.
2908      my ($self, $featureID, $function, $userID) = @_;      my ($self, $featureID, $function, $userID) = @_;
2909      # 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.
2910      my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
                                      "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],  
                                      'IsBidirectionalBestHitOf(to-link)');  
2911      # 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
2912      # functional assignment.      # functional assignment.
2913      my @retVal = ();      my @retVal = ();
# Line 2752  Line 3043 
3043      # Loop through the input triples.      # Loop through the input triples.
3044      my $n = length $sequence;      my $n = length $sequence;
3045      for (my $i = 0; $i < $n; $i += 3) {      for (my $i = 0; $i < $n; $i += 3) {
3046          # Get the current triple from the sequence.          # Get the current triple from the sequence. Note we convert to
3047          my $triple = substr($sequence, $i, 3);          # upper case to insure a match.
3048            my $triple = uc substr($sequence, $i, 3);
3049          # Translate it using the table.          # Translate it using the table.
3050          my $protein = "X";          my $protein = "X";
3051          if (exists $table->{$triple}) { $protein = $table->{$triple}; }          if (exists $table->{$triple}) { $protein = $table->{$triple}; }
# Line 2786  Line 3078 
3078      return @retVal;      return @retVal;
3079  }  }
3080    
3081    =head3 BBHMatrix
3082    
3083    C<< my %bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets); >>
3084    
3085    Find all the bidirectional best hits for the features of a genome in a
3086    specified list of target genomes. The return value will be a hash mapping
3087    features in the original genome to their bidirectional best hits in the
3088    target genomes.
3089    
3090    =over 4
3091    
3092    =item genomeID
3093    
3094    ID of the genome whose features are to be examined for bidirectional best hits.
3095    
3096    =item cutoff
3097    
3098    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3099    
3100    =item targets
3101    
3102    List of target genomes. Only pairs originating in the original
3103    genome and landing in one of the target genomes will be returned.
3104    
3105    =item RETURN
3106    
3107    Returns a hash mapping each feature in the original genome to a hash mapping its
3108    BBH pegs in the target genomes to their scores.
3109    
3110    =back
3111    
3112    =cut
3113    
3114    sub BBHMatrix {
3115        # Get the parameters.
3116        my ($self, $genomeID, $cutoff, @targets) = @_;
3117        # Declare the return variable.
3118        my %retVal = ();
3119        # Ask for the BBHs.
3120        my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets);
3121        # We now have a set of 4-tuples that we need to convert into a hash of hashes.
3122        for my $bbhData (@bbhList) {
3123            my ($peg1, $peg2, $score) = @{$bbhData};
3124            if (! exists $retVal{$peg1}) {
3125                $retVal{$peg1} = { $peg2 => $score };
3126            } else {
3127                $retVal{$peg1}->{$peg2} = $score;
3128            }
3129        }
3130        # Return the result.
3131        return %retVal;
3132    }
3133    
3134    
3135    =head3 SimMatrix
3136    
3137    C<< my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets); >>
3138    
3139    Find all the similarities for the features of a genome in a
3140    specified list of target genomes. The return value will be a hash mapping
3141    features in the original genome to their similarites in the
3142    target genomes.
3143    
3144    =over 4
3145    
3146    =item genomeID
3147    
3148    ID of the genome whose features are to be examined for similarities.
3149    
3150    =item cutoff
3151    
3152    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3153    
3154    =item targets
3155    
3156    List of target genomes. Only pairs originating in the original
3157    genome and landing in one of the target genomes will be returned.
3158    
3159    =item RETURN
3160    
3161    Returns a hash mapping each feature in the original genome to a hash mapping its
3162    similar pegs in the target genomes to their scores.
3163    
3164    =back
3165    
3166    =cut
3167    
3168    sub SimMatrix {
3169        # Get the parameters.
3170        my ($self, $genomeID, $cutoff, @targets) = @_;
3171        # Declare the return variable.
3172        my %retVal = ();
3173        # Get the list of features in the source organism.
3174        my @fids = $self->FeaturesOf($genomeID);
3175        # Ask for the sims. We only want similarities to fig features.
3176        my $simList = FIGRules::GetNetworkSims($self, \@fids, {}, 1000, $cutoff, "fig");
3177        if (! defined $simList) {
3178            Confess("Unable to retrieve similarities from server.");
3179        } else {
3180            Trace("Processing sims.") if T(3);
3181            # We now have a set of sims that we need to convert into a hash of hashes. First, we
3182            # Create a hash for the target genomes.
3183            my %targetHash = map { $_ => 1 } @targets;
3184            for my $simData (@{$simList}) {
3185                # Get the PEGs and the score.
3186                my ($peg1, $peg2, $score) = ($simData->id1, $simData->id2, $simData->psc);
3187                # Insure the second ID is in the target list.
3188                my ($genome2) = FIGRules::ParseFeatureID($peg2);
3189                if (exists $targetHash{$genome2}) {
3190                    # Here it is. Now we need to add it to the return hash. How we do that depends
3191                    # on whether or not $peg1 is new to us.
3192                    if (! exists $retVal{$peg1}) {
3193                        $retVal{$peg1} = { $peg2 => $score };
3194                    } else {
3195                        $retVal{$peg1}->{$peg2} = $score;
3196                    }
3197                }
3198            }
3199        }
3200        # Return the result.
3201        return %retVal;
3202    }
3203    
3204    
3205  =head3 LowBBHs  =head3 LowBBHs
3206    
3207  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
# Line 2817  Line 3233 
3233      my ($self, $featureID, $cutoff) = @_;      my ($self, $featureID, $cutoff) = @_;
3234      # Create the return hash.      # Create the return hash.
3235      my %retVal = ();      my %retVal = ();
3236      # Create a query to get the desired BBHs.      # Query for the desired BBHs.
3237      my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BBHData($featureID, $cutoff);
                                 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',  
                                 [$cutoff, $featureID],  
                                 ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);  
3238      # Form the results into the return hash.      # Form the results into the return hash.
3239      for my $pair (@bbhList) {      for my $pair (@bbhList) {
3240          $retVal{$pair->[0]} = $pair->[1];          my $fid = $pair->[0];
3241            if ($self->Exists('Feature', $fid)) {
3242                $retVal{$fid} = $pair->[1];
3243            }
3244      }      }
3245      # Return the result.      # Return the result.
3246      return %retVal;      return %retVal;
3247  }  }
3248    
3249    =head3 Sims
3250    
3251    C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>
3252    
3253    Get a list of similarities for a specified feature. Similarity information is not kept in the
3254    Sprout database; rather, they are retrieved from a network server. The similarities are
3255    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3256    so that its elements can be accessed by name.
3257    
3258    Similarities can be either raw or expanded. The raw similarities are basic
3259    hits between features with similar DNA. Expanding a raw similarity drags in any
3260    features considered substantially identical. So, for example, if features B<A1>,
3261    B<A2>, and B<A3> are all substantially identical to B<A>, then a raw similarity
3262    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3263    
3264    =over 4
3265    
3266    =item fid
3267    
3268    ID of the feature whose similarities are desired, or reference to a list of IDs
3269    of features whose similarities are desired.
3270    
3271    =item maxN
3272    
3273    Maximum number of similarities to return.
3274    
3275    =item maxP
3276    
3277    Minumum allowable similarity score.
3278    
3279    =item select
3280    
3281    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3282    means only similarities to FIG features are returned; C<all> means all expanded
3283    similarities are returned; and C<figx> means similarities are expanded until the
3284    number of FIG features equals the maximum.
3285    
3286    =item max_expand
3287    
3288    The maximum number of features to expand.
3289    
3290    =item filters
3291    
3292    Reference to a hash containing filter information, or a subroutine that can be
3293    used to filter the sims.
3294    
3295    =item RETURN
3296    
3297    Returns a reference to a list of similarity objects, or C<undef> if an error
3298    occurred.
3299    
3300    =back
3301    
3302    =cut
3303    
3304    sub Sims {
3305        # Get the parameters.
3306        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3307        # Create the shim object to test for deleted FIDs.
3308        my $shim = FidCheck->new($self);
3309        # Ask the network for sims.
3310        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3311        # Return the result.
3312        return $retVal;
3313    }
3314    
3315    =head3 IsAllGenomes
3316    
3317    C<< my $flag = $sprout->IsAllGenomes(\@list, \@checkList); >>
3318    
3319    Return TRUE if all genomes in the second list are represented in the first list at
3320    least one. Otherwise, return FALSE. If the second list is omitted, the first list is
3321    compared to a list of all the genomes.
3322    
3323    =over 4
3324    
3325    =item list
3326    
3327    Reference to the list to be compared to the second list.
3328    
3329    =item checkList (optional)
3330    
3331    Reference to the comparison target list. Every genome ID in this list must occur at
3332    least once in the first list. If this parameter is omitted, a list of all the genomes
3333    is used.
3334    
3335    =item RETURN
3336    
3337    Returns TRUE if every item in the second list appears at least once in the
3338    first list, else FALSE.
3339    
3340    =back
3341    
3342    =cut
3343    
3344    sub IsAllGenomes {
3345        # Get the parameters.
3346        my ($self, $list, $checkList) = @_;
3347        # Supply the checklist if it was omitted.
3348        $checkList = [$self->Genomes()] if ! defined($checkList);
3349        # Create a hash of the original list.
3350        my %testList = map { $_ => 1 } @{$list};
3351        # Declare the return variable. We assume that the representation
3352        # is complete and stop at the first failure.
3353        my $retVal = 1;
3354        my $n = scalar @{$checkList};
3355        for (my $i = 0; $retVal && $i < $n; $i++) {
3356            if (! $testList{$checkList->[$i]}) {
3357                $retVal = 0;
3358            }
3359        }
3360        # Return the result.
3361        return $retVal;
3362    }
3363    
3364  =head3 GetGroups  =head3 GetGroups
3365    
3366  C<< my %groups = $sprout->GetGroups(\@groupList); >>  C<< my %groups = $sprout->GetGroups(\@groupList); >>
# Line 2851  Line 3382 
3382          # Here we have a group list. Loop through them individually,          # Here we have a group list. Loop through them individually,
3383          # getting a list of the relevant genomes.          # getting a list of the relevant genomes.
3384          for my $group (@{$groupList}) {          for my $group (@{$groupList}) {
3385              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3386                  [$group], "Genome(id)");                  [$group], "Genome(id)");
3387              $retVal{$group} = \@genomeIDs;              $retVal{$group} = \@genomeIDs;
3388          }          }
# Line 2859  Line 3390 
3390          # 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
3391          # of the genome records, putting each one found into the appropriate          # of the genome records, putting each one found into the appropriate
3392          # 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
3393          # in groups are included in the return set.          # in real NMPDR groups are included in the return set.
3394          my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],          my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3395                                      ['Genome(id)', 'Genome(group-name)']);                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3396          # Loop through the genomes found.          # Loop through the genomes found.
3397          for my $genome (@genomes) {          for my $genome (@genomes) {
3398              # Pop this genome's ID off the current list.              # Pop this genome's ID off the current list.
# Line 2979  Line 3510 
3510      # Get the parameters.      # Get the parameters.
3511      my ($self, $genomeID, $testFlag) = @_;      my ($self, $genomeID, $testFlag) = @_;
3512      # Perform the delete for the genome's features.      # Perform the delete for the genome's features.
3513      my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);      my $retVal = $self->Delete('Feature', "fig|$genomeID.%", testMode => $testFlag);
3514      # Perform the delete for the primary genome data.      # Perform the delete for the primary genome data.
3515      my $stats = $self->Delete('Genome', $genomeID, $testFlag);      my $stats = $self->Delete('Genome', $genomeID, testMode => $testFlag);
3516      $retVal->Accumulate($stats);      $retVal->Accumulate($stats);
3517      # Return the result.      # Return the result.
3518      return $retVal;      return $retVal;
3519  }  }
3520    
3521    =head3 Fix
3522    
3523    C<< my %fixedHash = Sprout::Fix(%groupHash); >>
3524    
3525    Prepare a genome group hash (like that returned by L</GetGroups> for processing.
3526    Groups with the same primary name will be combined. The primary name is the
3527    first capitalized word in the group name.
3528    
3529    =over 4
3530    
3531    =item groupHash
3532    
3533    Hash to be fixed up.
3534    
3535    =item RETURN
3536    
3537    Returns a fixed-up version of the hash.
3538    
3539    =back
3540    
3541    =cut
3542    
3543    sub Fix {
3544        # Get the parameters.
3545        my (%groupHash) = @_;
3546        # Create the result hash.
3547        my %retVal = ();
3548        # Copy over the genomes.
3549        for my $groupID (keys %groupHash) {
3550            # Make a safety copy of the group ID.
3551            my $realGroupID = $groupID;
3552            # Yank the primary name.
3553            if ($groupID =~ /([A-Z]\w+)/) {
3554                $realGroupID = $1;
3555            }
3556            # Append this group's genomes into the result hash.
3557            Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}});
3558        }
3559        # Return the result hash.
3560        return %retVal;
3561    }
3562    
3563    =head3 GroupPageName
3564    
3565    C<< my $name = $sprout->GroupPageName($group); >>
3566    
3567    Return the name of the page for the specified NMPDR group.
3568    
3569    =over 4
3570    
3571    =item group
3572    
3573    Name of the relevant group.
3574    
3575    =item RETURN
3576    
3577    Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3578    memory it will be read in.
3579    
3580    =back
3581    
3582    =cut
3583    
3584    sub GroupPageName {
3585        # Get the parameters.
3586        my ($self, $group) = @_;
3587        # Declare the return variable.
3588        my $retVal;
3589        # Check for the group file data.
3590        if (! defined $self->{groupHash}) {
3591            # Read the group file.
3592            my %groupData = Sprout::ReadGroupFile($self->{_options}->{dataDir} . "/groups.tbl");
3593            # Store it in our object.
3594            $self->{groupHash} = \%groupData;
3595        }
3596        # Compute the real group name.
3597        my $realGroup = $group;
3598        if ($group =~ /([A-Z]\w+)/) {
3599            $realGroup = $1;
3600        }
3601        # Return the page name.
3602        $retVal = "../content/" . $self->{groupHash}->{$realGroup}->[1];
3603        # Return the result.
3604        return $retVal;
3605    }
3606    
3607    =head3 ReadGroupFile
3608    
3609    C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >>
3610    
3611    Read in the data from the specified group file. The group file contains information
3612    about each of the NMPDR groups.
3613    
3614    =over 4
3615    
3616    =item name
3617    
3618    Name of the group.
3619    
3620    =item page
3621    
3622    Name of the group's page on the web site (e.g. C<campy.php> for
3623    Campylobacter)
3624    
3625    =item genus
3626    
3627    Genus of the group
3628    
3629    =item species
3630    
3631    Species of the group, or an empty string if the group is for an entire
3632    genus. If the group contains more than one species, the species names
3633    should be separated by commas.
3634    
3635    =back
3636    
3637    The parameters to this method are as follows
3638    
3639    =over 4
3640    
3641    =item groupFile
3642    
3643    Name of the file containing the group data.
3644    
3645    =item RETURN
3646    
3647    Returns a hash keyed on group name. The value of each hash
3648    
3649    =back
3650    
3651    =cut
3652    
3653    sub ReadGroupFile {
3654        # Get the parameters.
3655        my ($groupFileName) = @_;
3656        # Declare the return variable.
3657        my %retVal;
3658        # Read the group file.
3659        my @groupLines = Tracer::GetFile($groupFileName);
3660        for my $groupLine (@groupLines) {
3661            my ($name, $page, $genus, $species) = split(/\t/, $groupLine);
3662            $retVal{$name} = [$page, $genus, $species];
3663        }
3664        # Return the result.
3665        return %retVal;
3666    }
3667    
3668    =head3 AddProperty
3669    
3670    C<< my  = $sprout->AddProperty($featureID, $key, @values); >>
3671    
3672    Add a new attribute value (Property) to a feature.
3673    
3674    =over 4
3675    
3676    =item peg
3677    
3678    ID of the feature to which the attribute is to be added.
3679    
3680    =item key
3681    
3682    Name of the attribute (key).
3683    
3684    =item values
3685    
3686    Values of the attribute.
3687    
3688    =back
3689    
3690    =cut
3691    #: Return Type ;
3692    sub AddProperty {
3693        # Get the parameters.
3694        my ($self, $featureID, $key, @values) = @_;
3695        # Add the property using the attached attributes object.
3696        $self->{_ca}->AddAttribute($featureID, $key, @values);
3697    }
3698    
3699    =head2 Virtual Methods
3700    
3701    =head3 CleanKeywords
3702    
3703    C<< my $cleanedString = $sprout->CleanKeywords($searchExpression); >>
3704    
3705    Clean up a search expression or keyword list. This involves converting the periods
3706    in EC numbers to underscores, converting non-leading minus signs to underscores,
3707    a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
3708    characters. In addition, any extra spaces are removed.
3709    
3710    =over 4
3711    
3712    =item searchExpression
3713    
3714    Search expression or keyword list to clean. Note that a search expression may
3715    contain boolean operators which need to be preserved. This includes leading
3716    minus signs.
3717    
3718    =item RETURN
3719    
3720    Cleaned expression or keyword list.
3721    
3722    =back
3723    
3724    =cut
3725    
3726    sub CleanKeywords {
3727        # Get the parameters.
3728        my ($self, $searchExpression) = @_;
3729        # Perform the standard cleanup.
3730        my $retVal = $self->ERDB::CleanKeywords($searchExpression);
3731        # Fix the periods in EC and TC numbers.
3732        $retVal =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g;
3733        # Fix non-trailing periods.
3734        $retVal =~ s/\.(\w)/_$1/g;
3735        # Fix non-leading minus signs.
3736        $retVal =~ s/(\w)[\-]/$1_/g;
3737        # Fix the vertical bars and colons
3738        $retVal =~ s/(\w)[|:](\w)/$1'$2/g;
3739        # Return the result.
3740        return $retVal;
3741    }
3742    
3743  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3744    
3745  =head3 ParseAssignment  =head3 ParseAssignment
# Line 3043  Line 3796 
3796      }      }
3797      # If we have an assignment, we need to clean the function text. There may be      # If we have an assignment, we need to clean the function text. There may be
3798      # extra junk at the end added as a note from the user.      # extra junk at the end added as a note from the user.
3799      if (@retVal) {      if (defined( $retVal[1] )) {
3800          $retVal[1] =~ s/(\t\S)?\s*$//;          $retVal[1] =~ s/(\t\S)?\s*$//;
3801      }      }
3802      # Return the result list.      # Return the result list.
3803      return @retVal;      return @retVal;
3804  }  }
3805    
3806  =head3 FriendlyTimestamp  =head3 _CheckFeature
3807    
3808  Convert a time number to a user-friendly time stamp for display.  C<< my $flag = $sprout->_CheckFeature($fid); >>
3809    
3810  This is a static method.  Return TRUE if the specified FID is probably an NMPDR feature ID, else FALSE.
3811    
3812  =over 4  =over 4
3813    
3814  =item timeValue  =item fid
3815    
3816  Numeric time value.  Feature ID to check.
3817    
3818  =item RETURN  =item RETURN
3819    
3820  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.
3821    
3822  =back  =back
3823    
3824  =cut  =cut
3825    
3826  sub FriendlyTimestamp {  sub _CheckFeature {
3827      my ($timeValue) = @_;      # Get the parameters.
3828      my $retVal = localtime($timeValue);      my ($self, $fid) = @_;
3829      return $retVal;      # Insure we have a genome hash.
3830        if (! defined $self->{genomeHash}) {
3831            my %genomeHash = map { $_ => 1 } $self->GetFlat(['Genome'], "", [], 'Genome(id)');
3832            $self->{genomeHash} = \%genomeHash;
3833        }
3834        # Get the feature's genome ID.
3835        my ($genomeID) = FIGRules::ParseFeatureID($fid);
3836        # Return an indicator of whether or not the genome ID is in the hash.
3837        return ($self->{genomeHash}->{$genomeID} ? 1 : 0);
3838  }  }
3839    
3840  =head3 AddProperty  =head3 FriendlyTimestamp
3841    
3842  C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>  Convert a time number to a user-friendly time stamp for display.
3843    
3844  Add a new attribute value (Property) to a feature. In the SEED system, attributes can  This is a static method.
 be added to almost any object. In Sprout, they can only be added to features. In  
 Sprout, attributes are implemented using I<properties>. A property represents a key/value  
 pair. If the particular key/value pair coming in is not already in the database, a new  
 B<Property> record is created to hold it.  
3845    
3846  =over 4  =over 4
3847    
3848  =item peg  =item timeValue
   
 ID of the feature to which the attribute is to be replied.  
   
 =item key  
   
 Name of the attribute (key).  
   
 =item value  
3849    
3850  Value of the attribute.  Numeric time value.
3851    
3852  =item url  =item RETURN
3853    
3854  URL or text citation from which the property was obtained.  Returns a string containing the same time in user-readable format.
3855    
3856  =back  =back
3857    
3858  =cut  =cut
3859  #: Return Type ;  
3860  sub AddProperty {  sub FriendlyTimestamp {
3861      # Get the parameters.      my ($timeValue) = @_;
3862      my ($self, $featureID, $key, $value, $url) = @_;      my $retVal = localtime($timeValue);
3863      # Declare the variable to hold the desired property ID.      return $retVal;
     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 });  
3864  }  }
3865    
3866    

Legend:
Removed from v.1.58  
changed lines
  Added in v.1.100

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3