[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.14, Thu Jun 9 19:06:55 2005 UTC revision 1.46, Thu Oct 20 11:52:36 2005 UTC
# Line 70  Line 70 
70    
71  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
72    
73    * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
74    
75  =back  =back
76    
77  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 88 
88          # 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
89          # the incoming data.          # the incoming data.
90          my $optionTable = Tracer::GetOptions({          my $optionTable = Tracer::GetOptions({
91                                             dbType               => 'mysql',                     # database type                         dbType       => $FIG_Config::dbms,
92                                             dataDir              => 'Data',                      # data file directory                                                          # database type
93                                             xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
94                                             userData             => 'root/',                     # user name and password                                                          # data file directory
95                                             port                 => 0,                           # database connection port                         xmlFileName  => "$FIG_Config::sproutData/SproutDBD.xml",
96                                                            # database definition file name
97                           userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
98                                                            # user name and password
99                           port         => $FIG_Config::dbport,
100                                                            # database connection port
101                                             maxSegmentLength => 4500,            # maximum feature segment length                                             maxSegmentLength => 4500,            # maximum feature segment length
102                                             maxSequenceLength => 8000,           # maximum contig sequence length                                             maxSequenceLength => 8000,           # maximum contig sequence length
103                           noDBOpen     => 0,               # 1 to suppress the database open
104                                            }, $options);                                            }, $options);
105          # Get the data directory.          # Get the data directory.
106          my $dataDir = $optionTable->{dataDir};          my $dataDir = $optionTable->{dataDir};
# Line 100  Line 108 
108          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
109          my ($userName, $password) = ($1, $2);          my ($userName, $password) = ($1, $2);
110          # Connect to the database.          # Connect to the database.
111          my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
112        if (! $optionTable->{noDBOpen}) {
113            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
114                                    $password, $optionTable->{port});
115        }
116          # Create the ERDB object.          # Create the ERDB object.
117          my $xmlFileName = "$optionTable->{xmlFileName}";          my $xmlFileName = "$optionTable->{xmlFileName}";
118          my $erdb = ERDB->new($dbh, $xmlFileName);          my $erdb = ERDB->new($dbh, $xmlFileName);
# Line 377  Line 389 
389    
390  =head3 LoadUpdate  =head3 LoadUpdate
391    
392  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
393    
394  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
395  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 432 
432          # Loop through the incoming table names.          # Loop through the incoming table names.
433          for my $tableName (@{$tableList}) {          for my $tableName (@{$tableList}) {
434                  # Find the table's file.                  # Find the table's file.
435                  my $fileName = "$dataDir/$tableName";          my $fileName = LoadFileName($dataDir, $tableName);
436                  if (! -e $fileName) {          if (! $fileName) {
437                          $fileName = "$fileName.dtx";              Trace("No load file found for $tableName in $dataDir.") if T(0);
438                  }          } else {
439                  # Attempt to load this table.                  # Attempt to load this table.
440                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);
441                  # Accumulate the resulting statistics.                  # Accumulate the resulting statistics.
442                  $retVal->Accumulate($result);                  $retVal->Accumulate($result);
443          }          }
444        }
445          # Return the statistics.          # Return the statistics.
446          return $retVal;          return $retVal;
447  }  }
# Line 570  Line 583 
583  =item RETURN  =item RETURN
584    
585  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
586  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context.
587    
588  =back  =back
589    
# Line 597  Line 610 
610                  if ($prevContig eq $contigID && $dir eq $prevDir) {                  if ($prevContig eq $contigID && $dir eq $prevDir) {
611                          # 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
612                          # new segment's beginning is next to the old segment's end.                          # new segment's beginning is next to the old segment's end.
613                          if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||              if ($dir eq "-" && $beg + $len == $prevBeg) {
614                                  ($dir eq "+" && $beg == $prevBeg + $prevLen)) {                  # Here we're merging two backward blocks, so we keep the new begin point
615                                  # Here we need to merge two segments. Adjust the beginning and length values                  # and adjust the length.
616                                  # to include both segments.                  $len += $prevLen;
617                    # Pop the old segment off. The new one will replace it later.
618                    pop @retVal;
619                } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
620                    # Here we need to merge two forward blocks. Adjust the beginning and
621                    # length values to include both segments.
622                                  $beg = $prevBeg;                                  $beg = $prevBeg;
623                                  $len += $prevLen;                                  $len += $prevLen;
624                                  # 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 627 
627                  }                  }
628                  # Remember this specifier for the adjacent-segment test the next time through.                  # Remember this specifier for the adjacent-segment test the next time through.
629                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
630            # Compute the initial base pair.
631            my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
632                  # Add the specifier to the list.                  # Add the specifier to the list.
633                  push @retVal, "${contigID}_$beg$dir$len";          push @retVal, "${contigID}_$start$dir$len";
634          }          }
635          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
636          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
637  }  }
638    
639  =head3 ParseLocation  =head3 ParseLocation
# Line 644  Line 664 
664      shift if UNIVERSAL::isa($_[0],__PACKAGE__);      shift if UNIVERSAL::isa($_[0],__PACKAGE__);
665          my ($location) = @_;          my ($location) = @_;
666          # Parse it into segments.          # Parse it into segments.
667          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
668          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
669          # If the direction is an underscore, convert it to a + or -.          # If the direction is an underscore, convert it to a + or -.
670          if ($dir eq "_") {          if ($dir eq "_") {
# Line 752  Line 772 
772                  # 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
773                  # before putting it in the return value.                  # before putting it in the return value.
774                  my ($start, $stop);                  my ($start, $stop);
775            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
776                  if ($dir eq "+") {                  if ($dir eq "+") {
777                          $start = $beg;                          $start = $beg;
778                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
779                  } else {                  } else {
780                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
781                          $stop = $beg;                          $stop = $beg;
782                  }                  }
783            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
784                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
785                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
786                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 770  Line 792 
792                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
793                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
794                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
795                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
796                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
797                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
798                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
799                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
800                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
801                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
802                  }                  }
803                  # 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.
804                  if ($dir eq '+') {                  if ($dir eq '+') {
805                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
806                  } else {                  } else {
807                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
808                  }                  }
809          }          }
810          # Return the result.          # Return the result.
# Line 851  Line 874 
874          # Set it from the sequence data, if any.          # Set it from the sequence data, if any.
875          if ($sequence) {          if ($sequence) {
876                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
877                  $retVal = $start + $len;          $retVal = $start + $len - 1;
878        }
879        # Return the result.
880        return $retVal;
881    }
882    
883    =head3 ClusterPEGs
884    
885    C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
886    
887    Cluster the PEGs in a list according to the cluster coding scheme of the specified
888    subsystem. In order for this to work properly, the subsystem object must have
889    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
890    This causes the cluster numbers to be pulled into the subsystem's color hash.
891    If a PEG is not found in the color hash, it will not appear in the output
892    sequence.
893    
894    =over 4
895    
896    =item sub
897    
898    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
899    method.
900    
901    =item pegs
902    
903    Reference to the list of PEGs to be clustered.
904    
905    =item RETURN
906    
907    Returns a list of the PEGs, grouped into smaller lists by cluster number.
908    
909    =back
910    
911    =cut
912    #: Return Type $@@;
913    sub ClusterPEGs {
914        # Get the parameters.
915        my ($self, $sub, $pegs) = @_;
916        # Declare the return variable.
917        my $retVal = [];
918        # Loop through the PEGs, creating arrays for each cluster.
919        for my $pegID (@{$pegs}) {
920            my $clusterNumber = $sub->get_cluster_number($pegID);
921            # Only proceed if the PEG is in a cluster.
922            if ($clusterNumber >= 0) {
923                # Push this PEG onto the sub-list for the specified cluster number.
924                push @{$retVal->[$clusterNumber]}, $pegID;
925            }
926          }          }
927          # Return the result.          # Return the result.
928          return $retVal;          return $retVal;
# Line 1001  Line 1072 
1072    
1073  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1074    
1075  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1076    
1077  Return the annotations of a feature.  Return the annotations of a feature.
1078    
# Line 1011  Line 1082 
1082    
1083  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1084    
1085    =item rawFlag
1086    
1087    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1088    will be returned in human-readable form.
1089    
1090  =item RETURN  =item RETURN
1091    
1092  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.
1093    
1094  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1095    
1096  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1097    
1098  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1099    
# Line 1029  Line 1105 
1105  #: Return Type @%;  #: Return Type @%;
1106  sub FeatureAnnotations {  sub FeatureAnnotations {
1107          # Get the parameters.          # Get the parameters.
1108          my ($self, $featureID) = @_;      my ($self, $featureID, $rawFlag) = @_;
1109          # 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.
1110          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1111                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 1042  Line 1118 
1118                          $annotation->Values(['IsTargetOfAnnotation(from-link)',                          $annotation->Values(['IsTargetOfAnnotation(from-link)',
1119                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1120                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1121            # Convert the time, if necessary.
1122            if (! $rawFlag) {
1123                $timeStamp = FriendlyTimestamp($timeStamp);
1124            }
1125                  # Assemble them into a hash.                  # Assemble them into a hash.
1126          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1127                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1128                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1129                  # Add it to the return list.                  # Add it to the return list.
1130                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1073  Line 1153 
1153    
1154  =item RETURN  =item RETURN
1155    
1156  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1157    
1158  =back  =back
1159    
# Line 1088  Line 1168 
1168                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);
1169          # Declare the return hash.          # Declare the return hash.
1170          my %retVal;          my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1171      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1172      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1173          # Loop until we run out of annotations.          # Loop until we run out of annotations.
# Line 1098  Line 1176 
1176          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text) = @{$annotation};
1177                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1178                  my ($user, $function) = _ParseAssignment($text);                  my ($user, $function) = _ParseAssignment($text);
1179          if ($user && ! exists $timeHash{$user}) {          if ($user && ! exists $retVal{$user}) {
1180              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1181              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1182              # return hash.              # return hash.
1183                          $retVal{$function} = $user;              $retVal{$user} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1184                  }                  }
1185          }          }
1186          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1120  Line 1196 
1196  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
1197  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
1198  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
1199  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
1200  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
1201  most features only have a small number of annotations.  most features only have a small number of annotations.
1202    
# Line 1211  Line 1287 
1287          return $retVal;          return $retVal;
1288  }  }
1289    
1290    =head3 FunctionsOf
1291    
1292    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1293    
1294    Return the functional assignments of a particular feature.
1295    
1296    The functional assignment is handled differently depending on the type of feature. If
1297    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1298    assignment is a type of annotation. The format of an assignment is described in
1299    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1300    annotation itself because it's a text field; however, this is not a big problem because
1301    most features only have a small number of annotations.
1302    
1303    If the feature is B<not> identified by a FIG ID, then the functional assignment
1304    information is taken from the B<ExternalAliasFunc> table. If the table does
1305    not contain an entry for the feature, an empty list is returned.
1306    
1307    =over 4
1308    
1309    =item featureID
1310    
1311    ID of the feature whose functional assignments are desired.
1312    
1313    =item RETURN
1314    
1315    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1316    that user.
1317    
1318    =back
1319    
1320    =cut
1321    #: Return Type @@;
1322    sub FunctionsOf {
1323        # Get the parameters.
1324        my ($self, $featureID) = @_;
1325        # Declare the return value.
1326        my @retVal = ();
1327        # Determine the ID type.
1328        if ($featureID =~ m/^fig\|/) {
1329            # Here we have a FIG feature ID. We must build the list of trusted
1330            # users.
1331            my %trusteeTable = ();
1332            # Build a query for all of the feature's annotations, sorted by date.
1333            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],
1334                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1335                                   [$featureID]);
1336            my $timeSelected = 0;
1337            # Loop until we run out of annotations.
1338            while (my $annotation = $query->Fetch()) {
1339                # Get the annotation text.
1340                my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);
1341                # Check to see if this is a functional assignment for a trusted user.
1342                my ($user, $function) = _ParseAssignment($text);
1343                if ($user) {
1344                    # Here it is a functional assignment.
1345                    push @retVal, [$user, $function];
1346                }
1347            }
1348        } else {
1349            # Here we have a non-FIG feature ID. In this case the user ID does not
1350            # matter. We simply get the information from the External Alias Function
1351            # table.
1352            push @retVal, $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']);
1353        }
1354        # Return the assignments found.
1355        return @retVal;
1356    }
1357    
1358  =head3 BBHList  =head3 BBHList
1359    
1360  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1230  Line 1374 
1374    
1375  =item RETURN  =item RETURN
1376    
1377  Returns a reference to a hash that maps the IDs of the incoming features to the IDs of  Returns a reference to a hash that maps the IDs of the incoming features to the best hits
1378  their best hits.  on the target genome.
1379    
1380  =back  =back
1381    
# Line 1248  Line 1392 
1392                  my $query = $self->Get(['IsBidirectionalBestHitOf'],                  my $query = $self->Get(['IsBidirectionalBestHitOf'],
1393                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",
1394                                                             [$featureID, $genomeID]);                                                             [$featureID, $genomeID]);
1395                  # Look for the best hit.          # Peel off the BBHs found.
1396                  my $bbh = $query->Fetch;          my @found = ();
1397                  if ($bbh) {          while (my $bbh = $query->Fetch) {
1398                          my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');
                         $retVal{$featureID} = $targetFeature;  
1399                  }                  }
1400            $retVal{$featureID} = \@found;
1401          }          }
1402          # Return the mapping.          # Return the mapping.
1403          return \%retVal;          return \%retVal;
1404  }  }
1405    
1406    =head3 SimList
1407    
1408    C<< my %similarities = $sprout->SimList($featureID, $count); >>
1409    
1410    Return a list of the similarities to the specified feature.
1411    
1412    Sprout does not support real similarities, so this method just returns the bidirectional
1413    best hits.
1414    
1415    =over 4
1416    
1417    =item featureID
1418    
1419    ID of the feature whose similarities are desired.
1420    
1421    =item count
1422    
1423    Maximum number of similar features to be returned, or C<0> to return them all.
1424    
1425    =back
1426    
1427    =cut
1428    #: Return Type %;
1429    sub SimList {
1430        # Get the parameters.
1431        my ($self, $featureID, $count) = @_;
1432        # Ask for the best hits.
1433        my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],
1434                                  "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",
1435                                  [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],
1436                                  $count);
1437        # Create the return value.
1438        my %retVal = ();
1439        for my $tuple (@lists) {
1440            $retVal{$tuple->[0]} = $tuple->[1];
1441        }
1442        # Return the result.
1443        return %retVal;
1444    }
1445    
1446    
1447    
1448    =head3 IsComplete
1449    
1450    C<< my $flag = $sprout->IsComplete($genomeID); >>
1451    
1452    Return TRUE if the specified genome is complete, else FALSE.
1453    
1454    =over 4
1455    
1456    =item genomeID
1457    
1458    ID of the genome whose completeness status is desired.
1459    
1460    =item RETURN
1461    
1462    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1463    not found.
1464    
1465    =back
1466    
1467    =cut
1468    #: Return Type $;
1469    sub IsComplete {
1470        # Get the parameters.
1471        my ($self, $genomeID) = @_;
1472        # Declare the return variable.
1473        my $retVal;
1474        # Get the genome's data.
1475        my $genomeData = $self->GetEntity('Genome', $genomeID);
1476        if ($genomeData) {
1477            # The genome exists, so get the completeness flag.
1478            ($retVal) = $genomeData->Value('complete');
1479        }
1480        # Return the result.
1481        return $retVal;
1482    }
1483    
1484  =head3 FeatureAliases  =head3 FeatureAliases
1485    
1486  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
# Line 1378  Line 1600 
1600          return %retVal;          return %retVal;
1601  }  }
1602    
1603    =head3 CouplingEvidence
1604    
1605    C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1606    
1607    Return the evidence for a functional coupling.
1608    
1609    A pair of features is considered evidence of a coupling between two other
1610    features if they occur close together on a contig and both are similar to
1611    the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1612    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1613    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1614    similar to B<A2>.
1615    
1616    The score of a coupling is determined by the number of pieces of evidence
1617    that are considered I<representative>. If several evidence items belong to
1618    a group of genomes that are close to each other, only one of those items
1619    is considered representative. The other evidence items are presumed to be
1620    there because of the relationship between the genomes rather than because
1621    the two proteins generated by the features have a related functionality.
1622    
1623    Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1624    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1625    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1626    and FALSE otherwise.
1627    
1628    =over 4
1629    
1630    =item peg1
1631    
1632    ID of the feature of interest.
1633    
1634    =item peg2
1635    
1636    ID of a feature functionally coupled to the feature of interest.
1637    
1638    =item RETURN
1639    
1640    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1641    of interest, a feature similar to the functionally coupled feature, and a flag
1642    that is TRUE for a representative piece of evidence and FALSE otherwise.
1643    
1644    =back
1645    
1646    =cut
1647    #: Return Type @@;
1648    sub CouplingEvidence {
1649        # Get the parameters.
1650        my ($self, $peg1, $peg2) = @_;
1651        # Declare the return variable.
1652        my @retVal = ();
1653        # Our first task is to find out the nature of the coupling: whether or not
1654        # it exists, its score, and whether the features are stored in the same
1655        # order as the ones coming in.
1656        my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1657        # Only proceed if a coupling exists.
1658        if ($couplingID) {
1659            # Determine the ordering to place on the evidence items. If we're
1660            # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1661            # we want feature 1 before feature 2 (normal).
1662            Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);
1663            my $ordering = ($inverted ? "DESC" : "");
1664            # Get the coupling evidence.
1665            my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
1666                                              "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",
1667                                              [$couplingID],
1668                                              ['PCH(used)', 'UsesAsEvidence(to-link)']);
1669            # Loop through the evidence items. Each piece of evidence is represented by two
1670            # positions in the evidence list, one for each feature on the other side of the
1671            # evidence link. If at some point we want to generalize to couplings with
1672            # more than two positions, this section of code will need to be re-done.
1673            while (@evidenceList > 0) {
1674                my $peg1Data = shift @evidenceList;
1675                my $peg2Data = shift @evidenceList;
1676                Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1677                push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1678            }
1679            Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1680        }
1681        # Return the result.
1682        return @retVal;
1683    }
1684    
1685    =head3 GetCoupling
1686    
1687    C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>
1688    
1689    Return the coupling (if any) for the specified pair of PEGs. If a coupling
1690    exists, we return the coupling ID along with an indicator of whether the
1691    coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.
1692    In the second case, we say the coupling is I<inverted>. The importance of an
1693    inverted coupling is that the PEGs in the evidence will appear in reverse order.
1694    
1695    =over 4
1696    
1697    =item peg1
1698    
1699    ID of the feature of interest.
1700    
1701    =item peg2
1702    
1703    ID of the potentially coupled feature.
1704    
1705    =item RETURN
1706    
1707    Returns a three-element list. The first element contains the database ID of
1708    the coupling. The second element is FALSE if the coupling is stored in the
1709    database in the caller specified order and TRUE if it is stored in the
1710    inverted order. The third element is the coupling's score. If the coupling
1711    does not exist, all three list elements will be C<undef>.
1712    
1713    =back
1714    
1715    =cut
1716    #: Return Type $%@;
1717    sub GetCoupling {
1718        # Get the parameters.
1719        my ($self, $peg1, $peg2) = @_;
1720        # Declare the return values. We'll start with the coupling ID and undefine the
1721        # flag and score until we have more information.
1722        my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);
1723        # Find the coupling data.
1724        my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1725                                     "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1726                                     [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1727        # Check to see if we found anything.
1728        if (!@pegs) {
1729            Trace("No coupling found.") if T(Coupling => 4);
1730            # No coupling, so undefine the return value.
1731            $retVal = undef;
1732        } else {
1733            # We have a coupling! Get the score and check for inversion.
1734            $score = $pegs[0]->[1];
1735            my $firstFound = $pegs[0]->[0];
1736            $inverted = ($firstFound ne $peg1);
1737            Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1738        }
1739        # Return the result.
1740        return ($retVal, $inverted, $score);
1741    }
1742    
1743    =head3 CouplingID
1744    
1745    C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>
1746    
1747    Return the coupling ID for a pair of feature IDs.
1748    
1749    The coupling ID is currently computed by joining the feature IDs in
1750    sorted order with a space. Client modules (that is, modules which
1751    use Sprout) should not, however, count on this always being the
1752    case. This method provides a way for abstracting the concept of a
1753    coupling ID. All that we know for sure about it is that it can be
1754    generated easily from the feature IDs and the order of the IDs
1755    in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>
1756    will have the same value as C<CouplingID("b1", "a1")>.
1757    
1758    =over 4
1759    
1760    =item peg1
1761    
1762    First feature of interest.
1763    
1764    =item peg2
1765    
1766    Second feature of interest.
1767    
1768    =item RETURN
1769    
1770    Returns the ID that would be used to represent a functional coupling of
1771    the two specified PEGs.
1772    
1773    =back
1774    
1775    =cut
1776    #: Return Type $;
1777    sub CouplingID {
1778        return join " ", sort @_;
1779    }
1780    
1781  =head3 GetEntityTypes  =head3 GetEntityTypes
1782    
1783  C<< my @entityList = $sprout->GetEntityTypes(); >>  C<< my @entityList = $sprout->GetEntityTypes(); >>
# Line 1439  Line 1839 
1839                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1840                          # 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.
1841                          if ($id) {                          if ($id) {
1842                                  $retVal{$id} = uc $sequence;                  $retVal{$id} = lc $sequence;
1843                          }                          }
1844                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
1845                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
1846                  } else {                  } else {
1847                          # 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.
1848                          # 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
1849                          # case.                          # case.
1850                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
1851                          $sequence .= $1;                          $sequence .= $1;
# Line 1453  Line 1853 
1853          }          }
1854          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
1855          if ($sequence) {          if ($sequence) {
1856                  $retVal{$id} = uc $sequence;          $retVal{$id} = lc $sequence;
1857          }          }
1858          # Close the file.          # Close the file.
1859          close FASTAFILE;          close FASTAFILE;
# Line 1572  Line 1972 
1972  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
1973  property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.  property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
1974    
1975  C<< $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence = 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>  C<< $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>
1976    
1977  =over 4  =over 4
1978    
# Line 1779  Line 2179 
2179          # Get the parameters.          # Get the parameters.
2180          my ($self, $entityName, $entityID) = @_;          my ($self, $entityName, $entityID) = @_;
2181          # Check for the entity instance.          # Check for the entity instance.
2182        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
2183          my $testInstance = $self->GetEntity($entityName, $entityID);          my $testInstance = $self->GetEntity($entityName, $entityID);
2184          # Return an existence indicator.          # Return an existence indicator.
2185          my $retVal = ($testInstance ? 1 : 0);          my $retVal = ($testInstance ? 1 : 0);
# Line 1970  Line 2371 
2371          return @retVal;          return @retVal;
2372  }  }
2373    
2374    =head3 GetProperties
2375    
2376    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2377    
2378    Return a list of the properties with the specified characteristics.
2379    
2380    Properties are arbitrary key-value pairs associated with a feature. (At some point they
2381    will also be associated with genomes.) A property value is represented by a 4-tuple of
2382    the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2383    
2384    =over 4
2385    
2386    =item fid
2387    
2388    ID of the feature possessing the property.
2389    
2390    =item key
2391    
2392    Name or key of the property.
2393    
2394    =item value
2395    
2396    Value of the property.
2397    
2398    =item url
2399    
2400    URL of the document that indicated the property should have this particular value, or an
2401    empty string if no such document exists.
2402    
2403    =back
2404    
2405    The parameters act as a filter for the desired data. Any non-null parameter will
2406    automatically match all the tuples returned. So, specifying just the I<$fid> will
2407    return all the properties of the specified feature; similarly, specifying the I<$key>
2408    and I<$value> parameters will return all the features having the specified property
2409    value.
2410    
2411    A single property key can have many values, representing different ideas about the
2412    feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2413    virulent, and another may declare that it is not virulent. A query about the virulence of
2414    C<fig|83333.1.peg.10> would be coded as
2415    
2416        my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2417    
2418    Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2419    not to be filtered. The tuples returned would be
2420    
2421        ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2422        ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2423    
2424    =cut
2425    #: Return Type @@;
2426    sub GetProperties {
2427        # Get the parameters.
2428        my ($self, @parms) = @_;
2429        # Declare the return variable.
2430        my @retVal = ();
2431        # Now we need to create a WHERE clause that will get us the data we want. First,
2432        # we create a list of the columns containing the data for each parameter.
2433        my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2434                        'Property(property-value)', 'HasProperty(evidence)');
2435        # Now we build the WHERE clause and the list of parameter values.
2436        my @where = ();
2437        my @values = ();
2438        for (my $i = 0; $i <= $#colNames; $i++) {
2439            my $parm = $parms[$i];
2440            if (defined $parm && ($parm ne '')) {
2441                push @where, "$colNames[$i] = ?";
2442                push @values, $parm;
2443            }
2444        }
2445        # Format the WHERE clause.
2446        my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2447        # Ask for all the propertie values with the desired characteristics.
2448        my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2449        while (my $valueObject = $query->Fetch()) {
2450            my @tuple = $valueObject->Values(\@colNames);
2451            push @retVal, \@tuple;
2452        }
2453        # Return the result.
2454        return @retVal;
2455    }
2456    
2457  =head3 FeatureProperties  =head3 FeatureProperties
2458    
2459  C<< my @properties = $sprout->FeatureProperties($featureID); >>  C<< my @properties = $sprout->FeatureProperties($featureID); >>
# Line 2164  Line 2648 
2648  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2649    
2650  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
2651  to the role the feature performs.  to the roles the feature performs.
2652    
2653  =over 4  =over 4
2654    
# Line 2174  Line 2658 
2658    
2659  =item RETURN  =item RETURN
2660    
2661  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.
2662    
2663  =back  =back
2664    
2665  =cut  =cut
2666  #: Return Type %;  #: Return Type %@;
2667  sub SubsystemsOf {  sub SubsystemsOf {
2668          # Get the parameters.          # Get the parameters.
2669          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
2670          # Use the SSCell to connect features to subsystems.      # Get the subsystem list.
2671          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2672                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2673                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2674          # Create the return value.          # Create the return value.
2675          my %retVal = ();          my %retVal = ();
2676        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2677        # in two spreadsheet cells.
2678        my %dupHash = ();
2679          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
2680          for my $record (@subsystems) {          for my $record (@subsystems) {
2681                  $retVal{$record->[0]} = $record->[1];          # Get this subsystem and role.
2682            my ($subsys, $role) = @{$record};
2683            # Insure it's the first time for both.
2684            my $dupKey = "$subsys\n$role";
2685            if (! exists $dupHash{"$subsys\n$role"}) {
2686                $dupHash{$dupKey} = 1;
2687                push @{$retVal{$subsys}}, $role;
2688            }
2689          }          }
2690          # Return the hash.          # Return the hash.
2691          return %retVal;          return %retVal;
2692  }  }
2693    
2694    =head3 SubsystemList
2695    
2696    C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2697    
2698    Return a list containing the names of the subsystems in which the specified
2699    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2700    subsystem names, not the roles.
2701    
2702    =over 4
2703    
2704    =item featureID
2705    
2706    ID of the feature whose subsystem names are desired.
2707    
2708    =item RETURN
2709    
2710    Returns a list of the names of the subsystems in which the feature participates.
2711    
2712    =back
2713    
2714    =cut
2715    #: Return Type @;
2716    sub SubsystemList {
2717        # Get the parameters.
2718        my ($self, $featureID) = @_;
2719        # Get the list of names.
2720        my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",
2721                                    [$featureID], 'HasSSCell(from-link)');
2722        # Return the result.
2723        return @retVal;
2724    }
2725    
2726  =head3 RelatedFeatures  =head3 RelatedFeatures
2727    
2728  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2615  Line 3141 
3141      return %retVal;      return %retVal;
3142  }  }
3143    
3144    =head3 MyGenomes
3145    
3146    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
3147    
3148    Return a list of the genomes to be included in the Sprout.
3149    
3150    This method is provided for use during the Sprout load. It presumes the Genome load file has
3151    already been created. (It will be in the Sprout data directory and called either C<Genome>
3152    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3153    IDs.
3154    
3155    =over 4
3156    
3157    =item dataDir
3158    
3159    Directory containing the Sprout load files.
3160    
3161    =back
3162    
3163    =cut
3164    #: Return Type @;
3165    sub MyGenomes {
3166        # Get the parameters.
3167        my ($dataDir) = @_;
3168        # Compute the genome file name.
3169        my $genomeFileName = LoadFileName($dataDir, "Genome");
3170        # Extract the genome IDs from the files.
3171        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3172        # Return the result.
3173        return @retVal;
3174    }
3175    
3176    =head3 LoadFileName
3177    
3178    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3179    
3180    Return the name of the load file for the specified table in the specified data
3181    directory.
3182    
3183    =over 4
3184    
3185    =item dataDir
3186    
3187    Directory containing the Sprout load files.
3188    
3189    =item tableName
3190    
3191    Name of the table whose load file is desired.
3192    
3193    =item RETURN
3194    
3195    Returns the name of the file containing the load data for the specified table, or
3196    C<undef> if no load file is present.
3197    
3198    =back
3199    
3200    =cut
3201    #: Return Type $;
3202    sub LoadFileName {
3203        # Get the parameters.
3204        my ($dataDir, $tableName) = @_;
3205        # Declare the return variable.
3206        my $retVal;
3207        # Check for the various file names.
3208        if (-e "$dataDir/$tableName") {
3209            $retVal = "$dataDir/$tableName";
3210        } elsif (-e "$dataDir/$tableName.dtx") {
3211            $retVal = "$dataDir/$tableName.dtx";
3212        }
3213        # Return the result.
3214        return $retVal;
3215    }
3216    
3217  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3218    
3219  =head3 ParseAssignment  =head3 ParseAssignment
# Line 2654  Line 3253 
3253          # Declare the return value.          # Declare the return value.
3254          my @retVal = ();          my @retVal = ();
3255          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3256          my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3257          if ($type =~ m/^set ([^ ]+) function to$/i) {          if ($type =~ m/^set ([^ ]+) function to$/i) {
3258                  # Here it is, so we return the user name (which is in $1), the functional role text,                  # Here it is, so we return the user name (which is in $1), the functional role text,
3259          # and the assigning user.          # and the assigning user.
3260                  @retVal = ($1, $function, $user);          @retVal = ($1, $function);
3261          }          }
3262          # Return the result list.          # Return the result list.
3263          return @retVal;          return @retVal;
# Line 2686  Line 3285 
3285    
3286  sub FriendlyTimestamp {  sub FriendlyTimestamp {
3287      my ($timeValue) = @_;      my ($timeValue) = @_;
3288      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
3289      return $retVal;      return $retVal;
3290  }  }
3291    
3292    =head3 AddProperty
3293    
3294    C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>
3295    
3296    Add a new attribute value (Property) to a feature. In the SEED system, attributes can
3297    be added to almost any object. In Sprout, they can only be added to features. In
3298    Sprout, attributes are implemented using I<properties>. A property represents a key/value
3299    pair. If the particular key/value pair coming in is not already in the database, a new
3300    B<Property> record is created to hold it.
3301    
3302    =over 4
3303    
3304    =item peg
3305    
3306    ID of the feature to which the attribute is to be replied.
3307    
3308    =item key
3309    
3310    Name of the attribute (key).
3311    
3312    =item value
3313    
3314    Value of the attribute.
3315    
3316    =item url
3317    
3318    URL or text citation from which the property was obtained.
3319    
3320    =back
3321    
3322    =cut
3323    #: Return Type ;
3324    sub AddProperty {
3325        # Get the parameters.
3326        my ($self, $featureID, $key, $value, $url) = @_;
3327        # Declare the variable to hold the desired property ID.
3328        my $propID;
3329        # Attempt to find a property record for this key/value pair.
3330        my @properties = $self->GetFlat(['Property'],
3331                                       "Property(property-name) = ? AND Property(property-value) = ?",
3332                                       [$key, $value], 'Property(id)');
3333        if (@properties) {
3334            # Here the property is already in the database. We save its ID.
3335            $propID = $properties[0];
3336            # Here the property value does not exist. We need to generate an ID. It will be set
3337            # to a number one greater than the maximum value in the database. This call to
3338            # GetAll will stop after one record.
3339            my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],
3340                                            1);
3341            $propID = $maxProperty[0]->[0] + 1;
3342            # Insert the new property value.
3343            $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });
3344        }
3345        # Now we connect the incoming feature to the property.
3346        $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3347    }
3348    
3349    
3350    
3351  1;  1;

Legend:
Removed from v.1.14  
changed lines
  Added in v.1.46

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3