[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.46, Thu Oct 20 11:52:36 2005 UTC revision 1.93, Sun Oct 22 05:15:56 2006 UTC
# Line 1  Line 1 
1  package Sprout;  package Sprout;
2    
3        require Exporter;
4        use ERDB;
5        @ISA = qw(Exporter ERDB);
6      use Data::Dumper;      use Data::Dumper;
7      use strict;      use strict;
8      use Carp;      use Carp;
# Line 7  Line 10 
10      use XML::Simple;      use XML::Simple;
11      use DBQuery;      use DBQuery;
12      use DBObject;      use DBObject;
     use ERDB;  
13      use Tracer;      use Tracer;
14      use FIGRules;      use FIGRules;
15        use FidCheck;
16      use Stats;      use Stats;
17      use POSIX qw(strftime);      use POSIX qw(strftime);
18        use BasicLocation;
19    
20  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
21    
# Line 32  Line 35 
35  query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and  query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and
36  L</dna_seq> returns the DNA sequence for a specified genome location.  L</dna_seq> returns the DNA sequence for a specified genome location.
37    
38    The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.
39    
40  =cut  =cut
41    
42  #: Constructor SFXlate->new_sprout_only();  #: Constructor SFXlate->new_sprout_only();
# Line 62  Line 67 
67    
68  * 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>)
69    
70  * 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)
71    
72  * B<port> connection port (default C<0>)  * B<port> connection port (default C<0>)
73    
74    * B<sock> connection socket (default same as SEED)
75    
76  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
77    
78  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
# Line 85  Line 92 
92  sub new {  sub new {
93      # Get the parameters.      # Get the parameters.
94      my ($class, $dbName, $options) = @_;      my ($class, $dbName, $options) = @_;
95        # Compute the DBD directory.
96        my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
97                                                      $FIG_Config::fig );
98      # Compute the options. We do this by starting with a table of defaults and overwriting with      # Compute the options. We do this by starting with a table of defaults and overwriting with
99      # the incoming data.      # the incoming data.
100      my $optionTable = Tracer::GetOptions({      my $optionTable = Tracer::GetOptions({
# Line 92  Line 102 
102                                                          # database type                                                          # database type
103                         dataDir      => $FIG_Config::sproutData,                         dataDir      => $FIG_Config::sproutData,
104                                                          # data file directory                                                          # data file directory
105                         xmlFileName  => "$FIG_Config::sproutData/SproutDBD.xml",                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
106                                                          # database definition file name                                                          # database definition file name
107                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
108                                                          # user name and password                                                          # user name and password
109                         port         => $FIG_Config::dbport,                         port         => $FIG_Config::dbport,
110                                                          # database connection port                                                          # database connection port
111                           sock         => $FIG_Config::dbsock,
112                           host         => $FIG_Config::dbhost,
113                         maxSegmentLength => 4500,        # maximum feature segment length                         maxSegmentLength => 4500,        # maximum feature segment length
114                         maxSequenceLength => 8000,       # maximum contig sequence length                         maxSequenceLength => 8000,       # maximum contig sequence length
115                         noDBOpen     => 0,               # 1 to suppress the database open                         noDBOpen     => 0,               # 1 to suppress the database open
# Line 111  Line 123 
123      my $dbh;      my $dbh;
124      if (! $optionTable->{noDBOpen}) {      if (! $optionTable->{noDBOpen}) {
125          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
126                                  $password, $optionTable->{port});                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
127      }      }
128      # Create the ERDB object.      # Create the ERDB object.
129      my $xmlFileName = "$optionTable->{xmlFileName}";      my $xmlFileName = "$optionTable->{xmlFileName}";
130      my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
131      # Create this object.      # Add the option table and XML file name.
132      my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
133      # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
134      bless $self;      # Set up space for the group file data.
135      return $self;      $retVal->{groupHash} = undef;
136        # Return it.
137        return $retVal;
138  }  }
139    
140  =head3 MaxSegment  =head3 MaxSegment
# Line 155  Line 169 
169      return $self->{_options}->{maxSequenceLength};      return $self->{_options}->{maxSequenceLength};
170  }  }
171    
 =head3 Get  
   
 C<< my $query = $sprout->Get(\@objectNames, $filterClause, \@parameterList); >>  
   
 This method allows a general query against the Sprout data using a specified filter clause.  
   
 The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each  
 field name represented in the form B<I<objectName>(I<fieldName>)>. For example, the  
 following call requests all B<Genome> objects for the genus specified in the variable  
 $genus.  
   
 C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>  
   
 The WHERE clause contains a single question mark, so there is a single additional  
 parameter representing the parameter value. It would also be possible to code  
   
 C<< $query = $sprout->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>  
   
 however, this version of the call would generate a syntax error if there were any quote  
 characters inside the variable C<$genus>.  
   
 The use of the strange parenthesized notation for field names enables us to distinguish  
 hyphens contained within field names from minus signs that participate in the computation  
 of the WHERE clause. All of the methods that manipulate fields will use this same notation.  
   
 It is possible to specify multiple entity and relationship names in order to retrieve more than  
 one object's data at the same time, which allows highly complex joined queries. For example,  
   
 C<< $query = $sprout->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>  
   
 This query returns all the genomes for a particular genus and allows access to the  
 sources from which they came. The join clauses to go from Genome to Source are generated  
 automatically.  
   
 Finally, the filter clause can contain sort information. To do this, simply put an C<ORDER BY>  
 clause at the end of the filter. Field references in the ORDER BY section follow the same rules  
 as they do in the filter itself; in other words, each one must be of the form B<I<objectName>(I<fieldName>)>.  
 For example, the following filter string gets all genomes for a particular genus and sorts  
 them by species name.  
   
 C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ? ORDER BY Genome(species)", [$genus]); >>  
   
 It is also permissible to specify I<only> an ORDER BY clause. For example, the following invocation gets  
 all genomes ordered by genus and species.  
   
 C<< $query = $sprout->Get(['Genome'], "ORDER BY Genome(genus), Genome(species)"); >>  
   
 Odd things may happen if one of the ORDER BY fields is in a secondary relation. So, for example, an  
 attempt to order B<Feature>s by alias may (depending on the underlying database engine used) cause  
 a single feature to appear more than once.  
   
 If multiple names are specified, then the query processor will automatically determine a  
 join path between the entities and relationships. The algorithm used is very simplistic.  
 In particular, you can't specify any entity or relationship more than once, and if a  
 relationship is recursive, the path is determined by the order in which the entity  
 and the relationship appear. For example, consider a recursive relationship B<IsParentOf>  
 which relates B<People> objects to other B<People> objects. If the join path is  
 coded as C<['People', 'IsParentOf']>, then the people returned will be parents. If, however,  
 the join path is C<['IsParentOf', 'People']>, then the people returned will be children.  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item RETURN  
   
 Returns a B<DBQuery> that can be used to iterate through all of the results.  
   
 =back  
   
 =cut  
   
 sub Get {  
     # Get the parameters.  
     my ($self, $objectNames, $filterClause, $parameterList) = @_;  
     # We differ from the ERDB Get method in that the parameter list is passed in as a list reference  
     # rather than a list of parameters. The next step is to convert the parameters from a reference  
     # to a real list. We can only do this if the parameters have been specified.  
     my @parameters;  
     if ($parameterList) { @parameters = @{$parameterList}; }  
     return $self->{_erdb}->Get($objectNames, $filterClause, @parameters);  
 }  
   
 =head3 GetEntity  
   
 C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>  
   
 Return an object describing the entity instance with a specified ID.  
   
 =over 4  
   
 =item entityType  
   
 Entity type name.  
   
 =item ID  
   
 ID of the desired entity.  
   
 =item RETURN  
   
 Returns a B<DBObject> representing the desired entity instance, or an undefined value if no  
 instance is found with the specified key.  
   
 =back  
   
 =cut  
   
 sub GetEntity {  
     # Get the parameters.  
     my ($self, $entityType, $ID) = @_;  
     # Call the ERDB method.  
     return $self->{_erdb}->GetEntity($entityType, $ID);  
 }  
   
 =head3 GetEntityValues  
   
 C<< my @values = GetEntityValues($entityType, $ID, \@fields); >>  
   
 Return a list of values from a specified entity instance.  
   
 =over 4  
   
 =item entityType  
   
 Entity type name.  
   
 =item ID  
   
 ID of the desired entity.  
   
 =item fields  
   
 List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.  
   
 =item RETURN  
   
 Returns a flattened list of the values of the specified fields for the specified entity.  
   
 =back  
   
 =cut  
 #: Return Type @;  
 sub GetEntityValues {  
     # Get the parameters.  
     my ($self, $entityType, $ID, $fields) = @_;  
     # Call the ERDB method.  
     return $self->{_erdb}->GetEntityValues($entityType, $ID, $fields);  
 }  
   
 =head3 ShowMetaData  
   
 C<< $sprout->ShowMetaData($fileName); >>  
   
 This method outputs a description of the database to an HTML file in the data directory.  
   
 =over 4  
   
 =item fileName  
   
 Fully-qualified name to give to the output file.  
   
 =back  
   
 =cut  
   
 sub ShowMetaData {  
     # Get the parameters.  
     my ($self, $fileName) = @_;  
     # Compute the file name.  
     my $options = $self->{_options};  
     # Call the show method on the underlying ERDB object.  
     $self->{_erdb}->ShowMetaData($fileName);  
 }  
   
