[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.5, Tue Jan 25 03:02:07 2005 UTC revision 1.84, Thu Sep 14 14:11:09 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();
43    
   
44  =head2 Public Methods  =head2 Public Methods
45    
46  =head3 new  =head3 new
# Line 63  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 84  Line 92 
92  sub new {  sub new {
93          # Get the parameters.          # Get the parameters.
94          my ($class, $dbName, $options) = @_;          my ($class, $dbName, $options) = @_;
95        # Compute the DBD directory.
96        my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
97                                                      $FIG_Config::fig );
98          # Compute the options. We do this by starting with a table of defaults and overwriting with          # Compute the options. We do this by starting with a table of defaults and overwriting with
99          # the incoming data.          # the incoming data.
100          my $optionTable = Tracer::GetOptions({          my $optionTable = Tracer::GetOptions({
101                                             dbType               => 'mysql',                     # database type                         dbType       => $FIG_Config::dbms,
102                                             dataDir              => 'Data',                      # data file directory                                                          # database type
103                                             xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
104                                             userData             => 'root/',                     # user name and password                                                          # data file directory
105                                             port                 => 0,                           # database connection port                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
106                                                            # database definition file name
107                           userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
108                                                            # user name and password
109                           port         => $FIG_Config::dbport,
110                                                            # database connection port
111                           sock         => $FIG_Config::dbsock,
112                           host         => $FIG_Config::dbhost,
113                                             maxSegmentLength => 4500,            # maximum feature segment length                                             maxSegmentLength => 4500,            # maximum feature segment length
114                                             maxSequenceLength => 8000,           # maximum contig sequence length                                             maxSequenceLength => 8000,           # maximum contig sequence length
115                           noDBOpen     => 0,               # 1 to suppress the database open
116                                            }, $options);                                            }, $options);
117          # Get the data directory.          # Get the data directory.
118          my $dataDir = $optionTable->{dataDir};          my $dataDir = $optionTable->{dataDir};
# Line 101  Line 120 
120          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
121          my ($userName, $password) = ($1, $2);          my ($userName, $password) = ($1, $2);
122          # Connect to the database.          # Connect to the database.
123          my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
124        if (! $optionTable->{noDBOpen}) {
125            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
126                                    $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
127        }
128          # Create the ERDB object.          # Create the ERDB object.
129          my $xmlFileName = "$optionTable->{xmlFileName}";          my $xmlFileName = "$optionTable->{xmlFileName}";
130          my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
131          # Create this object.      # Add the option table and XML file name.
132          my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
133          # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
134          bless $self;      # Return it.
135          return $self;      return $retVal;
136  }  }
137    
138  =head3 MaxSegment  =head3 MaxSegment
# Line 125  Line 148 
148  =cut  =cut
149  #: Return Type $;  #: Return Type $;
150  sub MaxSegment {  sub MaxSegment {
151          my $self = shift @_;      my ($self) = @_;
152          return $self->{_options}->{maxSegmentLength};          return $self->{_options}->{maxSegmentLength};
153  }  }
154    
# Line 140  Line 163 
163  =cut  =cut
164  #: Return Type $;  #: Return Type $;
165  sub MaxSequence {  sub MaxSequence {
166          my $self = shift @_;      my ($self) = @_;
167          return $self->{_options}->{maxSequenceLength};          return $self->{_options}->{maxSequenceLength};
168  }  }
169    
170  =head3 Get  =head3 Load
   
 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]); >>  
171    
172  It is also permissible to specify I<only> an ORDER BY clause. For example, the following invocation gets  C<< $sprout->Load($rebuild); >>;
 all genomes ordered by genus and species.  
173    
174  C<< $query = $sprout->Get(['Genome'], "ORDER BY Genome(genus), Genome(species)"); >>  Load the database from files in the data directory, optionally re-creating the tables.
175    
176  Odd things may happen if one of the ORDER BY fields is in a secondary relation. So, for example, an  This method always deletes the data from the database before loading, even if the tables are not
177  attempt to order B<Feature>s by alias may (depending on the underlying database engine used) cause  re-created. The data is loaded into the relations from files in the data directory either having the
178  a single feature to appear more than once.  same name as the target relation with no extension or with an extension of C<.dtx>. Files without an
179    extension are used in preference to the files with an extension.
180    
181  If multiple names are specified, then the query processor will automatically determine a  The files are loaded based on the presumption that each line of the file is a record in the
182  join path between the entities and relationships. The algorithm used is very simplistic.  relation, and the individual fields are delimited by tabs. Tab and new-line characters inside
183  In particular, you can't specify any entity or relationship more than once, and if a  fields must be represented by the escape sequences C<\t> and C<\n>, respectively. The fields must
184  relationship is recursive, the path is determined by the order in which the entity  be presented in the order given in the relation tables produced by the L</ShowMetaData> method.
 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.  
185    
186  =over 4  =over 4
187    
188  =item objectNames  =item rebuild
   
 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  
189    
190  List of the parameters to be substituted in for the parameters marks in the filter clause.  TRUE if the data tables need to be created or re-created, else FALSE
191    
192  =item RETURN  =item RETURN
193    
194  Returns a B<DBQuery> that can be used to iterate through all of the results.  Returns a statistical object containing the number of records read, the number of duplicates found,
195    the number of errors, and a list of the error messages.
196    
197  =back  =back
198    
199  =cut  =cut
200    #: Return Type %;
201  sub Get {  sub Load {
202          # Get the parameters.          # Get the parameters.
203          my $self = shift @_;      my ($self, $rebuild) = @_;
204          my ($objectNames, $filterClause, $parameterList) = @_;      # Load the tables from the data directory.
205          # We differ from the ERDB Get method in that the parameter list is passed in as a list reference      my $retVal = $self->LoadTables($self->{_options}->{dataDir}, $rebuild);
206          # rather than a list of parameters. The next step is to convert the parameters from a reference      # Return the statistics.
207          # to a real list. We can only do this if the parameters have been specified.      return $retVal;
         my @parameters;  
         if ($parameterList) { @parameters = @{$parameterList}; }  
         return $self->{_erdb}->Get($objectNames, $filterClause, @parameters);  
208  }  }
209    
210  =head3 GetEntity  =head3 LoadUpdate
211    
212  C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
213    
214  Return an object describing the entity instance with a specified ID.  Load updates to one or more database tables. This method enables the client to make changes to one
215    or two tables without reloading the whole database. For each table, there must be a corresponding
216    file in the data directory, either with the same name as the table, or with a C<.dtx> suffix. So,
217    for example, to make updates to the B<FeatureTranslation> relation, there must be a
218    C<FeatureTranslation.dtx> file in the data directory. Unlike a full load, files without an extension
219    are not examined. This allows update files to co-exist with files from an original load.
220    
221  =over 4  =over 4
222    
223  =item entityType  =item truncateFlag
224    
225  Entity type name.  TRUE if the tables should be rebuilt before loading, else FALSE. A value of TRUE therefore causes
226    current data and schema of the tables to be replaced, while a value of FALSE means the new data
227    is added to the existing data in the various relations.
228    
229  =item ID  =item tableList
230    
231  ID of the desired entity.  List of the tables to be updated.
232    
233  =item RETURN  =item RETURN
234    
235  Returns a B<DBObject> representing the desired entity instance, or an undefined value if no  Returns a statistical object containing the number of records read, the number of duplicates found,
236  instance is found with the specified key.  the number of errors encountered, and a list of error messages.
237    
238  =back  =back
239    
240  =cut  =cut
241    #: Return Type $%;
242  sub GetEntity {  sub LoadUpdate {
243          # Get the parameters.          # Get the parameters.
244          my $self = shift @_;      my ($self, $truncateFlag, $tableList) = @_;
245          my ($entityType, $ID) = @_;      # Declare the return value.
246          # Create a query.      my $retVal = Stats->new();
247          my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);      # Get the data directory.
248          # Get the first (and only) object.      my $optionTable = $self->{_options};
249          my $retVal = $query->Fetch();      my $dataDir = $optionTable->{dataDir};
250          # Return the result.      # Loop through the incoming table names.
251        for my $tableName (@{$tableList}) {
252            # Find the table's file.
253            my $fileName = LoadFileName($dataDir, $tableName);
254            if (! $fileName) {
255                Trace("No load file found for $tableName in $dataDir.") if T(0);
256            } else {
257                # Attempt to load this table.
258                my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);
259                # Accumulate the resulting statistics.
260                $retVal->Accumulate($result);
261            }
262        }
263        # Return the statistics.
264          return $retVal;          return $retVal;
265  }  }
266    
267  =head3 GetEntityValues  =head3 GenomeCounts
268    
269  C<< my @values = GetEntityValues($entityType, $ID, \@fields); >>  C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>
270    
271  Return a list of values from a specified entity instance.  Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
272    genomes will be included in the counts.
273    
274  =over 4  =over 4
275    
276  =item entityType  =item complete
277    
278  Entity type name.  TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
279    counted
 =item ID  
   
 ID of the desired entity.  
   
 =item fields  
   
 List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.  
280    
281  =item RETURN  =item RETURN
282    
283  Returns a flattened list of the values of the specified fields for the specified entity.  A six-element list containing the number of genomes in each of six categories--
284    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
 =back  
   
 =cut  
 #: Return Type @;  
 sub GetEntityValues {  
         # Get the parameters.  
         my $self = shift @_;  
         my ($entityType, $ID, $fields) = @_;  
         # Get the specified entity.  
         my $entity = $self->GetEntity($entityType, $ID);  
         # Declare the return list.  
         my @retVal = ();  
         # If we found the entity, push the values into the return list.  
         if ($entity) {  
                 push @retVal, $entity->Values($fields);  
         }  
         # Return the result.  
         return @retVal;  
 }  
   
 =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.  
285    
286  =back  =back
287    
288  =cut  =cut
289    
290  sub ShowMetaData {  sub GenomeCounts {
291          # Get the parameters.          # Get the parameters.
292          my $self = shift @_;      my ($self, $complete) = @_;
293          my ($fileName) = @_;      # Set the filter based on the completeness flag.
294          # Compute the file name.      my $filter = ($complete ? "Genome(complete) = 1" : "");
295          my $options = $self->{_options};      # Get all the genomes and the related taxonomy information.
296          # Call the show method on the underlying ERDB object.      my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
297          $self->{_erdb}->ShowMetaData($fileName);      # Clear the counters.
298        my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
299        # Loop through, counting the domains.
300        for my $genome (@genomes) {
301            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
302            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
303            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
304            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
305            elsif ($genome->[1] =~ /^env/i)      { ++$env }
306            else  { ++$unk }
307        }
308        # Return the counts.
309        return ($arch, $bact, $euk, $vir, $env, $unk);
310  }  }
311    
312  =head3 Load  =head3 ContigCount
   
 C<< $sprout->Load($rebuild); >>;  
   
 Load the database from files in the data directory, optionally re-creating the tables.  
313    
314  This method always deletes the data from the database before loading, even if the tables are not  C<< my $count = $sprout->ContigCount($genomeID); >>
 re-created. The data is loaded into the relations from files in the data directory either having the  
 same name as the target relation with no extension or with an extension of C<.dtx>. Files without an  
 extension are used in preference to the files with an extension.  
315    
316  The files are loaded based on the presumption that each line of the file is a record in the  Return the number of contigs for the specified genome ID.
 relation, and the individual fields are delimited by tabs. Tab and new-line characters inside  
 fields must be represented by the escape sequences C<\t> and C<\n>, respectively. The fields must  
 be presented in the order given in the relation tables produced by the L</ShowMetaData> method.  
317    
318  =over 4  =over 4
319    
320  =item rebuild  =item genomeID
321    
322  TRUE if the data tables need to be created or re-created, else FALSE  ID of the genome whose contig count is desired.
323    
324  =item RETURN  =item RETURN
325    
326  Returns a statistical object containing the number of records read, the number of duplicates found,  Returns the number of contigs for the specified genome.
 the number of errors, and a list of the error messages.  
