[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.40, Wed Oct 12 03:12:24 2005 UTC revision 1.78, Wed Jul 26 14:47:03 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                         maxSegmentLength => 4500,        # maximum feature segment length                         maxSegmentLength => 4500,        # maximum feature segment length
113                         maxSequenceLength => 8000,       # maximum contig sequence length                         maxSequenceLength => 8000,       # maximum contig sequence length
114                         noDBOpen     => 0,               # 1 to suppress the database open                         noDBOpen     => 0,               # 1 to suppress the database open
# Line 111  Line 122 
122      my $dbh;      my $dbh;
123      if (! $optionTable->{noDBOpen}) {      if (! $optionTable->{noDBOpen}) {
124          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
125                                  $password, $optionTable->{port});                                  $password, $optionTable->{port}, undef, $optionTable->{sock});
126      }      }
127      # Create the ERDB object.      # Create the ERDB object.
128      my $xmlFileName = "$optionTable->{xmlFileName}";      my $xmlFileName = "$optionTable->{xmlFileName}";
129      my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
130      # Create this object.      # Add the option table and XML file name.
131      my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
132      # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
133      bless $self;      # Return it.
134      return $self;      return $retVal;
135  }  }
136    
137  =head3 MaxSegment  =head3 MaxSegment
# Line 155  Line 166 
166      return $self->{_options}->{maxSequenceLength};      return $self->{_options}->{maxSequenceLength};
167  }  }
168    
 =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);  
 }  
   