172  =head3 Load  =head3 Load
173    
174  C<< $sprout->Load($rebuild); >>;  C<< $sprout->Load($rebuild); >>;
# Line 379  Line 203 
203  sub Load {  sub Load {
204      # Get the parameters.      # Get the parameters.
205      my ($self, $rebuild) = @_;      my ($self, $rebuild) = @_;
     # Get the database object.  
     my $erdb = $self->{_erdb};  
206      # Load the tables from the data directory.      # Load the tables from the data directory.
207      my $retVal = $erdb->LoadTables($self->{_options}->{dataDir}, $rebuild);      my $retVal = $self->LoadTables($self->{_options}->{dataDir}, $rebuild);
208      # Return the statistics.      # Return the statistics.
209      return $retVal;      return $retVal;
210  }  }
# Line 422  Line 244 
244  sub LoadUpdate {  sub LoadUpdate {
245      # Get the parameters.      # Get the parameters.
246      my ($self, $truncateFlag, $tableList) = @_;      my ($self, $truncateFlag, $tableList) = @_;
     # Get the database object.  
     my $erdb = $self->{_erdb};  
247      # Declare the return value.      # Declare the return value.
248      my $retVal = Stats->new();      my $retVal = Stats->new();
249      # Get the data directory.      # Get the data directory.
# Line 437  Line 257 
257              Trace("No load file found for $tableName in $dataDir.") if T(0);              Trace("No load file found for $tableName in $dataDir.") if T(0);
258          } else {          } else {
259              # Attempt to load this table.              # Attempt to load this table.
260              my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);              my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);
261              # Accumulate the resulting statistics.              # Accumulate the resulting statistics.
262              $retVal->Accumulate($result);              $retVal->Accumulate($result);
263          }          }
# Line 446  Line 266 
266      return $retVal;      return $retVal;
267  }  }
268    
269    =head3 GenomeCounts
270    
271    C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>
272    
273    Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
274    genomes will be included in the counts.
275    
276    =over 4
277    
278    =item complete
279    
280    TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
281    counted
282    
283    =item RETURN
284    
285    A six-element list containing the number of genomes in each of six categories--
286    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
287    
288    =back
289    
290    =cut
291    
292    sub GenomeCounts {
293        # Get the parameters.
294        my ($self, $complete) = @_;
295        # Set the filter based on the completeness flag.
296        my $filter = ($complete ? "Genome(complete) = 1" : "");
297        # Get all the genomes and the related taxonomy information.
298        my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
299        # Clear the counters.
300        my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
301        # Loop through, counting the domains.
302        for my $genome (@genomes) {
303            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
304            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
305            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
306            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
307            elsif ($genome->[1] =~ /^env/i)      { ++$env }
308            else  { ++$unk }
309        }
310        # Return the counts.
311        return ($arch, $bact, $euk, $vir, $env, $unk);
312    }
313    
314    =head3 ContigCount
315    
316    C<< my $count = $sprout->ContigCount($genomeID); >>
317    
318    Return the number of contigs for the specified genome ID.
319    
320    =over 4
321    
322    =item genomeID
323    
324    ID of the genome whose contig count is desired.
325    
326    =item RETURN
327    
328    Returns the number of contigs for the specified genome.
329    
330    =back
331    
332    =cut
333    
334    sub ContigCount {
335        # Get the parameters.
336        my ($self, $genomeID) = @_;
337        # Get the contig count.
338        my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
339        # Return the result.
340        return $retVal;
341    }
342    
343    =head3 GeneMenu
344    
345    C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected); >>
346    
347    Return an HTML select menu of genomes. Each genome will be an option in the menu,
348    and will be displayed by name with the ID and a contig count attached. The selection
349    value will be the genome ID. The genomes will be sorted by genus/species name.
350    
351    =over 4
352    
353    =item attributes
354    
355    Reference to a hash mapping attributes to values for the SELECT tag generated.
356    
357    =item filterString
358    
359    A filter string for use in selecting the genomes. The filter string must conform
360    to the rules for the C<< ERDB->Get >> method.
361    
362    =item params
363    
364    Reference to a list of values to be substituted in for the parameter marks in
365    the filter string.
366    
367    =item selected (optional)
368    
369    ID of the genome to be initially selected.
370    
371    =item fast (optional)
372    
373    If specified and TRUE, the contig counts will be omitted to improve performance.
374    
375    =item RETURN
376    
377    Returns an HTML select menu with the specified genomes as selectable options.
378    
379    =back
380    
381    =cut
382    
383    sub GeneMenu {
384        # Get the parameters.
385        my ($self, $attributes, $filterString, $params, $selected, $fast) = @_;
386        my $slowMode = ! $fast;
387        # Default to nothing selected. This prevents an execution warning if "$selected"
388        # is undefined.
389        $selected = "" unless defined $selected;
390        Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3);
391        # Start the menu.
392        my $retVal = "<select " .
393            join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
394            ">\n";
395        # Get the genomes.
396        my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
397                                                                         'Genome(genus)',
398                                                                         'Genome(species)',
399                                                                         'Genome(unique-characterization)']);
400        # Sort them by name.
401        my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
402        # Loop through the genomes, creating the option tags.
403        for my $genomeData (@sorted) {
404            # Get the data for this genome.
405            my ($genomeID, $genus, $species, $strain) = @{$genomeData};
406            # Get the contig count.
407            my $contigInfo = "";
408            if ($slowMode) {
409                my $count = $self->ContigCount($genomeID);
410                my $counting = ($count == 1 ? "contig" : "contigs");
411                $contigInfo = "[$count $counting]";
412            }
413            # Find out if we're selected.
414            my $selectOption = ($selected eq $genomeID ? " selected" : "");
415            # Build the option tag.
416            $retVal .= "<option value=\"$genomeID\"$selectOption>$genus $species $strain ($genomeID)$contigInfo</option>\n";
417        }
418        # Close the SELECT tag.
419        $retVal .= "</select>\n";
420        # Return the result.
421        return $retVal;
422    }
423    
424  =head3 Build  =head3 Build
425    
426  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 460  Line 435 
435      # Get the parameters.      # Get the parameters.
436      my ($self) = @_;      my ($self) = @_;
437      # Create the tables.      # Create the tables.
438      $self->{_erdb}->CreateTables;      $self->CreateTables();
439  }  }
440    
441  =head3 Genomes  =head3 Genomes
# Line 680  Line 655 
655      return ($contigID, $start, $dir, $len);      return ($contigID, $start, $dir, $len);
656  }  }
657    
658    
659    
660  =head3 PointLocation  =head3 PointLocation
661    
662  C<< my $found = Sprout::PointLocation($location, $point); >>  C<< my $found = Sprout::PointLocation($location, $point); >>
# Line 740  Line 717 
717  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,
718  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>.
719    
720    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
721    between positions 1401 and 1532, inclusive.
722    
723        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
724    
725  =over 4  =over 4
726    
727  =item locationList  =item locationList
728    
729  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
730  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
731    
732  =item RETURN  =item RETURN
733    
# Line 841  Line 823 
823      return @retVal;      return @retVal;
824  }  }
825    
826    =head3 GenomeLength
827    
828    C<< my $length = $sprout->GenomeLength($genomeID); >>
829    
830    Return the length of the specified genome in base pairs.
831    
832    =over 4
833    
834    =item genomeID
835    
836    ID of the genome whose base pair count is desired.
837    
838    =item RETURN
839    
840    Returns the number of base pairs in all the contigs of the specified
841    genome.
842    
843    =back
844    
845    =cut
846    
847    sub GenomeLength {
848        # Get the parameters.
849        my ($self, $genomeID) = @_;
850        # Declare the return variable.
851        my $retVal = 0;
852        # Get the genome's contig sequence lengths.
853        my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
854                           [$genomeID], 'IsMadeUpOf(len)');
855        # Sum the lengths.
856        map { $retVal += $_ } @lens;
857        # Return the result.
858        return $retVal;
859    }
860    
861    =head3 FeatureCount
862    
863    C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
864    
865    Return the number of features of the specified type in the specified genome.
866    
867    =over 4
868    
869    =item genomeID
870    
871    ID of the genome whose feature count is desired.
872    
873    =item type
874    
875    Type of feature to count (eg. C<peg>, C<rna>, etc.).
876    
877    =item RETURN
878    
879    Returns the number of features of the specified type for the specified genome.
880    
881    =back
882    
883    =cut
884    
885    sub FeatureCount {
886        # Get the parameters.
887        my ($self, $genomeID, $type) = @_;
888        # Compute the count.
889        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
890                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
891                                    [$genomeID, $type]);
892        # Return the result.
893        return $retVal;
894    }
895    
896    =head3 GenomeAssignments
897    
898    C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
899    
900    Return a list of a genome's assigned features. The return hash will contain each
901    assigned feature of the genome mapped to the text of its most recent functional
902    assignment.
903    
904    =over 4
905    
906    =item genomeID
907    
908    ID of the genome whose functional assignments are desired.
909    
910    =item RETURN
911    
912    Returns a reference to a hash which maps each feature to its most recent
913    functional assignment.
914    
915    =back
916    
917    =cut
918    
919    sub GenomeAssignments {
920        # Get the parameters.
921        my ($self, $genomeID) = @_;
922        # Declare the return variable.
923        my $retVal = {};
924        # Query the genome's features.
925        my $query = $self->Get(['HasFeature', 'Feature'], "HasFeature(from-link) = ?",
926                               [$genomeID]);
927        # Loop through the features.
928        while (my $data = $query->Fetch) {
929            # Get the feature ID and assignment.
930            my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']);
931            if ($assignment) {
932                $retVal->{$fid} = $assignment;
933            }
934        }
935        # Return the result.
936        return $retVal;
937    }
938    
939  =head3 ContigLength  =head3 ContigLength
940    
941  C<< my $length = $sprout->ContigLength($contigID); >>  C<< my $length = $sprout->ContigLength($contigID); >>
# Line 1163  Line 1258 
1258      # Get the parameters.      # Get the parameters.
1259      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1260      # Get all of the feature's annotations.      # Get all of the feature's annotations.
1261      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1262                              "IsTargetOfAnnotation(from-link) = ?",                              "IsTargetOfAnnotation(from-link) = ?",
1263                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1264                                               'MadeAnnotation(from-link)']);
1265      # Declare the return hash.      # Declare the return hash.
1266      my %retVal;      my %retVal;
1267      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
# Line 1173  Line 1269 
1269      # Loop until we run out of annotations.      # Loop until we run out of annotations.
1270      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1271          # Get the annotation fields.          # Get the annotation fields.
1272          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1273          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
1274          my ($user, $function) = _ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1275          if ($user && ! exists $retVal{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1276              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1277              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1278              # return hash.              # return hash.
1279              $retVal{$user} = $function;              $retVal{$actualUser} = $function;
1280          }          }
1281      }      }
1282      # Return the hash of assignments found.      # Return the hash of assignments found.
# Line 1194  Line 1290 
1290  Return the most recently-determined functional assignment of a particular feature.  Return the most recently-determined functional assignment of a particular feature.
1291    
1292  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
1293  the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional  the feature is identified by a FIG ID (begins with the string C<fig|>), then the functional
1294  assignment is a type of annotation. The format of an assignment is described in  assignment is taken from the B<Feature> or C<Annotation> table, depending.
 L</ParseAssignment>. Its worth noting that we cannot filter on the content of the  
 annotation itself because it's a text field; however, this is not a big problem because  
 most features only have a small number of annotations.  
