[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.12, Wed May 4 03:24:43 2005 UTC revision 1.77, Sun Jul 23 16:44:10 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>)
79    
80    * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
81    
82  =back  =back
83    
84  For example, the following constructor call specifies a database named I<Sprout> and a user name of  For example, the following constructor call specifies a database named I<Sprout> and a user name of
# Line 86  Line 95 
95          # 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
96          # the incoming data.          # the incoming data.
97          my $optionTable = Tracer::GetOptions({          my $optionTable = Tracer::GetOptions({
98                                             dbType               => 'mysql',                     # database type                         dbType       => $FIG_Config::dbms,
99                                             dataDir              => 'Data',                      # data file directory                                                          # database type
100                                             xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
101                                             userData             => 'root/',                     # user name and password                                                          # data file directory
102                                             port                 => 0,                           # database connection port                         xmlFileName  => "$FIG_Config::fig/SproutDBD.xml",
103                                                            # database definition file name
104                           userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
105                                                            # user name and password
106                           port         => $FIG_Config::dbport,
107                                                            # database connection port
108                           sock         => $FIG_Config::dbsock,
109                                             maxSegmentLength => 4500,            # maximum feature segment length                                             maxSegmentLength => 4500,            # maximum feature segment length
110                                             maxSequenceLength => 8000,           # maximum contig sequence length                                             maxSequenceLength => 8000,           # maximum contig sequence length
111                           noDBOpen     => 0,               # 1 to suppress the database open
112                                            }, $options);                                            }, $options);
113          # Get the data directory.          # Get the data directory.
114          my $dataDir = $optionTable->{dataDir};          my $dataDir = $optionTable->{dataDir};
# Line 100  Line 116 
116          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
117          my ($userName, $password) = ($1, $2);          my ($userName, $password) = ($1, $2);
118          # Connect to the database.          # Connect to the database.
119          my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
120        if (! $optionTable->{noDBOpen}) {
121            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
122                                    $password, $optionTable->{port}, undef, $optionTable->{sock});
123        }
124          # Create the ERDB object.          # Create the ERDB object.
125          my $xmlFileName = "$optionTable->{xmlFileName}";          my $xmlFileName = "$optionTable->{xmlFileName}";
126          my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
127          # Create this object.      # Add the option table and XML file name.
128          my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
129          # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
130          bless $self;      # Return it.
131          return $self;      return $retVal;
132  }  }
133    
134  =head3 MaxSegment  =head3 MaxSegment
# Line 143  Line 163 
163          return $self->{_options}->{maxSequenceLength};          return $self->{_options}->{maxSequenceLength};
164  }  }
165    
 =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);  
 }  
   