169  =head3 Load  =head3 Load
170    
171  C<< $sprout->Load($rebuild); >>;  C<< $sprout->Load($rebuild); >>;
# Line 379  Line 200 
200  sub Load {  sub Load {
201      # Get the parameters.      # Get the parameters.
202      my ($self, $rebuild) = @_;      my ($self, $rebuild) = @_;
     # Get the database object.  
     my $erdb = $self->{_erdb};  
203      # Load the tables from the data directory.      # Load the tables from the data directory.
204      my $retVal = $erdb->LoadTables($self->{_options}->{dataDir}, $rebuild);      my $retVal = $self->LoadTables($self->{_options}->{dataDir}, $rebuild);
205      # Return the statistics.      # Return the statistics.
206      return $retVal;      return $retVal;
207  }  }
208    
209  =head3 LoadUpdate  =head3 LoadUpdate
210    
211  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
212    
213  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
214  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 422  Line 241 
241  sub LoadUpdate {  sub LoadUpdate {
242      # Get the parameters.      # Get the parameters.
243      my ($self, $truncateFlag, $tableList) = @_;      my ($self, $truncateFlag, $tableList) = @_;
     # Get the database object.  
     my $erdb = $self->{_erdb};  
244      # Declare the return value.      # Declare the return value.
245      my $retVal = Stats->new();      my $retVal = Stats->new();
246      # Get the data directory.      # Get the data directory.
# Line 437  Line 254 
254              Trace("No load file found for $tableName in $dataDir.") if T(0);              Trace("No load file found for $tableName in $dataDir.") if T(0);
255          } else {          } else {
256              # Attempt to load this table.              # Attempt to load this table.
257              my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);              my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);
258              # Accumulate the resulting statistics.              # Accumulate the resulting statistics.
259              $retVal->Accumulate($result);              $retVal->Accumulate($result);
260          }          }
# Line 446  Line 263 
263      return $retVal;      return $retVal;
264  }  }
265    
266    =head3 GenomeCounts
267    
268    C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>
269    
270    Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
271    genomes will be included in the counts.
272    
273    =over 4
274    
275    =item complete
276    
277    TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
278    counted
279    
280    =item RETURN
281    
282    A six-element list containing the number of genomes in each of six categories--
283    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
284    
285    =back
286    
287    =cut
288    
289    sub GenomeCounts {
290        # Get the parameters.
291        my ($self, $complete) = @_;
292        # Set the filter based on the completeness flag.
293        my $filter = ($complete ? "Genome(complete) = 1" : "");
294        # Get all the genomes and the related taxonomy information.
295        my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
296        # Clear the counters.
297        my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
298        # Loop through, counting the domains.
299        for my $genome (@genomes) {
300            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
301            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
302            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
303            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
304            elsif ($genome->[1] =~ /^env/i)      { ++$env }
305            else  { ++$unk }
306        }
307        # Return the counts.
308        return ($arch, $bact, $euk, $vir, $env, $unk);
309    }
310    
311    =head3 ContigCount
312    
313    C<< my $count = $sprout->ContigCount($genomeID); >>
314    
315    Return the number of contigs for the specified genome ID.
316    
317    =over 4
318    
319    =item genomeID
320    
321    ID of the genome whose contig count is desired.
322    
323    =item RETURN
324    
325    Returns the number of contigs for the specified genome.
326    
327    =back
328    
329    =cut
330    
331    sub ContigCount {
332        # Get the parameters.
333        my ($self, $genomeID) = @_;
334        # Get the contig count.
335        my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
336        # Return the result.
337        return $retVal;
338    }
339    
340    =head3 GeneMenu
341    
342    C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params); >>
343    
344    Return an HTML select menu of genomes. Each genome will be an option in the menu,
345    and will be displayed by name with the ID and a contig count attached. The selection
346    value will be the genome ID. The genomes will be sorted by genus/species name.
347    
348    =over 4
349    
350    =item attributes
351    
352    Reference to a hash mapping attributes to values for the SELECT tag generated.
353    
354    =item filterString
355    
356    A filter string for use in selecting the genomes. The filter string must conform
357    to the rules for the C<< ERDB->Get >> method.
358    
359    =item params
360    
361    Reference to a list of values to be substituted in for the parameter marks in
362    the filter string.
363    
364    =item RETURN
365    
366    Returns an HTML select menu with the specified genomes as selectable options.
367    
368    =back
369    
370    =cut
371    
372    sub GeneMenu {
373        # Get the parameters.
374        my ($self, $attributes, $filterString, $params) = @_;
375        # Start the menu.
376        my $retVal = "<select " .
377            join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
378            ">\n";
379        # Get the genomes.
380        my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
381                                                                         'Genome(genus)',
382                                                                         'Genome(species)',
383                                                                         'Genome(unique-characterization)']);
384        # Sort them by name.
385        my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
386        # Loop through the genomes, creating the option tags.
387        for my $genomeData (@sorted) {
388            # Get the data for this genome.
389            my ($genomeID, $genus, $species, $strain) = @{$genomeData};
390            # Get the contig count.
391            my $count = $self->ContigCount($genomeID);
392            my $counting = ($count == 1 ? "contig" : "contigs");
393            # Build the option tag.
394            $retVal .= "<option value=\"$genomeID\">$genus $species $strain ($genomeID) [$count $counting]</option>\n";
395            Trace("Option tag built for $genomeID: $genus $species $strain.") if T(3);
396        }
397        # Close the SELECT tag.
398        $retVal .= "</select>\n";
399        # Return the result.
400        return $retVal;
401    }
402  =head3 Build  =head3 Build
403    
404  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 460  Line 413 
413      # Get the parameters.      # Get the parameters.
414      my ($self) = @_;      my ($self) = @_;
415      # Create the tables.      # Create the tables.
416      $self->{_erdb}->CreateTables;      $self->CreateTables();
417  }  }
418    
419  =head3 Genomes  =head3 Genomes
# Line 610  Line 563 
563          if ($prevContig eq $contigID && $dir eq $prevDir) {          if ($prevContig eq $contigID && $dir eq $prevDir) {
564              # 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
565              # new segment's beginning is next to the old segment's end.              # new segment's beginning is next to the old segment's end.
566              if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||              if ($dir eq "-" && $beg + $len == $prevBeg) {
567                  ($dir eq "+" && $beg == $prevBeg + $prevLen)) {                  # Here we're merging two backward blocks, so we keep the new begin point
568                  # Here we need to merge two segments. Adjust the beginning and length values                  # and adjust the length.
569                  # to include both segments.                  $len += $prevLen;
570                    # Pop the old segment off. The new one will replace it later.
571                    pop @retVal;
572                } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
573                    # Here we need to merge two forward blocks. Adjust the beginning and
574                    # length values to include both segments.
575                  $beg = $prevBeg;                  $beg = $prevBeg;
576                  $len += $prevLen;                  $len += $prevLen;
577                  # 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 735  Line 693 
693  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,
694  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>.
695    
696    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
697    between positions 1401 and 1532, inclusive.
698    
699        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
700    
701  =over 4  =over 4
702    
703  =item locationList  =item locationList
704    
705  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
706  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
707    
708  =item RETURN  =item RETURN
709    
# Line 836  Line 799 
799      return @retVal;      return @retVal;
800  }  }
801    
802    =head3 GenomeLength
803    
804    C<< my $length = $sprout->GenomeLength($genomeID); >>
805    
806    Return the length of the specified genome in base pairs.
807    
808    =over 4
809    
810    =item genomeID
811    
812    ID of the genome whose base pair count is desired.
813    
814    =item RETURN
815    
816    Returns the number of base pairs in all the contigs of the specified
817    genome.
818    
819    =back
820    
821    =cut
822    
823    sub GenomeLength {
824        # Get the parameters.
825        my ($self, $genomeID) = @_;
826        # Declare the return variable.
827        my $retVal = 0;
828        # Get the genome's contig sequence lengths.
829        my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
830                           [$genomeID], 'IsMadeUpOf(len)');
831        # Sum the lengths.
832        map { $retVal += $_ } @lens;
833        # Return the result.
834        return $retVal;
835    }
836    
837    =head3 FeatureCount
838    
839    C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
840    
841    Return the number of features of the specified type in the specified genome.
842    
843    =over 4
844    
845    =item genomeID
846    
847    ID of the genome whose feature count is desired.
848    
849    =item type
850    
851    Type of feature to count (eg. C<peg>, C<rna>, etc.).
852    
853    =item RETURN
854    
855    Returns the number of features of the specified type for the specified genome.
856    
857    =back
858    
859    =cut
860    
861    sub FeatureCount {
862        # Get the parameters.
863        my ($self, $genomeID, $type) = @_;
864        # Compute the count.
865        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
866                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
867                                    [$genomeID, $type]);
868        # Return the result.
869        return $retVal;
870    }
871    
872    =head3 GenomeAssignments
873    
874    C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
875    
876    Return a list of a genome's assigned features. The return hash will contain each
877    assigned feature of the genome mapped to the text of its most recent functional
878    assignment.
879    
880    =over 4
881    
882    =item genomeID
883    
884    ID of the genome whose functional assignments are desired.
885    
886    =item RETURN
887    
888    Returns a reference to a hash which maps each feature to its most recent
889    functional assignment.
890    
891    =back
892    
893    =cut
894    
895    sub GenomeAssignments {
896        # Get the parameters.
897        my ($self, $genomeID) = @_;
898        # Declare the return variable.
899        my $retVal = {};
900        # Query the genome's features and annotations. We'll put the oldest annotations
901        # first so that the last assignment to go into the hash will be the correct one.
902        my $query = $self->Get(['HasFeature', 'IsTargetOfAnnotation', 'Annotation'],
903                               "HasFeature(from-link) = ? ORDER BY Annotation(time)",
904                               [$genomeID]);
905        # Loop through the annotations.
906        while (my $data = $query->Fetch) {
907            # Get the feature ID and annotation text.
908            my ($fid, $annotation) = $data->Values(['HasFeature(to-link)',
909                                                    'Annotation(annotation)']);
910            # Check to see if this is an assignment. Note that the user really
911            # doesn't matter to us, other than we use it to determine whether or
912            # not this is an assignment.
913            my ($user, $assignment) = _ParseAssignment('fig', $annotation);
914            if ($user) {
915                # Here it's an assignment. We put it in the return hash, overwriting
916                # any older assignment that might be present.
917                $retVal->{$fid} = $assignment;
918            }
919        }
920        # Return the result.
921        return $retVal;
922    }
923    
924  =head3 ContigLength  =head3 ContigLength
925    
926  C<< my $length = $sprout->ContigLength($contigID); >>  C<< my $length = $sprout->ContigLength($contigID); >>
# Line 1148  Line 1233 
1233    
1234  =item RETURN  =item RETURN
1235    
1236  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1237    
1238  =back  =back
1239    
# Line 1158  Line 1243 
1243      # Get the parameters.      # Get the parameters.
1244      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1245      # Get all of the feature's annotations.      # Get all of the feature's annotations.
1246      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1247                              "IsTargetOfAnnotation(from-link) = ?",                              "IsTargetOfAnnotation(from-link) = ?",
1248                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1249                                               'MadeAnnotation(from-link)']);
1250      # Declare the return hash.      # Declare the return hash.
1251      my %retVal;      my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1252      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1253      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1254      # Loop until we run out of annotations.      # Loop until we run out of annotations.
1255      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1256          # Get the annotation fields.          # Get the annotation fields.
1257          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1258          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
1259          my ($user, $function) = _ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1260          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1261              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1262              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1263              # return hash.              # return hash.
1264              $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1265          }          }
1266      }      }
1267      # Return the hash of assignments found.      # Return the hash of assignments found.
# Line 1195  Line 1277 
1277  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
1278  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
1279  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
1280  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
1281  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
1282  most features only have a small number of annotations.  most features only have a small number of annotations.
1283    
# Line 1257  Line 1339 
1339              }              }
1340          }          }
1341          # 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.
1342          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1343                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1344                                 [$featureID]);                                 [$featureID]);
1345          my $timeSelected = 0;          my $timeSelected = 0;
1346          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1347          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1348              # Get the annotation text.              # Get the annotation text.
1349              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);              my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1350                                                         'Annotation(time)', 'MadeAnnotation(from-link)']);
1351              # 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.
1352              my ($user, $function) = _ParseAssignment($text);              my ($actualUser, $function) = _ParseAssignment($user, $text);
1353              if ($user) {              Trace("Assignment user is $actualUser, text is $function.") if T(4);
1354                if ($actualUser) {
1355                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1356                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1357                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                  if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1358                      $retVal = $function;                      $retVal = $function;
1359                      $timeSelected = $time;                      $timeSelected = $time;
1360                  }                  }
# Line 1286  Line 1370 
1370      return $retVal;      return $retVal;
1371  }  }
1372    
1373    =head3 FunctionsOf
1374    
1375    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1376    
1377    Return the functional assignments of a particular feature.
1378    
1379    The functional assignment is handled differently depending on the type of feature. If
1380    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1381    assignment is a type of annotation. The format of an assignment is described in
1382    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1383    annotation itself because it's a text field; however, this is not a big problem because
1384    most features only have a small number of annotations.
1385    
1386    If the feature is B<not> identified by a FIG ID, then the functional assignment
1387    information is taken from the B<ExternalAliasFunc> table. If the table does
1388    not contain an entry for the feature, an empty list is returned.
1389    
1390    =over 4
1391    
1392    =item featureID
1393    
1394    ID of the feature whose functional assignments are desired.
1395    
1396    =item RETURN
1397    
1398    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1399    that user.
1400    
1401    =back
1402    
1403    =cut
1404    #: Return Type @@;
1405    sub FunctionsOf {
1406        # Get the parameters.
1407        my ($self, $featureID) = @_;
1408        # Declare the return value.
1409        my @retVal = ();
1410        # Determine the ID type.
1411        if ($featureID =~ m/^fig\|/) {
1412            # Here we have a FIG feature ID. We must build the list of trusted
1413            # users.
1414            my %trusteeTable = ();
1415            # Build a query for all of the feature's annotations, sorted by date.
1416            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1417                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1418                                   [$featureID]);
1419            my $timeSelected = 0;
1420            # Loop until we run out of annotations.
1421            while (my $annotation = $query->Fetch()) {
1422                # Get the annotation text.
1423                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1424                                                                'Annotation(time)',
1425                                                                'MadeAnnotation(user)']);
1426                # Check to see if this is a functional assignment for a trusted user.
1427                my ($actualUser, $function) = _ParseAssignment($user, $text);
1428                if ($actualUser) {
1429                    # Here it is a functional assignment.
1430                    push @retVal, [$actualUser, $function];
1431                }
1432            }
1433        } else {
1434            # Here we have a non-FIG feature ID. In this case the user ID does not
1435            # matter. We simply get the information from the External Alias Function
1436            # table.
1437            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1438                                                     ['ExternalAliasFunc(func)']);
1439            push @retVal, map { ['master', $_] } @assignments;
1440        }
1441        # Return the assignments found.
1442        return @retVal;
1443    }
1444    
1445  =head3 BBHList  =head3 BBHList
1446    
1447  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1406  Line 1562 
1562      my $genomeData = $self->GetEntity('Genome', $genomeID);      my $genomeData = $self->GetEntity('Genome', $genomeID);
1563      if ($genomeData) {      if ($genomeData) {
1564          # The genome exists, so get the completeness flag.          # The genome exists, so get the completeness flag.
1565          ($retVal) = $genomeData->Value('complete');          ($retVal) = $genomeData->Value('Genome(complete)');
1566      }      }
1567      # Return the result.      # Return the result.
1568      return $retVal;      return $retVal;
# Line 1446  Line 1602 
1602    
1603  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1604    
1605  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1606    
1607  =over 4  =over 4
1608    
1609  =item featureID  =item featureID
1610    
1611  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1612    
1613  =item RETURN  =item RETURN
1614    
1615  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
1616  an undefined value.  found, returns an undefined value.
1617    
1618  =back  =back
1619    
# Line 1466  Line 1622 
1622  sub GenomeOf {  sub GenomeOf {
1623      # Get the parameters.      # Get the parameters.
1624      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1625      # Create a query to find the genome associated with the feature.      # Create a query to find the genome associated with the incoming ID.
1626      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1627                               [$featureID, $featureID]);
1628      # Declare the return value.      # Declare the return value.
1629      my $retVal;      my $retVal;
1630      # Get the genome ID.      # Get the genome ID.
# Line 1502  Line 1659 
1659  sub CoupledFeatures {  sub CoupledFeatures {
1660      # Get the parameters.      # Get the parameters.
1661      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1662        Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1663      # Create a query to retrieve the functionally-coupled features.      # Create a query to retrieve the functionally-coupled features.
1664      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1665                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);
# Line 1514  Line 1672 
1672          # Get the ID and score of the coupling.          # Get the ID and score of the coupling.
1673          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1674                                                          'Coupling(score)']);                                                          'Coupling(score)']);
1675          # 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);
1676          # this information to find the ID of the other feature.          # Get the other feature that participates in the coupling.
1677          my ($fid1, $fid2) = split / /, $couplingID;          my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],
1678          my $otherFeatureID = ($featureID eq $fid1 ? $fid2 : $fid1);                                             "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",
1679                                               [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');
1680            Trace("$couplingID target feature is $otherFeatureID.") if T(coupling => 4);
1681          # Attach the other feature's score to its ID.          # Attach the other feature's score to its ID.
1682          $retVal{$otherFeatureID} = $score;          $retVal{$otherFeatureID} = $score;
1683          $found = 1;          $found = 1;
# Line 1650  Line 1810 
1810      my ($self, $peg1, $peg2) = @_;      my ($self, $peg1, $peg2) = @_;
1811      # 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
1812      # flag and score until we have more information.      # flag and score until we have more information.
1813      my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);      my ($retVal, $inverted, $score) = ($self->CouplingID($peg1, $peg2), undef, undef);
1814      # Find the coupling data.      # Find the coupling data.
1815      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1816                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
# Line 1671  Line 1831 
1831      return ($retVal, $inverted, $score);      return ($retVal, $inverted, $score);
1832  }  }
1833    
1834    =head3 GetSynonymGroup
1835    
1836    C<< my $id = $sprout->GetSynonymGroup($fid); >>
1837    
1838    Return the synonym group name for the specified feature.
1839    
1840    =over 4
1841    
1842    =item fid
1843    
1844    ID of the feature whose synonym group is desired.
1845    
1846    =item RETURN
1847    
1848    The name of the synonym group to which the feature belongs. If the feature does
1849    not belong to a synonym group, the feature ID itself is returned.
1850    
1851    =back
1852    
1853    =cut
1854    
1855    sub GetSynonymGroup {
1856        # Get the parameters.
1857        my ($self, $fid) = @_;
1858        # Declare the return variable.
1859        my $retVal;
1860        # Find the synonym group.
1861        my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1862                                       [$fid], 'IsSynonymGroupFor(from-link)');
1863        # Check to see if we found anything.
1864        if (@groups) {
1865            $retVal = $groups[0];
1866        } else {
1867            $retVal = $fid;
1868        }
1869        # Return the result.
1870        return $retVal;
1871    }
1872    
1873    =head3 GetBoundaries
1874    
1875    C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>
1876    
1877    Determine the begin and end boundaries for the locations in a list. All of the
1878    locations must belong to the same contig and have mostly the same direction in
1879    order for this method to produce a meaningful result. The resulting
1880    begin/end pair will contain all of the bases in any of the locations.
1881    
1882    =over 4
1883    
1884    =item locList
1885    
1886    List of locations to process.
1887    
1888    =item RETURN
1889    
1890    Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1891    and the ending boundary. The beginning boundary will be left of the
1892    end for mostly-forward locations and right of the end for mostly-backward
1893    locations.
1894    
1895    =back
1896    
1897    =cut
1898    
1899    sub GetBoundaries {
1900        # Get the parameters.
1901        my ($self, @locList) = @_;
1902        # Set up the counters used to determine the most popular direction.
1903        my %counts = ( '+' => 0, '-' => 0 );
1904        # Get the last location and parse it.
1905        my $locObject = BasicLocation->new(pop @locList);
1906        # Prime the loop with its data.
1907        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
1908        # Count its direction.
1909        $counts{$locObject->Dir}++;
1910        # Loop through the remaining locations. Note that in most situations, this loop
1911        # will not iterate at all, because most of the time we will be dealing with a
1912        # singleton list.
1913        for my $loc (@locList) {
1914            # Create a location object.
1915            my $locObject = BasicLocation->new($loc);
1916            # Count the direction.
1917            $counts{$locObject->Dir}++;
1918            # Get the left end and the right end.
1919            my $left = $locObject->Left;
1920            my $right = $locObject->Right;
1921            # Merge them into the return variables.
1922            if ($left < $beg) {
1923                $beg = $left;
1924            }
1925            if ($right > $end) {
1926                $end = $right;
1927            }
1928        }
1929        # If the most common direction is reverse, flip the begin and end markers.
1930        if ($counts{'-'} > $counts{'+'}) {
1931            ($beg, $end) = ($end, $beg);
1932        }
1933        # Return the result.
1934        return ($contig, $beg, $end);
1935    }
1936    
1937  =head3 CouplingID  =head3 CouplingID
1938    
1939  C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>  C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >>
1940    
1941  Return the coupling ID for a pair of feature IDs.  Return the coupling ID for a pair of feature IDs.
1942    
# Line 1706  Line 1969 
1969  =cut  =cut
1970  #: Return Type $;  #: Return Type $;
1971  sub CouplingID {  sub CouplingID {
1972      return join " ", sort @_;      my ($self, @pegs) = @_;
1973  }      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();  
1974  }  }
1975    
1976  =head3 ReadFasta  =head3 ReadFasta
# Line 1871  Line 2118 
2118      # Get the data directory name.      # Get the data directory name.
2119      my $outputDirectory = $self->{_options}->{dataDir};      my $outputDirectory = $self->{_options}->{dataDir};
2120      # Dump the relations.      # Dump the relations.
2121      $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2122  }  }
2123    
2124  =head3 XMLFileName  =head3 XMLFileName
# Line 1923  Line 2170 
2170      # Get the parameters.      # Get the parameters.
2171      my ($self, $objectType, $fieldHash) = @_;      my ($self, $objectType, $fieldHash) = @_;
2172      # Call the underlying method.      # Call the underlying method.
2173      $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2174  }  }
2175    
2176  =head3 Annotate  =head3 Annotate
# Line 2082  Line 2329 
2329      return @retVal;      return @retVal;
2330  }  }
2331    
 =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;  
 }  
   