1295    
1296  Each user has an associated list of trusted users. The assignment returned will be the most  Each user has an associated list of trusted users. The assignment returned will be the most
1297  recent one by at least one of the trusted users. If no trusted user list is available, then  recent one by at least one of the trusted users. If no trusted user list is available, then
# Line 1217  Line 1310 
1310    
1311  =item userID (optional)  =item userID (optional)
1312    
1313  ID of the user whose function determination is desired. If omitted, only the latest  ID of the user whose function determination is desired. If omitted, the primary
1314  C<FIG> assignment will be returned.  functional assignment in the B<Feature> table will be returned.
1315    
1316  =item RETURN  =item RETURN
1317    
# Line 1235  Line 1328 
1328      my $retVal;      my $retVal;
1329      # Determine the ID type.      # Determine the ID type.
1330      if ($featureID =~ m/^fig\|/) {      if ($featureID =~ m/^fig\|/) {
1331          # Here we have a FIG feature ID. We must build the list of trusted          # Here we have a FIG feature ID.
1332          # users.          if (!$userID) {
1333                # Use the primary assignment.
1334                ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']);
1335            } else {
1336                # We must build the list of trusted users.
1337          my %trusteeTable = ();          my %trusteeTable = ();
1338          # Check the user ID.          # Check the user ID.
1339          if (!$userID) {          if (!$userID) {
# Line 1258  Line 1355 
1355              }              }
1356          }          }
1357          # 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.
1358          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],              my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1359                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1360                                 [$featureID]);                                 [$featureID]);
1361          my $timeSelected = 0;          my $timeSelected = 0;
1362          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1363          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1364              # Get the annotation text.              # Get the annotation text.
1365              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);                  my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1366                                                             'Annotation(time)', 'MadeAnnotation(from-link)']);
1367              # 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.
1368              my ($user, $function) = _ParseAssignment($text);                  my ($actualUser, $function) = _ParseAssignment($user, $text);
1369              if ($user) {                  Trace("Assignment user is $actualUser, text is $function.") if T(4);
1370                    if ($actualUser) {
1371                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1372                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1373                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                      if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1374                      $retVal = $function;                      $retVal = $function;
1375                      $timeSelected = $time;                      $timeSelected = $time;
1376                  }                  }
1377              }              }
1378          }          }
1379            }
1380      } else {      } else {
1381          # Here we have a non-FIG feature ID. In this case the user ID does not          # Here we have a non-FIG feature ID. In this case the user ID does not
1382          # matter. We simply get the information from the External Alias Function          # matter. We simply get the information from the External Alias Function
# Line 1330  Line 1430 
1430          # users.          # users.
1431          my %trusteeTable = ();          my %trusteeTable = ();
1432          # 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.
1433          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1434                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1435                                 [$featureID]);                                 [$featureID]);
1436          my $timeSelected = 0;          my $timeSelected = 0;
1437          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1438          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1439              # Get the annotation text.              # Get the annotation text.
1440              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);              my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1441                                                                'Annotation(time)',
1442                                                                'MadeAnnotation(user)']);
1443              # 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.
1444              my ($user, $function) = _ParseAssignment($text);              my ($actualUser, $function) = _ParseAssignment($user, $text);
1445              if ($user) {              if ($actualUser) {
1446                  # Here it is a functional assignment.                  # Here it is a functional assignment.
1447                  push @retVal, [$user, $function];                  push @retVal, [$actualUser, $function];
1448              }              }
1449          }          }
1450      } else {      } else {
1451          # Here we have a non-FIG feature ID. In this case the user ID does not          # Here we have a non-FIG feature ID. In this case the user ID does not
1452          # matter. We simply get the information from the External Alias Function          # matter. We simply get the information from the External Alias Function
1453          # table.          # table.
1454          push @retVal, $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']);          my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1455                                                     ['ExternalAliasFunc(func)']);
1456            push @retVal, map { ['master', $_] } @assignments;
1457      }      }
1458      # Return the assignments found.      # Return the assignments found.
1459      return @retVal;      return @retVal;
# Line 1388  Line 1492 
1492      my %retVal = ();      my %retVal = ();
1493      # Loop through the incoming features.      # Loop through the incoming features.
1494      for my $featureID (@{$featureList}) {      for my $featureID (@{$featureList}) {
1495          # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1496          my $query = $self->Get(['IsBidirectionalBestHitOf'],          my @bbhData = FIGRules::BBHData($featureID);
                                "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",  
                                [$featureID, $genomeID]);  
1497          # Peel off the BBHs found.          # Peel off the BBHs found.
1498          my @found = ();          my @found = ();
1499          while (my $bbh = $query->Fetch) {          for my $bbh (@bbhData) {
1500              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');              push @found, $bbh->[0];
1501          }          }
1502          $retVal{$featureID} = \@found;          $retVal{$featureID} = \@found;
1503      }      }
# Line 1409  Line 1511 
1511    
1512  Return a list of the similarities to the specified feature.  Return a list of the similarities to the specified feature.
1513    
1514  Sprout does not support real similarities, so this method just returns the bidirectional  This method just returns the bidirectional best hits for performance reasons.
 best hits.  