327    
328  =back  =back
329    
330  =cut  =cut
331  #: Return Type %;  
332  sub Load {  sub ContigCount {
333          # Get the parameters.          # Get the parameters.
334          my $self = shift @_;      my ($self, $genomeID) = @_;
335          my ($rebuild) = @_;      # Get the contig count.
336          # Get the database object.      my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
337          my $erdb = $self->{_erdb};      # Return the result.
         # Load the tables from the data directory.  
         my $retVal = $erdb->LoadTables($self->{_options}->{dataDir}, $rebuild);  
         # Return the statistics.  
338          return $retVal;          return $retVal;
339  }  }
340    
341  =head3 LoadUpdate  =head3 GeneMenu
342    
343  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params); >>
344    
345  Load updates to one or more database tables. This method enables the client to make changes to one  Return an HTML select menu of genomes. Each genome will be an option in the menu,
346  or two tables without reloading the whole database. For each table, there must be a corresponding  and will be displayed by name with the ID and a contig count attached. The selection
347  file in the data directory, either with the same name as the table, or with a C<.dtx> suffix. So,  value will be the genome ID. The genomes will be sorted by genus/species name.
 for example, to make updates to the B<FeatureTranslation> relation, there must be a  
 C<FeatureTranslation.dtx> file in the data directory. Unlike a full load, files without an extension  
 are not examined. This allows update files to co-exist with files from an original load.  
348    
349  =over 4  =over 4
350    
351  =item truncateFlag  =item attributes
352    
353  TRUE if the tables should be rebuilt before loading, else FALSE. A value of TRUE therefore causes  Reference to a hash mapping attributes to values for the SELECT tag generated.
 current data and schema of the tables to be replaced, while a value of FALSE means the new data  
 is added to the existing data in the various relations.  
354    
355  =item tableList  =item filterString
356    
357  List of the tables to be updated.  A filter string for use in selecting the genomes. The filter string must conform
358    to the rules for the C<< ERDB->Get >> method.
359    
360    =item params
361    
362    Reference to a list of values to be substituted in for the parameter marks in
363    the filter string.
364    
365  =item RETURN  =item RETURN
366    
367  Returns a statistical object containing the number of records read, the number of duplicates found,  Returns an HTML select menu with the specified genomes as selectable options.
 the number of errors encountered, and a list of error messages.  
368    
369  =back  =back
370    
371  =cut  =cut
372  #: Return Type %;  
373  sub LoadUpdate {  sub GeneMenu {
374          # Get the parameters.          # Get the parameters.
375          my $self = shift @_;      my ($self, $attributes, $filterString, $params) = @_;
376          my ($truncateFlag, $tableList) = @_;      # Start the menu.
377          # Get the database object.      my $retVal = "<select " .
378          my $erdb = $self->{_erdb};          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
379          # Declare the return value.          ">\n";
380          my $retVal = Stats->new();      # Get the genomes.
381          # Get the data directory.      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
382          my $optionTable = $self->{_options};                                                                       'Genome(genus)',
383          my $dataDir = $optionTable->{dataDir};                                                                       'Genome(species)',
384          # Loop through the incoming table names.                                                                       'Genome(unique-characterization)']);
385          for my $tableName (@{$tableList}) {      # Sort them by name.
386                  # Find the table's file.      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
387                  my $fileName = "$dataDir/$tableName";      # Loop through the genomes, creating the option tags.
388                  if (! -e $fileName) {      for my $genomeData (@sorted) {
389                          $fileName = "$fileName.dtx";          # Get the data for this genome.
390                  }          my ($genomeID, $genus, $species, $strain) = @{$genomeData};
391                  # Attempt to load this table.          # Get the contig count.
392                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);          my $count = $self->ContigCount($genomeID);
393                  # Accumulate the resulting statistics.          my $counting = ($count == 1 ? "contig" : "contigs");
394                  $retVal->Accumulate($result);          # Build the option tag.
395            $retVal .= "<option value=\"$genomeID\">$genus $species $strain ($genomeID) [$count $counting]</option>\n";
396            Trace("Option tag built for $genomeID: $genus $species $strain.") if T(3);
397          }          }
398          # Return the statistics.      # Close the SELECT tag.
399        $retVal .= "</select>\n";
400        # Return the result.
401          return $retVal;          return $retVal;
402  }  }
   
403  =head3 Build  =head3 Build
404    
405  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 464  Line 412 
412  #: Return Type ;  #: Return Type ;
413  sub Build {  sub Build {
414          # Get the parameters.          # Get the parameters.
415          my $self = shift @_;      my ($self) = @_;
416          # Create the tables.          # Create the tables.
417          $self->{_erdb}->CreateTables;      $self->CreateTables();
418  }  }
419    
420  =head3 Genomes  =head3 Genomes
# Line 479  Line 427 
427  #: Return Type @;  #: Return Type @;
428  sub Genomes {  sub Genomes {
429          # Get the parameters.          # Get the parameters.
430          my $self = shift @_;      my ($self) = @_;
431          # Get all the genomes.          # Get all the genomes.
432          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');
433          # Return the list of IDs.          # Return the list of IDs.
# Line 509  Line 457 
457  #: Return Type $;  #: Return Type $;
458  sub GenusSpecies {  sub GenusSpecies {
459          # Get the parameters.          # Get the parameters.
460          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
461          # Get the data for the specified genome.          # Get the data for the specified genome.
462          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',
463                                                                                                                            'Genome(unique-characterization)']);                                                                                                                            'Genome(unique-characterization)']);
# Line 546  Line 493 
493  #: Return Type @;  #: Return Type @;
494  sub FeaturesOf {  sub FeaturesOf {
495          # Get the parameters.          # Get the parameters.
496          my $self = shift @_;      my ($self, $genomeID,$ftype) = @_;
         my ($genomeID,$ftype) = @_;  
497          # Get the features we want.          # Get the features we want.
498          my @features;          my @features;
499          if (!$ftype) {          if (!$ftype) {
# Line 591  Line 537 
537  =item RETURN  =item RETURN
538    
539  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
540  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context.
541    
542  =back  =back
543    
# Line 600  Line 546 
546  #: Return Type $;  #: Return Type $;
547  sub FeatureLocation {  sub FeatureLocation {
548          # Get the parameters.          # Get the parameters.
549          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
550          # Create a query for the feature locations.          # Create a query for the feature locations.
551          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",
552                                                     [$featureID]);                                                     [$featureID]);
# Line 619  Line 564 
564                  if ($prevContig eq $contigID && $dir eq $prevDir) {                  if ($prevContig eq $contigID && $dir eq $prevDir) {
565                          # 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
566                          # new segment's beginning is next to the old segment's end.                          # new segment's beginning is next to the old segment's end.
567                          if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||              if ($dir eq "-" && $beg + $len == $prevBeg) {
568                                  ($dir eq "+" && $beg == $prevBeg + $prevLen)) {                  # Here we're merging two backward blocks, so we keep the new begin point
569                                  # Here we need to merge two segments. Adjust the beginning and length values                  # and adjust the length.
570                                  # to include both segments.                  $len += $prevLen;
571                    # Pop the old segment off. The new one will replace it later.
572                    pop @retVal;
573                } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
574                    # Here we need to merge two forward blocks. Adjust the beginning and
575                    # length values to include both segments.
576                                  $beg = $prevBeg;                                  $beg = $prevBeg;
577                                  $len += $prevLen;                                  $len += $prevLen;
578                                  # 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 631  Line 581 
581                  }                  }
582                  # Remember this specifier for the adjacent-segment test the next time through.                  # Remember this specifier for the adjacent-segment test the next time through.
583                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
584            # Compute the initial base pair.
585            my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
586                  # Add the specifier to the list.                  # Add the specifier to the list.
587                  push @retVal, "${contigID}_$beg$dir$len";          push @retVal, "${contigID}_$start$dir$len";
588          }          }
589          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
590          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
591  }  }
592    
593  =head3 ParseLocation  =head3 ParseLocation
# Line 661  Line 613 
613  =cut  =cut
614  #: Return Type @;  #: Return Type @;
615  sub ParseLocation {  sub ParseLocation {
616          # Get the parameter.      # Get the parameter. Note that if we're called as an instance method, we ignore
617        # the first parameter.
618        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
619          my ($location) = @_;          my ($location) = @_;
620          # Parse it into segments.          # Parse it into segments.
621          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
622          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
623          # If the direction is an underscore, convert it to a + or -.          # If the direction is an underscore, convert it to a + or -.
624          if ($dir eq "_") {          if ($dir eq "_") {
# Line 680  Line 634 
634          return ($contigID, $start, $dir, $len);          return ($contigID, $start, $dir, $len);
635  }  }
636    
637    =head3 PointLocation
638    
639    C<< my $found = Sprout::PointLocation($location, $point); >>
640    
641    Return the offset into the specified location of the specified point on the contig. If
642    the specified point is before the location, a negative value will be returned. If it is
643    beyond the location, an undefined value will be returned. It is assumed that the offset
644    is for the location's contig. The location can either be new-style (using a C<+> or C<->
645    and a length) or old-style (using C<_> and start and end positions.
646    
647    =over 4
648    
649    =item location
650    
651    A location specifier (see L</FeatureLocation> for a description).
652    
653    =item point
654    
655    The offset into the contig of the point in which we're interested.
656    
657    =item RETURN
658    
659    Returns the offset inside the specified location of the specified point, a negative
660    number if the point is before the location, or an undefined value if the point is past
661    the location. If the length of the location is 0, this method will B<always> denote
662    that it is outside the location. The offset will always be relative to the left-most
663    position in the location.
664    
665    =back
666    
667    =cut
668    #: Return Type $;
669    sub PointLocation {
670        # Get the parameter. Note that if we're called as an instance method, we ignore
671        # the first parameter.
672        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
673        my ($location, $point) = @_;
674        # Parse out the location elements. Note that this works on both old-style and new-style
675        # locations.
676        my ($contigID, $start, $dir, $len) = ParseLocation($location);
677        # Declare the return variable.
678        my $retVal;
679        # Compute the offset. The computation is dependent on the direction of the location.
680        my $offset = (($dir == '+') ? $point - $start : $point - ($start - $len + 1));
681        # Return the offset if it's valid.
682        if ($offset < $len) {
683            $retVal = $offset;
684        }
685        # Return the offset found.
686        return $retVal;
687    }
688    
689  =head3 DNASeq  =head3 DNASeq
690    
691  C<< my $sequence = $sprout->DNASeq(\@locationList); >>  C<< my $sequence = $sprout->DNASeq(\@locationList); >>
# Line 688  Line 694 
694  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,
695  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>.
696    
697    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
698    between positions 1401 and 1532, inclusive.
699    
700        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
701    
702  =over 4  =over 4
703    
704  =item locationList  =item locationList
705    
706  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
707  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
708    
709  =item RETURN  =item RETURN
710    
# Line 705  Line 716 
716  #: Return Type $;  #: Return Type $;
717  sub DNASeq {  sub DNASeq {
718          # Get the parameters.          # Get the parameters.
719          my $self = shift @_;      my ($self, $locationList) = @_;
         my ($locationList) = @_;  
720          # Create the return string.          # Create the return string.
721          my $retVal = "";          my $retVal = "";
722          # Loop through the locations.          # Loop through the locations.
# Line 721  Line 731 
731                  # 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
732                  # before putting it in the return value.                  # before putting it in the return value.
733                  my ($start, $stop);                  my ($start, $stop);
734            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
735                  if ($dir eq "+") {                  if ($dir eq "+") {
736                          $start = $beg;                          $start = $beg;
737                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
738                  } else {                  } else {
739                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
740                          $stop = $beg;                          $stop = $beg;
741                  }                  }
742            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
743                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
744                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
745                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 739  Line 751 
751                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
752                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
753                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
754                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
755                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
756                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
757                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
758                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
759                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
760                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
761                  }                  }
762                  # 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.
763                  if ($dir eq '+') {                  if ($dir eq '+') {
764                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
765                  } else {                  } else {
766                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
767                  }                  }
768          }          }
769          # Return the result.          # Return the result.
# Line 779  Line 792 
792  #: Return Type @;  #: Return Type @;
793  sub AllContigs {  sub AllContigs {
794          # Get the parameters.          # Get the parameters.
795          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
796          # Ask for the genome's Contigs.          # Ask for the genome's Contigs.
797          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],
798                                                                  'HasContig(to-link)');                                                                  'HasContig(to-link)');
# Line 788  Line 800 
800          return @retVal;          return @retVal;
801  }  }
802    
803  =head3 ContigLength  =head3 GenomeLength
804    
805  C<< my $length = $sprout->ContigLength($contigID); >>  C<< my $length = $sprout->GenomeLength($genomeID); >>
806    
807  Compute the length of a contig.  Return the length of the specified genome in base pairs.
808    
809  =over 4  =over 4
810    
811  =item contigID  =item genomeID
812    
813  ID of the contig whose length is desired.  ID of the genome whose base pair count is desired.
814    
815  =item RETURN  =item RETURN
816    
817  Returns the number of positions in the contig.  Returns the number of base pairs in all the contigs of the specified
818    genome.
819    
820  =back  =back
821    
822  =cut  =cut
823  #: Return Type $;  
824  sub ContigLength {  sub GenomeLength {
825          # Get the parameters.          # Get the parameters.
826          my $self = shift @_;      my ($self, $genomeID) = @_;
827          my ($contigID) = @_;      # Declare the return variable.
         # Get the contig's last sequence.  
         my $query = $self->Get(['IsMadeUpOf'],  
                 "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",  
                 [$contigID]);  
         my $sequence = $query->Fetch();  
         # Declare the return value.  
828          my $retVal = 0;          my $retVal = 0;
829          # Set it from the sequence data, if any.      # Get the genome's contig sequence lengths.
830          if ($sequence) {      my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
831                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);                         [$genomeID], 'IsMadeUpOf(len)');
832                  $retVal = $start + $len;      # Sum the lengths.
833          }      map { $retVal += $_ } @lens;
834          # Return the result.          # Return the result.
835          return $retVal;          return $retVal;
836  }  }
837    
838  =head3 GenesInRegion  =head3 FeatureCount
839    
840  C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>  C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
841    
842  List the features which overlap a specified region in a contig.  Return the number of features of the specified type in the specified genome.
843    
844  =over 4  =over 4
845    
846  =item contigID  =item genomeID
847    
848  ID of the contig containing the region of interest.  ID of the genome whose feature count is desired.
849    
850  =item start  =item type
851    
852  Offset of the first residue in the region of interest.  Type of feature to count (eg. C<peg>, C<rna>, etc.).
853    
854  =item stop  =item RETURN
855    
856  Offset of the last residue in the region of interest.  Returns the number of features of the specified type for the specified genome.
857    
858    =back
859    
860    =cut
861    
862    sub FeatureCount {
863        # Get the parameters.
864        my ($self, $genomeID, $type) = @_;
865        # Compute the count.
866        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
867                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
868                                    [$genomeID, $type]);
869        # Return the result.
870        return $retVal;
871    }
872    
873    =head3 GenomeAssignments
874    
875    C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
876    
877    Return a list of a genome's assigned features. The return hash will contain each
878    assigned feature of the genome mapped to the text of its most recent functional
879    assignment.
880    
881    =over 4
882    
883    =item genomeID
884    
885    ID of the genome whose functional assignments are desired.
886    
887  =item RETURN  =item RETURN
888    
889  Returns a three-element list. The first element is a list of feature IDs for the features that  Returns a reference to a hash which maps each feature to its most recent
890  overlap the region of interest. The second and third elements are the minimum and maximum  functional assignment.
 locations of the features provided on the specified contig. These may extend outside  
 the start and stop values.  