2332  =head3 FeatureTranslation  =head3 FeatureTranslation
2333    
2334  C<< my $translation = $sprout->FeatureTranslation($featureID); >>  C<< my $translation = $sprout->FeatureTranslation($featureID); >>
# Line 2604  Line 2816 
2816                                      ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                      ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2817      # Create the return value.      # Create the return value.
2818      my %retVal = ();      my %retVal = ();
2819        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2820        # in two spreadsheet cells.
2821        my %dupHash = ();
2822      # Loop through the results, adding them to the hash.      # Loop through the results, adding them to the hash.
2823      for my $record (@subsystems) {      for my $record (@subsystems) {
2824            # Get this subsystem and role.
2825          my ($subsys, $role) = @{$record};          my ($subsys, $role) = @{$record};
2826          if (exists $retVal{$subsys}) {          # Insure it's the first time for both.
2827            my $dupKey = "$subsys\n$role";
2828            if (! exists $dupHash{"$subsys\n$role"}) {
2829                $dupHash{$dupKey} = 1;
2830              push @{$retVal{$subsys}}, $role;              push @{$retVal{$subsys}}, $role;
         } else {  
             $retVal{$subsys} = [$role];  
2831          }          }
2832      }      }
2833      # Return the hash.      # Return the hash.
# Line 2750  Line 2967 
2967      return @retVal;      return @retVal;
2968  }  }
2969    
 =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;  
 }  
   