1515    
1516  =over 4  =over 4
1517    
# Line 1430  Line 1531 
1531      # Get the parameters.      # Get the parameters.
1532      my ($self, $featureID, $count) = @_;      my ($self, $featureID, $count) = @_;
1533      # Ask for the best hits.      # Ask for the best hits.
1534      my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],      my @lists = FIGRules::BBHData($featureID);
                               "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",  
                               [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],  
                               $count);  
1535      # Create the return value.      # Create the return value.
1536      my %retVal = ();      my %retVal = ();
1537      for my $tuple (@lists) {      for my $tuple (@lists) {
# Line 1443  Line 1541 
1541      return %retVal;      return %retVal;
1542  }  }
1543    
   
   
1544  =head3 IsComplete  =head3 IsComplete
1545    
1546  C<< my $flag = $sprout->IsComplete($genomeID); >>  C<< my $flag = $sprout->IsComplete($genomeID); >>
# Line 1475  Line 1571 
1571      my $genomeData = $self->GetEntity('Genome', $genomeID);      my $genomeData = $self->GetEntity('Genome', $genomeID);
1572      if ($genomeData) {      if ($genomeData) {
1573          # The genome exists, so get the completeness flag.          # The genome exists, so get the completeness flag.
1574          ($retVal) = $genomeData->Value('complete');          ($retVal) = $genomeData->Value('Genome(complete)');
1575      }      }
1576      # Return the result.      # Return the result.
1577      return $retVal;      return $retVal;
# Line 1515  Line 1611 
1611    
1612  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1613    
1614  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1615    
1616  =over 4  =over 4
1617    
1618  =item featureID  =item featureID
1619    
1620  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1621    
1622  =item RETURN  =item RETURN
1623    
1624  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
1625  an undefined value.  found, returns an undefined value.
1626    
1627  =back  =back
1628    
# Line 1535  Line 1631 
1631  sub GenomeOf {  sub GenomeOf {
1632      # Get the parameters.      # Get the parameters.
1633      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1634      # Create a query to find the genome associated with the feature.      # Create a query to find the genome associated with the incoming ID.
1635      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1636                               [$featureID, $featureID]);
1637      # Declare the return value.      # Declare the return value.
1638      my $retVal;      my $retVal;
1639      # Get the genome ID.      # Get the genome ID.
# Line 1571  Line 1668 
1668  sub CoupledFeatures {  sub CoupledFeatures {
1669      # Get the parameters.      # Get the parameters.
1670      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1671        Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1672      # Create a query to retrieve the functionally-coupled features.      # Create a query to retrieve the functionally-coupled features.
1673      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1674                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);
# Line 1583  Line 1681 
1681          # Get the ID and score of the coupling.          # Get the ID and score of the coupling.
1682          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1683                                                          'Coupling(score)']);                                                          'Coupling(score)']);
1684          # The coupling ID contains the two feature IDs separated by a space. We use          Trace("$featureID coupled with score $score to ID $couplingID.") if T(coupling => 4);
1685          # this information to find the ID of the other feature.          # Get the other feature that participates in the coupling.
1686          my ($fid1, $fid2) = split / /, $couplingID;          my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],
1687          my $otherFeatureID = ($featureID eq $fid1 ? $fid2 : $fid1);                                             "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",
1688                                               [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');
1689            Trace("$couplingID target feature is $otherFeatureID.") if T(coupling => 4);
1690          # Attach the other feature's score to its ID.          # Attach the other feature's score to its ID.
1691          $retVal{$otherFeatureID} = $score;          $retVal{$otherFeatureID} = $score;
1692          $found = 1;          $found = 1;
# Line 1719  Line 1819 
1819      my ($self, $peg1, $peg2) = @_;      my ($self, $peg1, $peg2) = @_;
1820      # Declare the return values. We'll start with the coupling ID and undefine the      # Declare the return values. We'll start with the coupling ID and undefine the
1821      # flag and score until we have more information.      # flag and score until we have more information.
1822      my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);      my ($retVal, $inverted, $score) = ($self->CouplingID($peg1, $peg2), undef, undef);
1823      # Find the coupling data.      # Find the coupling data.
1824      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1825                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
# Line 1740  Line 1840 
1840      return ($retVal, $inverted, $score);      return ($retVal, $inverted, $score);
1841  }  }
1842    
1843  =head3 CouplingID  =head3 GetSynonymGroup
1844    
1845  C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>  C<< my $id = $sprout->GetSynonymGroup($fid); >>
1846    
1847  Return the coupling ID for a pair of feature IDs.  Return the synonym group name for the specified feature.
1848    
1849    =over 4
1850    
1851    =item fid
1852    
1853    ID of the feature whose synonym group is desired.
1854    
1855    =item RETURN
1856    
1857    The name of the synonym group to which the feature belongs. If the feature does
1858    not belong to a synonym group, the feature ID itself is returned.
1859    
1860    =back
1861    
1862    =cut
1863    
1864    sub GetSynonymGroup {
1865        # Get the parameters.
1866        my ($self, $fid) = @_;
1867        # Declare the return variable.
1868        my $retVal;
1869        # Find the synonym group.
1870        my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1871                                       [$fid], 'IsSynonymGroupFor(from-link)');
1872        # Check to see if we found anything.
1873        if (@groups) {
1874            $retVal = $groups[0];
1875        } else {
1876            $retVal = $fid;
1877        }
1878        # Return the result.
1879        return $retVal;
1880    }
1881    
1882    =head3 GetBoundaries
1883    
1884    C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>
1885    
1886    Determine the begin and end boundaries for the locations in a list. All of the
1887    locations must belong to the same contig and have mostly the same direction in
1888    order for this method to produce a meaningful result. The resulting
1889    begin/end pair will contain all of the bases in any of the locations.
1890    
1891    =over 4
1892    
1893    =item locList
1894    
1895    List of locations to process.
1896    
1897    =item RETURN
1898    
1899    Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1900    and the ending boundary. The beginning boundary will be left of the
1901    end for mostly-forward locations and right of the end for mostly-backward
1902    locations.
1903    
1904    =back
1905    
1906    =cut
1907    
1908    sub GetBoundaries {
1909        # Get the parameters.
1910        my ($self, @locList) = @_;
1911        # Set up the counters used to determine the most popular direction.
1912        my %counts = ( '+' => 0, '-' => 0 );
1913        # Get the last location and parse it.
1914        my $locObject = BasicLocation->new(pop @locList);
1915        # Prime the loop with its data.
1916        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
1917        # Count its direction.
1918        $counts{$locObject->Dir}++;
1919        # Loop through the remaining locations. Note that in most situations, this loop
1920        # will not iterate at all, because most of the time we will be dealing with a
1921        # singleton list.
1922        for my $loc (@locList) {
1923            # Create a location object.
1924            my $locObject = BasicLocation->new($loc);
1925            # Count the direction.
1926            $counts{$locObject->Dir}++;
1927            # Get the left end and the right end.
1928            my $left = $locObject->Left;
1929            my $right = $locObject->Right;
1930            # Merge them into the return variables.
1931            if ($left < $beg) {
1932                $beg = $left;
1933            }
1934            if ($right > $end) {
1935                $end = $right;
1936            }
1937        }
1938        # If the most common direction is reverse, flip the begin and end markers.
1939        if ($counts{'-'} > $counts{'+'}) {
1940            ($beg, $end) = ($end, $beg);
1941        }
1942        # Return the result.
1943        return ($contig, $beg, $end);
1944    }
1945    
1946    =head3 CouplingID
1947    
1948    C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >>
1949    
1950    Return the coupling ID for a pair of feature IDs.
1951    
1952  The coupling ID is currently computed by joining the feature IDs in  The coupling ID is currently computed by joining the feature IDs in
1953  sorted order with a space. Client modules (that is, modules which  sorted order with a space. Client modules (that is, modules which
# Line 1775  Line 1978 
1978  =cut  =cut
1979  #: Return Type $;  #: Return Type $;
1980  sub CouplingID {  sub CouplingID {
1981      return join " ", sort @_;      my ($self, @pegs) = @_;
1982  }      return $self->DigestKey(join " ", sort @pegs);
   
 =head3 GetEntityTypes  
   
 C<< my @entityList = $sprout->GetEntityTypes(); >>  
   
 Return the list of supported entity types.  
   
 =cut  
 #: Return Type @;  
 sub GetEntityTypes {  
     # Get the parameters.  
     my ($self) = @_;  
     # Get the underlying database object.  
     my $erdb = $self->{_erdb};  
     # Get its entity type list.  
     my @retVal = $erdb->GetEntityTypes();  
1983  }  }
1984    
1985  =head3 ReadFasta  =head3 ReadFasta
# Line 1940  Line 2127 
2127      # Get the data directory name.      # Get the data directory name.
2128      my $outputDirectory = $self->{_options}->{dataDir};      my $outputDirectory = $self->{_options}->{dataDir};
2129      # Dump the relations.      # Dump the relations.
2130      $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2131  }  }
2132    
2133  =head3 XMLFileName  =head3 XMLFileName
# Line 1992  Line 2179 
2179      # Get the parameters.      # Get the parameters.
2180      my ($self, $objectType, $fieldHash) = @_;      my ($self, $objectType, $fieldHash) = @_;
2181      # Call the underlying method.      # Call the underlying method.
2182      $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2183  }  }
2184    
2185  =head3 Annotate  =head3 Annotate
# Line 2151  Line 2338 
2338      return @retVal;      return @retVal;
2339  }  }
2340    
 =head3 Exists  
   
 C<< my $found = $sprout->Exists($entityName, $entityID); >>  
   
 Return TRUE if an entity exists, else FALSE.  
   
 =over 4  
   
 =item entityName  
   
 Name of the entity type (e.g. C<Feature>) relevant to the existence check.  
   
 =item entityID  
   
 ID of the entity instance whose existence is to be checked.  
   
 =item RETURN  
   
 Returns TRUE if the entity instance exists, else FALSE.  
   
 =back  
   
 =cut  
 #: Return Type $;  
 sub Exists {  
     # Get the parameters.  
     my ($self, $entityName, $entityID) = @_;  
     # Check for the entity instance.  
     Trace("Checking existence of $entityName with ID=$entityID.") if T(4);  
     my $testInstance = $self->GetEntity($entityName, $entityID);  
     # Return an existence indicator.  
     my $retVal = ($testInstance ? 1 : 0);  
     return $retVal;  
 }  
   
