[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.17, Mon Jun 27 20:00:55 2005 UTC revision 1.57, Sat May 13 03:10:15 2006 UTC
# Line 62  Line 62 
62    
63  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)
64    
65  * B<userData> user name and password, delimited by a slash (default C<root/>)  * B<userData> user name and password, delimited by a slash (default same as SEED)
66    
67  * B<port> connection port (default C<0>)  * B<port> connection port (default C<0>)
68    
69    * B<sock> connection socket (default same as SEED)
70    
71  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
72    
73  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
74    
75    * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
76    
77  =back  =back
78    
79  For example, the following constructor call specifies a database named I<Sprout> and a user name of  For example, the following constructor call specifies a database named I<Sprout> and a user name of
# Line 86  Line 90 
90      # 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
91      # the incoming data.      # the incoming data.
92      my $optionTable = Tracer::GetOptions({      my $optionTable = Tracer::GetOptions({
93                         dbType       => 'mysql',         # database type                         dbType       => $FIG_Config::dbms,
94                         dataDir      => 'Data',          # data file directory                                                          # database type
95                         xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
96                         userData     => 'root/',         # user name and password                                                          # data file directory
97                         port         => 0,               # database connection port                         xmlFileName  => "$FIG_Config::fig/SproutDBD.xml",
98                                                            # database definition file name
99                           userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
100                                                            # user name and password
101                           port         => $FIG_Config::dbport,
102                                                            # database connection port
103                           sock         => $FIG_Config::dbsock,
104                         maxSegmentLength => 4500,        # maximum feature segment length                         maxSegmentLength => 4500,        # maximum feature segment length
105                         maxSequenceLength => 8000,       # maximum contig sequence length                         maxSequenceLength => 8000,       # maximum contig sequence length
106                           noDBOpen     => 0,               # 1 to suppress the database open
107                        }, $options);                        }, $options);
108      # Get the data directory.      # Get the data directory.
109      my $dataDir = $optionTable->{dataDir};      my $dataDir = $optionTable->{dataDir};
# Line 100  Line 111 
111      $optionTable->{userData} =~ m!([^/]*)/(.*)$!;      $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
112      my ($userName, $password) = ($1, $2);      my ($userName, $password) = ($1, $2);
113      # Connect to the database.      # Connect to the database.
114      my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
115        if (! $optionTable->{noDBOpen}) {
116            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
117                                    $password, $optionTable->{port}, undef, $optionTable->{sock});
118        }
119      # Create the ERDB object.      # Create the ERDB object.
120      my $xmlFileName = "$optionTable->{xmlFileName}";      my $xmlFileName = "$optionTable->{xmlFileName}";
121      my $erdb = ERDB->new($dbh, $xmlFileName);      my $erdb = ERDB->new($dbh, $xmlFileName);
# Line 377  Line 392 
392    
393  =head3 LoadUpdate  =head3 LoadUpdate
394    
395  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
396    
397  Load updates to one or more database tables. This method enables the client to make changes to one  Load updates to one or more database tables. This method enables the client to make changes to one
398  or two tables without reloading the whole database. For each table, there must be a corresponding  or two tables without reloading the whole database. For each table, there must be a corresponding
# Line 420  Line 435 
435      # Loop through the incoming table names.      # Loop through the incoming table names.
436      for my $tableName (@{$tableList}) {      for my $tableName (@{$tableList}) {
437          # Find the table's file.          # Find the table's file.
438          my $fileName = "$dataDir/$tableName";          my $fileName = LoadFileName($dataDir, $tableName);
439          if (! -e $fileName) {          if (! $fileName) {
440              $fileName = "$fileName.dtx";              Trace("No load file found for $tableName in $dataDir.") if T(0);
441          }          } else {
442          # Attempt to load this table.          # Attempt to load this table.
443          my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);          my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);
444          # Accumulate the resulting statistics.          # Accumulate the resulting statistics.
445          $retVal->Accumulate($result);          $retVal->Accumulate($result);
446      }      }
447        }
448      # Return the statistics.      # Return the statistics.
449      return $retVal;      return $retVal;
450  }  }
# Line 570  Line 586 
586  =item RETURN  =item RETURN
587    
588  Returns a list of the feature's contig segments. The locations are returned as a list in a list  Returns a list of the feature's contig segments. The locations are returned as a list in a list
589  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context.
590    
591  =back  =back
592    
# Line 597  Line 613 
613          if ($prevContig eq $contigID && $dir eq $prevDir) {          if ($prevContig eq $contigID && $dir eq $prevDir) {
614              # Here the new segment is in the same direction on the same contig. Insure the              # Here the new segment is in the same direction on the same contig. Insure the
615              # new segment's beginning is next to the old segment's end.              # new segment's beginning is next to the old segment's end.
616              if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||              if ($dir eq "-" && $beg + $len == $prevBeg) {
617                  ($dir eq "+" && $beg == $prevBeg + $prevLen)) {                  # Here we're merging two backward blocks, so we keep the new begin point
618                  # Here we need to merge two segments. Adjust the beginning and length values                  # and adjust the length.
619                  # to include both segments.                  $len += $prevLen;
620                    # Pop the old segment off. The new one will replace it later.
621                    pop @retVal;
622                } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
623                    # Here we need to merge two forward blocks. Adjust the beginning and
624                    # length values to include both segments.
625                  $beg = $prevBeg;                  $beg = $prevBeg;
626                  $len += $prevLen;                  $len += $prevLen;
627                  # Pop the old segment off. The new one will replace it later.                  # Pop the old segment off. The new one will replace it later.
# Line 609  Line 630 
630          }          }
631          # Remember this specifier for the adjacent-segment test the next time through.          # Remember this specifier for the adjacent-segment test the next time through.
632          ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);          ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
633            # Compute the initial base pair.
634            my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
635          # Add the specifier to the list.          # Add the specifier to the list.
636          push @retVal, "${contigID}_$beg$dir$len";          push @retVal, "${contigID}_$start$dir$len";
637      }      }
638      # Return the list in the format indicated by the context.      # Return the list in the format indicated by the context.
639      return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
640  }  }
641    
642  =head3 ParseLocation  =head3 ParseLocation
# Line 644  Line 667 
667      shift if UNIVERSAL::isa($_[0],__PACKAGE__);      shift if UNIVERSAL::isa($_[0],__PACKAGE__);
668      my ($location) = @_;      my ($location) = @_;
669      # Parse it into segments.      # Parse it into segments.
670      $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
671      my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);      my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
672      # If the direction is an underscore, convert it to a + or -.      # If the direction is an underscore, convert it to a + or -.
673      if ($dir eq "_") {      if ($dir eq "_") {
# Line 720  Line 743 
743  should be of the form returned by L</featureLocation> when in a list context. In other words,  should be of the form returned by L</featureLocation> when in a list context. In other words,
744  each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.  each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.
745    
746    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
747    between positions 1401 and 1532, inclusive.
748    
749        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
750    
751  =over 4  =over 4
752    
753  =item locationList  =item locationList
754    
755  List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<end> (see  List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<len> or
756  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
757    
758  =item RETURN  =item RETURN
759    
# Line 752  Line 780 
780          # the start point is the ending. Note that in the latter case we must reverse the DNA string          # the start point is the ending. Note that in the latter case we must reverse the DNA string
781          # before putting it in the return value.          # before putting it in the return value.
782          my ($start, $stop);          my ($start, $stop);
783            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
784          if ($dir eq "+") {          if ($dir eq "+") {
785              $start = $beg;              $start = $beg;
786              $stop = $beg + $len - 1;              $stop = $beg + $len - 1;
787          } else {          } else {
788              $start = $beg + $len + 1;              $start = $beg - $len + 1;
789              $stop = $beg;              $stop = $beg;
790          }          }
791            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
792          my $query = $self->Get(['IsMadeUpOf','Sequence'],          my $query = $self->Get(['IsMadeUpOf','Sequence'],
793              "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .              "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
794              " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",              " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 770  Line 800 
800                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
801                                     'IsMadeUpOf(len)']);                                     'IsMadeUpOf(len)']);
802              my $stopPosition = $startPosition + $sequenceLength;              my $stopPosition = $startPosition + $sequenceLength;
803                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
804              # Figure out the start point and length of the relevant section.              # Figure out the start point and length of the relevant section.
805              my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);              my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
806              my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
807                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
808              # Add the relevant data to the location data.              # Add the relevant data to the location data.
809              $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
810          }          }
811          # Add this location's data to the return string. Note that we may need to reverse it.          # Add this location's data to the return string. Note that we may need to reverse it.
812          if ($dir eq '+') {          if ($dir eq '+') {
813              $retVal .= $locationDNA;              $retVal .= $locationDNA;
814          } else {          } else {
815              $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
             $retVal .= $locationDNA;  
816          }          }
817      }      }
818      # Return the result.      # Return the result.
# Line 851  Line 882 
882      # Set it from the sequence data, if any.      # Set it from the sequence data, if any.
883      if ($sequence) {      if ($sequence) {
884          my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);          my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
885          $retVal = $start + $len;          $retVal = $start + $len - 1;
886        }
887        # Return the result.
888        return $retVal;
889    }
890    
891    =head3 ClusterPEGs
892    
893    C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
894    
895    Cluster the PEGs in a list according to the cluster coding scheme of the specified
896    subsystem. In order for this to work properly, the subsystem object must have
897    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
898    This causes the cluster numbers to be pulled into the subsystem's color hash.
899    If a PEG is not found in the color hash, it will not appear in the output
900    sequence.
901    
902    =over 4
903    
904    =item sub
905    
906    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
907    method.
908    
909    =item pegs
910    
911    Reference to the list of PEGs to be clustered.
912    
913    =item RETURN
914    
915    Returns a list of the PEGs, grouped into smaller lists by cluster number.
916    
917    =back
918    
919    =cut
920    #: Return Type $@@;
921    sub ClusterPEGs {
922        # Get the parameters.
923        my ($self, $sub, $pegs) = @_;
924        # Declare the return variable.
925        my $retVal = [];
926        # Loop through the PEGs, creating arrays for each cluster.
927        for my $pegID (@{$pegs}) {
928            my $clusterNumber = $sub->get_cluster_number($pegID);
929            # Only proceed if the PEG is in a cluster.
930            if ($clusterNumber >= 0) {
931                # Push this PEG onto the sub-list for the specified cluster number.
932                push @{$retVal->[$clusterNumber]}, $pegID;
933            }
934      }      }
935      # Return the result.      # Return the result.
936      return $retVal;      return $retVal;
# Line 1001  Line 1080 
1080    
1081  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1082    
1083  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1084    
1085  Return the annotations of a feature.  Return the annotations of a feature.
1086    
# Line 1011  Line 1090 
1090    
1091  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1092    
1093    =item rawFlag
1094    
1095    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1096    will be returned in human-readable form.
1097    
1098  =item RETURN  =item RETURN
1099    
1100  Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.  Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.
1101    
1102  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1103    
1104  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1105    
1106  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1107    
# Line 1029  Line 1113 
1113  #: Return Type @%;  #: Return Type @%;
1114  sub FeatureAnnotations {  sub FeatureAnnotations {
1115      # Get the parameters.      # Get the parameters.
1116      my ($self, $featureID) = @_;      my ($self, $featureID, $rawFlag) = @_;
1117      # Create a query to get the feature's annotations and the associated users.      # Create a query to get the feature's annotations and the associated users.
1118      my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],      my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1119                             "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                             "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 1042  Line 1126 
1126              $annotation->Values(['IsTargetOfAnnotation(from-link)',              $annotation->Values(['IsTargetOfAnnotation(from-link)',
1127                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1128                                   'Annotation(annotation)']);                                   'Annotation(annotation)']);
1129            # Convert the time, if necessary.
1130            if (! $rawFlag) {
1131                $timeStamp = FriendlyTimestamp($timeStamp);
1132            }
1133          # Assemble them into a hash.          # Assemble them into a hash.
1134          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1135                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1136                                 user => $user, text => $text };                                 user => $user, text => $text };
1137          # Add it to the return list.          # Add it to the return list.
1138          push @retVal, $annotationHash;          push @retVal, $annotationHash;
# Line 1073  Line 1161 
1161    
1162  =item RETURN  =item RETURN
1163    
1164  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1165    
1166  =back  =back
1167    
# Line 1083  Line 1171 
1171      # Get the parameters.      # Get the parameters.
1172      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1173      # Get all of the feature's annotations.      # Get all of the feature's annotations.
1174      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1175                              "IsTargetOfAnnotation(from-link) = ?",                              "IsTargetOfAnnotation(from-link) = ?",
1176                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1177                                               'MadeAnnotation(from-link)']);
1178      # Declare the return hash.      # Declare the return hash.
1179      my %retVal;      my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1180      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1181      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1182      # Loop until we run out of annotations.      # Loop until we run out of annotations.
1183      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1184          # Get the annotation fields.          # Get the annotation fields.
1185          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1186          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
1187          my ($user, $function) = _ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1188          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1189              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1190              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1191              # return hash.              # return hash.
1192              $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1193          }          }
1194      }      }
1195      # Return the hash of assignments found.      # Return the hash of assignments found.
# Line 1120  Line 1205 
1205  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
1206  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 a functional
1207  assignment is a type of annotation. The format of an assignment is described in  assignment is a type of annotation. The format of an assignment is described in
1208  L</ParseLocation>. Its worth noting that we cannot filter on the content of the  L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1209  annotation itself because it's a text field; however, this is not a big problem because  annotation itself because it's a text field; however, this is not a big problem because
1210  most features only have a small number of annotations.  most features only have a small number of annotations.
1211    
# Line 1182  Line 1267 
1267              }              }
1268          }          }
1269          # Build a query for all of the feature's annotations, sorted by date.          # Build a query for all of the feature's annotations, sorted by date.
1270          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1271                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1272                                 [$featureID]);                                 [$featureID]);
1273          my $timeSelected = 0;          my $timeSelected = 0;
1274          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1275          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1276              # Get the annotation text.              # Get the annotation text.
1277              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);              my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1278                                                         'Annotation(time)', 'MadeAnnotation(from-link)']);
1279              # Check to see if this is a functional assignment for a trusted user.              # Check to see if this is a functional assignment for a trusted user.
1280              my ($user, $function) = _ParseAssignment($text);              my ($actualUser, $function) = _ParseAssignment($user, $text);
1281              if ($user) {              Trace("Assignment user is $actualUser, text is $function.") if T(4);
1282                if ($actualUser) {
1283                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1284                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1285                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                  if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1286                      $retVal = $function;                      $retVal = $function;
1287                      $timeSelected = $time;                      $timeSelected = $time;
1288                  }                  }
# Line 1211  Line 1298 
1298      return $retVal;      return $retVal;
1299  }  }
1300    
1301    =head3 FunctionsOf
1302    
1303    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1304    
1305    Return the functional assignments of a particular feature.
1306    
1307    The functional assignment is handled differently depending on the type of feature. If
1308    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1309    assignment is a type of annotation. The format of an assignment is described in
1310    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1311    annotation itself because it's a text field; however, this is not a big problem because
1312    most features only have a small number of annotations.
1313    
1314    If the feature is B<not> identified by a FIG ID, then the functional assignment
1315    information is taken from the B<ExternalAliasFunc> table. If the table does
1316    not contain an entry for the feature, an empty list is returned.
1317    
1318    =over 4
1319    
1320    =item featureID
1321    
1322    ID of the feature whose functional assignments are desired.
1323    
1324    =item RETURN
1325    
1326    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1327    that user.
1328    
1329    =back
1330    
1331    =cut
1332    #: Return Type @@;
1333    sub FunctionsOf {
1334        # Get the parameters.
1335        my ($self, $featureID) = @_;
1336        # Declare the return value.
1337        my @retVal = ();
1338        # Determine the ID type.
1339        if ($featureID =~ m/^fig\|/) {
1340            # Here we have a FIG feature ID. We must build the list of trusted
1341            # users.
1342            my %trusteeTable = ();
1343            # Build a query for all of the feature's annotations, sorted by date.
1344            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1345                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1346                                   [$featureID]);
1347            my $timeSelected = 0;
1348            # Loop until we run out of annotations.
1349            while (my $annotation = $query->Fetch()) {
1350                # Get the annotation text.
1351                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1352                                                                'Annotation(time)',
1353                                                                'MadeAnnotation(user)']);
1354                # Check to see if this is a functional assignment for a trusted user.
1355                my ($actualUser, $function) = _ParseAssignment($user, $text);
1356                if ($actualUser) {
1357                    # Here it is a functional assignment.
1358                    push @retVal, [$actualUser, $function];
1359                }
1360            }
1361        } else {
1362            # Here we have a non-FIG feature ID. In this case the user ID does not
1363            # matter. We simply get the information from the External Alias Function
1364            # table.
1365            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1366                                                     ['ExternalAliasFunc(func)']);
1367            push @retVal, map { ['master', $_] } @assignments;
1368        }
1369        # Return the assignments found.
1370        return @retVal;
1371    }
1372    
1373  =head3 BBHList  =head3 BBHList
1374    
1375  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1248  Line 1407 
1407          my $query = $self->Get(['IsBidirectionalBestHitOf'],          my $query = $self->Get(['IsBidirectionalBestHitOf'],
1408                                 "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",                                 "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",
1409                                 [$featureID, $genomeID]);                                 [$featureID, $genomeID]);
1410          # Look for the best hit.          # Peel off the BBHs found.
1411          my $bbh = $query->Fetch;          my @found = ();
1412          if ($bbh) {          while (my $bbh = $query->Fetch) {
1413              my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');
             $retVal{$featureID} = $targetFeature;  
1414          }          }
1415            $retVal{$featureID} = \@found;
1416      }      }
1417      # Return the mapping.      # Return the mapping.
1418      return \%retVal;      return \%retVal;
# Line 1331  Line 1490 
1490      my $genomeData = $self->GetEntity('Genome', $genomeID);      my $genomeData = $self->GetEntity('Genome', $genomeID);
1491      if ($genomeData) {      if ($genomeData) {
1492          # The genome exists, so get the completeness flag.          # The genome exists, so get the completeness flag.
1493          ($retVal) = $genomeData->Value('complete');          ($retVal) = $genomeData->Value('Genome(complete)');
1494      }      }
1495      # Return the result.      # Return the result.
1496      return $retVal;      return $retVal;
# Line 1371  Line 1530 
1530    
1531  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1532    
1533  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1534    
1535  =over 4  =over 4
1536    
1537  =item featureID  =item featureID
1538    
1539  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1540    
1541  =item RETURN  =item RETURN
1542    
1543  Returns the ID of the genome for the specified feature. If the feature is not found, returns  Returns the ID of the genome for the specified feature or contig. If the feature or contig is not
1544  an undefined value.  found, returns an undefined value.
1545    
1546  =back  =back
1547    
# Line 1391  Line 1550 
1550  sub GenomeOf {  sub GenomeOf {
1551      # Get the parameters.      # Get the parameters.
1552      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1553      # Create a query to find the genome associated with the feature.      # Create a query to find the genome associated with the incoming ID.
1554      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1555                               [$featureID, $featureID]);
1556      # Declare the return value.      # Declare the return value.
1557      my $retVal;      my $retVal;
1558      # Get the genome ID.      # Get the genome ID.
# Line 1506  Line 1666 
1666      my ($self, $peg1, $peg2) = @_;      my ($self, $peg1, $peg2) = @_;
1667      # Declare the return variable.      # Declare the return variable.
1668      my @retVal = ();      my @retVal = ();
1669      # Our first task is to find out the nature of the coupling.      # Our first task is to find out the nature of the coupling: whether or not
1670        # it exists, its score, and whether the features are stored in the same
1671        # order as the ones coming in.
1672      my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);      my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1673      # Only proceed if a coupling exists.      # Only proceed if a coupling exists.
1674      if ($couplingID) {      if ($couplingID) {
1675          # Determine the ordering to place on the evidence items. If we're          # Determine the ordering to place on the evidence items. If we're
1676          # inverted, we want to see feature 2 before feature 1; otherwise,          # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1677          # we want the reverse.          # we want feature 1 before feature 2 (normal).
1678            Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);
1679          my $ordering = ($inverted ? "DESC" : "");          my $ordering = ($inverted ? "DESC" : "");
1680          # Get the coupling evidence.          # Get the coupling evidence.
1681          my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],          my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
# Line 1526  Line 1689 
1689          while (@evidenceList > 0) {          while (@evidenceList > 0) {
1690              my $peg1Data = shift @evidenceList;              my $peg1Data = shift @evidenceList;
1691              my $peg2Data = shift @evidenceList;              my $peg2Data = shift @evidenceList;
1692                Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1693              push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];              push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1694          }          }
1695            Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1696      }      }
     # TODO: code  