891    
892  =back  =back
893    
894  =cut  =cut
895  #: Return Type @;  
896  sub GenesInRegion {  sub GenomeAssignments {
897          # Get the parameters.          # Get the parameters.
898          my $self = shift @_;      my ($self, $genomeID) = @_;
899          my ($contigID, $start, $stop) = @_;      # Declare the return variable.
900          # Get the maximum segment length.      my $retVal = {};
901          my $maximumSegmentLength = $self->MaxSegment;      # Query the genome's features and annotations. We'll put the oldest annotations
902          # Create a hash to receive the feature list. We use a hash so that we can eliminate      # first so that the last assignment to go into the hash will be the correct one.
903          # duplicates easily.      my $query = $self->Get(['HasFeature', 'IsTargetOfAnnotation', 'Annotation'],
904          my %featuresFound = ();                             "HasFeature(from-link) = ? ORDER BY Annotation(time)",
905          # Prime the values we'll use for the returned beginning and end.                             [$genomeID]);
906          my ($min, $max) = ($self->ContigLength($contigID), 0);      # Loop through the annotations.
907          # Create a table of parameters for each query. Each query looks for features travelling in      while (my $data = $query->Fetch) {
908          # a particular direction. The query parameters include the contig ID, the feature direction,          # Get the feature ID and annotation text.
909            my ($fid, $annotation) = $data->Values(['HasFeature(to-link)',
910                                                    'Annotation(annotation)']);
911            # Check to see if this is an assignment. Note that the user really
912            # doesn't matter to us, other than we use it to determine whether or
913            # not this is an assignment.
914            my ($user, $assignment) = _ParseAssignment('fig', $annotation);
915            if ($user) {
916                # Here it's an assignment. We put it in the return hash, overwriting
917                # any older assignment that might be present.
918                $retVal->{$fid} = $assignment;
919            }
920        }
921        # Return the result.
922        return $retVal;
923    }
924    
925    =head3 ContigLength
926    
927    C<< my $length = $sprout->ContigLength($contigID); >>
928    
929    Compute the length of a contig.
930    
931    =over 4
932    
933    =item contigID
934    
935    ID of the contig whose length is desired.
936    
937    =item RETURN
938    
939    Returns the number of positions in the contig.
940    
941    =back
942    
943    =cut
944    #: Return Type $;
945    sub ContigLength {
946        # Get the parameters.
947        my ($self, $contigID) = @_;
948        # Get the contig's last sequence.
949        my $query = $self->Get(['IsMadeUpOf'],
950            "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
951            [$contigID]);
952        my $sequence = $query->Fetch();
953        # Declare the return value.
954        my $retVal = 0;
955        # Set it from the sequence data, if any.
956        if ($sequence) {
957            my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
958            $retVal = $start + $len - 1;
959        }
960        # Return the result.
961        return $retVal;
962    }
963    
964    =head3 ClusterPEGs
965    
966    C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
967    
968    Cluster the PEGs in a list according to the cluster coding scheme of the specified
969    subsystem. In order for this to work properly, the subsystem object must have
970    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
971    This causes the cluster numbers to be pulled into the subsystem's color hash.
972    If a PEG is not found in the color hash, it will not appear in the output
973    sequence.
974    
975    =over 4
976    
977    =item sub
978    
979    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
980    method.
981    
982    =item pegs
983    
984    Reference to the list of PEGs to be clustered.
985    
986    =item RETURN
987    
988    Returns a list of the PEGs, grouped into smaller lists by cluster number.
989    
990    =back
991    
992    =cut
993    #: Return Type $@@;
994    sub ClusterPEGs {
995        # Get the parameters.
996        my ($self, $sub, $pegs) = @_;
997        # Declare the return variable.
998        my $retVal = [];
999        # Loop through the PEGs, creating arrays for each cluster.
1000        for my $pegID (@{$pegs}) {
1001            my $clusterNumber = $sub->get_cluster_number($pegID);
1002            # Only proceed if the PEG is in a cluster.
1003            if ($clusterNumber >= 0) {
1004                # Push this PEG onto the sub-list for the specified cluster number.
1005                push @{$retVal->[$clusterNumber]}, $pegID;
1006            }
1007        }
1008        # Return the result.
1009        return $retVal;
1010    }
1011    
1012    =head3 GenesInRegion
1013    
1014    C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>
1015    
1016    List the features which overlap a specified region in a contig.
1017    
1018    =over 4
1019    
1020    =item contigID
1021    
1022    ID of the contig containing the region of interest.
1023    
1024    =item start
1025    
1026    Offset of the first residue in the region of interest.
1027    
1028    =item stop
1029    
1030    Offset of the last residue in the region of interest.
1031    
1032    =item RETURN
1033    
1034    Returns a three-element list. The first element is a list of feature IDs for the features that
1035    overlap the region of interest. The second and third elements are the minimum and maximum
1036    locations of the features provided on the specified contig. These may extend outside
1037    the start and stop values. The first element (that is, the list of features) is sorted
1038    roughly by location.
1039    
1040    =back
1041    
1042    =cut
1043    #: Return Type @@;
1044    sub GenesInRegion {
1045        # Get the parameters.
1046        my ($self, $contigID, $start, $stop) = @_;
1047        # Get the maximum segment length.
1048        my $maximumSegmentLength = $self->MaxSegment;
1049        # Create a hash to receive the feature list. We use a hash so that we can eliminate
1050        # duplicates easily. The hash key will be the feature ID. The value will be a two-element
1051        # containing the minimum and maximum offsets. We will use the offsets to sort the results
1052        # when we're building the result set.
1053        my %featuresFound = ();
1054        # Prime the values we'll use for the returned beginning and end.
1055        my @initialMinMax = ($self->ContigLength($contigID), 0);
1056        my ($min, $max) = @initialMinMax;
1057        # Create a table of parameters for each query. Each query looks for features travelling in
1058        # a particular direction. The query parameters include the contig ID, the feature direction,
1059          # the lowest possible start position, and the highest possible start position. This works          # the lowest possible start position, and the highest possible start position. This works
1060          # because each feature segment length must be no greater than the maximum segment length.          # because each feature segment length must be no greater than the maximum segment length.
1061          my %queryParms = (forward => [$contigID, '+', $start - $maximumSegmentLength + 1, $stop],          my %queryParms = (forward => [$contigID, '+', $start - $maximumSegmentLength + 1, $stop],
# Line 899  Line 1083 
1083                                          $found = 1;                                          $found = 1;
1084                                  }                                  }
1085                          } elsif ($dir eq '-') {                          } elsif ($dir eq '-') {
1086                                  $end = $beg - $len;                  # Note we switch things around so that the beginning is to the left of the
1087                                  if ($end <= $stop) {                  # ending.
1088                    ($beg, $end) = ($beg - $len, $beg);
1089                    if ($beg <= $stop) {
1090                                          # Denote we found a useful feature.                                          # Denote we found a useful feature.
1091                                          $found = 1;                                          $found = 1;
1092                                  }                                  }
1093                          }                          }
1094                          if ($found) {                          if ($found) {
1095                                  # Here we need to record the feature and update the minimum and maximum.                  # Here we need to record the feature and update the minima and maxima. First,
1096                                  $featuresFound{$featureID} = 1;                  # get the current entry for the specified feature.
1097                                  if ($beg < $min) { $min = $beg; }                  my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :
1098                                  if ($end < $min) { $min = $end; }                                       @initialMinMax);
1099                                  if ($beg > $max) { $max = $beg; }                  # Merge the current segment's begin and end into the feature begin and end and the
1100                                  if ($end > $max) { $max = $end; }                  # global min and max.
1101                    if ($beg < $loc1) {
1102                        $loc1 = $beg;
1103                        $min = $beg if $beg < $min;
1104                    }
1105                    if ($end > $loc2) {
1106                        $loc2 = $end;
1107                        $max = $end if $end > $max;
1108                    }
1109                    # Store the entry back into the hash table.
1110                    $featuresFound{$featureID} = [$loc1, $loc2];
1111                          }                          }
1112                  }                  }
1113          }          }
1114          # Compute a list of the IDs for the features found.      # Now we must compute the list of the IDs for the features found. We start with a list
1115          my @list = (sort (keys %featuresFound));      # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1116        # but the result of the sort will be the same.)
1117        my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;
1118        # Now we sort by midpoint and yank out the feature IDs.
1119        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1120          # Return it along with the min and max.          # Return it along with the min and max.
1121          return (\@list, $min, $max);      return (\@retVal, $min, $max);
1122  }  }
1123    
1124  =head3 FType  =head3 FType
# Line 944  Line 1144 
1144  #: Return Type $;  #: Return Type $;
1145  sub FType {  sub FType {
1146          # Get the parameters.          # Get the parameters.
1147          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1148          # Get the specified feature's type.          # Get the specified feature's type.
1149          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
1150          # Return the result.          # Return the result.
# Line 954  Line 1153 
1153    
1154  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1155    
1156  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1157    
1158  Return the annotations of a feature.  Return the annotations of a feature.
1159    
# Line 964  Line 1163 
1163    
1164  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1165    
1166    =item rawFlag
1167    
1168    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1169    will be returned in human-readable form.
1170    
1171  =item RETURN  =item RETURN
1172    
1173  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.
1174    
1175  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1176    
1177  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1178    
1179  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1180    
# Line 982  Line 1186 
1186  #: Return Type @%;  #: Return Type @%;
1187  sub FeatureAnnotations {  sub FeatureAnnotations {
1188          # Get the parameters.          # Get the parameters.
1189          my $self = shift @_;      my ($self, $featureID, $rawFlag) = @_;
         my ($featureID) = @_;  
1190          # 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.
1191          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1192                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 996  Line 1199 
1199                          $annotation->Values(['IsTargetOfAnnotation(from-link)',                          $annotation->Values(['IsTargetOfAnnotation(from-link)',
1200                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1201                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1202            # Convert the time, if necessary.
1203            if (! $rawFlag) {
1204                $timeStamp = FriendlyTimestamp($timeStamp);
1205            }
1206                  # Assemble them into a hash.                  # Assemble them into a hash.
1207          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1208                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1209                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1210                  # Add it to the return list.                  # Add it to the return list.
1211                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1012  Line 1219 
1219  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>
1220    
1221  Return all of the functional assignments for a particular feature. The data is returned as a  Return all of the functional assignments for a particular feature. The data is returned as a
1222  hash of functional assignments to user IDs. A functional assignment is a type of annotation.  hash of functional assignments to user IDs. A functional assignment is a type of annotation,
1223  It has the format "XXXX\nset XXXX function to\nYYYYY". In this instance, XXXX is the user ID  Functional assignments are described in the L</ParseAssignment> function. Its worth noting that
1224  and YYYYY is the functional assignment text. Its worth noting that we cannot filter on the content  we cannot filter on the content of the annotation itself because it's a text field; however,
1225  of the annotation itself because it's a text field; however, this is not a big problem because most  this is not a big problem because most features only have a small number of annotations.
1226  features only have a small number of annotations. Finally, if a single user has multiple  Finally, if a single user has multiple functional assignments, we will only keep the most
1227  functional assignments, we will only keep the most recent one.  recent one.
1228    
1229  =over 4  =over 4
1230    
# Line 1027  Line 1234 
1234    
1235  =item RETURN  =item RETURN
1236    
1237  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1238    
1239  =back  =back
1240    
# Line 1035  Line 1242 
1242  #: Return Type %;  #: Return Type %;
1243  sub AllFunctionsOf {  sub AllFunctionsOf {
1244          # Get the parameters.          # Get the parameters.
1245          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1246          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1247      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1248                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1249                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1250                                               'MadeAnnotation(from-link)']);
1251          # Declare the return hash.          # Declare the return hash.
1252          my %retVal;          my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1253      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1254      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1255          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1256      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1257          # Get the annotation fields.          # Get the annotation fields.
1258          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1259                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1260                  my ($user, $function) = ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1261          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1262              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1263              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1264              # return hash.              # return hash.
1265                          $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1266                  }                  }
1267          }          }
1268          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1074  Line 1277 
1277    
1278  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
1279  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
1280  assignment is a type of annotation. It has the format "XXXX\nset XXXX function to\nYYYYY". In this  assignment is a type of annotation. The format of an assignment is described in
1281  instance, XXXX is the user ID and YYYYY is the functional assignment text. Its worth noting that  L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1282  we cannot filter on the content of the annotation itself because it's a text field; however, this  annotation itself because it's a text field; however, this is not a big problem because
1283  is not a big problem because most features only have a small number of annotations.  most features only have a small number of annotations.
1284    
1285  Each user has an associated list of trusted users. The assignment returned will be the most  Each user has an associated list of trusted users. The assignment returned will be the most
1286  recent one by at least one of the trusted users. If no trusted user list is available, then  recent one by at least one of the trusted users. If no trusted user list is available, then
# Line 1109  Line 1312 
1312  #: Return Type $;  #: Return Type $;
1313  sub FunctionOf {  sub FunctionOf {
1314          # Get the parameters.          # Get the parameters.
1315          my $self = shift @_;      my ($self, $featureID, $userID) = @_;
         my ($featureID, $userID) = @_;  
1316      # Declare the return value.      # Declare the return value.
1317      my $retVal;      my $retVal;
1318      # Determine the ID type.      # Determine the ID type.
# Line 1138  Line 1340 
1340              }              }
1341          }          }
1342          # 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.
1343          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1344                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1345                                 [$featureID]);                                 [$featureID]);
1346          my $timeSelected = 0;          my $timeSelected = 0;
1347          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1348          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1349              # Get the annotation text.              # Get the annotation text.
1350              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);              my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1351                                                         'Annotation(time)', 'MadeAnnotation(from-link)']);
1352              # 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.
1353              my ($user, $type, $function) = split(/\n/, $text);              my ($actualUser, $function) = _ParseAssignment($user, $text);
1354              if ($type =~ m/^set $user function to$/i) {              Trace("Assignment user is $actualUser, text is $function.") if T(4);
1355                if ($actualUser) {
1356                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1357                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1358                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                  if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1359                      $retVal = $function;                      $retVal = $function;
1360                      $timeSelected = $time;                      $timeSelected = $time;
1361                  }                  }
# Line 1167  Line 1371 
1371          return $retVal;          return $retVal;
1372  }  }
1373    
1374    =head3 FunctionsOf
1375    
1376    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1377    
1378    Return the functional assignments of a particular feature.
1379    
1380    The functional assignment is handled differently depending on the type of feature. If
1381    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1382    assignment is a type of annotation. The format of an assignment is described in
1383    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1384    annotation itself because it's a text field; however, this is not a big problem because
1385    most features only have a small number of annotations.
1386    
1387    If the feature is B<not> identified by a FIG ID, then the functional assignment
1388    information is taken from the B<ExternalAliasFunc> table. If the table does
1389    not contain an entry for the feature, an empty list is returned.
1390    
1391    =over 4
1392    
1393    =item featureID
1394    
1395    ID of the feature whose functional assignments are desired.
1396    
1397    =item RETURN
1398    
1399    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1400    that user.
1401    
1402    =back
1403    
1404    =cut
1405    #: Return Type @@;
1406    sub FunctionsOf {
1407        # Get the parameters.
1408        my ($self, $featureID) = @_;
1409        # Declare the return value.
1410        my @retVal = ();
1411        # Determine the ID type.
1412        if ($featureID =~ m/^fig\|/) {
1413            # Here we have a FIG feature ID. We must build the list of trusted
1414            # users.
1415            my %trusteeTable = ();
1416            # Build a query for all of the feature's annotations, sorted by date.
1417            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1418                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1419                                   [$featureID]);
1420            my $timeSelected = 0;
1421            # Loop until we run out of annotations.
1422            while (my $annotation = $query->Fetch()) {
1423                # Get the annotation text.
1424                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1425                                                                'Annotation(time)',
1426                                                                'MadeAnnotation(user)']);
1427                # Check to see if this is a functional assignment for a trusted user.
1428                my ($actualUser, $function) = _ParseAssignment($user, $text);
1429                if ($actualUser) {
1430                    # Here it is a functional assignment.
1431                    push @retVal, [$actualUser, $function];
1432                }
1433            }
1434        } else {
1435            # Here we have a non-FIG feature ID. In this case the user ID does not
1436            # matter. We simply get the information from the External Alias Function
1437            # table.
1438            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1439                                                     ['ExternalAliasFunc(func)']);
1440            push @retVal, map { ['master', $_] } @assignments;
1441        }
1442        # Return the assignments found.
1443        return @retVal;
1444    }
1445    
1446  =head3 BBHList  =head3 BBHList
1447    
1448  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1186  Line 1462 
1462    
1463  =item RETURN  =item RETURN
1464    
1465  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
1466  their best hits.  on the target genome.
1467    
1468  =back  =back
1469    
# Line 1195  Line 1471 
1471  #: Return Type %;  #: Return Type %;
1472  sub BBHList {  sub BBHList {
1473          # Get the parameters.          # Get the parameters.
1474          my $self = shift @_;      my ($self, $genomeID, $featureList) = @_;
         my ($genomeID, $featureList) = @_;  
1475          # Create the return structure.          # Create the return structure.
1476          my %retVal = ();          my %retVal = ();
1477          # Loop through the incoming features.          # Loop through the incoming features.
1478          for my $featureID (@{$featureList}) {          for my $featureID (@{$featureList}) {
1479                  # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1480                  my $query = $self->Get(['IsBidirectionalBestHitOf'],          my @bbhData = FIGRules::BBHData($featureID);
1481                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",          # Peel off the BBHs found.
1482                                                             [$featureID, $genomeID]);          my @found = ();
1483                  # Look for the best hit.          for my $bbh (@bbhData) {
1484                  my $bbh = $query->Fetch;              push @found, $bbh->[0];
                 if ($bbh) {  
                         my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');  
                         $retVal{$featureID} = $targetFeature;  
1485                  }                  }
1486            $retVal{$featureID} = \@found;
1487          }          }
1488          # Return the mapping.          # Return the mapping.
1489          return \%retVal;          return \%retVal;
1490  }  }
1491    
1492    =head3 SimList
1493    
1494    C<< my %similarities = $sprout->SimList($featureID, $count); >>
1495    
1496    Return a list of the similarities to the specified feature.
1497    
1498    This method just returns the bidirectional best hits for performance reasons.
1499    
1500    =over 4
1501    
1502    =item featureID
1503    
1504    ID of the feature whose similarities are desired.
1505    
1506    =item count
1507    
1508    Maximum number of similar features to be returned, or C<0> to return them all.
1509    
1510    =back
1511    
1512    =cut
1513    #: Return Type %;
1514    sub SimList {
1515        # Get the parameters.
1516        my ($self, $featureID, $count) = @_;
1517        # Ask for the best hits.
1518        my @lists = FIGRules::BBHData($featureID);
1519        # Create the return value.
1520        my %retVal = ();
1521        for my $tuple (@lists) {
1522            $retVal{$tuple->[0]} = $tuple->[1];
1523        }
1524        # Return the result.
1525        return %retVal;
1526    }
1527    
1528    =head3 IsComplete
1529    
1530    C<< my $flag = $sprout->IsComplete($genomeID); >>
1531    
1532    Return TRUE if the specified genome is complete, else FALSE.
1533    
1534    =over 4
1535    
1536    =item genomeID
1537    
1538    ID of the genome whose completeness status is desired.
1539    
1540    =item RETURN
1541    
1542    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1543    not found.
1544    
1545    =back
1546    
1547    =cut
1548    #: Return Type $;
1549    sub IsComplete {
1550        # Get the parameters.
1551        my ($self, $genomeID) = @_;
1552        # Declare the return variable.
1553        my $retVal;
1554        # Get the genome's data.
1555        my $genomeData = $self->GetEntity('Genome', $genomeID);
1556        if ($genomeData) {
1557            # The genome exists, so get the completeness flag.
1558            ($retVal) = $genomeData->Value('Genome(complete)');
1559        }
1560        # Return the result.
1561        return $retVal;
1562    }
1563    
1564  =head3 FeatureAliases  =head3 FeatureAliases
1565    
1566  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
# Line 1239  Line 1584 
1584  #: Return Type @;  #: Return Type @;
1585  sub FeatureAliases {  sub FeatureAliases {
1586          # Get the parameters.          # Get the parameters.
1587          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1588          # Get the desired feature's aliases          # Get the desired feature's aliases
1589          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);
1590          # Return the result.          # Return the result.
# Line 1251  Line 1595 
1595    
1596  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1597    
1598  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1599    
1600  =over 4  =over 4
1601    
1602  =item featureID  =item featureID
1603    
1604  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1605    
1606  =item RETURN  =item RETURN
1607    
1608  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
1609  an undefined value.  found, returns an undefined value.
1610    
1611  =back  =back
1612    
# Line 1270  Line 1614 
1614  #: Return Type $;  #: Return Type $;
1615  sub GenomeOf {  sub GenomeOf {
1616          # Get the parameters.          # Get the parameters.
1617          my $self = shift @_;      my ($self, $featureID) = @_;
1618          my ($featureID) = @_;      # Create a query to find the genome associated with the incoming ID.
1619          # Create a query to find the genome associated with the feature.      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1620          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);                             [$featureID, $featureID]);
1621          # Declare the return value.          # Declare the return value.
1622          my $retVal;          my $retVal;
1623          # Get the genome ID.          # Get the genome ID.
# Line 1307  Line 1651 
1651  #: Return Type %;  #: Return Type %;
1652  sub CoupledFeatures {  sub CoupledFeatures {
1653          # Get the parameters.          # Get the parameters.
1654          my $self = shift @_;      my ($self, $featureID) = @_;
1655          my ($featureID) = @_;      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1656          # Create a query to retrieve the functionally-coupled features. Note that we depend on the      # Create a query to retrieve the functionally-coupled features.
1657          # fact that the functional coupling is physically paired. If (A,B) is in the database, then      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1658          # (B,A) will also be found.                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);
         my $query = $self->Get(['IsClusteredOnChromosomeWith'],  
                                                    "IsClusteredOnChromosomeWith(from-link) = ?", [$featureID]);  
1659          # 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.
1660          my $found = 0;          my $found = 0;
1661          # Create the return hash.          # Create the return hash.
1662          my %retVal = ();          my %retVal = ();
1663          # Retrieve the relationship records and store them in the hash.          # Retrieve the relationship records and store them in the hash.
1664          while (my $clustering = $query->Fetch()) {          while (my $clustering = $query->Fetch()) {
1665                  my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',          # Get the ID and score of the coupling.
1666                                                                      'IsClusteredOnChromosomeWith(score)']);          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1667                                                            'Coupling(score)']);
1668            Trace("$featureID coupled with score $score to ID $couplingID.") if T(coupling => 4);
1669            # Get the other feature that participates in the coupling.
1670            my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],
1671                                               "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",
1672                                               [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');
1673            Trace("$couplingID target feature is $otherFeatureID.") if T(coupling => 4);
1674            # Attach the other feature's score to its ID.
1675                  $retVal{$otherFeatureID} = $score;                  $retVal{$otherFeatureID} = $score;
1676                  $found = 1;                  $found = 1;
1677          }          }
# Line 1334  Line 1684 
1684          return %retVal;          return %retVal;
1685  }  }
1686    
1687  =head3 GetEntityTypes  =head3 CouplingEvidence
1688    
1689  C<< my @entityList = $sprout->GetEntityTypes(); >>  C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1690    
1691  Return the list of supported entity types.  Return the evidence for a functional coupling.
1692    
1693    A pair of features is considered evidence of a coupling between two other
1694    features if they occur close together on a contig and both are similar to
1695    the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1696    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1697    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1698    similar to B<A2>.
1699    
1700    The score of a coupling is determined by the number of pieces of evidence
1701    that are considered I<representative>. If several evidence items belong to
1702    a group of genomes that are close to each other, only one of those items
1703    is considered representative. The other evidence items are presumed to be
1704    there because of the relationship between the genomes rather than because
1705    the two proteins generated by the features have a related functionality.
1706    
1707    Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1708    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1709    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1710    and FALSE otherwise.
1711    
1712    =over 4
1713    
1714    =item peg1
1715    
1716    ID of the feature of interest.
1717    
1718    =item peg2
1719    
1720    ID of a feature functionally coupled to the feature of interest.
1721    
1722    =item RETURN
1723    
1724    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1725    of interest, a feature similar to the functionally coupled feature, and a flag
1726    that is TRUE for a representative piece of evidence and FALSE otherwise.
1727    
1728    =back
1729    
1730  =cut  =cut
1731  #: Return Type @;  #: Return Type @@;
1732  sub GetEntityTypes {  sub CouplingEvidence {
1733          # Get the parameters.          # Get the parameters.
1734          my $self = shift @_;      my ($self, $peg1, $peg2) = @_;
1735          # Get the underlying database object.      # Declare the return variable.
1736          my $erdb = $self->{_erdb};      my @retVal = ();
1737          # Get its entity type list.      # Our first task is to find out the nature of the coupling: whether or not
1738          my @retVal = $erdb->GetEntityTypes();      # it exists, its score, and whether the features are stored in the same
1739        # order as the ones coming in.
1740        my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1741        # Only proceed if a coupling exists.
1742        if ($couplingID) {
1743            # Determine the ordering to place on the evidence items. If we're
1744            # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1745            # we want feature 1 before feature 2 (normal).
1746            Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);
1747            my $ordering = ($inverted ? "DESC" : "");
1748            # Get the coupling evidence.
1749            my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
1750                                              "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",
1751                                              [$couplingID],
1752                                              ['PCH(used)', 'UsesAsEvidence(to-link)']);
1753            # Loop through the evidence items. Each piece of evidence is represented by two
1754            # positions in the evidence list, one for each feature on the other side of the
1755            # evidence link. If at some point we want to generalize to couplings with
1756            # more than two positions, this section of code will need to be re-done.
1757            while (@evidenceList > 0) {
1758                my $peg1Data = shift @evidenceList;
1759                my $peg2Data = shift @evidenceList;
1760                Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1761                push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1762            }
1763            Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1764        }
1765        # Return the result.
1766        return @retVal;
1767  }  }
1768    
1769  =head3 ReadFasta  =head3 GetCoupling
1770    
1771  C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>  C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>
1772    
1773  Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by  Return the coupling (if any) for the specified pair of PEGs. If a coupling
1774  one or more lines of data. The first line begins with a > character and contains an ID.  exists, we return the coupling ID along with an indicator of whether the
1775  The remaining lines contain the sequence data in order.  coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.
1776    In the second case, we say the coupling is I<inverted>. The importance of an
1777    inverted coupling is that the PEGs in the evidence will appear in reverse order.
1778    
1779  =over 4  =over 4
1780    
1781  =item fileName  =item peg1
1782    
1783  Name of the FASTA file.  ID of the feature of interest.
1784    
1785  =item prefix (optional)  =item peg2
1786    
1787  Prefix to be put in front of each ID found.  ID of the potentially coupled feature.
1788    
1789  =item RETURN  =item RETURN
1790    
1791  Returns a hash that maps each ID to its sequence.  Returns a three-element list. The first element contains the database ID of
1792    the coupling. The second element is FALSE if the coupling is stored in the
1793    database in the caller specified order and TRUE if it is stored in the
1794    inverted order. The third element is the coupling's score. If the coupling
1795    does not exist, all three list elements will be C<undef>.
1796    
1797  =back  =back
1798    
1799  =cut  =cut
1800  #: Return Type %;  #: Return Type $%@;
1801  sub ReadFasta {  sub GetCoupling {
1802          # Get the parameters.          # Get the parameters.
1803          my ($fileName, $prefix) = @_;      my ($self, $peg1, $peg2) = @_;
1804          # Create the return hash.      # Declare the return values. We'll start with the coupling ID and undefine the
1805          my %retVal = ();      # flag and score until we have more information.
1806          # Open the file for input.      my ($retVal, $inverted, $score) = ($self->CouplingID($peg1, $peg2), undef, undef);
1807          open FASTAFILE, '<', $fileName;      # Find the coupling data.
1808          # Declare the ID variable and clear the sequence accumulator.      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1809          my $sequence = "";                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1810          my $id = "";                                   [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1811          # Loop through the file.      # Check to see if we found anything.
1812          while (<FASTAFILE>) {      if (!@pegs) {
1813                  # Get the current line.          Trace("No coupling found.") if T(Coupling => 4);
1814                  my $line = $_;          # No coupling, so undefine the return value.
1815                  # Check for a header line.          $retVal = undef;
1816                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {      } else {
1817            # We have a coupling! Get the score and check for inversion.
1818            $score = $pegs[0]->[1];
1819            my $firstFound = $pegs[0]->[0];
1820            $inverted = ($firstFound ne $peg1);
1821            Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1822        }
1823        # Return the result.
1824        return ($retVal, $inverted, $score);
1825    }
1826    
1827    =head3 GetSynonymGroup
1828    
1829    C<< my $id = $sprout->GetSynonymGroup($fid); >>
1830    
1831    Return the synonym group name for the specified feature.
1832    
1833    =over 4
1834    
1835    =item fid
1836    
1837    ID of the feature whose synonym group is desired.
1838    
1839    =item RETURN
1840    
1841    The name of the synonym group to which the feature belongs. If the feature does
1842    not belong to a synonym group, the feature ID itself is returned.
1843    
1844    =back
1845    
1846    =cut
1847    
1848    sub GetSynonymGroup {
1849        # Get the parameters.
1850        my ($self, $fid) = @_;
1851        # Declare the return variable.
1852        my $retVal;
1853        # Find the synonym group.
1854        my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1855                                       [$fid], 'IsSynonymGroupFor(from-link)');
1856        # Check to see if we found anything.
1857        if (@groups) {
1858            $retVal = $groups[0];
1859        } else {
1860            $retVal = $fid;
1861        }
1862        # Return the result.
1863        return $retVal;
1864    }
1865    
1866    =head3 GetBoundaries
1867    
1868    C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>
1869    
1870    Determine the begin and end boundaries for the locations in a list. All of the
1871    locations must belong to the same contig and have mostly the same direction in
1872    order for this method to produce a meaningful result. The resulting
1873    begin/end pair will contain all of the bases in any of the locations.
1874    
1875    =over 4
1876    
1877    =item locList
1878    
1879    List of locations to process.
1880    
1881    =item RETURN
1882    
1883    Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1884    and the ending boundary. The beginning boundary will be left of the
1885    end for mostly-forward locations and right of the end for mostly-backward
1886    locations.
1887    
1888    =back
1889    
1890    =cut
1891    
1892    sub GetBoundaries {
1893        # Get the parameters.
1894        my ($self, @locList) = @_;
1895        # Set up the counters used to determine the most popular direction.
1896        my %counts = ( '+' => 0, '-' => 0 );
1897        # Get the last location and parse it.
1898        my $locObject = BasicLocation->new(pop @locList);
1899        # Prime the loop with its data.
1900        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
1901        # Count its direction.
1902        $counts{$locObject->Dir}++;
1903        # Loop through the remaining locations. Note that in most situations, this loop
1904        # will not iterate at all, because most of the time we will be dealing with a
1905        # singleton list.
1906        for my $loc (@locList) {
1907            # Create a location object.
1908            my $locObject = BasicLocation->new($loc);
1909            # Count the direction.
1910            $counts{$locObject->Dir}++;
1911            # Get the left end and the right end.
1912            my $left = $locObject->Left;
1913            my $right = $locObject->Right;
1914            # Merge them into the return variables.
1915            if ($left < $beg) {
1916                $beg = $left;
1917            }
1918            if ($right > $end) {
1919                $end = $right;
1920            }
1921        }
1922        # If the most common direction is reverse, flip the begin and end markers.
1923        if ($counts{'-'} > $counts{'+'}) {
1924            ($beg, $end) = ($end, $beg);
1925        }
1926        # Return the result.
1927        return ($contig, $beg, $end);
1928    }
1929    
1930    =head3 CouplingID
1931    
1932    C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >>
1933    
1934    Return the coupling ID for a pair of feature IDs.
1935    
1936    The coupling ID is currently computed by joining the feature IDs in
1937    sorted order with a space. Client modules (that is, modules which
1938    use Sprout) should not, however, count on this always being the
1939    case. This method provides a way for abstracting the concept of a
1940    coupling ID. All that we know for sure about it is that it can be
1941    generated easily from the feature IDs and the order of the IDs
1942    in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>
1943    will have the same value as C<CouplingID("b1", "a1")>.
1944    
1945    =over 4
1946    
1947    =item peg1
1948    
1949    First feature of interest.
1950    
1951    =item peg2
1952    
1953    Second feature of interest.
1954    
1955    =item RETURN
1956    
1957    Returns the ID that would be used to represent a functional coupling of
1958    the two specified PEGs.
1959    
1960    =back
1961    
1962    =cut
1963    #: Return Type $;
1964    sub CouplingID {
1965        my ($self, @pegs) = @_;
1966        return $self->DigestKey(join " ", sort @pegs);
1967    }
1968    
1969    =head3 ReadFasta
1970    
1971    C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>
1972    
1973    Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by
1974    one or more lines of data. The first line begins with a > character and contains an ID.
1975    The remaining lines contain the sequence data in order.
1976    
1977    =over 4
1978    
1979    =item fileName
1980    
1981    Name of the FASTA file.
1982    
1983    =item prefix (optional)
1984    
1985    Prefix to be put in front of each ID found.
1986    
1987    =item RETURN
1988    
1989    Returns a hash that maps each ID to its sequence.
1990    
1991    =back
1992    
1993    =cut
1994    #: Return Type %;
1995    sub ReadFasta {
1996        # Get the parameters.
1997        my ($fileName, $prefix) = @_;
1998        # Create the return hash.
1999        my %retVal = ();
2000        # Open the file for input.
2001        open FASTAFILE, '<', $fileName;
2002        # Declare the ID variable and clear the sequence accumulator.
2003        my $sequence = "";
2004        my $id = "";
2005        # Loop through the file.
2006        while (<FASTAFILE>) {
2007            # Get the current line.
2008            my $line = $_;
2009            # Check for a header line.
2010            if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
2011                          # 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.
2012                          if ($id) {                          if ($id) {
2013                                  $retVal{$id} = $sequence;                  $retVal{$id} = lc $sequence;
2014                          }                          }
2015                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
2016                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
2017                  } else {                  } else {
2018                          # 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.
2019                          # First, we get the actual data out.              # First, we get the actual data out. Note that we normalize to lower
2020                # case.
2021                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
2022                          $sequence .= $1;                          $sequence .= $1;
2023                  }                  }
2024          }          }
2025          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
2026          if ($sequence) {          if ($sequence) {
2027                  $retVal {$id} = $sequence;          $retVal{$id} = lc $sequence;
2028          }          }
2029        # Close the file.
2030        close FASTAFILE;
2031          # Return the hash constructed from the file.          # Return the hash constructed from the file.
2032          return %retVal;          return %retVal;
2033  }  }
# Line 1420  Line 2038 
2038    
2039  Insure that a list of feature locations is in the Sprout format. The Sprout feature location  Insure that a list of feature locations is in the Sprout format. The Sprout feature location
2040  format is I<contig>_I<beg*len> where I<*> is C<+> for a forward gene and C<-> for a backward  format is I<contig>_I<beg*len> where I<*> is C<+> for a forward gene and C<-> for a backward
2041  gene. The old format is I<contig>_I<beg>_I<end>.  gene. The old format is I<contig>_I<beg>_I<end>. If a feature is in the new format already,
2042    it will not be changed; otherwise, it will be converted. This method can also be used to
2043    perform the reverse task-- insuring that all the locations are in the old format.
2044    
2045  =over 4  =over 4
2046    
# Line 1447  Line 2067 
2067  #: Return Type @;  #: Return Type @;
2068  sub FormatLocations {  sub FormatLocations {
2069          # Get the parameters.          # Get the parameters.
2070          my $self = shift @_;      my ($self, $prefix, $locations, $oldFormat) = @_;
         my ($prefix, $locations, $oldFormat) = @_;  
2071          # Create the return list.          # Create the return list.
2072          my @retVal = ();          my @retVal = ();
2073          # Check to see if any locations were passed in.          # Check to see if any locations were passed in.
2074          if ($locations eq '') {          if ($locations eq '') {
2075              confess "No locations specified.";          Confess("No locations specified.");
2076          } else {          } else {
2077                  # Loop through the locations, converting them to the new format.                  # Loop through the locations, converting them to the new format.
2078                  for my $location (@{$locations}) {                  for my $location (@{$locations}) {
# Line 1488  Line 2107 
2107    
2108  sub DumpData {  sub DumpData {
2109          # Get the parameters.          # Get the parameters.
2110          my $self = shift @_;      my ($self) = @_;
2111          # Get the data directory name.          # Get the data directory name.
2112          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
2113          # Dump the relations.          # Dump the relations.
2114          $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2115  }  }
2116    
2117  =head3 XMLFileName  =head3 XMLFileName
# Line 1504  Line 2123 
2123  =cut  =cut
2124  #: Return Type $;  #: Return Type $;
2125  sub XMLFileName {  sub XMLFileName {
2126          my $self = shift @_;      my ($self) = @_;
2127          return $self->{_xmlName};          return $self->{_xmlName};
2128  }  }
2129    
# Line 1524  Line 2143 
2143  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
2144  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>.
2145    
2146  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'}); >>
2147    
2148  =over 4  =over 4
2149    
# Line 1542  Line 2161 
2161  #: Return Type ;  #: Return Type ;
2162  sub Insert {  sub Insert {
2163          # Get the parameters.          # Get the parameters.
2164          my $self = shift @_;      my ($self, $objectType, $fieldHash) = @_;
         my ($objectType, $fieldHash) = @_;  
2165          # Call the underlying method.          # Call the underlying method.
2166          $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2167  }  }
2168    
2169  =head3 Annotate  =head3 Annotate
# Line 1584  Line 2202 
2202  #: Return Type $;  #: Return Type $;
2203  sub Annotate {  sub Annotate {
2204          # Get the parameters.          # Get the parameters.
2205          my $self = shift @_;      my ($self, $fid, $timestamp, $user, $text) = @_;
         my ($fid, $timestamp, $user, $text) = @_;  
2206          # Create the annotation ID.          # Create the annotation ID.
2207          my $aid = "$fid:$timestamp";          my $aid = "$fid:$timestamp";
2208          # Insert the Annotation object.          # Insert the Annotation object.
# Line 1605  Line 2222 
2222    
2223  =head3 AssignFunction  =head3 AssignFunction
2224    
2225  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function); >>  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>
2226    
2227  This method assigns a function to a feature. Functions are a special type of annotation. The general  This method assigns a function to a feature. Functions are a special type of annotation. The general
2228  format is "XXXX\nset XXXX function to\nYYYYY" where XXXX is the feature type and YYYY is the functional  format is described in L</ParseAssignment>.
 assignment text.  
2229    
2230  =over 4  =over 4
2231    
# Line 1619  Line 2235 
2235    
2236  =item user  =item user
2237    
2238  Name of the user making the assignment. This is frequently a group name, like C<kegg> or C<fig>.  Name of the user group making the assignment, such as C<kegg> or C<fig>.
2239    
2240  =item function  =item function
2241    
2242  Text of the function being assigned.  Text of the function being assigned.
2243    
2244    =item assigningUser (optional)
2245    
2246    Name of the individual user making the assignment. If omitted, defaults to the user group.
2247    
2248  =item RETURN  =item RETURN
2249    
2250  Returns 1 if successful, 0 if an error occurred.  Returns 1 if successful, 0 if an error occurred.
# Line 1635  Line 2255 
2255  #: Return Type $;  #: Return Type $;
2256  sub AssignFunction {  sub AssignFunction {
2257          # Get the parameters.          # Get the parameters.
2258          my $self = shift @_;      my ($self, $featureID, $user, $function, $assigningUser) = @_;
2259          my ($featureID, $user, $function) = @_;      # Default the assigning user.
2260        if (! $assigningUser) {
2261            $assigningUser = $user;
2262        }
2263          # Create an annotation string from the parameters.          # Create an annotation string from the parameters.
2264          my $annotationText = "$user\nset $user function to\n$function";      my $annotationText = "$assigningUser\nset $user function to\n$function";
2265          # Get the current time.          # Get the current time.
2266          my $now = time;          my $now = time;
2267          # Declare the return variable.          # Declare the return variable.
# Line 1683  Line 2306 
2306  #: Return Type @;  #: Return Type @;
2307  sub FeaturesByAlias {  sub FeaturesByAlias {
2308          # Get the parameters.          # Get the parameters.
2309          my $self = shift @_;      my ($self, $alias) = @_;
         my ($alias) = @_;  
2310          # Declare the return variable.          # Declare the return variable.
2311          my @retVal = ();          my @retVal = ();
2312          # Parse the alias.          # Parse the alias.
# Line 1700  Line 2322 
2322          return @retVal;          return @retVal;
2323  }  }
2324    
 =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 = shift @_;  
         my ($entityName, $entityID) = @_;  
         # Check for the entity instance.  
         my $testInstance = $self->GetEntity($entityName, $entityID);  
         # Return an existence indicator.  
         my $retVal = ($testInstance ? 1 : 0);  
         return $retVal;  
 }  
   
2325  =head3 FeatureTranslation  =head3 FeatureTranslation
2326    
2327  C<< my $translation = $sprout->FeatureTranslation($featureID); >>  C<< my $translation = $sprout->FeatureTranslation($featureID); >>
# Line 1757  Line 2344 
2344  #: Return Type $;  #: Return Type $;
2345  sub FeatureTranslation {  sub FeatureTranslation {
2346          # Get the parameters.          # Get the parameters.
2347          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2348          # Get the specified feature's translation.          # Get the specified feature's translation.
2349          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
2350          return $retVal;          return $retVal;
# Line 1790  Line 2376 
2376  #: Return Type @;  #: Return Type @;
2377  sub Taxonomy {  sub Taxonomy {
2378          # Get the parameters.          # Get the parameters.
2379          my $self = shift @_;      my ($self, $genome) = @_;
         my ($genome) = @_;  
2380          # Find the specified genome's taxonomy string.          # Find the specified genome's taxonomy string.
2381          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);
2382          # Declare the return variable.          # Declare the return variable.
# Line 1834  Line 2419 
2419  #: Return Type $;  #: Return Type $;
2420  sub CrudeDistance {  sub CrudeDistance {
2421          # Get the parameters.          # Get the parameters.
2422          my $self = shift @_;      my ($self, $genome1, $genome2) = @_;
         my ($genome1, $genome2) = @_;  
2423          # Insure that the distance is commutative by sorting the genome IDs.          # Insure that the distance is commutative by sorting the genome IDs.
2424          my ($genomeA, $genomeB);          my ($genomeA, $genomeB);
2425          if ($genome2 < $genome2) {          if ($genome2 < $genome2) {
# Line 1882  Line 2466 
2466  #: Return Type $;  #: Return Type $;
2467  sub RoleName {  sub RoleName {
2468          # Get the parameters.          # Get the parameters.
2469          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2470          # Get the specified role's name.          # Get the specified role's name.
2471          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);
2472          # Use the ID if the role has no name.          # Use the ID if the role has no name.
# Line 1916  Line 2499 
2499  #: Return Type @;  #: Return Type @;
2500  sub RoleDiagrams {  sub RoleDiagrams {
2501          # Get the parameters.          # Get the parameters.
2502          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2503          # Query for the diagrams.          # Query for the diagrams.
2504          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2505                                                                  'RoleOccursIn(to-link)');                                                                  'RoleOccursIn(to-link)');
# Line 1925  Line 2507 
2507          return @retVal;          return @retVal;
2508  }  }
2509    
2510    =head3 GetProperties
2511    
2512    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2513    
2514    Return a list of the properties with the specified characteristics.
2515    
2516    Properties are arbitrary key-value pairs associated with a feature. (At some point they
2517    will also be associated with genomes.) A property value is represented by a 4-tuple of
2518    the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2519    
2520    =over 4
2521    
2522    =item fid
2523    
2524    ID of the feature possessing the property.
2525    
2526    =item key
2527    
2528    Name or key of the property.
2529    
2530    =item value
2531    
2532    Value of the property.
2533    
2534    =item url
2535    
2536    URL of the document that indicated the property should have this particular value, or an
2537    empty string if no such document exists.
2538    
2539    =back
2540    
2541    The parameters act as a filter for the desired data. Any non-null parameter will
2542    automatically match all the tuples returned. So, specifying just the I<$fid> will
2543    return all the properties of the specified feature; similarly, specifying the I<$key>
2544    and I<$value> parameters will return all the features having the specified property
2545    value.
2546    
2547    A single property key can have many values, representing different ideas about the
2548    feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2549    virulent, and another may declare that it is not virulent. A query about the virulence of
2550    C<fig|83333.1.peg.10> would be coded as
2551    
2552        my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2553    
2554    Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2555    not to be filtered. The tuples returned would be
2556    
2557        ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2558        ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2559    
2560    =cut
2561    #: Return Type @@;
2562    sub GetProperties {
2563        # Get the parameters.
2564        my ($self, @parms) = @_;
2565        # Declare the return variable.
2566        my @retVal = ();
2567        # Now we need to create a WHERE clause that will get us the data we want. First,
2568        # we create a list of the columns containing the data for each parameter.
2569        my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2570                        'Property(property-value)', 'HasProperty(evidence)');
2571        # Now we build the WHERE clause and the list of parameter values.
2572        my @where = ();
2573        my @values = ();
2574        for (my $i = 0; $i <= $#colNames; $i++) {
2575            my $parm = $parms[$i];
2576            if (defined $parm && ($parm ne '')) {
2577                push @where, "$colNames[$i] = ?";
2578                push @values, $parm;
2579            }
2580        }
2581        # Format the WHERE clause.
2582        my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2583        # Ask for all the propertie values with the desired characteristics.
2584        my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2585        while (my $valueObject = $query->Fetch()) {
2586            my @tuple = $valueObject->Values(\@colNames);
2587            push @retVal, \@tuple;
2588        }
2589        # Return the result.
2590        return @retVal;
2591    }
2592    
2593  =head3 FeatureProperties  =head3 FeatureProperties
2594    
2595  C<< my @properties = $sprout->FeatureProperties($featureID); >>  C<< my @properties = $sprout->FeatureProperties($featureID); >>
# Line 1954  Line 2619 
2619  #: Return Type @@;  #: Return Type @@;
2620  sub FeatureProperties {  sub FeatureProperties {
2621          # Get the parameters.          # Get the parameters.
2622          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2623          # Get the properties.          # Get the properties.
2624          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],
2625                                                          ['Property(property-name)', 'Property(property-value)',                                                          ['Property(property-name)', 'Property(property-value)',
# Line 1986  Line 2650 
2650  #: Return Type $;  #: Return Type $;
2651  sub DiagramName {  sub DiagramName {
2652          # Get the parameters.          # Get the parameters.
2653          my $self = shift @_;      my ($self, $diagramID) = @_;
         my ($diagramID) = @_;  
2654          # Get the specified diagram's name and return it.          # Get the specified diagram's name and return it.
2655          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);
2656          return $retVal;          return $retVal;
# Line 2019  Line 2682 
2682  #: Return Type @;  #: Return Type @;
2683  sub MergedAnnotations {  sub MergedAnnotations {
2684          # Get the parameters.          # Get the parameters.
2685          my $self = shift @_;      my ($self, $list) = @_;
         my ($list) = @_;  
2686          # Create a list to hold the annotation tuples found.          # Create a list to hold the annotation tuples found.
2687          my @tuples = ();          my @tuples = ();
2688          # Loop through the features in the input list.          # Loop through the features in the input list.
# Line 2068  Line 2730 
2730  #: Return Type @;  #: Return Type @;
2731  sub RoleNeighbors {  sub RoleNeighbors {
2732          # Get the parameters.          # Get the parameters.
2733          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2734          # Get all the diagrams containing this role.          # Get all the diagrams containing this role.
2735          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2736                                                                    'RoleOccursIn(to-link)');                                                                    'RoleOccursIn(to-link)');
# Line 2111  Line 2772 
2772  #: Return Type @;  #: Return Type @;
2773  sub FeatureLinks {  sub FeatureLinks {
2774          # Get the parameters.          # Get the parameters.
2775          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2776          # Get the feature's links.          # Get the feature's links.
2777          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);
2778          # Return the feature's links.          # Return the feature's links.
# Line 2124  Line 2784 
2784  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2785    
2786  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
2787  to the role the feature performs.  to the roles the feature performs.
2788    
2789  =over 4  =over 4
2790    
# Line 2134  Line 2794 
2794    
2795  =item RETURN  =item RETURN
2796    
2797  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.
2798    
2799  =back  =back
2800    
2801  =cut  =cut
2802  #: Return Type %;  #: Return Type %@;
2803  sub SubsystemsOf {  sub SubsystemsOf {
2804          # Get the parameters.          # Get the parameters.
2805          my $self = shift @_;      my ($self, $featureID) = @_;
2806          my ($featureID) = @_;      # Get the subsystem list.
         # Use the SSCell to connect features to subsystems.  
2807          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2808                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2809                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2810          # Create the return value.          # Create the return value.
2811          my %retVal = ();          my %retVal = ();
2812        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2813        # in two spreadsheet cells.
2814        my %dupHash = ();
2815          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
2816          for my $record (@subsystems) {          for my $record (@subsystems) {
2817                  $retVal{$record->[0]} = $record->[1];          # Get this subsystem and role.
2818            my ($subsys, $role) = @{$record};
2819            # Insure it's the first time for both.
2820            my $dupKey = "$subsys\n$role";
2821            if (! exists $dupHash{"$subsys\n$role"}) {
2822                $dupHash{$dupKey} = 1;
2823                push @{$retVal{$subsys}}, $role;
2824            }
2825          }          }
2826          # Return the hash.          # Return the hash.
2827          return %retVal;          return %retVal;
2828  }  }
2829    
2830    =head3 SubsystemList
2831    
2832    C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2833    
2834    Return a list containing the names of the subsystems in which the specified
2835    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2836    subsystem names, not the roles.
2837    
2838    =over 4
2839    
2840    =item featureID
2841    
2842    ID of the feature whose subsystem names are desired.
2843    
2844    =item RETURN
2845    
2846    Returns a list of the names of the subsystems in which the feature participates.
2847    
2848    =back
2849    
2850    =cut
2851    #: Return Type @;
2852    sub SubsystemList {
2853        # Get the parameters.
2854        my ($self, $featureID) = @_;
2855        # Get the list of names.
2856        my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",
2857                                    [$featureID], 'HasSSCell(from-link)');
2858        # Return the result.
2859        return @retVal;
2860    }
2861    
2862    =head3 GenomeSubsystemData
2863    
2864    C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>
2865    
2866    Return a hash mapping genome features to their subsystem roles.
2867    
2868    =over 4
2869    
2870    =item genomeID
2871    
2872    ID of the genome whose subsystem feature map is desired.
2873    
2874    =item RETURN
2875    
2876    Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb
2877    2-tuple contains a subsystem name followed by a role ID.
2878    
2879    =back
2880    
2881    =cut
2882    
2883    sub GenomeSubsystemData {
2884        # Get the parameters.
2885        my ($self, $genomeID) = @_;
2886        # Declare the return variable.
2887        my %retVal = ();
2888        # Get a list of the genome features that participate in subsystems. For each
2889        # feature we get its spreadsheet cells and the corresponding roles.
2890        my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],
2891                                 "HasFeature(from-link) = ?", [$genomeID],
2892                                 ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);
2893        # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems
2894        # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the
2895        # list. We use it at the beginning to get all the spreadsheet cells for the genome and
2896        # again at the end to filter out participation in subsystems with a negative variant code.
2897        my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],
2898                                     "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?",
2899                                     [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']);
2900        # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features.
2901        # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We
2902        # link these two lists together to create the result. First, we want a hash mapping
2903        # spreadsheet cells to subsystem names.
2904        my %subHash = map { $_->[0] => $_->[1] } @cellData;
2905        # We loop through @cellData to build the hash.
2906        for my $roleEntry (@roleData) {
2907            # Get the data for this feature and cell.
2908            my ($fid, $cellID, $role) = @{$roleEntry};
2909            # Check for a subsystem name.
2910            my $subsys = $subHash{$cellID};
2911            if ($subsys) {
2912                # Insure this feature has an entry in the return hash.
2913                if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
2914                # Merge in this new data.
2915                push @{$retVal{$fid}}, [$subsys, $role];
2916            }
2917        }
2918        # Return the result.
2919        return %retVal;
2920    }
2921    
2922  =head3 RelatedFeatures  =head3 RelatedFeatures
2923    
2924  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2191  Line 2952 
2952  #: Return Type @;  #: Return Type @;
2953  sub RelatedFeatures {  sub RelatedFeatures {
2954          # Get the parameters.          # Get the parameters.
2955          my $self = shift @_;      my ($self, $featureID, $function, $userID) = @_;
         my ($featureID, $function, $userID) = @_;  
2956          # Get a list of the features that are BBHs of the incoming feature.          # Get a list of the features that are BBHs of the incoming feature.
2957          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
                                                                          "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],  
                                                                          'IsBidirectionalBestHitOf(to-link)');  
2958          # Now we loop through the features, pulling out the ones that have the correct          # Now we loop through the features, pulling out the ones that have the correct
2959          # functional assignment.          # functional assignment.
2960          my @retVal = ();          my @retVal = ();
# Line 2240  Line 2998 
2998  #: Return Type @;  #: Return Type @;
2999  sub TaxonomySort {  sub TaxonomySort {
3000          # Get the parameters.          # Get the parameters.
3001          my $self = shift @_;      my ($self, $featureIDs) = @_;
         my ($featureIDs) = @_;  
3002          # Create the working hash table.          # Create the working hash table.
3003          my %hashBuffer = ();          my %hashBuffer = ();
3004          # Loop through the features.          # Loop through the features.
# Line 2250  Line 3007 
3007                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
3008                                                                                  [$fid], 'Genome(taxonomy)');                                                                                  [$fid], 'Genome(taxonomy)');
3009                  # Add this feature to the hash buffer.                  # Add this feature to the hash buffer.
3010                  if (exists $hashBuffer{$taxonomy}) {          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);
                         push @{$hashBuffer{$taxonomy}}, $fid;  
                 } else {  
                         $hashBuffer{$taxonomy} = [$fid];  
                 }  
3011          }          }
3012          # Sort the keys and get the elements.          # Sort the keys and get the elements.
3013          my @retVal = ();          my @retVal = ();
# Line 2265  Line 3018 
3018          return @retVal;          return @retVal;
3019  }  }
3020    
 =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 = shift @_;  
         my ($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 = shift @_;  
         my ($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;  
 }  
   
3021  =head3 Protein  =head3 Protein
3022    
3023  C<< my $protein = Sprout::Protein($sequence, $table); >>  C<< my $protein = Sprout::Protein($sequence, $table); >>
# Line 2496  Line 3115 
3115  #: Return Type @;  #: Return Type @;
3116  sub LoadInfo {  sub LoadInfo {
3117          # Get the parameters.          # Get the parameters.
3118          my $self = shift @_;      my ($self) = @_;
3119          # 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.
3120          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
3121          # Concatenate the table names.          # Concatenate the table names.
3122          push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
3123          # Return the result.          # Return the result.
3124          return @retVal;          return @retVal;
3125  }  }
3126    
3127  =head3 LowBBHs  =head3 LowBBHs
3128    
3129  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
3130    
3131  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
3132  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 2533  Line 3152 
3152  #: Return Type %;  #: Return Type %;
3153  sub LowBBHs {  sub LowBBHs {
3154          # Get the parsameters.          # Get the parsameters.
3155          my $self = shift @_;      my ($self, $featureID, $cutoff) = @_;
         my ($featureID, $cutoff) = @_;  
3156          # Create the return hash.          # Create the return hash.
3157          my %retVal = ();          my %retVal = ();
3158          # Create a query to get the desired BBHs.      # Query for the desired BBHs.
3159          my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BBHData($featureID, $cutoff);
                                                                 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',  
                                                                 [$cutoff, $featureID],  
                                                                 ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);  
3160          # Form the results into the return hash.          # Form the results into the return hash.
3161          for my $pair (@bbhList) {          for my $pair (@bbhList) {
3162                  $retVal{$pair->[0]} = $pair->[1];                  $retVal{$pair->[0]} = $pair->[1];
# Line 2550  Line 3165 
3165          return %retVal;          return %retVal;
3166  }  }
3167    
3168    =head3 Sims
3169    
3170    C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>
3171    
3172    Get a list of similarities for a specified feature. Similarity information is not kept in the
3173    Sprout database; rather, they are retrieved from a network server. The similarities are
3174    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3175    so that its elements can be accessed by name.
3176    
3177    Similarities can be either raw or expanded. The raw similarities are basic
3178    hits between features with similar DNA. Expanding a raw similarity drags in any
3179    features considered substantially identical. So, for example, if features B<A1>,
3180    B<A2>, and B<A3> are all substatially identical to B<A>, then a raw similarity
3181    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3182    
3183    =over 4
3184    
3185    =item fid
3186    
3187    ID of the feature whose similarities are desired.
3188    
3189    =item maxN
3190    
3191    Maximum number of similarities to return.
3192    
3193    =item maxP
3194    
3195    Minumum allowable similarity score.
3196    
3197    =item select
3198    
3199    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3200    means only similarities to FIG features are returned; C<all> means all expanded
3201    similarities are returned; and C<figx> means similarities are expanded until the
3202    number of FIG features equals the maximum.
3203    
3204    =item max_expand
3205    
3206    The maximum number of features to expand.
3207    
3208    =item filters
3209    
3210    Reference to a hash containing filter information, or a subroutine that can be
3211    used to filter the sims.
3212    
3213    =item RETURN
3214    
3215    Returns a reference to a list of similarity objects, or C<undef> if an error
3216    occurred.
3217    
3218    =back
3219    
3220    =cut
3221    
3222    sub Sims {
3223        # Get the parameters.
3224        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3225        # Create the shim object to test for deleted FIDs.
3226        my $shim = FidCheck->new($self);
3227        # Ask the network for sims.
3228        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3229        # Return the result.
3230        return $retVal;
3231    }
3232    
3233    =head3 GetGroups
3234    
3235    C<< my %groups = $sprout->GetGroups(\@groupList); >>
3236    
3237    Return a hash mapping each group to the IDs of the genomes in the group.
3238    A list of groups may be specified, in which case only those groups will be
3239    shown. Alternatively, if no parameter is supplied, all groups will be
3240    included. Genomes that are not in any group are omitted.
3241    
3242    =cut
3243    #: Return Type %@;
3244    sub GetGroups {
3245        # Get the parameters.
3246        my ($self, $groupList) = @_;
3247        # Declare the return value.
3248        my %retVal = ();
3249        # Determine whether we are getting all the groups or just some.
3250        if (defined $groupList) {
3251            # Here we have a group list. Loop through them individually,
3252            # getting a list of the relevant genomes.
3253            for my $group (@{$groupList}) {
3254                my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",
3255                    [$group], "Genome(id)");
3256                $retVal{$group} = \@genomeIDs;
3257            }
3258        } else {
3259            # Here we need all of the groups. In this case, we run through all
3260            # of the genome records, putting each one found into the appropriate
3261            # group. Note that we use a filter clause to insure that only genomes
3262            # in groups are included in the return set.
3263            my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],
3264                                        ['Genome(id)', 'Genome(group-name)']);
3265            # Loop through the genomes found.
3266            for my $genome (@genomes) {
3267                # Pop this genome's ID off the current list.
3268                my @groups = @{$genome};
3269                my $genomeID = shift @groups;
3270                # Loop through the groups, adding the genome ID to each group's
3271                # list.
3272                for my $group (@groups) {
3273                    Tracer::AddToListMap(\%retVal, $group, $genomeID);
3274                }
3275            }
3276        }
3277        # Return the hash we just built.
3278        return %retVal;
3279    }
3280    
3281    =head3 MyGenomes
3282    
3283    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
3284    
3285    Return a list of the genomes to be included in the Sprout.
3286    
3287    This method is provided for use during the Sprout load. It presumes the Genome load file has
3288    already been created. (It will be in the Sprout data directory and called either C<Genome>
3289    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3290    IDs.
3291    
3292    =over 4
3293    
3294    =item dataDir
3295    
3296    Directory containing the Sprout load files.
3297    
3298    =back
3299    
3300    =cut
3301    #: Return Type @;
3302    sub MyGenomes {
3303        # Get the parameters.
3304        my ($dataDir) = @_;
3305        # Compute the genome file name.
3306        my $genomeFileName = LoadFileName($dataDir, "Genome");
3307        # Extract the genome IDs from the files.
3308        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3309        # Return the result.
3310        return @retVal;
3311    }
3312    
3313    =head3 LoadFileName
3314    
3315    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3316    
3317    Return the name of the load file for the specified table in the specified data
3318    directory.
3319    
3320    =over 4
3321    
3322    =item dataDir
3323    
3324    Directory containing the Sprout load files.
3325    
3326    =item tableName
3327    
3328    Name of the table whose load file is desired.
3329    
3330    =item RETURN
3331    
3332    Returns the name of the file containing the load data for the specified table, or
3333    C<undef> if no load file is present.
3334    
3335    =back
3336    
3337    =cut
3338    #: Return Type $;
3339    sub LoadFileName {
3340        # Get the parameters.
3341        my ($dataDir, $tableName) = @_;
3342        # Declare the return variable.
3343        my $retVal;
3344        # Check for the various file names.
3345        if (-e "$dataDir/$tableName") {
3346            $retVal = "$dataDir/$tableName";
3347        } elsif (-e "$dataDir/$tableName.dtx") {
3348            $retVal = "$dataDir/$tableName.dtx";
3349        }
3350        # Return the result.
3351        return $retVal;
3352    }
3353    
3354    =head3 DeleteGenome
3355    
3356    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3357    
3358    Delete a genome from the database.
3359    
3360    =over 4
3361    
3362    =item genomeID
3363    
3364    ID of the genome to delete
3365    
3366    =item testFlag
3367    
3368    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3369    
3370    =item RETURN
3371    
3372    Returns a statistics object describing the rows deleted.
3373    
3374    =back
3375    
3376    =cut
3377    #: Return Type $%;
3378    sub DeleteGenome {
3379        # Get the parameters.
3380        my ($self, $genomeID, $testFlag) = @_;
3381        # Perform the delete for the genome's features.
3382        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);
3383        # Perform the delete for the primary genome data.
3384        my $stats = $self->Delete('Genome', $genomeID, $testFlag);
3385        $retVal->Accumulate($stats);
3386        # Return the result.
3387        return $retVal;
3388    }
3389    
3390    =head3 Fix
3391    
3392    C<< my %fixedHash = Sprout::Fix(%groupHash); >>
3393    
3394    Prepare a genome group hash (like that returned by L</GetGroups> for processing.
3395    Groups with the same primary name will be combined. The primary name is the
3396    first capitalized word in the group name.
3397    
3398    =over 4
3399    
3400    =item groupHash
3401    
3402    Hash to be fixed up.
3403    
3404    =item RETURN
3405    
3406    Returns a fixed-up version of the hash.
3407    
3408    =back
3409    
3410    =cut
3411    
3412    sub Fix {
3413        # Get the parameters.
3414        my (%groupHash) = @_;
3415        # Create the result hash.
3416        my %retVal = ();
3417        # Copy over the genomes.
3418        for my $groupID (keys %groupHash) {
3419            # Make a safety copy of the group ID.
3420            my $realGroupID = $groupID;
3421            # Yank the primary name.
3422            if ($groupID =~ /([A-Z]\w+)/) {
3423                $realGroupID = $1;
3424            }
3425            # Append this group's genomes into the result hash.
3426            Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}});
3427        }
3428        # Return the result hash.
3429        return %retVal;
3430    }
3431    
3432    =head3 ReadGroupFile
3433    
3434    C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >>
3435    
3436    Read in the data from the specified group file. The group file contains information
3437    about each of the NMPDR groups.
3438    
3439    =over 4
3440    
3441    =item name
3442    
3443    Name of the group.
3444    
3445    =item page
3446    
3447    Name of the group's page on the web site (e.g. C<campy.php> for
3448    Campylobacter)
3449    
3450    =item genus
3451    
3452    Genus of the group
3453    
3454    =item species
3455    
3456    Species of the group, or an empty string if the group is for an entire
3457    genus. If the group contains more than one species, the species names
3458    should be separated by commas.
3459    
3460    =back
3461    
3462    The parameters to this method are as follows
3463    
3464    =over 4
3465    
3466    =item groupFile
3467    
3468    Name of the file containing the group data.
3469    
3470    =item RETURN
3471    
3472    Returns a hash keyed on group name. The value of each hash
3473    
3474    =back
3475    
3476    =cut
3477    
3478    sub ReadGroupFile {
3479        # Get the parameters.
3480        my ($groupFileName) = @_;
3481        # Declare the return variable.
3482        my %retVal;
3483        # Read the group file.
3484        my @groupLines = Tracer::GetFile($groupFileName);
3485        for my $groupLine (@groupLines) {
3486            my ($name, $page, $genus, $species) = split(/\t/, $groupLine);
3487            $retVal{$name} = [$page, $genus, $species];
3488        }
3489        # Return the result.
3490        return %retVal;
3491    }
3492    
3493  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3494    
3495  =head3 ParseAssignment  =head3 ParseAssignment
3496    
3497  Parse annotation text to determine whether or not it is a functional assignment. If it is,  Parse annotation text to determine whether or not it is a functional assignment. If it is,
3498  the user and function text will be returned as a 2-element list. If it isn't, an empty list  the user, function text, and assigning user will be returned as a 3-element list. If it
3499  will be returned.  isn't, an empty list will be returned.
3500    
3501    A functional assignment is always of the form
3502    
3503        C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3504    
3505    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3506    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3507    not always the case.
3508    
3509    In addition, the functional role may contain extra data that is stripped, such as
3510    terminating spaces or a comment separated from the rest of the text by a tab.
3511    
3512  This is a static method.  This is a static method.
3513    
3514  =over 4  =over 4
3515    
3516    =item user
3517    
3518    Name of the assigning user.
3519    
3520  =item text  =item text
3521    
3522  Text of the annotation.  Text of the annotation.
# Line 2575  Line 3530 
3530    
3531  =cut  =cut
3532    
3533  sub ParseAssignment {  sub _ParseAssignment {
3534          # Get the parameters.          # Get the parameters.
3535          my ($text) = @_;      my ($user, $text) = @_;
3536          # Declare the return value.          # Declare the return value.
3537          my @retVal = ();          my @retVal = ();
3538          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3539          my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3540          if ($type =~ m/^set $user function to$/i) {      if ($type =~ m/^set function to$/i) {
3541                  # Here it is, so we return the user name and function text.          # Here we have an assignment without a user, so we use the incoming user ID.
3542                  @retVal = ($user, $function);                  @retVal = ($user, $function);
3543        } elsif ($type =~ m/^set (\S+) function to$/i) {
3544            # Here we have an assignment with a user that is passed back to the caller.
3545            @retVal = ($1, $function);
3546        }
3547        # If we have an assignment, we need to clean the function text. There may be
3548        # extra junk at the end added as a note from the user.
3549        if (defined( $retVal[1] )) {
3550            $retVal[1] =~ s/(\t\S)?\s*$//;
3551          }          }
3552          # Return the result list.          # Return the result list.
3553          return @retVal;          return @retVal;
# Line 2612  Line 3575 
3575    
3576  sub FriendlyTimestamp {  sub FriendlyTimestamp {
3577      my ($timeValue) = @_;      my ($timeValue) = @_;
3578      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
3579      return $retVal;      return $retVal;
3580  }  }
3581    
3582    =head3 AddProperty
3583    
3584    C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>
3585    
3586    Add a new attribute value (Property) to a feature. In the SEED system, attributes can
3587    be added to almost any object. In Sprout, they can only be added to features. In
3588    Sprout, attributes are implemented using I<properties>. A property represents a key/value
3589    pair. If the particular key/value pair coming in is not already in the database, a new
3590    B<Property> record is created to hold it.
3591    
3592    =over 4
3593    
3594    =item peg
3595    
3596    ID of the feature to which the attribute is to be replied.
3597    
3598    =item key
3599    
3600    Name of the attribute (key).
3601    
3602    =item value
3603    
3604    Value of the attribute.
3605    
3606    =item url
3607    
3608    URL or text citation from which the property was obtained.
3609    
3610    =back
3611    
3612    =cut
3613    #: Return Type ;
3614    sub AddProperty {
3615        # Get the parameters.
3616        my ($self, $featureID, $key, $value, $url) = @_;
3617        # Declare the variable to hold the desired property ID.
3618        my $propID;
3619        # Attempt to find a property record for this key/value pair.
3620        my @properties = $self->GetFlat(['Property'],
3621                                       "Property(property-name) = ? AND Property(property-value) = ?",
3622                                       [$key, $value], 'Property(id)');
3623        if (@properties) {
3624            # Here the property is already in the database. We save its ID.
3625            $propID = $properties[0];
3626            # Here the property value does not exist. We need to generate an ID. It will be set
3627            # to a number one greater than the maximum value in the database. This call to
3628            # GetAll will stop after one record.
3629            my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],
3630                                            1);
3631            $propID = $maxProperty[0]->[0] + 1;
3632            # Insert the new property value.
3633            $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });
3634        }
3635        # Now we connect the incoming feature to the property.
3636        $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3637    }
3638    
3639    
3640  1;  1;

Legend:
Removed from v.1.5  
changed lines
  Added in v.1.84

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3