2341  =head3 FeatureTranslation  =head3 FeatureTranslation
2342    
2343  C<< my $translation = $sprout->FeatureTranslation($featureID); >>  C<< my $translation = $sprout->FeatureTranslation($featureID); >>
# Line 2520  Line 2672 
2672      return $retVal;      return $retVal;
2673  }  }
2674    
2675    =head3 PropertyID
2676    
2677    C<< my $id = $sprout->PropertyID($propName, $propValue); >>
2678    
2679    Return the ID of the specified property name and value pair, if the
2680    pair exists.
2681    
2682    =over 4
2683    
2684    =item propName
2685    
2686    Name of the desired property.
2687    
2688    =item propValue
2689    
2690    Value expected for the desired property.
2691    
2692    =item RETURN
2693    
2694    Returns the ID of the name/value pair, or C<undef> if the pair does not exist.
2695    
2696    =back
2697    
2698    =cut
2699    
2700    sub PropertyID {
2701        # Get the parameters.
2702        my ($self, $propName, $propValue) = @_;
2703        # Try to find the ID.
2704        my ($retVal) = $self->GetFlat(['Property'],
2705                                      "Property(property-name) = ? AND Property(property-value) = ?",
2706                                      [$propName, $propValue], 'Property(id)');
2707        # Return the result.
2708        return $retVal;
2709    }
2710    
2711  =head3 MergedAnnotations  =head3 MergedAnnotations
2712    
2713  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>
# Line 2717  Line 2905 
2905      # Get the parameters.      # Get the parameters.
2906      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2907      # Get the list of names.      # Get the list of names.
2908      my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",      my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?",
2909                                  [$featureID], 'HasSSCell(from-link)');                                  [$featureID], 'HasRoleInSubsystem(to-link)');
2910        # Return the result, sorted.
2911        return sort @retVal;
2912    }
2913    
2914    =head3 GenomeSubsystemData
2915    
2916    C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>
2917    
2918    Return a hash mapping genome features to their subsystem roles.
2919    
2920    =over 4
2921    
2922    =item genomeID
2923    
2924    ID of the genome whose subsystem feature map is desired.
2925    
2926    =item RETURN
2927    
2928    Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb
2929    2-tuple contains a subsystem name followed by a role ID.
2930    
2931    =back
2932    
2933    =cut
2934    
2935    sub GenomeSubsystemData {
2936        # Get the parameters.
2937        my ($self, $genomeID) = @_;
2938        # Declare the return variable.
2939        my %retVal = ();
2940        # Get a list of the genome features that participate in subsystems. For each
2941        # feature we get its spreadsheet cells and the corresponding roles.
2942        my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],
2943                                 "HasFeature(from-link) = ?", [$genomeID],
2944                                 ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);
2945        # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems
2946        # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the
2947        # list. We use it at the beginning to get all the spreadsheet cells for the genome and
2948        # again at the end to filter out participation in subsystems with a negative variant code.
2949        my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],
2950                                     "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?",
2951                                     [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']);
2952        # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features.
2953        # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We
2954        # link these two lists together to create the result. First, we want a hash mapping
2955        # spreadsheet cells to subsystem names.
2956        my %subHash = map { $_->[0] => $_->[1] } @cellData;
2957        # We loop through @cellData to build the hash.
2958        for my $roleEntry (@roleData) {
2959            # Get the data for this feature and cell.
2960            my ($fid, $cellID, $role) = @{$roleEntry};
2961            # Check for a subsystem name.
2962            my $subsys = $subHash{$cellID};
2963            if ($subsys) {
2964                # Insure this feature has an entry in the return hash.
2965                if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
2966                # Merge in this new data.
2967                push @{$retVal{$fid}}, [$subsys, $role];
2968            }
2969        }
2970      # Return the result.      # Return the result.
2971      return @retVal;      return %retVal;
2972  }  }
2973    
2974  =head3 RelatedFeatures  =head3 RelatedFeatures
# Line 2758  Line 3006 
3006      # Get the parameters.      # Get the parameters.
3007      my ($self, $featureID, $function, $userID) = @_;      my ($self, $featureID, $function, $userID) = @_;
3008      # Get a list of the features that are BBHs of the incoming feature.      # Get a list of the features that are BBHs of the incoming feature.
3009      my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
                                      "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],  
                                      'IsBidirectionalBestHitOf(to-link)');  