1697      # Return the result.      # Return the result.
1698      return @retVal;      return @retVal;
1699  }  }
# Line 1578  Line 1742 
1742                                   [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);                                   [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1743      # Check to see if we found anything.      # Check to see if we found anything.
1744      if (!@pegs) {      if (!@pegs) {
1745            Trace("No coupling found.") if T(Coupling => 4);
1746          # No coupling, so undefine the return value.          # No coupling, so undefine the return value.
1747          $retVal = undef;          $retVal = undef;
1748      } else {      } else {
1749          # We have a coupling! Get the score and check for inversion.          # We have a coupling! Get the score and check for inversion.
1750          $score = $pegs[0]->[1];          $score = $pegs[0]->[1];
1751          $inverted = ($pegs[0]->[0] eq $peg1);          my $firstFound = $pegs[0]->[0];
1752            $inverted = ($firstFound ne $peg1);
1753            Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1754      }      }
1755      # Return the result.      # Return the result.
1756      return ($retVal, $inverted, $score);      return ($retVal, $inverted, $score);
# Line 1688  Line 1855 
1855          if ($line =~ m/^>\s*(.+?)(\s|\n)/) {          if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1856              # Here we have a new header. Store the current sequence if we have one.              # Here we have a new header. Store the current sequence if we have one.
1857              if ($id) {              if ($id) {
1858                  $retVal{$id} = uc $sequence;                  $retVal{$id} = lc $sequence;
1859              }              }
1860              # Clear the sequence accumulator and save the new ID.              # Clear the sequence accumulator and save the new ID.
1861              ($id, $sequence) = ("$prefix$1", "");              ($id, $sequence) = ("$prefix$1", "");
1862          } else {          } else {
1863              # Here we have a data line, so we add it to the sequence accumulator.              # Here we have a data line, so we add it to the sequence accumulator.
1864              # First, we get the actual data out. Note that we normalize to upper              # First, we get the actual data out. Note that we normalize to lower
1865              # case.              # case.
1866              $line =~ /^\s*(.*?)(\s|\n)/;              $line =~ /^\s*(.*?)(\s|\n)/;
1867              $sequence .= $1;              $sequence .= $1;
# Line 1702  Line 1869 
1869      }      }
1870      # Flush out the last sequence (if any).      # Flush out the last sequence (if any).
1871      if ($sequence) {      if ($sequence) {
1872          $retVal{$id} = uc $sequence;          $retVal{$id} = lc $sequence;
1873      }      }
1874      # Close the file.      # Close the file.
1875      close FASTAFILE;      close FASTAFILE;
# Line 2028  Line 2195 
2195      # Get the parameters.      # Get the parameters.
2196      my ($self, $entityName, $entityID) = @_;      my ($self, $entityName, $entityID) = @_;
2197      # Check for the entity instance.      # Check for the entity instance.
2198        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
2199      my $testInstance = $self->GetEntity($entityName, $entityID);      my $testInstance = $self->GetEntity($entityName, $entityID);
2200      # Return an existence indicator.      # Return an existence indicator.
2201      my $retVal = ($testInstance ? 1 : 0);      my $retVal = ($testInstance ? 1 : 0);
# Line 2219  Line 2387 
2387      return @retVal;      return @retVal;
2388  }  }
2389    
2390    =head3 GetProperties
2391    
2392    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2393    
2394    Return a list of the properties with the specified characteristics.
2395    
2396    Properties are arbitrary key-value pairs associated with a feature. (At some point they
2397    will also be associated with genomes.) A property value is represented by a 4-tuple of
2398    the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2399    
2400    =over 4
2401    
2402    =item fid
2403    
2404    ID of the feature possessing the property.
2405    
2406    =item key
2407    
2408    Name or key of the property.
2409    
2410    =item value
2411    
2412    Value of the property.
2413    
2414    =item url
2415    
2416    URL of the document that indicated the property should have this particular value, or an
2417    empty string if no such document exists.
2418    
2419    =back
2420    
2421    The parameters act as a filter for the desired data. Any non-null parameter will
2422    automatically match all the tuples returned. So, specifying just the I<$fid> will
2423    return all the properties of the specified feature; similarly, specifying the I<$key>
2424    and I<$value> parameters will return all the features having the specified property
2425    value.
2426    
2427    A single property key can have many values, representing different ideas about the
2428    feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2429    virulent, and another may declare that it is not virulent. A query about the virulence of
2430    C<fig|83333.1.peg.10> would be coded as
2431    
2432        my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2433    
2434    Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2435    not to be filtered. The tuples returned would be
2436    
2437        ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2438        ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2439    
2440    =cut
2441    #: Return Type @@;
2442    sub GetProperties {
2443        # Get the parameters.
2444        my ($self, @parms) = @_;
2445        # Declare the return variable.
2446        my @retVal = ();
2447        # Now we need to create a WHERE clause that will get us the data we want. First,
2448        # we create a list of the columns containing the data for each parameter.
2449        my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2450                        'Property(property-value)', 'HasProperty(evidence)');
2451        # Now we build the WHERE clause and the list of parameter values.
2452        my @where = ();
2453        my @values = ();
2454        for (my $i = 0; $i <= $#colNames; $i++) {
2455            my $parm = $parms[$i];
2456            if (defined $parm && ($parm ne '')) {
2457                push @where, "$colNames[$i] = ?";
2458                push @values, $parm;
2459            }
2460        }
2461        # Format the WHERE clause.
2462        my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2463        # Ask for all the propertie values with the desired characteristics.
2464        my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2465        while (my $valueObject = $query->Fetch()) {
2466            my @tuple = $valueObject->Values(\@colNames);
2467            push @retVal, \@tuple;
2468        }
2469        # Return the result.
2470        return @retVal;
2471    }
2472    
2473  =head3 FeatureProperties  =head3 FeatureProperties
2474    
2475  C<< my @properties = $sprout->FeatureProperties($featureID); >>  C<< my @properties = $sprout->FeatureProperties($featureID); >>
# Line 2413  Line 2664 
2664  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2665    
2666  Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped  Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped
2667  to the role the feature performs.  to the roles the feature performs.
2668    
2669  =over 4  =over 4
2670    
# Line 2423  Line 2674 
2674    
2675  =item RETURN  =item RETURN
2676    
2677  Returns a hash mapping all the feature's subsystems to the feature's role.  Returns a hash mapping all the feature's subsystems to a list of the feature's roles.
2678    
2679  =back  =back
2680    
2681  =cut  =cut
2682  #: Return Type %;  #: Return Type %@;
2683  sub SubsystemsOf {  sub SubsystemsOf {
2684      # Get the parameters.      # Get the parameters.
2685      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
# Line 2438  Line 2689 
2689                                      ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                      ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2690      # Create the return value.      # Create the return value.
2691      my %retVal = ();      my %retVal = ();
2692        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2693        # in two spreadsheet cells.
2694        my %dupHash = ();
2695      # Loop through the results, adding them to the hash.      # Loop through the results, adding them to the hash.
2696      for my $record (@subsystems) {      for my $record (@subsystems) {
2697          $retVal{$record->[0]} = $record->[1];          # Get this subsystem and role.
2698            my ($subsys, $role) = @{$record};
2699            # Insure it's the first time for both.
2700            my $dupKey = "$subsys\n$role";
2701            if (! exists $dupHash{"$subsys\n$role"}) {
2702                $dupHash{$dupKey} = 1;
2703                push @{$retVal{$subsys}}, $role;
2704            }
2705      }      }
2706      # Return the hash.      # Return the hash.
2707      return %retVal;      return %retVal;
# Line 2478  Line 2739 
2739      return @retVal;      return @retVal;
2740  }  }
2741    
2742    
2743    
2744  =head3 RelatedFeatures  =head3 RelatedFeatures
2745    
2746  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2896  Line 3159 
3159      return %retVal;      return %retVal;
3160  }  }
3161    
3162    =head3 MyGenomes
3163    
3164    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
3165    
3166    Return a list of the genomes to be included in the Sprout.
3167    
3168    This method is provided for use during the Sprout load. It presumes the Genome load file has
3169    already been created. (It will be in the Sprout data directory and called either C<Genome>
3170    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3171    IDs.
3172    
3173    =over 4
3174    
3175    =item dataDir
3176    
3177    Directory containing the Sprout load files.
3178    
3179    =back
3180    
3181    =cut
3182    #: Return Type @;
3183    sub MyGenomes {
3184        # Get the parameters.
3185        my ($dataDir) = @_;
3186        # Compute the genome file name.
3187        my $genomeFileName = LoadFileName($dataDir, "Genome");
3188        # Extract the genome IDs from the files.
3189        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3190        # Return the result.
3191        return @retVal;
3192    }
3193    
3194    =head3 LoadFileName
3195    
3196    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3197    
3198    Return the name of the load file for the specified table in the specified data
3199    directory.
3200    
3201    =over 4
3202    
3203    =item dataDir
3204    
3205    Directory containing the Sprout load files.
3206    
3207    =item tableName
3208    
3209    Name of the table whose load file is desired.
3210    
3211    =item RETURN
3212    
3213    Returns the name of the file containing the load data for the specified table, or
3214    C<undef> if no load file is present.
3215    
3216    =back
3217    
3218    =cut
3219    #: Return Type $;
3220    sub LoadFileName {
3221        # Get the parameters.
3222        my ($dataDir, $tableName) = @_;
3223        # Declare the return variable.
3224        my $retVal;
3225        # Check for the various file names.
3226        if (-e "$dataDir/$tableName") {
3227            $retVal = "$dataDir/$tableName";
3228        } elsif (-e "$dataDir/$tableName.dtx") {
3229            $retVal = "$dataDir/$tableName.dtx";
3230        }
3231        # Return the result.
3232        return $retVal;
3233    }
3234    
3235    =head3 DeleteGenome
3236    
3237    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3238    
3239    Delete a genome from the database.
3240    
3241    =over 4
3242    
3243    =item genomeID
3244    
3245    ID of the genome to delete
3246    
3247    =item testFlag
3248    
3249    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3250    
3251    =item RETURN
3252    
3253    Returns a statistics object describing the rows deleted.
3254    
3255    =back
3256    
3257    =cut
3258    #: Return Type $%;
3259    sub DeleteGenome {
3260        # Get the parameters.
3261        my ($self, $genomeID, $testFlag) = @_;
3262        # Perform the delete for the genome's features.
3263        my $retVal = $self->{_erdb}->Delete('Feature', "fig|$genomeID.%", $testFlag);
3264        # Perform the delete for the primary genome data.
3265        my $stats = $self->{_erdb}->Delete('Genome', $genomeID, $testFlag);
3266        $retVal->Accumulate($stats);
3267        # Return the result.
3268        return $retVal;
3269    }
3270    
3271  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3272    
3273  =head3 ParseAssignment  =head3 ParseAssignment
# Line 2906  Line 3278 
3278    
3279  A functional assignment is always of the form  A functional assignment is always of the form
3280    
3281      I<XXXX>C<\nset >I<YYYY>C< function to\n>I<ZZZZZ>      C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3282    
3283    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3284    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3285    not always the case.
3286    
3287  where I<XXXX> is the B<assigning user>, I<YYYY> is the B<user>, and I<ZZZZ> is the  In addition, the functional role may contain extra data that is stripped, such as
3288  actual functional role. In most cases, the user and the assigning user will be the  terminating spaces or a comment separated from the rest of the text by a tab.
 same, but that is not always the case.  
3289    
3290  This is a static method.  This is a static method.
3291    
3292  =over 4  =over 4
3293    
3294    =item user
3295    
3296    Name of the assigning user.
3297    
3298  =item text  =item text
3299    
3300  Text of the annotation.  Text of the annotation.
# Line 2931  Line 3310 
3310    
3311  sub _ParseAssignment {  sub _ParseAssignment {
3312      # Get the parameters.      # Get the parameters.
3313      my ($text) = @_;      my ($user, $text) = @_;
3314      # Declare the return value.      # Declare the return value.
3315      my @retVal = ();      my @retVal = ();
3316      # Check to see if this is a functional assignment.      # Check to see if this is a functional assignment.
3317      my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3318      if ($type =~ m/^set ([^ ]+) function to$/i) {      if ($type =~ m/^set function to$/i) {
3319          # Here it is, so we return the user name (which is in $1), the functional role text,          # Here we have an assignment without a user, so we use the incoming user ID.
3320          # and the assigning user.          @retVal = ($user, $function);
3321          @retVal = ($1, $function, $user);      } elsif ($type =~ m/^set (\S+) function to$/i) {
3322            # Here we have an assignment with a user that is passed back to the caller.
3323            @retVal = ($1, $function);
3324        }
3325        # If we have an assignment, we need to clean the function text. There may be
3326        # extra junk at the end added as a note from the user.
3327        if (@retVal) {
3328            $retVal[1] =~ s/(\t\S)?\s*$//;
3329      }      }
3330      # Return the result list.      # Return the result list.
3331      return @retVal;      return @retVal;
# Line 2967  Line 3353 
3353    
3354  sub FriendlyTimestamp {  sub FriendlyTimestamp {
3355      my ($timeValue) = @_;      my ($timeValue) = @_;
3356      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
3357      return $retVal;      return $retVal;
3358  }  }
3359    
# Line 3028  Line 3414 
3414      $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });      $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3415  }  }
3416    
3417    
3418  1;  1;

Legend:
Removed from v.1.17  
changed lines
  Added in v.1.57

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3