166  =head3 Load  =head3 Load
167    
168  C<< $sprout->Load($rebuild); >>;  C<< $sprout->Load($rebuild); >>;
# Line 367  Line 197 
197  sub Load {  sub Load {
198          # Get the parameters.          # Get the parameters.
199          my ($self, $rebuild) = @_;          my ($self, $rebuild) = @_;
         # Get the database object.  
         my $erdb = $self->{_erdb};  
200          # Load the tables from the data directory.          # Load the tables from the data directory.
201          my $retVal = $erdb->LoadTables($self->{_options}->{dataDir}, $rebuild);      my $retVal = $self->LoadTables($self->{_options}->{dataDir}, $rebuild);
202          # Return the statistics.          # Return the statistics.
203          return $retVal;          return $retVal;
204  }  }
205    
206  =head3 LoadUpdate  =head3 LoadUpdate
207    
208  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
209    
210  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
211  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 410  Line 238 
238  sub LoadUpdate {  sub LoadUpdate {
239          # Get the parameters.          # Get the parameters.
240          my ($self, $truncateFlag, $tableList) = @_;          my ($self, $truncateFlag, $tableList) = @_;
         # Get the database object.  
         my $erdb = $self->{_erdb};  
241          # Declare the return value.          # Declare the return value.
242          my $retVal = Stats->new();          my $retVal = Stats->new();
243          # Get the data directory.          # Get the data directory.
# Line 420  Line 246 
246          # Loop through the incoming table names.          # Loop through the incoming table names.
247          for my $tableName (@{$tableList}) {          for my $tableName (@{$tableList}) {
248                  # Find the table's file.                  # Find the table's file.
249                  my $fileName = "$dataDir/$tableName";          my $fileName = LoadFileName($dataDir, $tableName);
250                  if (! -e $fileName) {          if (! $fileName) {
251                          $fileName = "$fileName.dtx";              Trace("No load file found for $tableName in $dataDir.") if T(0);
252                  }          } else {
253                  # Attempt to load this table.                  # Attempt to load this table.
254                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);              my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);
255                  # Accumulate the resulting statistics.                  # Accumulate the resulting statistics.
256                  $retVal->Accumulate($result);                  $retVal->Accumulate($result);
257          }          }
258        }
259          # Return the statistics.          # Return the statistics.
260          return $retVal;          return $retVal;
261  }  }
262    
263    =head3 GenomeCounts
264    
265    C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>
266    
267    Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
268    genomes will be included in the counts.
269    
270    =over 4
271    
272    =item complete
273    
274    TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
275    counted
276    
277    =item RETURN
278    
279    A six-element list containing the number of genomes in each of six categories--
280    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
281    
282    =back
283    
284    =cut
285    
286    sub GenomeCounts {
287        # Get the parameters.
288        my ($self, $complete) = @_;
289        # Set the filter based on the completeness flag.
290        my $filter = ($complete ? "Genome(complete) = 1" : "");
291        # Get all the genomes and the related taxonomy information.
292        my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
293        # Clear the counters.
294        my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
295        # Loop through, counting the domains.
296        for my $genome (@genomes) {
297            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
298            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
299            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
300            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
301            elsif ($genome->[1] =~ /^env/i)      { ++$env }
302            else  { ++$unk }
303        }
304        # Return the counts.
305        return ($arch, $bact, $euk, $vir, $env, $unk);
306    }
307    
308    =head3 ContigCount
309    
310    C<< my $count = $sprout->ContigCount($genomeID); >>
311    
312    Return the number of contigs for the specified genome ID.
313    
314    =over 4
315    
316    =item genomeID
317    
318    ID of the genome whose contig count is desired.
319    
320    =item RETURN
321    
322    Returns the number of contigs for the specified genome.
323    
324    =back
325    
326    =cut
327    
328    sub ContigCount {
329        # Get the parameters.
330        my ($self, $genomeID) = @_;
331        # Get the contig count.
332        my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
333        # Return the result.
334        return $retVal;
335    }
336    
337    =head3 GeneMenu
338    
339    C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params); >>
340    
341    Return an HTML select menu of genomes. Each genome will be an option in the menu,
342    and will be displayed by name with the ID and a contig count attached. The selection
343    value will be the genome ID. The genomes will be sorted by genus/species name.
344    
345    =over 4
346    
347    =item attributes
348    
349    Reference to a hash mapping attributes to values for the SELECT tag generated.
350    
351    =item filterString
352    
353    A filter string for use in selecting the genomes. The filter string must conform
354    to the rules for the C<< ERDB->Get >> method.
355    
356    =item params
357    
358    Reference to a list of values to be substituted in for the parameter marks in
359    the filter string.
360    
361    =item RETURN
362    
363    Returns an HTML select menu with the specified genomes as selectable options.
364    
365    =back
366    
367    =cut
368    
369    sub GeneMenu {
370        # Get the parameters.
371        my ($self, $attributes, $filterString, $params) = @_;
372        # Start the menu.
373        my $retVal = "<select " .
374            join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
375            ">\n";
376        # Get the genomes.
377        my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
378                                                                         'Genome(genus)',
379                                                                         'Genome(species)',
380                                                                         'Genome(unique-characterization)']);
381        # Sort them by name.
382        my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
383        # Loop through the genomes, creating the option tags.
384        for my $genomeData (@sorted) {
385            # Get the data for this genome.
386            my ($genomeID, $genus, $species, $strain) = @{$genomeData};
387            # Get the contig count.
388            my $count = $self->ContigCount($genomeID);
389            my $counting = ($count == 1 ? "contig" : "contigs");
390            # Build the option tag.
391            $retVal .= "<option value=\"$genomeID\">$genus $species $strain ($genomeID) [$count $counting]</option>\n";
392            Trace("Option tag built for $genomeID: $genus $species $strain.") if T(3);
393        }
394        # Close the SELECT tag.
395        $retVal .= "</select>\n";
396        # Return the result.
397        return $retVal;
398    }
399  =head3 Build  =head3 Build
400    
401  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 447  Line 410 
410          # Get the parameters.          # Get the parameters.
411          my ($self) = @_;          my ($self) = @_;
412          # Create the tables.          # Create the tables.
413          $self->{_erdb}->CreateTables;      $self->CreateTables();
414  }  }
415    
416  =head3 Genomes  =head3 Genomes
# Line 570  Line 533 
533  =item RETURN  =item RETURN
534    
535  Returns a list of the feature's contig segments. The locations are returned as a list in a list  Returns a list of the feature's contig segments. The locations are returned as a list in a list
536  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context.
537    
538  =back  =back
539    
# Line 597  Line 560 
560                  if ($prevContig eq $contigID && $dir eq $prevDir) {                  if ($prevContig eq $contigID && $dir eq $prevDir) {
561                          # 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
562                          # new segment's beginning is next to the old segment's end.                          # new segment's beginning is next to the old segment's end.
563                          if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||              if ($dir eq "-" && $beg + $len == $prevBeg) {
564                                  ($dir eq "+" && $beg == $prevBeg + $prevLen)) {                  # Here we're merging two backward blocks, so we keep the new begin point
565                                  # Here we need to merge two segments. Adjust the beginning and length values                  # and adjust the length.
566                                  # to include both segments.                  $len += $prevLen;
567                    # Pop the old segment off. The new one will replace it later.
568                    pop @retVal;
569                } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
570                    # Here we need to merge two forward blocks. Adjust the beginning and
571                    # length values to include both segments.
572                                  $beg = $prevBeg;                                  $beg = $prevBeg;
573                                  $len += $prevLen;                                  $len += $prevLen;
574                                  # Pop the old segment off. The new one will replace it later.                                  # Pop the old segment off. The new one will replace it later.
# Line 609  Line 577 
577                  }                  }
578                  # Remember this specifier for the adjacent-segment test the next time through.                  # Remember this specifier for the adjacent-segment test the next time through.
579                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
580            # Compute the initial base pair.
581            my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
582                  # Add the specifier to the list.                  # Add the specifier to the list.
583                  push @retVal, "${contigID}_$beg$dir$len";          push @retVal, "${contigID}_$start$dir$len";
584          }          }
585          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
586          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
587  }  }
588    
589  =head3 ParseLocation  =head3 ParseLocation
# Line 644  Line 614 
614      shift if UNIVERSAL::isa($_[0],__PACKAGE__);      shift if UNIVERSAL::isa($_[0],__PACKAGE__);
615          my ($location) = @_;          my ($location) = @_;
616          # Parse it into segments.          # Parse it into segments.
617          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
618          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
619          # If the direction is an underscore, convert it to a + or -.          # If the direction is an underscore, convert it to a + or -.
620          if ($dir eq "_") {          if ($dir eq "_") {
# Line 720  Line 690 
690  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,
691  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>.
692    
693    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
694    between positions 1401 and 1532, inclusive.
695    
696        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
697    
698  =over 4  =over 4
699    
700  =item locationList  =item locationList
701    
702  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
703  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
704    
705  =item RETURN  =item RETURN
706    
# Line 752  Line 727 
727                  # the start point is the ending. Note that in the latter case we must reverse the DNA string                  # the start point is the ending. Note that in the latter case we must reverse the DNA string
728                  # before putting it in the return value.                  # before putting it in the return value.
729                  my ($start, $stop);                  my ($start, $stop);
730            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
731                  if ($dir eq "+") {                  if ($dir eq "+") {
732                          $start = $beg;                          $start = $beg;
733                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
734                  } else {                  } else {
735                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
736                          $stop = $beg;                          $stop = $beg;
737                  }                  }
738            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
739                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
740                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
741                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 770  Line 747 
747                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
748                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
749                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
750                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
751                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
752                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
753                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
754                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
755                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
756                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
757                  }                  }
758                  # Add this location's data to the return string. Note that we may need to reverse it.                  # Add this location's data to the return string. Note that we may need to reverse it.
759                  if ($dir eq '+') {                  if ($dir eq '+') {
760                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
761                  } else {                  } else {
762                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
763                  }                  }
764          }          }
765          # Return the result.          # Return the result.
# Line 818  Line 796 
796          return @retVal;          return @retVal;
797  }  }
798    
799    =head3 GenomeLength
800    
801    C<< my $length = $sprout->GenomeLength($genomeID); >>
802    
803    Return the length of the specified genome in base pairs.
804    
805    =over 4
806    
807    =item genomeID
808    
809    ID of the genome whose base pair count is desired.
810    
811    =item RETURN
812    
813    Returns the number of base pairs in all the contigs of the specified
814    genome.
815    
816    =back
817    
818    =cut
819    
820    sub GenomeLength {
821        # Get the parameters.
822        my ($self, $genomeID) = @_;
823        # Declare the return variable.
824        my $retVal = 0;
825        # Get the genome's contig sequence lengths.
826        my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
827                           [$genomeID], 'IsMadeUpOf(len)');
828        # Sum the lengths.
829        map { $retVal += $_ } @lens;
830        # Return the result.
831        return $retVal;
832    }
833    
834    =head3 FeatureCount
835    
836    C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
837    
838    Return the number of features of the specified type in the specified genome.
839    
840    =over 4
841    
842    =item genomeID
843    
844    ID of the genome whose feature count is desired.
845    
846    =item type
847    
848    Type of feature to count (eg. C<peg>, C<rna>, etc.).
849    
850    =item RETURN
851    
852    Returns the number of features of the specified type for the specified genome.
853    
854    =back
855    
856    =cut
857    
858    sub FeatureCount {
859        # Get the parameters.
860        my ($self, $genomeID, $type) = @_;
861        # Compute the count.
862        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
863                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
864                                    [$genomeID, $type]);
865        # Return the result.
866        return $retVal;
867    }
868    
869    =head3 GenomeAssignments
870    
871    C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
872    
873    Return a list of a genome's assigned features. The return hash will contain each
874    assigned feature of the genome mapped to the text of its most recent functional
875    assignment.
876    
877    =over 4
878    
879    =item genomeID
880    
881    ID of the genome whose functional assignments are desired.
882    
883    =item RETURN
884    
885    Returns a reference to a hash which maps each feature to its most recent
886    functional assignment.
887    
888    =back
889    
890    =cut
891    
892    sub GenomeAssignments {
893        # Get the parameters.
894        my ($self, $genomeID) = @_;
895        # Declare the return variable.
896        my $retVal = {};
897        # Query the genome's features and annotations. We'll put the oldest annotations
898        # first so that the last assignment to go into the hash will be the correct one.
899        my $query = $self->Get(['HasFeature', 'IsTargetOfAnnotation', 'Annotation'],
900                               "HasFeature(from-link) = ? ORDER BY Annotation(time)",
901                               [$genomeID]);
902        # Loop through the annotations.
903        while (my $data = $query->Fetch) {
904            # Get the feature ID and annotation text.
905            my ($fid, $annotation) = $data->Values(['HasFeature(to-link)',
906                                                    'Annotation(annotation)']);
907            # Check to see if this is an assignment. Note that the user really
908            # doesn't matter to us, other than we use it to determine whether or
909            # not this is an assignment.
910            my ($user, $assignment) = _ParseAssignment('fig', $annotation);
911            if ($user) {
912                # Here it's an assignment. We put it in the return hash, overwriting
913                # any older assignment that might be present.
914                $retVal->{$fid} = $assignment;
915            }
916        }
917        # Return the result.
918        return $retVal;
919    }
920    
921  =head3 ContigLength  =head3 ContigLength
922    
923  C<< my $length = $sprout->ContigLength($contigID); >>  C<< my $length = $sprout->ContigLength($contigID); >>
# Line 851  Line 951 
951          # Set it from the sequence data, if any.          # Set it from the sequence data, if any.
952          if ($sequence) {          if ($sequence) {
953                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
954                  $retVal = $start + $len;          $retVal = $start + $len - 1;
955        }
956        # Return the result.
957        return $retVal;
958    }
959    
960    =head3 ClusterPEGs
961    
962    C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
963    
964    Cluster the PEGs in a list according to the cluster coding scheme of the specified
965    subsystem. In order for this to work properly, the subsystem object must have
966    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
967    This causes the cluster numbers to be pulled into the subsystem's color hash.
968    If a PEG is not found in the color hash, it will not appear in the output
969    sequence.
970    
971    =over 4
972    
973    =item sub
974    
975    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
976    method.
977    
978    =item pegs
979    
980    Reference to the list of PEGs to be clustered.
981    
982    =item RETURN
983    
984    Returns a list of the PEGs, grouped into smaller lists by cluster number.
985    
986    =back
987    
988    =cut
989    #: Return Type $@@;
990    sub ClusterPEGs {
991        # Get the parameters.
992        my ($self, $sub, $pegs) = @_;
993        # Declare the return variable.
994        my $retVal = [];
995        # Loop through the PEGs, creating arrays for each cluster.
996        for my $pegID (@{$pegs}) {
997            my $clusterNumber = $sub->get_cluster_number($pegID);
998            # Only proceed if the PEG is in a cluster.
999            if ($clusterNumber >= 0) {
1000                # Push this PEG onto the sub-list for the specified cluster number.
1001                push @{$retVal->[$clusterNumber]}, $pegID;
1002            }
1003          }          }
1004          # Return the result.          # Return the result.
1005          return $retVal;          return $retVal;
# Line 1001  Line 1149 
1149    
1150  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1151    
1152  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1153    
1154  Return the annotations of a feature.  Return the annotations of a feature.
1155    
# Line 1011  Line 1159 
1159    
1160  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1161    
1162    =item rawFlag
1163    
1164    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1165    will be returned in human-readable form.
1166    
1167  =item RETURN  =item RETURN
1168    
1169  Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.  Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.
1170    
1171  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1172    
1173  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1174    
1175  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1176    
# Line 1029  Line 1182 
1182  #: Return Type @%;  #: Return Type @%;
1183  sub FeatureAnnotations {  sub FeatureAnnotations {
1184          # Get the parameters.          # Get the parameters.
1185          my ($self, $featureID) = @_;      my ($self, $featureID, $rawFlag) = @_;
1186          # Create a query to get the feature's annotations and the associated users.          # Create a query to get the feature's annotations and the associated users.
1187          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1188                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 1042  Line 1195 
1195                          $annotation->Values(['IsTargetOfAnnotation(from-link)',                          $annotation->Values(['IsTargetOfAnnotation(from-link)',
1196                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1197                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1198            # Convert the time, if necessary.
1199            if (! $rawFlag) {
1200                $timeStamp = FriendlyTimestamp($timeStamp);
1201            }
1202                  # Assemble them into a hash.                  # Assemble them into a hash.
1203          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1204                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1205                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1206                  # Add it to the return list.                  # Add it to the return list.
1207                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1073  Line 1230 
1230    
1231  =item RETURN  =item RETURN
1232    
1233  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1234    
1235  =back  =back
1236    
# Line 1083  Line 1240 
1240          # Get the parameters.          # Get the parameters.
1241          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
1242          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1243      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1244                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1245                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1246                                               'MadeAnnotation(from-link)']);
1247          # Declare the return hash.          # Declare the return hash.
1248          my %retVal;          my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1249      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1250      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1251          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1252      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1253          # Get the annotation fields.          # Get the annotation fields.
1254          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1255                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1256                  my ($user, $function) = _ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1257          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1258              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1259              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1260              # return hash.              # return hash.
1261                          $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1262                  }                  }
1263          }          }
1264          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1120  Line 1274 
1274  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
1275  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
1276  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
1277  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
1278  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
1279  most features only have a small number of annotations.  most features only have a small number of annotations.
1280    
# Line 1182  Line 1336 
1336              }              }
1337          }          }
1338          # 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.
1339          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1340                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1341                                 [$featureID]);                                 [$featureID]);
1342          my $timeSelected = 0;          my $timeSelected = 0;
1343          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1344          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1345              # Get the annotation text.              # Get the annotation text.
1346              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);              my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1347                                                         'Annotation(time)', 'MadeAnnotation(from-link)']);
1348              # 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.
1349              my ($user, $function) = _ParseAssignment($text);              my ($actualUser, $function) = _ParseAssignment($user, $text);
1350              if ($user) {              Trace("Assignment user is $actualUser, text is $function.") if T(4);
1351                if ($actualUser) {
1352                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1353                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1354                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                  if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1355                      $retVal = $function;                      $retVal = $function;
1356                      $timeSelected = $time;                      $timeSelected = $time;
1357                  }                  }
# Line 1211  Line 1367 
1367          return $retVal;          return $retVal;
1368  }  }
1369    
1370    =head3 FunctionsOf
1371    
1372    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1373    
1374    Return the functional assignments of a particular feature.
1375    
1376    The functional assignment is handled differently depending on the type of feature. If
1377    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1378    assignment is a type of annotation. The format of an assignment is described in
1379    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1380    annotation itself because it's a text field; however, this is not a big problem because
1381    most features only have a small number of annotations.
1382    
1383    If the feature is B<not> identified by a FIG ID, then the functional assignment
1384    information is taken from the B<ExternalAliasFunc> table. If the table does
1385    not contain an entry for the feature, an empty list is returned.
1386    
1387    =over 4
1388    
1389    =item featureID
1390    
1391    ID of the feature whose functional assignments are desired.
1392    
1393    =item RETURN
1394    
1395    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1396    that user.
1397    
1398    =back
1399    
1400    =cut
1401    #: Return Type @@;
1402    sub FunctionsOf {
1403        # Get the parameters.
1404        my ($self, $featureID) = @_;
1405        # Declare the return value.
1406        my @retVal = ();
1407        # Determine the ID type.
1408        if ($featureID =~ m/^fig\|/) {
1409            # Here we have a FIG feature ID. We must build the list of trusted
1410            # users.
1411            my %trusteeTable = ();
1412            # Build a query for all of the feature's annotations, sorted by date.
1413            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1414                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1415                                   [$featureID]);
1416            my $timeSelected = 0;
1417            # Loop until we run out of annotations.
1418            while (my $annotation = $query->Fetch()) {
1419                # Get the annotation text.
1420                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1421                                                                'Annotation(time)',
1422                                                                'MadeAnnotation(user)']);
1423                # Check to see if this is a functional assignment for a trusted user.
1424                my ($actualUser, $function) = _ParseAssignment($user, $text);
1425                if ($actualUser) {
1426                    # Here it is a functional assignment.
1427                    push @retVal, [$actualUser, $function];
1428                }
1429            }
1430        } else {
1431            # Here we have a non-FIG feature ID. In this case the user ID does not
1432            # matter. We simply get the information from the External Alias Function
1433            # table.
1434            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1435                                                     ['ExternalAliasFunc(func)']);
1436            push @retVal, map { ['master', $_] } @assignments;
1437        }
1438        # Return the assignments found.
1439        return @retVal;
1440    }
1441    
1442  =head3 BBHList  =head3 BBHList
1443    
1444  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1230  Line 1458 
1458    
1459  =item RETURN  =item RETURN
1460    
1461  Returns a reference to a hash that maps the IDs of the incoming features to the IDs of  Returns a reference to a hash that maps the IDs of the incoming features to the best hits
1462  their best hits.  on the target genome.
1463    
1464  =back  =back
1465    
# Line 1248  Line 1476 
1476                  my $query = $self->Get(['IsBidirectionalBestHitOf'],                  my $query = $self->Get(['IsBidirectionalBestHitOf'],
1477                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",
1478                                                             [$featureID, $genomeID]);                                                             [$featureID, $genomeID]);
1479                  # Look for the best hit.          # Peel off the BBHs found.
1480                  my $bbh = $query->Fetch;          my @found = ();
1481                  if ($bbh) {          while (my $bbh = $query->Fetch) {
1482                          my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');
                         $retVal{$featureID} = $targetFeature;  
1483                  }                  }
1484            $retVal{$featureID} = \@found;
1485          }          }
1486          # Return the mapping.          # Return the mapping.
1487          return \%retVal;          return \%retVal;
1488  }  }
1489    
1490    =head3 SimList
1491    
1492    C<< my %similarities = $sprout->SimList($featureID, $count); >>
1493    
1494    Return a list of the similarities to the specified feature.
1495    
1496    Sprout does not support real similarities, so this method just returns the bidirectional
1497    best hits.
1498    
1499    =over 4
1500    
1501    =item featureID
1502    
1503    ID of the feature whose similarities are desired.
1504    
1505    =item count
1506    
1507    Maximum number of similar features to be returned, or C<0> to return them all.
1508    
1509    =back
1510    
1511    =cut
1512    #: Return Type %;
1513    sub SimList {
1514        # Get the parameters.
1515        my ($self, $featureID, $count) = @_;
1516        # Ask for the best hits.
1517        my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],
1518                                  "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",
1519                                  [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],
1520                                  $count);
1521        # Create the return value.
1522        my %retVal = ();
1523        for my $tuple (@lists) {
1524            $retVal{$tuple->[0]} = $tuple->[1];
1525        }
1526        # Return the result.
1527        return %retVal;
1528    }
1529    
1530    
1531    
1532    =head3 IsComplete
1533    
1534    C<< my $flag = $sprout->IsComplete($genomeID); >>
1535    
1536    Return TRUE if the specified genome is complete, else FALSE.
1537    
1538    =over 4
1539    
1540    =item genomeID
1541    
1542    ID of the genome whose completeness status is desired.
1543    
1544    =item RETURN
1545    
1546    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1547    not found.
1548    
1549    =back
1550    
1551    =cut
1552    #: Return Type $;
1553    sub IsComplete {
1554        # Get the parameters.
1555        my ($self, $genomeID) = @_;
1556        # Declare the return variable.
1557        my $retVal;
1558        # Get the genome's data.
1559        my $genomeData = $self->GetEntity('Genome', $genomeID);
1560        if ($genomeData) {
1561            # The genome exists, so get the completeness flag.
1562            ($retVal) = $genomeData->Value('Genome(complete)');
1563        }
1564        # Return the result.
1565        return $retVal;
1566    }
1567    
1568  =head3 FeatureAliases  =head3 FeatureAliases
1569    
1570  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
# Line 1293  Line 1599 
1599    
1600  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1601    
1602  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1603    
1604  =over 4  =over 4
1605    
1606  =item featureID  =item featureID
1607    
1608  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1609    
1610  =item RETURN  =item RETURN
1611    
1612  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
1613  an undefined value.  found, returns an undefined value.
1614    
1615  =back  =back
1616    
# Line 1313  Line 1619 
1619  sub GenomeOf {  sub GenomeOf {
1620          # Get the parameters.          # Get the parameters.
1621          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
1622          # Create a query to find the genome associated with the feature.      # Create a query to find the genome associated with the incoming ID.
1623          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1624                               [$featureID, $featureID]);
1625          # Declare the return value.          # Declare the return value.
1626          my $retVal;          my $retVal;
1627          # Get the genome ID.          # Get the genome ID.
# Line 1349  Line 1656 
1656  sub CoupledFeatures {  sub CoupledFeatures {
1657          # Get the parameters.          # Get the parameters.
1658          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
1659          # Create a query to retrieve the functionally-coupled features. Note that we depend on the      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1660          # fact that the functional coupling is physically paired. If (A,B) is in the database, then      # Create a query to retrieve the functionally-coupled features.
1661          # (B,A) will also be found.      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1662          my $query = $self->Get(['IsClusteredOnChromosomeWith'],                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);
                                                    "IsClusteredOnChromosomeWith(from-link) = ?", [$featureID]);  
1663          # This value will be set to TRUE if we find at least one coupled feature.          # This value will be set to TRUE if we find at least one coupled feature.
1664          my $found = 0;          my $found = 0;
1665          # Create the return hash.          # Create the return hash.
1666          my %retVal = ();          my %retVal = ();
1667          # Retrieve the relationship records and store them in the hash.          # Retrieve the relationship records and store them in the hash.
1668          while (my $clustering = $query->Fetch()) {          while (my $clustering = $query->Fetch()) {
1669                  my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',          # Get the ID and score of the coupling.
1670                                                                      'IsClusteredOnChromosomeWith(score)']);          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1671                                                            'Coupling(score)']);
1672            Trace("$featureID coupled with score $score to ID $couplingID.") if T(coupling => 4);
1673            # Get the other feature that participates in the coupling.
1674            my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],
1675                                               "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",
1676                                               [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');
1677            Trace("$couplingID target feature is $otherFeatureID.") if T(coupling => 4);
1678            # Attach the other feature's score to its ID.
1679                  $retVal{$otherFeatureID} = $score;                  $retVal{$otherFeatureID} = $score;
1680                  $found = 1;                  $found = 1;
1681          }          }
# Line 1374  Line 1688 
1688          return %retVal;          return %retVal;
1689  }  }
1690    
1691  =head3 GetEntityTypes  =head3 CouplingEvidence
1692    
1693    C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1694    
1695    Return the evidence for a functional coupling.
1696    
1697    A pair of features is considered evidence of a coupling between two other
1698    features if they occur close together on a contig and both are similar to
1699    the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1700    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1701    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1702    similar to B<A2>.
1703    
1704  C<< my @entityList = $sprout->GetEntityTypes(); >>  The score of a coupling is determined by the number of pieces of evidence
1705    that are considered I<representative>. If several evidence items belong to
1706    a group of genomes that are close to each other, only one of those items
1707    is considered representative. The other evidence items are presumed to be
1708    there because of the relationship between the genomes rather than because
1709    the two proteins generated by the features have a related functionality.
1710    
1711  Return the list of supported entity types.  Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1712    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1713    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1714    and FALSE otherwise.
1715    
1716    =over 4
1717    
1718    =item peg1
1719    
1720    ID of the feature of interest.
1721    
1722    =item peg2
1723    
1724    ID of a feature functionally coupled to the feature of interest.
1725    
1726    =item RETURN
1727    
1728    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1729    of interest, a feature similar to the functionally coupled feature, and a flag
1730    that is TRUE for a representative piece of evidence and FALSE otherwise.
1731    
1732    =back
1733    
1734  =cut  =cut
1735  #: Return Type @;  #: Return Type @@;
1736  sub GetEntityTypes {  sub CouplingEvidence {
1737          # Get the parameters.          # Get the parameters.
1738          my ($self) = @_;      my ($self, $peg1, $peg2) = @_;
1739          # Get the underlying database object.      # Declare the return variable.
1740          my $erdb = $self->{_erdb};      my @retVal = ();
1741          # Get its entity type list.      # Our first task is to find out the nature of the coupling: whether or not
1742          my @retVal = $erdb->GetEntityTypes();      # it exists, its score, and whether the features are stored in the same
1743        # order as the ones coming in.
1744        my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1745        # Only proceed if a coupling exists.
1746        if ($couplingID) {
1747            # Determine the ordering to place on the evidence items. If we're
1748            # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1749            # we want feature 1 before feature 2 (normal).
1750            Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);
1751            my $ordering = ($inverted ? "DESC" : "");
1752            # Get the coupling evidence.
1753            my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
1754                                              "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",
1755                                              [$couplingID],
1756                                              ['PCH(used)', 'UsesAsEvidence(to-link)']);
1757            # Loop through the evidence items. Each piece of evidence is represented by two
1758            # positions in the evidence list, one for each feature on the other side of the
1759            # evidence link. If at some point we want to generalize to couplings with
1760            # more than two positions, this section of code will need to be re-done.
1761            while (@evidenceList > 0) {
1762                my $peg1Data = shift @evidenceList;
1763                my $peg2Data = shift @evidenceList;
1764                Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1765                push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1766            }
1767            Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1768        }
1769        # Return the result.
1770        return @retVal;
1771    }
1772    
1773    =head3 GetCoupling
1774    
1775    C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>
1776    
1777    Return the coupling (if any) for the specified pair of PEGs. If a coupling
1778    exists, we return the coupling ID along with an indicator of whether the
1779    coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.
1780    In the second case, we say the coupling is I<inverted>. The importance of an
1781    inverted coupling is that the PEGs in the evidence will appear in reverse order.
1782    
1783    =over 4
1784    
1785    =item peg1
1786    
1787    ID of the feature of interest.
1788    
1789    =item peg2
1790    
1791    ID of the potentially coupled feature.
1792    
1793    =item RETURN
1794    
1795    Returns a three-element list. The first element contains the database ID of
1796    the coupling. The second element is FALSE if the coupling is stored in the
1797    database in the caller specified order and TRUE if it is stored in the
1798    inverted order. The third element is the coupling's score. If the coupling
1799    does not exist, all three list elements will be C<undef>.
1800    
1801    =back
1802    
1803    =cut
1804    #: Return Type $%@;
1805    sub GetCoupling {
1806        # Get the parameters.
1807        my ($self, $peg1, $peg2) = @_;
1808        # Declare the return values. We'll start with the coupling ID and undefine the
1809        # flag and score until we have more information.
1810        my ($retVal, $inverted, $score) = ($self->CouplingID($peg1, $peg2), undef, undef);
1811        # Find the coupling data.
1812        my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1813                                     "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1814                                     [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1815        # Check to see if we found anything.
1816        if (!@pegs) {
1817            Trace("No coupling found.") if T(Coupling => 4);
1818            # No coupling, so undefine the return value.
1819            $retVal = undef;
1820        } else {
1821            # We have a coupling! Get the score and check for inversion.
1822            $score = $pegs[0]->[1];
1823            my $firstFound = $pegs[0]->[0];
1824            $inverted = ($firstFound ne $peg1);
1825            Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1826        }
1827        # Return the result.
1828        return ($retVal, $inverted, $score);
1829    }
1830    
1831    =head3 GetSynonymGroup
1832    
1833    C<< my $id = $sprout->GetSynonymGroup($fid); >>
1834    
1835    Return the synonym group name for the specified feature.
1836    
1837    =over 4
1838    
1839    =item fid
1840    
1841    ID of the feature whose synonym group is desired.
1842    
1843    =item RETURN
1844    
1845    The name of the synonym group to which the feature belongs. If the feature does
1846    not belong to a synonym group, the feature ID itself is returned.
1847    
1848    =back
1849    
1850    =cut
1851    
1852    sub GetSynonymGroup {
1853        # Get the parameters.
1854        my ($self, $fid) = @_;
1855        # Declare the return variable.
1856        my $retVal;
1857        # Find the synonym group.
1858        my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1859                                       [$fid], 'IsSynonymGroupFor(from-link)');
1860        # Check to see if we found anything.
1861        if (@groups) {
1862            $retVal = $groups[0];
1863        } else {
1864            $retVal = $fid;
1865        }
1866        # Return the result.
1867        return $retVal;
1868    }
1869    
1870    =head3 GetBoundaries
1871    
1872    C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>
1873    
1874    Determine the begin and end boundaries for the locations in a list. All of the
1875    locations must belong to the same contig and have mostly the same direction in
1876    order for this method to produce a meaningful result. The resulting
1877    begin/end pair will contain all of the bases in any of the locations.
1878    
1879    =over 4
1880    
1881    =item locList
1882    
1883    List of locations to process.
1884    
1885    =item RETURN
1886    
1887    Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1888    and the ending boundary. The beginning boundary will be left of the
1889    end for mostly-forward locations and right of the end for mostly-backward
1890    locations.
1891    
1892    =back
1893    
1894    =cut
1895    
1896    sub GetBoundaries {
1897        # Get the parameters.
1898        my ($self, @locList) = @_;
1899        # Set up the counters used to determine the most popular direction.
1900        my %counts = ( '+' => 0, '-' => 0 );
1901        # Get the last location and parse it.
1902        my $locObject = BasicLocation->new(pop @locList);
1903        # Prime the loop with its data.
1904        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
1905        # Count its direction.
1906        $counts{$locObject->Dir}++;
1907        # Loop through the remaining locations. Note that in most situations, this loop
1908        # will not iterate at all, because most of the time we will be dealing with a
1909        # singleton list.
1910        for my $loc (@locList) {
1911            # Create a location object.
1912            my $locObject = BasicLocation->new($loc);
1913            # Count the direction.
1914            $counts{$locObject->Dir}++;
1915            # Get the left end and the right end.
1916            my $left = $locObject->Left;
1917            my $right = $locObject->Right;
1918            # Merge them into the return variables.
1919            if ($left < $beg) {
1920                $beg = $left;
1921            }
1922            if ($right > $end) {
1923                $end = $right;
1924            }
1925        }
1926        # If the most common direction is reverse, flip the begin and end markers.
1927        if ($counts{'-'} > $counts{'+'}) {
1928            ($beg, $end) = ($end, $beg);
1929        }
1930        # Return the result.
1931        return ($contig, $beg, $end);
1932    }
1933    
1934    =head3 CouplingID
1935    
1936    C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >>
1937    
1938    Return the coupling ID for a pair of feature IDs.
1939    
1940    The coupling ID is currently computed by joining the feature IDs in
1941    sorted order with a space. Client modules (that is, modules which
1942    use Sprout) should not, however, count on this always being the
1943    case. This method provides a way for abstracting the concept of a
1944    coupling ID. All that we know for sure about it is that it can be
1945    generated easily from the feature IDs and the order of the IDs
1946    in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>
1947    will have the same value as C<CouplingID("b1", "a1")>.
1948    
1949    =over 4
1950    
1951    =item peg1
1952    
1953    First feature of interest.
1954    
1955    =item peg2
1956    
1957    Second feature of interest.
1958    
1959    =item RETURN
1960    
1961    Returns the ID that would be used to represent a functional coupling of
1962    the two specified PEGs.
1963    
1964    =back
1965    
1966    =cut
1967    #: Return Type $;
1968    sub CouplingID {
1969        my ($self, @pegs) = @_;
1970        return $self->DigestKey(join " ", sort @pegs);
1971  }  }
1972    
1973  =head3 ReadFasta  =head3 ReadFasta
# Line 1435  Line 2014 
2014                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
2015                          # Here we have a new header. Store the current sequence if we have one.                          # Here we have a new header. Store the current sequence if we have one.
2016                          if ($id) {                          if ($id) {
2017                                  $retVal{$id} = uc $sequence;                  $retVal{$id} = lc $sequence;
2018                          }                          }
2019                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
2020                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
2021                  } else {                  } else {
2022                          # Here we have a data line, so we add it to the sequence accumulator.                          # Here we have a data line, so we add it to the sequence accumulator.
2023                          # First, we get the actual data out. Note that we normalize to upper              # First, we get the actual data out. Note that we normalize to lower
2024                          # case.                          # case.
2025                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
2026                          $sequence .= $1;                          $sequence .= $1;
# Line 1449  Line 2028 
2028          }          }
2029          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
2030          if ($sequence) {          if ($sequence) {
2031                  $retVal{$id} = uc $sequence;          $retVal{$id} = lc $sequence;
2032          }          }
2033          # Close the file.          # Close the file.
2034          close FASTAFILE;          close FASTAFILE;
# Line 1536  Line 2115 
2115          # Get the data directory name.          # Get the data directory name.
2116          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
2117          # Dump the relations.          # Dump the relations.
2118          $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2119  }  }
2120    
2121  =head3 XMLFileName  =head3 XMLFileName
# Line 1568  Line 2147 
2147  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
2148  property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.  property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
2149    
2150  C<< $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence = 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>  C<< $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>
2151    
2152  =over 4  =over 4
2153    
# Line 1588  Line 2167 
2167          # Get the parameters.          # Get the parameters.
2168          my ($self, $objectType, $fieldHash) = @_;          my ($self, $objectType, $fieldHash) = @_;
2169          # Call the underlying method.          # Call the underlying method.
2170          $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2171  }  }
2172    
2173  =head3 Annotate  =head3 Annotate
# Line 1747  Line 2326 
2326          return @retVal;          return @retVal;
2327  }  }
2328    
 =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.  
         my $testInstance = $self->GetEntity($entityName, $entityID);  
         # Return an existence indicator.  
         my $retVal = ($testInstance ? 1 : 0);  
         return $retVal;  
 }  
   