3010      # Now we loop through the features, pulling out the ones that have the correct      # Now we loop through the features, pulling out the ones that have the correct
3011      # functional assignment.      # functional assignment.
3012      my @retVal = ();      my @retVal = ();
# Line 2824  Line 3070 
3070      return @retVal;      return @retVal;
3071  }  }
3072    
 =head3 GetAll  
   
 C<< my @list = $sprout->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>  
   
 Return a list of values taken from the objects returned by a query. The first three  
 parameters correspond to the parameters of the L</Get> method. The final parameter is  
 a list of the fields desired from each record found by the query. The field name  
 syntax is the standard syntax used for fields in the B<ERDB> system--  
 B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity  
 or relationship and I<fieldName> is the name of the field.  
   
 The list returned will be a list of lists. Each element of the list will contain  
 the values returned for the fields specified in the fourth parameter. If one of the  
 fields specified returns multiple values, they are flattened in with the rest. For  
 example, the following call will return a list of the features in a particular  
 spreadsheet cell, and each feature will be represented by a list containing the  
 feature ID followed by all of its aliases.  
   
 C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item fields  
   
 List of the fields to be returned in each element of the list returned.  
   
 =item count  
   
 Maximum number of records to return. If omitted or 0, all available records will be returned.  
   
 =item RETURN  
   
 Returns a list of list references. Each element of the return list contains the values for the  
 fields specified in the B<fields> parameter.  
   
 =back  
   
 =cut  
 #: Return Type @@;  
 sub GetAll {  
     # Get the parameters.  
     my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;  
     # Call the ERDB method.  
     my @retVal = $self->{_erdb}->GetAll($objectNames, $filterClause, $parameterList,  
                                         $fields, $count);  
     # Return the resulting list.  
     return @retVal;  
 }  
   
 =head3 GetFlat  
   
 C<< my @list = $sprout->GetFlat(\@objectNames, $filterClause, $parameterList, $field); >>  
   
 This is a variation of L</GetAll> that asks for only a single field per record and  
 returns a single flattened list.  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item field  
   
 Name of the field to be used to get the elements of the list returned.  
   
 =item RETURN  
   
 Returns a list of values.  
   
 =back  
   
 =cut  
 #: Return Type @;  
 sub GetFlat {  
     # Get the parameters.  
     my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;  
     # Construct the query.  
     my $query = $self->Get($objectNames, $filterClause, $parameterList);  
     # Create the result list.  
     my @retVal = ();  
     # Loop through the records, adding the field values found to the result list.  
     while (my $row = $query->Fetch()) {  
         push @retVal, $row->Value($field);  
     }  
     # Return the list created.  
     return @retVal;  
 }  
   
3073  =head3 Protein  =head3 Protein
3074    
3075  C<< my $protein = Sprout::Protein($sequence, $table); >>  C<< my $protein = Sprout::Protein($sequence, $table); >>
# Line 3015  Line 3142 
3142      # Loop through the input triples.      # Loop through the input triples.
3143      my $n = length $sequence;      my $n = length $sequence;
3144      for (my $i = 0; $i < $n; $i += 3) {      for (my $i = 0; $i < $n; $i += 3) {
3145          # Get the current triple from the sequence.          # Get the current triple from the sequence. Note we convert to
3146          my $triple = substr($sequence, $i, 3);          # upper case to insure a match.
3147            my $triple = uc substr($sequence, $i, 3);
3148          # Translate it using the table.          # Translate it using the table.
3149          my $protein = "X";          my $protein = "X";
3150          if (exists $table->{$triple}) { $protein = $table->{$triple}; }          if (exists $table->{$triple}) { $protein = $table->{$triple}; }
# Line 3044  Line 3172 
3172      # Create the return list, priming it with the name of the data directory.      # Create the return list, priming it with the name of the data directory.
3173      my @retVal = ($self->{_options}->{dataDir});      my @retVal = ($self->{_options}->{dataDir});
3174      # Concatenate the table names.      # Concatenate the table names.
3175      push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
3176      # Return the result.      # Return the result.
3177      return @retVal;      return @retVal;
3178  }  }
3179    
3180  =head3 LowBBHs  =head3 LowBBHs
3181    
3182  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
3183    
3184  Return the bidirectional best hits of a feature whose score is no greater than a  Return the bidirectional best hits of a feature whose score is no greater than a
3185  specified cutoff value. A higher cutoff value will allow inclusion of hits with  specified cutoff value. A higher cutoff value will allow inclusion of hits with
# Line 3080  Line 3208 
3208      my ($self, $featureID, $cutoff) = @_;      my ($self, $featureID, $cutoff) = @_;
3209      # Create the return hash.      # Create the return hash.
3210      my %retVal = ();      my %retVal = ();
3211      # Create a query to get the desired BBHs.      # Query for the desired BBHs.
3212      my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BBHData($featureID, $cutoff);
                                 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',  
                                 [$cutoff, $featureID],  
                                 ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);  