2970  =head3 Protein  =head3 Protein
2971    
2972  C<< my $protein = Sprout::Protein($sequence, $table); >>  C<< my $protein = Sprout::Protein($sequence, $table); >>
# Line 2970  Line 3068 
3068      # 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.
3069      my @retVal = ($self->{_options}->{dataDir});      my @retVal = ($self->{_options}->{dataDir});
3070      # Concatenate the table names.      # Concatenate the table names.
3071      push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
3072      # Return the result.      # Return the result.
3073      return @retVal;      return @retVal;
3074  }  }
3075    
3076  =head3 LowBBHs  =head3 LowBBHs
3077    
3078  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
3079    
3080  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
3081  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 3019  Line 3117 
3117      return %retVal;      return %retVal;
3118  }  }
3119    
3120    =head3 Sims
3121    
3122    C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>
3123    
3124    Get a list of similarities for a specified feature. Similarity information is not kept in the
3125    Sprout database; rather, they are retrieved from a network server. The similarities are
3126    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3127    so that its elements can be accessed by name.
3128    
3129    Similarities can be either raw or expanded. The raw similarities are basic
3130    hits between features with similar DNA. Expanding a raw similarity drags in any
3131    features considered substantially identical. So, for example, if features B<A1>,
3132    B<A2>, and B<A3> are all substatially identical to B<A>, then a raw similarity
3133    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3134    
3135    =over 4
3136    
3137    =item fid
3138    
3139    ID of the feature whose similarities are desired.
3140    
3141    =item maxN
3142    
3143    Maximum number of similarities to return.
3144    
3145    =item maxP
3146    
3147    Minumum allowable similarity score.
3148    
3149    =item select
3150    
3151    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3152    means only similarities to FIG features are returned; C<all> means all expanded
3153    similarities are returned; and C<figx> means similarities are expanded until the
3154    number of FIG features equals the maximum.
3155    
3156    =item max_expand
3157    
3158    The maximum number of features to expand.
3159    
3160    =item filters
3161    
3162    Reference to a hash containing filter information, or a subroutine that can be
3163    used to filter the sims.
3164    
3165    =item RETURN
3166    
3167    Returns a reference to a list of similarity objects, or C<undef> if an error
3168    occurred.
3169    
3170    =back
3171    
3172    =cut
3173    
3174    sub Sims {
3175        # Get the parameters.
3176        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3177        # Create the shim object to test for deleted FIDs.
3178        my $shim = FidCheck->new($self);
3179        # Ask the network for sims.
3180        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3181        # Return the result.
3182        return $retVal;
3183    }
3184    
3185  =head3 GetGroups  =head3 GetGroups
3186    
3187  C<< my %groups = $sprout->GetGroups(\@groupList); >>  C<< my %groups = $sprout->GetGroups(\@groupList); >>
# Line 3140  Line 3303 
3303      return $retVal;      return $retVal;
3304  }  }
3305    
3306    =head3 DeleteGenome
3307    
3308    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3309    
3310    Delete a genome from the database.
3311    
3312    =over 4
3313    
3314    =item genomeID
3315    
3316    ID of the genome to delete
3317    
3318    =item testFlag
3319    
3320    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3321    
3322    =item RETURN
3323    
3324    Returns a statistics object describing the rows deleted.
3325    
3326    =back
3327    
3328    =cut
3329    #: Return Type $%;
3330    sub DeleteGenome {
3331        # Get the parameters.
3332        my ($self, $genomeID, $testFlag) = @_;
3333        # Perform the delete for the genome's features.
3334        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);
3335        # Perform the delete for the primary genome data.
3336        my $stats = $self->Delete('Genome', $genomeID, $testFlag);
3337        $retVal->Accumulate($stats);
3338        # Return the result.
3339        return $retVal;
3340    }
3341    
3342  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3343    
3344  =head3 ParseAssignment  =head3 ParseAssignment
# Line 3150  Line 3349 
3349    
3350  A functional assignment is always of the form  A functional assignment is always of the form
3351    
3352      I<XXXX>C<\nset >I<YYYY>C< function to\n>I<ZZZZZ>      C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3353    
3354  where I<XXXX> is the B<assigning user>, I<YYYY> is the B<user>, and I<ZZZZ> is the  where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3355  actual functional role. In most cases, the user and the assigning user will be the  the user and the assigning user (from MadeAnnotation) will be the same, but that is
3356  same, but that is not always the case.  not always the case.
3357    
3358    In addition, the functional role may contain extra data that is stripped, such as
3359    terminating spaces or a comment separated from the rest of the text by a tab.
3360    
3361  This is a static method.  This is a static method.
3362    
3363  =over 4  =over 4
3364    
3365    =item user
3366    
3367    Name of the assigning user.
3368    
3369  =item text  =item text
3370    
3371  Text of the annotation.  Text of the annotation.
# Line 3175  Line 3381 
3381    
3382  sub _ParseAssignment {  sub _ParseAssignment {
3383      # Get the parameters.      # Get the parameters.
3384      my ($text) = @_;      my ($user, $text) = @_;
3385      # Declare the return value.      # Declare the return value.
3386      my @retVal = ();      my @retVal = ();
3387      # Check to see if this is a functional assignment.      # Check to see if this is a functional assignment.
3388      my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3389      if ($type =~ m/^set ([^ ]+) function to$/i) {      if ($type =~ m/^set function to$/i) {
3390          # Here it is, so we return the user name (which is in $1), the functional role text,          # Here we have an assignment without a user, so we use the incoming user ID.
3391          # and the assigning user.          @retVal = ($user, $function);
3392          @retVal = ($1, $function, $user);      } elsif ($type =~ m/^set (\S+) function to$/i) {
3393            # Here we have an assignment with a user that is passed back to the caller.
3394            @retVal = ($1, $function);
3395        }
3396        # If we have an assignment, we need to clean the function text. There may be
3397        # extra junk at the end added as a note from the user.
3398        if (@retVal) {
3399            $retVal[1] =~ s/(\t\S)?\s*$//;
3400      }      }
3401      # Return the result list.      # Return the result list.
3402      return @retVal;      return @retVal;
# Line 3273  Line 3486 
3486  }  }
3487    
3488    
   
3489  1;  1;

Legend:
Removed from v.1.40  
changed lines
  Added in v.1.78

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3