2329  =head3 FeatureTranslation  =head3 FeatureTranslation
2330    
2331  C<< my $translation = $sprout->FeatureTranslation($featureID); >>  C<< my $translation = $sprout->FeatureTranslation($featureID); >>
# Line 1966  Line 2511 
2511          return @retVal;          return @retVal;
2512  }  }
2513    
2514    =head3 GetProperties
2515    
2516    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2517    
2518    Return a list of the properties with the specified characteristics.
2519    
2520    Properties are arbitrary key-value pairs associated with a feature. (At some point they
2521    will also be associated with genomes.) A property value is represented by a 4-tuple of
2522    the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2523    
2524    =over 4
2525    
2526    =item fid
2527    
2528    ID of the feature possessing the property.
2529    
2530    =item key
2531    
2532    Name or key of the property.
2533    
2534    =item value
2535    
2536    Value of the property.
2537    
2538    =item url
2539    
2540    URL of the document that indicated the property should have this particular value, or an
2541    empty string if no such document exists.
2542    
2543    =back
2544    
2545    The parameters act as a filter for the desired data. Any non-null parameter will
2546    automatically match all the tuples returned. So, specifying just the I<$fid> will
2547    return all the properties of the specified feature; similarly, specifying the I<$key>
2548    and I<$value> parameters will return all the features having the specified property
2549    value.
2550    
2551    A single property key can have many values, representing different ideas about the
2552    feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2553    virulent, and another may declare that it is not virulent. A query about the virulence of
2554    C<fig|83333.1.peg.10> would be coded as
2555    
2556        my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2557    
2558    Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2559    not to be filtered. The tuples returned would be
2560    
2561        ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2562        ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2563    
2564    =cut
2565    #: Return Type @@;
2566    sub GetProperties {
2567        # Get the parameters.
2568        my ($self, @parms) = @_;
2569        # Declare the return variable.
2570        my @retVal = ();
2571        # Now we need to create a WHERE clause that will get us the data we want. First,
2572        # we create a list of the columns containing the data for each parameter.
2573        my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2574                        'Property(property-value)', 'HasProperty(evidence)');
2575        # Now we build the WHERE clause and the list of parameter values.
2576        my @where = ();
2577        my @values = ();
2578        for (my $i = 0; $i <= $#colNames; $i++) {
2579            my $parm = $parms[$i];
2580            if (defined $parm && ($parm ne '')) {
2581                push @where, "$colNames[$i] = ?";
2582                push @values, $parm;
2583            }
2584        }
2585        # Format the WHERE clause.
2586        my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2587        # Ask for all the propertie values with the desired characteristics.
2588        my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2589        while (my $valueObject = $query->Fetch()) {
2590            my @tuple = $valueObject->Values(\@colNames);
2591            push @retVal, \@tuple;
2592        }
2593        # Return the result.
2594        return @retVal;
2595    }
2596    
2597  =head3 FeatureProperties  =head3 FeatureProperties
2598    
2599  C<< my @properties = $sprout->FeatureProperties($featureID); >>  C<< my @properties = $sprout->FeatureProperties($featureID); >>
# Line 2160  Line 2788 
2788  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2789    
2790  Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped  Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped
2791  to the role the feature performs.  to the roles the feature performs.
2792    
2793  =over 4  =over 4
2794    
# Line 2170  Line 2798 
2798    
2799  =item RETURN  =item RETURN
2800    
2801  Returns a hash mapping all the feature's subsystems to the feature's role.  Returns a hash mapping all the feature's subsystems to a list of the feature's roles.
2802    
2803  =back  =back
2804    
2805  =cut  =cut
2806  #: Return Type %;  #: Return Type %@;
2807  sub SubsystemsOf {  sub SubsystemsOf {
2808          # Get the parameters.          # Get the parameters.
2809          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
2810          # Use the SSCell to connect features to subsystems.      # Get the subsystem list.
2811          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2812                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2813                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2814          # Create the return value.          # Create the return value.
2815          my %retVal = ();          my %retVal = ();
2816        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2817        # in two spreadsheet cells.
2818        my %dupHash = ();
2819          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
2820          for my $record (@subsystems) {          for my $record (@subsystems) {
2821                  $retVal{$record->[0]} = $record->[1];          # Get this subsystem and role.
2822            my ($subsys, $role) = @{$record};
2823            # Insure it's the first time for both.
2824            my $dupKey = "$subsys\n$role";
2825            if (! exists $dupHash{"$subsys\n$role"}) {
2826                $dupHash{$dupKey} = 1;
2827                push @{$retVal{$subsys}}, $role;
2828            }
2829          }          }
2830          # Return the hash.          # Return the hash.
2831          return %retVal;          return %retVal;
2832  }  }
2833    
2834    =head3 SubsystemList
2835    
2836    C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2837    
2838    Return a list containing the names of the subsystems in which the specified
2839    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2840    subsystem names, not the roles.
2841    
2842    =over 4
2843    
2844    =item featureID
2845    
2846    ID of the feature whose subsystem names are desired.
2847    
2848    =item RETURN
2849    
2850    Returns a list of the names of the subsystems in which the feature participates.
2851    
2852    =back
2853    
2854    =cut
2855    #: Return Type @;
2856    sub SubsystemList {
2857        # Get the parameters.
2858        my ($self, $featureID) = @_;
2859        # Get the list of names.
2860        my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",
2861                                    [$featureID], 'HasSSCell(from-link)');
2862        # Return the result.
2863        return @retVal;
2864    }
2865    
2866  =head3 RelatedFeatures  =head3 RelatedFeatures
2867    
2868  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2294  Line 2964 
2964          return @retVal;          return @retVal;
2965  }  }
2966    
 =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) = @_;  
         # Create the query.  
         my $query = $self->Get($objectNames, $filterClause, $parameterList);  
         # Set up a counter of the number of records read.  
         my $fetched = 0;  
         # Insure the counter has a value.  
         if (!defined $count) {  
                 $count = 0;  
         }  
         # Loop through the records returned, extracting the fields. Note that if the  
         # counter is non-zero, we stop when the number of records read hits the count.  
         my @retVal = ();  
         while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {  
                 my @rowData = $row->Values($fields);  
                 push @retVal, \@rowData;  
                 $fetched++;  
         }  
         # 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;  
 }  
   