3213      # Form the results into the return hash.      # Form the results into the return hash.
3214      for my $pair (@bbhList) {      for my $pair (@bbhList) {
3215          $retVal{$pair->[0]} = $pair->[1];          $retVal{$pair->[0]} = $pair->[1];
# Line 3093  Line 3218 
3218      return %retVal;      return %retVal;
3219  }  }
3220    
3221    =head3 Sims
3222    
3223    C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>
3224    
3225    Get a list of similarities for a specified feature. Similarity information is not kept in the
3226    Sprout database; rather, they are retrieved from a network server. The similarities are
3227    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3228    so that its elements can be accessed by name.
3229    
3230    Similarities can be either raw or expanded. The raw similarities are basic
3231    hits between features with similar DNA. Expanding a raw similarity drags in any
3232    features considered substantially identical. So, for example, if features B<A1>,
3233    B<A2>, and B<A3> are all substatially identical to B<A>, then a raw similarity
3234    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3235    
3236    =over 4
3237    
3238    =item fid
3239    
3240    ID of the feature whose similarities are desired.
3241    
3242    =item maxN
3243    
3244    Maximum number of similarities to return.
3245    
3246    =item maxP
3247    
3248    Minumum allowable similarity score.
3249    
3250    =item select
3251    
3252    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3253    means only similarities to FIG features are returned; C<all> means all expanded
3254    similarities are returned; and C<figx> means similarities are expanded until the
3255    number of FIG features equals the maximum.
3256    
3257    =item max_expand
3258    
3259    The maximum number of features to expand.
3260    
3261    =item filters
3262    
3263    Reference to a hash containing filter information, or a subroutine that can be
3264    used to filter the sims.
3265    
3266    =item RETURN
3267    
3268    Returns a reference to a list of similarity objects, or C<undef> if an error
3269    occurred.
3270    
3271    =back
3272    
3273    =cut
3274    
3275    sub Sims {
3276        # Get the parameters.
3277        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3278        # Create the shim object to test for deleted FIDs.
3279        my $shim = FidCheck->new($self);
3280        # Ask the network for sims.
3281        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3282        # Return the result.
3283        return $retVal;
3284    }
3285    
3286    =head3 IsAllGenomes
3287    
3288    C<< my $flag = $sprout->IsAllGenomes(\@list, \@checkList); >>
3289    
3290    Return TRUE if all genomes in the second list are represented in the first list at
3291    least one. Otherwise, return FALSE. If the second list is omitted, the first list is
3292    compared to a list of all the genomes.
3293    
3294    =over 4
3295    
3296    =item list
3297    
3298    Reference to the list to be compared to the second list.
3299    
3300    =item checkList (optional)
3301    
3302    Reference to the comparison target list. Every genome ID in this list must occur at
3303    least once in the first list. If this parameter is omitted, a list of all the genomes
3304    is used.
3305    
3306    =item RETURN
3307    
3308    Returns TRUE if every item in the second list appears at least once in the
3309    first list, else FALSE.
3310    
3311    =back
3312    
3313    =cut
3314    
3315    sub IsAllGenomes {
3316        # Get the parameters.
3317        my ($self, $list, $checkList) = @_;
3318        # Supply the checklist if it was omitted.
3319        $checkList = [$self->Genomes()] if ! defined($checkList);
3320        # Create a hash of the original list.
3321        my %testList = map { $_ => 1 } @{$list};
3322        # Declare the return variable. We assume that the representation
3323        # is complete and stop at the first failure.
3324        my $retVal = 1;
3325        my $n = scalar @{$checkList};
3326        for (my $i = 0; $retVal && $i < $n; $i++) {
3327            if (! $testList{$checkList->[$i]}) {
3328                $retVal = 0;
3329            }
3330        }
3331        # Return the result.
3332        return $retVal;
3333    }
3334    
3335  =head3 GetGroups  =head3 GetGroups
3336    
3337  C<< my %groups = $sprout->GetGroups(\@groupList); >>  C<< my %groups = $sprout->GetGroups(\@groupList); >>
# Line 3114  Line 3353 
3353          # Here we have a group list. Loop through them individually,          # Here we have a group list. Loop through them individually,
3354          # getting a list of the relevant genomes.          # getting a list of the relevant genomes.
3355          for my $group (@{$groupList}) {          for my $group (@{$groupList}) {
3356              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3357                  [$group], "Genome(id)");                  [$group], "Genome(id)");
3358              $retVal{$group} = \@genomeIDs;              $retVal{$group} = \@genomeIDs;
3359          }          }
# Line 3122  Line 3361 
3361          # Here we need all of the groups. In this case, we run through all          # Here we need all of the groups. In this case, we run through all
3362          # of the genome records, putting each one found into the appropriate          # of the genome records, putting each one found into the appropriate
3363          # group. Note that we use a filter clause to insure that only genomes          # group. Note that we use a filter clause to insure that only genomes
3364          # in groups are included in the return set.          # in real NMPDR groups are included in the return set.
3365          my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],          my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3366                                      ['Genome(id)', 'Genome(group-name)']);                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3367          # Loop through the genomes found.          # Loop through the genomes found.
3368          for my $genome (@genomes) {          for my $genome (@genomes) {
3369              # Pop this genome's ID off the current list.              # Pop this genome's ID off the current list.
# Line 3214  Line 3453 
3453      return $retVal;      return $retVal;
3454  }  }
3455    
3456  =head2 Internal Utility Methods  =head3 DeleteGenome
3457    
3458  =head3 ParseAssignment  C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3459    
3460  Parse annotation text to determine whether or not it is a functional assignment. If it is,  Delete a genome from the database.
 the user, function text, and assigning user will be returned as a 3-element list. If it  
 isn't, an empty list will be returned.  
3461    
3462  A functional assignment is always of the form  =over 4
3463    
3464    =item genomeID
3465    
3466      I<XXXX>C<\nset >I<YYYY>C< function to\n>I<ZZZZZ>  ID of the genome to delete
3467    
3468  where I<XXXX> is the B<assigning user>, I<YYYY> is the B<user>, and I<ZZZZ> is the  =item testFlag
 actual functional role. In most cases, the user and the assigning user will be the  
 same, but that is not always the case.  
3469    
3470  This is a static method.  If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3471    
3472    =item RETURN
3473    
3474    Returns a statistics object describing the rows deleted.
3475    
3476    =back
3477    
3478    =cut
3479    #: Return Type $%;
3480    sub DeleteGenome {
3481        # Get the parameters.
3482        my ($self, $genomeID, $testFlag) = @_;
3483        # Perform the delete for the genome's features.
3484        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);
3485        # Perform the delete for the primary genome data.
3486        my $stats = $self->Delete('Genome', $genomeID, $testFlag);
3487        $retVal->Accumulate($stats);
3488        # Return the result.
3489        return $retVal;
3490    }
3491    
3492    =head3 Fix
3493    
3494    C<< my %fixedHash = Sprout::Fix(%groupHash); >>
3495    
3496    Prepare a genome group hash (like that returned by L</GetGroups> for processing.
3497    Groups with the same primary name will be combined. The primary name is the
3498    first capitalized word in the group name.
3499    
3500  =over 4  =over 4
3501    
3502  =item text  =item groupHash
3503    
3504  Text of the annotation.  Hash to be fixed up.
3505    
3506  =item RETURN  =item RETURN
3507    
3508  Returns an empty list if the annotation is not a functional assignment; otherwise, returns  Returns a fixed-up version of the hash.
 a two-element list containing the user name and the function text.  
3509    
3510  =back  =back
3511    
3512  =cut  =cut
3513    
3514  sub _ParseAssignment {  sub Fix {
3515      # Get the parameters.      # Get the parameters.
3516      my ($text) = @_;      my (%groupHash) = @_;
3517      # Declare the return value.      # Create the result hash.
3518      my @retVal = ();      my %retVal = ();
3519      # Check to see if this is a functional assignment.      # Copy over the genomes.
3520      my ($type, $function) = split(/\n/, $text);      for my $groupID (keys %groupHash) {
3521      if ($type =~ m/^set ([^ ]+) function to$/i) {          # Make a safety copy of the group ID.
3522          # Here it is, so we return the user name (which is in $1), the functional role text,          my $realGroupID = $groupID;
3523          # and the assigning user.          # Yank the primary name.
3524          @retVal = ($1, $function);          if ($groupID =~ /([A-Z]\w+)/) {
3525                $realGroupID = $1;
3526      }      }
3527      # Return the result list.          # Append this group's genomes into the result hash.
3528      return @retVal;          Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}});
3529        }
3530        # Return the result hash.
3531        return %retVal;
3532  }  }
3533    
3534  =head3 FriendlyTimestamp  =head3 GroupPageName
3535    
3536  Convert a time number to a user-friendly time stamp for display.  C<< my $name = $sprout->GroupPageName($group); >>
3537    
3538  This is a static method.  Return the name of the page for the specified NMPDR group.
3539    
3540  =over 4  =over 4
3541    
3542  =item timeValue  =item group
3543    
3544  Numeric time value.  Name of the relevant group.
3545    
3546  =item RETURN  =item RETURN
3547    
3548  Returns a string containing the same time in user-readable format.  Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3549    memory it will be read in.
3550    
3551  =back  =back
3552    
3553  =cut  =cut
3554    
3555  sub FriendlyTimestamp {  sub GroupPageName {
3556      my ($timeValue) = @_;      # Get the parameters.
3557      my $retVal = localtime($timeValue);      my ($self, $group) = @_;
3558        # Declare the return variable.
3559        my $retVal;
3560        # Check for the group file data.
3561        if (! defined $self->{groupHash}) {
3562            # Read the group file.
3563            my %groupData = Sprout::ReadGroupFile($self->{_options}->{dataDir} . "/groups.tbl");
3564            # Store it in our object.
3565            $self->{groupHash} = \%groupData;
3566        }
3567        # Compute the real group name.
3568        my $realGroup = $group;
3569        if ($group =~ /([A-Z]\w+)/) {
3570            $realGroup = $1;
3571        }
3572        # Return the page name.
3573        $retVal = "../content/" . $self->{groupHash}->{$realGroup}->[1];
3574        # Return the result.
3575      return $retVal;      return $retVal;
3576  }  }
3577    
3578    =head3 ReadGroupFile
3579    
3580    C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >>
3581    
3582    Read in the data from the specified group file. The group file contains information
3583    about each of the NMPDR groups.
3584    
3585    =over 4
3586    
3587    =item name
3588    
3589    Name of the group.
3590    
3591    =item page
3592    
3593    Name of the group's page on the web site (e.g. C<campy.php> for
3594    Campylobacter)
3595    
3596    =item genus
3597    
3598    Genus of the group
3599    
3600    =item species
3601    
3602    Species of the group, or an empty string if the group is for an entire
3603    genus. If the group contains more than one species, the species names
3604    should be separated by commas.
3605    
3606    =back
3607    
3608    The parameters to this method are as follows
3609    
3610    =over 4
3611    
3612    =item groupFile
3613    
3614    Name of the file containing the group data.
3615    
3616    =item RETURN
3617    
3618    Returns a hash keyed on group name. The value of each hash
3619    
3620    =back
3621    
3622    =cut
3623    
3624    sub ReadGroupFile {
3625        # Get the parameters.
3626        my ($groupFileName) = @_;
3627        # Declare the return variable.
3628        my %retVal;
3629        # Read the group file.
3630        my @groupLines = Tracer::GetFile($groupFileName);
3631        for my $groupLine (@groupLines) {
3632            my ($name, $page, $genus, $species) = split(/\t/, $groupLine);
3633            $retVal{$name} = [$page, $genus, $species];
3634        }
3635        # Return the result.
3636        return %retVal;
3637    }
3638    
3639  =head3 AddProperty  =head3 AddProperty
3640    
3641  C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>  C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>
# Line 3346  Line 3693 
3693      $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });      $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3694  }  }
3695    
3696    =head2 Virtual Methods
3697    
3698    =head3 CleanKeywords
3699    
3700    C<< my $cleanedString = $sprout->CleanKeywords($searchExpression); >>
3701    
3702    Clean up a search expression or keyword list. This involves converting the periods
3703    in EC numbers to underscores, converting non-leading minus signs to underscores,
3704    a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
3705    characters. In addition, any extra spaces are removed.
3706    
3707    =over 4
3708    
3709    =item searchExpression
3710    
3711    Search expression or keyword list to clean. Note that a search expression may
3712    contain boolean operators which need to be preserved. This includes leading
3713    minus signs.
3714    
3715    =item RETURN
3716    
3717    Cleaned expression or keyword list.
3718    
3719    =back
3720    
3721    =cut
3722    
3723    sub CleanKeywords {
3724        # Get the parameters.
3725        my ($self, $searchExpression) = @_;
3726        # Perform the standard cleanup.
3727        my $retVal = $self->ERDB::CleanKeywords($searchExpression);
3728        # Fix the periods in EC and TC numbers.
3729        $retVal =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g;
3730        # Fix non-trailing periods.
3731        $retVal =~ s/\.(\w)/_$1/g;
3732        # Fix non-leading minus signs.
3733        $retVal =~ s/(\w)[\-]/$1_/g;
3734        # Fix the vertical bars and colons
3735        $retVal =~ s/(\w)[|:](\w)/$1'$2/g;
3736        # Return the result.
3737        return $retVal;
3738    }
3739    
3740    =head2 Internal Utility Methods
3741    
3742    =head3 ParseAssignment
3743    
3744    Parse annotation text to determine whether or not it is a functional assignment. If it is,
3745    the user, function text, and assigning user will be returned as a 3-element list. If it
3746    isn't, an empty list will be returned.
3747    
3748    A functional assignment is always of the form
3749    
3750        C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3751    
3752    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3753    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3754    not always the case.
3755    
3756    In addition, the functional role may contain extra data that is stripped, such as
3757    terminating spaces or a comment separated from the rest of the text by a tab.
3758    
3759    This is a static method.
3760    
3761    =over 4
3762    
3763    =item user
3764    
3765    Name of the assigning user.
3766    
3767    =item text
3768    
3769    Text of the annotation.
3770    
3771    =item RETURN
3772    
3773    Returns an empty list if the annotation is not a functional assignment; otherwise, returns
3774    a two-element list containing the user name and the function text.
3775    
3776    =back
3777    
3778    =cut
3779    
3780    sub _ParseAssignment {
3781        # Get the parameters.
3782        my ($user, $text) = @_;
3783        # Declare the return value.
3784        my @retVal = ();
3785        # Check to see if this is a functional assignment.
3786        my ($type, $function) = split(/\n/, $text);
3787        if ($type =~ m/^set function to$/i) {
3788            # Here we have an assignment without a user, so we use the incoming user ID.
3789            @retVal = ($user, $function);
3790        } elsif ($type =~ m/^set (\S+) function to$/i) {
3791            # Here we have an assignment with a user that is passed back to the caller.
3792            @retVal = ($1, $function);
3793        }
3794        # If we have an assignment, we need to clean the function text. There may be
3795        # extra junk at the end added as a note from the user.
3796        if (defined( $retVal[1] )) {
3797            $retVal[1] =~ s/(\t\S)?\s*$//;
3798        }
3799        # Return the result list.
3800        return @retVal;
3801    }
3802    
3803    =head3 FriendlyTimestamp
3804    
3805    Convert a time number to a user-friendly time stamp for display.
3806    
3807    This is a static method.
3808    
3809    =over 4
3810    
3811    =item timeValue
3812    
3813    Numeric time value.
3814    
3815    =item RETURN
3816    
3817    Returns a string containing the same time in user-readable format.
3818    
3819    =back
3820    
3821    =cut
3822    
3823    sub FriendlyTimestamp {
3824        my ($timeValue) = @_;
3825        my $retVal = localtime($timeValue);
3826        return $retVal;
3827    }
3828    
3829    
3830  1;  1;

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3