2967  =head3 Protein  =head3 Protein
2968    
2969  C<< my $protein = Sprout::Protein($sequence, $table); >>  C<< my $protein = Sprout::Protein($sequence, $table); >>
# Line 2527  Line 3065 
3065          # 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.
3066          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
3067          # Concatenate the table names.          # Concatenate the table names.
3068          push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
3069          # Return the result.          # Return the result.
3070          return @retVal;          return @retVal;
3071  }  }
3072    
3073  =head3 LowBBHs  =head3 LowBBHs
3074    
3075  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
3076    
3077  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
3078  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 2576  Line 3114 
3114          return %retVal;          return %retVal;
3115  }  }
3116    
3117    =head3 Sims
3118    
3119    C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>
3120    
3121    Get a list of similarities for a specified feature. Similarity information is not kept in the
3122    Sprout database; rather, they are retrieved from a network server. The similarities are
3123    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3124    so that its elements can be accessed by name.
3125    
3126    Similarities can be either raw or expanded. The raw similarities are basic
3127    hits between features with similar DNA. Expanding a raw similarity drags in any
3128    features considered substantially identical. So, for example, if features B<A1>,
3129    B<A2>, and B<A3> are all substatially identical to B<A>, then a raw similarity
3130    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3131    
3132    =over 4
3133    
3134    =item fid
3135    
3136    ID of the feature whose similarities are desired.
3137    
3138    =item maxN
3139    
3140    Maximum number of similarities to return.
3141    
3142    =item maxP
3143    
3144    Minumum allowable similarity score.
3145    
3146    =item select
3147    
3148    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3149    means only similarities to FIG features are returned; C<all> means all expanded
3150    similarities are returned; and C<figx> means similarities are expanded until the
3151    number of FIG features equals the maximum.
3152    
3153    =item max_expand
3154    
3155    The maximum number of features to expand.
3156    
3157    =item filters
3158    
3159    Reference to a hash containing filter information, or a subroutine that can be
3160    used to filter the sims.
3161    
3162    =item RETURN
3163    
3164    Returns a reference to a list of similarity objects, or C<undef> if an error
3165    occurred.
3166    
3167    =back
3168    
3169    =cut
3170    
3171    sub Sims {
3172        # Get the parameters.
3173        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3174        # Create the shim object to test for deleted FIDs.
3175        my $shim = FidCheck->new($self);
3176        # Ask the network for sims.
3177        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3178        # Return the result.
3179        return $retVal;
3180    }
3181    
3182  =head3 GetGroups  =head3 GetGroups
3183    
3184  C<< my %groups = $sprout->GetGroups(\@groupList); >>  C<< my %groups = $sprout->GetGroups(\@groupList); >>
# Line 2624  Line 3227 
3227      return %retVal;      return %retVal;
3228  }  }
3229    
3230    =head3 MyGenomes
3231    
3232    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
3233    
3234    Return a list of the genomes to be included in the Sprout.
3235    
3236    This method is provided for use during the Sprout load. It presumes the Genome load file has
3237    already been created. (It will be in the Sprout data directory and called either C<Genome>
3238    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3239    IDs.
3240    
3241    =over 4
3242    
3243    =item dataDir
3244    
3245    Directory containing the Sprout load files.
3246    
3247    =back
3248    
3249    =cut
3250    #: Return Type @;
3251    sub MyGenomes {
3252        # Get the parameters.
3253        my ($dataDir) = @_;
3254        # Compute the genome file name.
3255        my $genomeFileName = LoadFileName($dataDir, "Genome");
3256        # Extract the genome IDs from the files.
3257        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3258        # Return the result.
3259        return @retVal;
3260    }
3261    
3262    =head3 LoadFileName
3263    
3264    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3265    
3266    Return the name of the load file for the specified table in the specified data
3267    directory.
3268    
3269    =over 4
3270    
3271    =item dataDir
3272    
3273    Directory containing the Sprout load files.
3274    
3275    =item tableName
3276    
3277    Name of the table whose load file is desired.
3278    
3279    =item RETURN
3280    
3281    Returns the name of the file containing the load data for the specified table, or
3282    C<undef> if no load file is present.
3283    
3284    =back
3285    
3286    =cut
3287    #: Return Type $;
3288    sub LoadFileName {
3289        # Get the parameters.
3290        my ($dataDir, $tableName) = @_;
3291        # Declare the return variable.
3292        my $retVal;
3293        # Check for the various file names.
3294        if (-e "$dataDir/$tableName") {
3295            $retVal = "$dataDir/$tableName";
3296        } elsif (-e "$dataDir/$tableName.dtx") {
3297            $retVal = "$dataDir/$tableName.dtx";
3298        }
3299        # Return the result.
3300        return $retVal;
3301    }
3302    
3303    =head3 DeleteGenome
3304    
3305    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3306    
3307    Delete a genome from the database.
3308    
3309    =over 4
3310    
3311    =item genomeID
3312    
3313    ID of the genome to delete
3314    
3315    =item testFlag
3316    
3317    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3318    
3319    =item RETURN
3320    
3321    Returns a statistics object describing the rows deleted.
3322    
3323    =back
3324    
3325    =cut
3326    #: Return Type $%;
3327    sub DeleteGenome {
3328        # Get the parameters.
3329        my ($self, $genomeID, $testFlag) = @_;
3330        # Perform the delete for the genome's features.
3331        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);
3332        # Perform the delete for the primary genome data.
3333        my $stats = $self->Delete('Genome', $genomeID, $testFlag);
3334        $retVal->Accumulate($stats);
3335        # Return the result.
3336        return $retVal;
3337    }
3338    
3339  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3340    
3341  =head3 ParseAssignment  =head3 ParseAssignment
# Line 2634  Line 3346 
3346    
3347  A functional assignment is always of the form  A functional assignment is always of the form
3348    
3349      I<XXXX>C<\nset >I<YYYY>C< function to\n>I<ZZZZZ>      C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3350    
3351  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,
3352  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
3353  same, but that is not always the case.  not always the case.
3354    
3355    In addition, the functional role may contain extra data that is stripped, such as
3356    terminating spaces or a comment separated from the rest of the text by a tab.
3357    
3358  This is a static method.  This is a static method.
3359    
3360  =over 4  =over 4
3361    
3362    =item user
3363    
3364    Name of the assigning user.
3365    
3366  =item text  =item text
3367    
3368  Text of the annotation.  Text of the annotation.
# Line 2659  Line 3378 
3378    
3379  sub _ParseAssignment {  sub _ParseAssignment {
3380          # Get the parameters.          # Get the parameters.
3381          my ($text) = @_;      my ($user, $text) = @_;
3382          # Declare the return value.          # Declare the return value.
3383          my @retVal = ();          my @retVal = ();
3384          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3385          my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3386          if ($type =~ m/^set ([^ ]+) function to$/i) {      if ($type =~ m/^set function to$/i) {
3387                  # 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.
3388          # and the assigning user.          @retVal = ($user, $function);
3389                  @retVal = ($1, $function, $user);      } elsif ($type =~ m/^set (\S+) function to$/i) {
3390            # Here we have an assignment with a user that is passed back to the caller.
3391            @retVal = ($1, $function);
3392        }
3393        # If we have an assignment, we need to clean the function text. There may be
3394        # extra junk at the end added as a note from the user.
3395        if (@retVal) {
3396            $retVal[1] =~ s/(\t\S)?\s*$//;
3397          }          }
3398          # Return the result list.          # Return the result list.
3399          return @retVal;          return @retVal;
# Line 2695  Line 3421 
3421    
3422  sub FriendlyTimestamp {  sub FriendlyTimestamp {
3423      my ($timeValue) = @_;      my ($timeValue) = @_;
3424      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
3425      return $retVal;      return $retVal;
3426  }  }
3427    
3428    =head3 AddProperty
3429    
3430    C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>
3431    
3432    Add a new attribute value (Property) to a feature. In the SEED system, attributes can
3433    be added to almost any object. In Sprout, they can only be added to features. In
3434    Sprout, attributes are implemented using I<properties>. A property represents a key/value
3435    pair. If the particular key/value pair coming in is not already in the database, a new
3436    B<Property> record is created to hold it.
3437    
3438    =over 4
3439    
3440    =item peg
3441    
3442    ID of the feature to which the attribute is to be replied.
3443    
3444    =item key
3445    
3446    Name of the attribute (key).
3447    
3448    =item value
3449    
3450    Value of the attribute.
3451    
3452    =item url
3453    
3454    URL or text citation from which the property was obtained.
3455    
3456    =back
3457    
3458    =cut
3459    #: Return Type ;
3460    sub AddProperty {
3461        # Get the parameters.
3462        my ($self, $featureID, $key, $value, $url) = @_;
3463        # Declare the variable to hold the desired property ID.
3464        my $propID;
3465        # Attempt to find a property record for this key/value pair.
3466        my @properties = $self->GetFlat(['Property'],
3467                                       "Property(property-name) = ? AND Property(property-value) = ?",
3468                                       [$key, $value], 'Property(id)');
3469        if (@properties) {
3470            # Here the property is already in the database. We save its ID.
3471            $propID = $properties[0];
3472            # Here the property value does not exist. We need to generate an ID. It will be set
3473            # to a number one greater than the maximum value in the database. This call to
3474            # GetAll will stop after one record.
3475            my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],
3476                                            1);
3477            $propID = $maxProperty[0]->[0] + 1;
3478            # Insert the new property value.
3479            $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });
3480        }
3481        # Now we connect the incoming feature to the property.
3482        $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3483    }
3484    
3485    
3486  1;  1;

Legend:
Removed from v.1.12  
changed lines
  Added in v.1.77

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3