[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.2, Sun Jan 23 22:31:29 2005 UTC revision 1.71, Sun Jun 25 00:07:22 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);
18    
19    
20  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
# Line 31  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();
43    
44  =head2 Public Methods  =head2 Public Methods
45    
# Line 61  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 85  Line 95 
95          # Compute the options. We do this by starting with a table of defaults and overwriting with          # Compute the options. We do this by starting with a table of defaults and overwriting with
96          # the incoming data.          # the incoming data.
97          my $optionTable = Tracer::GetOptions({          my $optionTable = Tracer::GetOptions({
98                                             dbType               => 'mysql',                     # database type                         dbType       => $FIG_Config::dbms,
99                                             dataDir              => 'Data',                      # data file directory                                                          # database type
100                                             xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
101                                             userData             => 'root/',                     # user name and password                                                          # data file directory
102                                             port                 => 0,                           # database connection port                         xmlFileName  => "$FIG_Config::fig/SproutDBD.xml",
103                                                            # database definition file name
104                           userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
105                                                            # user name and password
106                           port         => $FIG_Config::dbport,
107                                                            # database connection port
108                           sock         => $FIG_Config::dbsock,
109                                             maxSegmentLength => 4500,            # maximum feature segment length                                             maxSegmentLength => 4500,            # maximum feature segment length
110                                             maxSequenceLength => 8000,           # maximum contig sequence length                                             maxSequenceLength => 8000,           # maximum contig sequence length
111                           noDBOpen     => 0,               # 1 to suppress the database open
112                                            }, $options);                                            }, $options);
113          # Get the data directory.          # Get the data directory.
114          my $dataDir = $optionTable->{dataDir};          my $dataDir = $optionTable->{dataDir};
# Line 99  Line 116 
116          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
117          my ($userName, $password) = ($1, $2);          my ($userName, $password) = ($1, $2);
118          # Connect to the database.          # Connect to the database.
119          my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
120        if (! $optionTable->{noDBOpen}) {
121            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
122                                    $password, $optionTable->{port}, undef, $optionTable->{sock});
123        }
124          # Create the ERDB object.          # Create the ERDB object.
125          my $xmlFileName = "$optionTable->{xmlFileName}";          my $xmlFileName = "$optionTable->{xmlFileName}";
126          my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
127          # Create this object.      # Add the option table and XML file name.
128          my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
129          # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
130          bless $self;      # Return it.
131          return $self;      return $retVal;
132  }  }
133    
134  =head3 MaxSegment  =head3 MaxSegment
# Line 121  Line 142 
142  and 10999.  and 10999.
143    
144  =cut  =cut
145    #: Return Type $;
146  sub MaxSegment {  sub MaxSegment {
147          my $self = shift @_;      my ($self) = @_;
148          return $self->{_options}->{maxSegmentLength};          return $self->{_options}->{maxSegmentLength};
149  }  }
150    
# Line 136  Line 157 
157  we generally only need a few sequences in memory rather than the entire contig.  we generally only need a few sequences in memory rather than the entire contig.
158    
159  =cut  =cut
160    #: Return Type $;
161  sub MaxSequence {  sub MaxSequence {
162          my $self = shift @_;      my ($self) = @_;
163          return $self->{_options}->{maxSequenceLength};          return $self->{_options}->{maxSequenceLength};
164  }  }
165    
166  =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]); >>  
167    
168  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.  
169    
170  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.
171    
172  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
173  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
174  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
175    extension are used in preference to the files with an extension.
176    
177  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
178  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
179  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
180  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.  
181    
182  =over 4  =over 4
183    
184  =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  
185    
186  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
187    
188  =item RETURN  =item RETURN
189    
190  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,
191    the number of errors, and a list of the error messages.
192    
193  =back  =back
194    
195  =cut  =cut
196    #: Return Type %;
197  sub Get {  sub Load {
198          # Get the parameters.          # Get the parameters.
199          my $self = shift @_;      my ($self, $rebuild) = @_;
200          my ($objectNames, $filterClause, $parameterList) = @_;      # Load the tables from the data directory.
201          # 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);
202          # rather than a list of parameters. The next step is to convert the parameters from a reference      # Return the statistics.
203          # 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);  
204  }  }
205    
206  =head3 GetEntity  =head3 LoadUpdate
207    
208  C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
209    
210  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
211    or two tables without reloading the whole database. For each table, there must be a corresponding
212    file in the data directory, either with the same name as the table, or with a C<.dtx> suffix. So,
213    for example, to make updates to the B<FeatureTranslation> relation, there must be a
214    C<FeatureTranslation.dtx> file in the data directory. Unlike a full load, files without an extension
215    are not examined. This allows update files to co-exist with files from an original load.
216    
217  =over 4  =over 4
218    
219  =item entityType  =item truncateFlag
220    
221  Entity type name.  TRUE if the tables should be rebuilt before loading, else FALSE. A value of TRUE therefore causes
222    current data and schema of the tables to be replaced, while a value of FALSE means the new data
223    is added to the existing data in the various relations.
224    
225  =item ID  =item tableList
226    
227  ID of the desired entity.  List of the tables to be updated.
228    
229  =item RETURN  =item RETURN
230    
231  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,
232  instance is found with the specified key.  the number of errors encountered, and a list of error messages.
233    
234  =back  =back
235    
236  =cut  =cut
237    #: Return Type $%;
238  sub GetEntity {  sub LoadUpdate {
239          # Get the parameters.          # Get the parameters.
240          my $self = shift @_;      my ($self, $truncateFlag, $tableList) = @_;
241          my ($entityType, $ID) = @_;      # Declare the return value.
242          # Create a query.      my $retVal = Stats->new();
243          my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);      # Get the data directory.
244          # Get the first (and only) object.      my $optionTable = $self->{_options};
245          my $retVal = $query->Fetch();      my $dataDir = $optionTable->{dataDir};
246          # Return the result.      # Loop through the incoming table names.
247        for my $tableName (@{$tableList}) {
248            # Find the table's file.
249            my $fileName = LoadFileName($dataDir, $tableName);
250            if (! $fileName) {
251                Trace("No load file found for $tableName in $dataDir.") if T(0);
252            } else {
253                # Attempt to load this table.
254                my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);
255                # Accumulate the resulting statistics.
256                $retVal->Accumulate($result);
257            }
258        }
259        # Return the statistics.
260          return $retVal;          return $retVal;
261  }  }
262    
263  =head3 GetEntityValues  =head3 GenomeCounts
264    
265  C<< my @values = GetEntityValues($entityType, $ID, \@fields); >>  C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>
266    
267  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
268    genomes will be included in the counts.
269    
270  =over 4  =over 4
271    
272  =item entityType  =item complete
   
 Entity type name.  
273    
274  =item ID  TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
275    counted
 ID of the desired entity.  
   
 =item fields  
   
 List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.  
276    
277  =item RETURN  =item RETURN
278    
279  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--
280    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
281    
282  =back  =back
283    
284  =cut  =cut
285    
286  sub GetEntityValues {  sub GenomeCounts {
287          # Get the parameters.          # Get the parameters.
288          my $self = shift @_;      my ($self, $complete) = @_;
289          my ($entityType, $ID, $fields) = @_;      # Set the filter based on the completeness flag.
290          # Get the specified entity.      my $filter = ($complete ? "Genome(complete) = 1" : "");
291          my $entity = $self->GetEntity($entityType, $ID);      # Get all the genomes and the related taxonomy information.
292          # Declare the return list.      my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
293          my @retVal = ();      # Clear the counters.
294          # If we found the entity, push the values into the return list.      my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
295          if ($entity) {      # Loop through, counting the domains.
296                  push @retVal, $entity->Values($fields);      for my $genome (@genomes) {
297            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
298            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
299            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
300            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
301            elsif ($genome->[1] =~ /^env/i)      { ++$env }
302            else  { ++$unk }
303          }          }
304          # Return the result.      # Return the counts.
305          return @retVal;      return ($arch, $bact, $euk, $vir, $env, $unk);
 }  
   
 =head3 ShowMetaData  
   
 C<< $sprout->ShowMetaData($fileName); >>  
   
 This method outputs a description of the database to an HTML file in the data directory.  
   
 =over 4  
   
 =item fileName  
   
 Fully-qualified name to give to the output file.  
   
 =back  
   
 =cut  
   
 sub ShowMetaData {  
         # Get the parameters.  
         my $self = shift @_;  
         my ($fileName) = @_;  
         # Compute the file name.  
         my $options = $self->{_options};  
         # Call the show method on the underlying ERDB object.  
         $self->{_erdb}->ShowMetaData($fileName);  
306  }  }
307    
308  =head3 Load  =head3 ContigCount
   
 C<< $sprout->Load($rebuild); >>;  
   
 Load the database from files in the data directory, optionally re-creating the tables.  
309    
310  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.  
311    
312  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.  
313    
314  =over 4  =over 4
315    
316  =item rebuild  =item genomeID
317    
318  TRUE if the data tables need to be created or re-created, else FALSE  ID of the genome whose contig count is desired.
319    
320  =item RETURN  =item RETURN
321    
322  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.  
323    
324  =back  =back
325    
326  =cut  =cut
327    
328  sub Load {  sub ContigCount {
329          # Get the parameters.          # Get the parameters.
330          my $self = shift @_;      my ($self, $genomeID) = @_;
331          my ($rebuild) = @_;      # Get the contig count.
332          # Get the database object.      my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
333          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.  
334          return $retVal;          return $retVal;
335  }  }
336    
337  =head3 LoadUpdate  =head3 GeneMenu
338    
339  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params); >>
340    
341  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,
342  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
343  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.  
344    
345  =over 4  =over 4
346    
347  =item truncateFlag  =item attributes
348    
349  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.  
350    
351  =item tableList  =item filterString
352    
353  List of the tables to be updated.  A filter string for use in selecting the genomes. The filter string must conform
354    to the rules for the C<< ERDB->Get >> method.
355    
356    =item params
357    
358    Reference to a list of values to be substituted in for the parameter marks in
359    the filter string.
360    
361  =item RETURN  =item RETURN
362    
363  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.  
364    
365  =back  =back
366    
367  =cut  =cut
368    
369  sub LoadUpdate {  sub GeneMenu {
370          # Get the parameters.          # Get the parameters.
371          my $self = shift @_;      my ($self, $attributes, $filterString, $params) = @_;
372          my ($truncateFlag, $tableList) = @_;      # Start the menu.
373          # Get the database object.      my $retVal = "<select " .
374          my $erdb = $self->{_erdb};          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
375          # Declare the return value.          ">\n";
376          my $retVal = Stats->new();      # Get the genomes.
377          # Get the data directory.      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
378          my $optionTable = $self->{_options};                                                                       'Genome(genus)',
379          my $dataDir = $optionTable->{dataDir};                                                                       'Genome(species)',
380          # Loop through the incoming table names.                                                                       'Genome(unique-characterization)']);
381          for my $tableName (@{$tableList}) {      # Sort them by name.
382                  # Find the table's file.      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
383                  my $fileName = "$dataDir/$tableName";      # Loop through the genomes, creating the option tags.
384                  if (! -e $fileName) {      for my $genomeData (@sorted) {
385                          $fileName = "$fileName.dtx";          # Get the data for this genome.
386                  }          my ($genomeID, $genus, $species, $strain) = @{$genomeData};
387                  # Attempt to load this table.          # Get the contig count.
388                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);          my $count = $self->ContigCount($genomeID);
389                  # Accumulate the resulting statistics.          my $counting = ($count == 1 ? "contig" : "contigs");
390                  $retVal->Accumulate($result);          # Build the option tag.
391            $retVal .= "<option value=\"$genomeID\">$genus $species $strain ($genomeID) [$count $counting]</option>\n";
392            Trace("Option tag built for $genomeID: $genus $species $strain.") if T(3);
393          }          }
394          # Return the statistics.      # Close the SELECT tag.
395        $retVal .= "</select>\n";
396        # Return the result.
397          return $retVal;          return $retVal;
398  }  }
   
399  =head3 Build  =head3 Build
400    
401  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 459  Line 405 
405  changed.  changed.
406    
407  =cut  =cut
408    #: Return Type ;
409  sub Build {  sub Build {
410          # Get the parameters.          # Get the parameters.
411          my $self = shift @_;      my ($self) = @_;
412          # Create the tables.          # Create the tables.
413          $self->{_erdb}->CreateTables;      $self->CreateTables();
414  }  }
415    
416  =head3 Genomes  =head3 Genomes
# Line 474  Line 420 
420  Return a list of all the genome IDs.  Return a list of all the genome IDs.
421    
422  =cut  =cut
423    #: Return Type @;
424  sub Genomes {  sub Genomes {
425          # Get the parameters.          # Get the parameters.
426          my $self = shift @_;      my ($self) = @_;
427          # Get all the genomes.          # Get all the genomes.
428          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');
429          # Return the list of IDs.          # Return the list of IDs.
# Line 504  Line 450 
450  =back  =back
451    
452  =cut  =cut
453    #: Return Type $;
454  sub GenusSpecies {  sub GenusSpecies {
455          # Get the parameters.          # Get the parameters.
456          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
457          # Get the data for the specified genome.          # Get the data for the specified genome.
458          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',
459                                                                                                                            'Genome(unique-characterization)']);                                                                                                                            'Genome(unique-characterization)']);
# Line 541  Line 486 
486  =back  =back
487    
488  =cut  =cut
489    #: Return Type @;
490  sub FeaturesOf {  sub FeaturesOf {
491          # Get the parameters.          # Get the parameters.
492          my $self = shift @_;      my ($self, $genomeID,$ftype) = @_;
         my ($genomeID,$ftype) = @_;  
493          # Get the features we want.          # Get the features we want.
494          my @features;          my @features;
495          if (!$ftype) {          if (!$ftype) {
# Line 589  Line 533 
533  =item RETURN  =item RETURN
534    
535  Returns a list of the feature's contig segments. The locations are returned as a list in a list  Returns a list of the feature's contig segments. The locations are returned as a list in a list
536  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context.
537    
538  =back  =back
539    
540  =cut  =cut
541    #: Return Type @;
542    #: Return Type $;
543  sub FeatureLocation {  sub FeatureLocation {
544          # Get the parameters.          # Get the parameters.
545          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
546          # Create a query for the feature locations.          # Create a query for the feature locations.
547          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",
548                                                     [$featureID]);                                                     [$featureID]);
# Line 616  Line 560 
560                  if ($prevContig eq $contigID && $dir eq $prevDir) {                  if ($prevContig eq $contigID && $dir eq $prevDir) {
561                          # Here the new segment is in the same direction on the same contig. Insure the                          # Here the new segment is in the same direction on the same contig. Insure the
562                          # new segment's beginning is next to the old segment's end.                          # new segment's beginning is next to the old segment's end.
563                          if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||              if ($dir eq "-" && $beg + $len == $prevBeg) {
564                                  ($dir eq "+" && $beg == $prevBeg + $prevLen)) {                  # Here we're merging two backward blocks, so we keep the new begin point
565                                  # Here we need to merge two segments. Adjust the beginning and length values                  # and adjust the length.
566                                  # to include both segments.                  $len += $prevLen;
567                    # Pop the old segment off. The new one will replace it later.
568                    pop @retVal;
569                } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
570                    # Here we need to merge two forward blocks. Adjust the beginning and
571                    # length values to include both segments.
572                                  $beg = $prevBeg;                                  $beg = $prevBeg;
573                                  $len += $prevLen;                                  $len += $prevLen;
574                                  # Pop the old segment off. The new one will replace it later.                                  # Pop the old segment off. The new one will replace it later.
# Line 628  Line 577 
577                  }                  }
578                  # Remember this specifier for the adjacent-segment test the next time through.                  # Remember this specifier for the adjacent-segment test the next time through.
579                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
580            # Compute the initial base pair.
581            my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
582                  # Add the specifier to the list.                  # Add the specifier to the list.
583                  push @retVal, "${contigID}_$beg$dir$len";          push @retVal, "${contigID}_$start$dir$len";
584          }          }
585          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
586          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
587  }  }
588    
589  =head3 ParseLocation  =head3 ParseLocation
# Line 656  Line 607 
607  =back  =back
608    
609  =cut  =cut
610    #: Return Type @;
611  sub ParseLocation {  sub ParseLocation {
612          # Get the parameter.      # Get the parameter. Note that if we're called as an instance method, we ignore
613        # the first parameter.
614        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
615          my ($location) = @_;          my ($location) = @_;
616          # Parse it into segments.          # Parse it into segments.
617          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
618          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
619          # If the direction is an underscore, convert it to a + or -.          # If the direction is an underscore, convert it to a + or -.
620          if ($dir eq "_") {          if ($dir eq "_") {
# Line 677  Line 630 
630          return ($contigID, $start, $dir, $len);          return ($contigID, $start, $dir, $len);
631  }  }
632    
633    =head3 PointLocation
634    
635    C<< my $found = Sprout::PointLocation($location, $point); >>
636    
637    Return the offset into the specified location of the specified point on the contig. If
638    the specified point is before the location, a negative value will be returned. If it is
639    beyond the location, an undefined value will be returned. It is assumed that the offset
640    is for the location's contig. The location can either be new-style (using a C<+> or C<->
641    and a length) or old-style (using C<_> and start and end positions.
642    
643    =over 4
644    
645    =item location
646    
647    A location specifier (see L</FeatureLocation> for a description).
648    
649    =item point
650    
651    The offset into the contig of the point in which we're interested.
652    
653    =item RETURN
654    
655    Returns the offset inside the specified location of the specified point, a negative
656    number if the point is before the location, or an undefined value if the point is past
657    the location. If the length of the location is 0, this method will B<always> denote
658    that it is outside the location. The offset will always be relative to the left-most
659    position in the location.
660    
661    =back
662    
663    =cut
664    #: Return Type $;
665    sub PointLocation {
666        # Get the parameter. Note that if we're called as an instance method, we ignore
667        # the first parameter.
668        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
669        my ($location, $point) = @_;
670        # Parse out the location elements. Note that this works on both old-style and new-style
671        # locations.
672        my ($contigID, $start, $dir, $len) = ParseLocation($location);
673        # Declare the return variable.
674        my $retVal;
675        # Compute the offset. The computation is dependent on the direction of the location.
676        my $offset = (($dir == '+') ? $point - $start : $point - ($start - $len + 1));
677        # Return the offset if it's valid.
678        if ($offset < $len) {
679            $retVal = $offset;
680        }
681        # Return the offset found.
682        return $retVal;
683    }
684    
685  =head3 DNASeq  =head3 DNASeq
686    
687  C<< my $sequence = $sprout->DNASeq(\@locationList); >>  C<< my $sequence = $sprout->DNASeq(\@locationList); >>
# Line 685  Line 690 
690  should be of the form returned by L</featureLocation> when in a list context. In other words,  should be of the form returned by L</featureLocation> when in a list context. In other words,
691  each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.  each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.
692    
693    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
694    between positions 1401 and 1532, inclusive.
695    
696        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
697    
698  =over 4  =over 4
699    
700  =item locationList  =item locationList
701    
702  List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<end> (see  List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<len> or
703  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
704    
705  =item RETURN  =item RETURN
706    
# Line 699  Line 709 
709  =back  =back
710    
711  =cut  =cut
712    #: Return Type $;
713  sub DNASeq {  sub DNASeq {
714          # Get the parameters.          # Get the parameters.
715          my $self = shift @_;      my ($self, $locationList) = @_;
         my ($locationList) = @_;  
716          # Create the return string.          # Create the return string.
717          my $retVal = "";          my $retVal = "";
718          # Loop through the locations.          # Loop through the locations.
# Line 718  Line 727 
727                  # the start point is the ending. Note that in the latter case we must reverse the DNA string                  # the start point is the ending. Note that in the latter case we must reverse the DNA string
728                  # before putting it in the return value.                  # before putting it in the return value.
729                  my ($start, $stop);                  my ($start, $stop);
730            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
731                  if ($dir eq "+") {                  if ($dir eq "+") {
732                          $start = $beg;                          $start = $beg;
733                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
734                  } else {                  } else {
735                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
736                          $stop = $beg;                          $stop = $beg;
737                  }                  }
738            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
739                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
740                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
741                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 736  Line 747 
747                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
748                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
749                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
750                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
751                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
752                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
753                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
754                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
755                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
756                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
757                  }                  }
758                  # Add this location's data to the return string. Note that we may need to reverse it.                  # Add this location's data to the return string. Note that we may need to reverse it.
759                  if ($dir eq '+') {                  if ($dir eq '+') {
760                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
761                  } else {                  } else {
762                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
763                  }                  }
764          }          }
765          # Return the result.          # Return the result.
# Line 773  Line 785 
785  =back  =back
786    
787  =cut  =cut
788    #: Return Type @;
789  sub AllContigs {  sub AllContigs {
790          # Get the parameters.          # Get the parameters.
791          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
792          # Ask for the genome's Contigs.          # Ask for the genome's Contigs.
793          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],
794                                                                  'HasContig(to-link)');                                                                  'HasContig(to-link)');
# Line 785  Line 796 
796          return @retVal;          return @retVal;
797  }  }
798    
799  =head3 ContigLength  =head3 GenomeLength
800    
801  C<< my $length = $sprout->ContigLength($contigID); >>  C<< my $length = $sprout->GenomeLength($genomeID); >>
802    
803  Compute the length of a contig.  Return the length of the specified genome in base pairs.
804    
805  =over 4  =over 4
806    
807  =item contigID  =item genomeID
808    
809  ID of the contig whose length is desired.  ID of the genome whose base pair count is desired.
810    
811    =item RETURN
812    
813    Returns the number of base pairs in all the contigs of the specified
814    genome.
815    
816  =back  =back
817    
818  =cut  =cut
819    
820  sub ContigLength {  sub GenomeLength {
821          # Get the parameters.          # Get the parameters.
822          my $self = shift @_;      my ($self, $genomeID) = @_;
823          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.  
824          my $retVal = 0;          my $retVal = 0;
825          # Set it from the sequence data, if any.      # Get the genome's contig sequence lengths.
826          if ($sequence) {      my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
827                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);                         [$genomeID], 'IsMadeUpOf(len)');
828                  $retVal = $start + $len;      # Sum the lengths.
829          }      map { $retVal += $_ } @lens;
830          # Return the result.          # Return the result.
831          return $retVal;          return $retVal;
832  }  }
833    
834  =head3 GenesInRegion  =head3 FeatureCount
835    
836  C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>  C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
837    
838  List the features which overlap a specified region in a contig.  Return the number of features of the specified type in the specified genome.
839    
840  =over 4  =over 4
841    
842  =item contigID  =item genomeID
843    
844  ID of the contig containing the region of interest.  ID of the genome whose feature count is desired.
845    
846  =item start  =item type
847    
848  Offset of the first residue in the region of interest.  Type of feature to count (eg. C<peg>, C<rna>, etc.).
849    
850  =item stop  =item RETURN
851    
852  Offset of the last residue in the region of interest.  Returns the number of features of the specified type for the specified genome.
853    
854    =back
855    
856    =cut
857    
858    sub FeatureCount {
859        # Get the parameters.
860        my ($self, $genomeID, $type) = @_;
861        # Compute the count.
862        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
863                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
864                                    [$genomeID, $type]);
865        # Return the result.
866        return $retVal;
867    }
868    
869    =head3 GenomeAssignments
870    
871    C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
872    
873    Return a list of a genome's assigned features. The return hash will contain each
874    assigned feature of the genome mapped to the text of its most recent functional
875    assignment.
876    
877    =over 4
878    
879    =item genomeID
880    
881    ID of the genome whose functional assignments are desired.
882    
883  =item RETURN  =item RETURN
884    
885  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
886  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.  
887    
888  =back  =back
889    
890  =cut  =cut
891    
892  sub GenesInRegion {  sub GenomeAssignments {
893          # Get the parameters.          # Get the parameters.
894          my $self = shift @_;      my ($self, $genomeID) = @_;
895          my ($contigID, $start, $stop) = @_;      # Declare the return variable.
896          # Get the maximum segment length.      my $retVal = {};
897          my $maximumSegmentLength = $self->MaxSegment;      # Query the genome's features and annotations. We'll put the oldest annotations
898          # 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.
899          # duplicates easily.      my $query = $self->Get(['HasFeature', 'IsTargetOfAnnotation', 'Annotation'],
900          my %featuresFound = ();                             "HasFeature(from-link) = ? ORDER BY Annotation(time)",
901          # Prime the values we'll use for the returned beginning and end.                             [$genomeID]);
902          my ($min, $max) = ($self->ContigLength($contigID), 0);      # Loop through the annotations.
903          # Create a table of parameters for each query. Each query looks for features travelling in      while (my $data = $query->Fetch) {
904          # a particular direction. The query parameters include the contig ID, the feature direction,          # Get the feature ID and annotation text.
905          # the lowest possible start position, and the highest possible start position. This works          my ($fid, $annotation) = $data->Values(['HasFeature(to-link)',
906          # because each feature segment length must be no greater than the maximum segment length.                                                  'Annotation(annotation)']);
907            # Check to see if this is an assignment. Note that the user really
908            # doesn't matter to us, other than we use it to determine whether or
909            # not this is an assignment.
910            my ($user, $assignment) = _ParseAssignment('fig', $annotation);
911            if ($user) {
912                # Here it's an assignment. We put it in the return hash, overwriting
913                # any older assignment that might be present.
914                $retVal->{$fid} = $assignment;
915            }
916        }
917        # Return the result.
918        return $retVal;
919    }
920    
921    =head3 ContigLength
922    
923    C<< my $length = $sprout->ContigLength($contigID); >>
924    
925    Compute the length of a contig.
926    
927    =over 4
928    
929    =item contigID
930    
931    ID of the contig whose length is desired.
932    
933    =item RETURN
934    
935    Returns the number of positions in the contig.
936    
937    =back
938    
939    =cut
940    #: Return Type $;
941    sub ContigLength {
942        # Get the parameters.
943        my ($self, $contigID) = @_;
944        # Get the contig's last sequence.
945        my $query = $self->Get(['IsMadeUpOf'],
946            "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
947            [$contigID]);
948        my $sequence = $query->Fetch();
949        # Declare the return value.
950        my $retVal = 0;
951        # Set it from the sequence data, if any.
952        if ($sequence) {
953            my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
954            $retVal = $start + $len - 1;
955        }
956        # Return the result.
957        return $retVal;
958    }
959    
960    =head3 ClusterPEGs
961    
962    C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
963    
964    Cluster the PEGs in a list according to the cluster coding scheme of the specified
965    subsystem. In order for this to work properly, the subsystem object must have
966    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
967    This causes the cluster numbers to be pulled into the subsystem's color hash.
968    If a PEG is not found in the color hash, it will not appear in the output
969    sequence.
970    
971    =over 4
972    
973    =item sub
974    
975    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
976    method.
977    
978    =item pegs
979    
980    Reference to the list of PEGs to be clustered.
981    
982    =item RETURN
983    
984    Returns a list of the PEGs, grouped into smaller lists by cluster number.
985    
986    =back
987    
988    =cut
989    #: Return Type $@@;
990    sub ClusterPEGs {
991        # Get the parameters.
992        my ($self, $sub, $pegs) = @_;
993        # Declare the return variable.
994        my $retVal = [];
995        # Loop through the PEGs, creating arrays for each cluster.
996        for my $pegID (@{$pegs}) {
997            my $clusterNumber = $sub->get_cluster_number($pegID);
998            # Only proceed if the PEG is in a cluster.
999            if ($clusterNumber >= 0) {
1000                # Push this PEG onto the sub-list for the specified cluster number.
1001                push @{$retVal->[$clusterNumber]}, $pegID;
1002            }
1003        }
1004        # Return the result.
1005        return $retVal;
1006    }
1007    
1008    =head3 GenesInRegion
1009    
1010    C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>
1011    
1012    List the features which overlap a specified region in a contig.
1013    
1014    =over 4
1015    
1016    =item contigID
1017    
1018    ID of the contig containing the region of interest.
1019    
1020    =item start
1021    
1022    Offset of the first residue in the region of interest.
1023    
1024    =item stop
1025    
1026    Offset of the last residue in the region of interest.
1027    
1028    =item RETURN
1029    
1030    Returns a three-element list. The first element is a list of feature IDs for the features that
1031    overlap the region of interest. The second and third elements are the minimum and maximum
1032    locations of the features provided on the specified contig. These may extend outside
1033    the start and stop values. The first element (that is, the list of features) is sorted
1034    roughly by location.
1035    
1036    =back
1037    
1038    =cut
1039    #: Return Type @@;
1040    sub GenesInRegion {
1041        # Get the parameters.
1042        my ($self, $contigID, $start, $stop) = @_;
1043        # Get the maximum segment length.
1044        my $maximumSegmentLength = $self->MaxSegment;
1045        # Create a hash to receive the feature list. We use a hash so that we can eliminate
1046        # duplicates easily. The hash key will be the feature ID. The value will be a two-element
1047        # containing the minimum and maximum offsets. We will use the offsets to sort the results
1048        # when we're building the result set.
1049        my %featuresFound = ();
1050        # Prime the values we'll use for the returned beginning and end.
1051        my @initialMinMax = ($self->ContigLength($contigID), 0);
1052        my ($min, $max) = @initialMinMax;
1053        # Create a table of parameters for each query. Each query looks for features travelling in
1054        # a particular direction. The query parameters include the contig ID, the feature direction,
1055        # the lowest possible start position, and the highest possible start position. This works
1056        # because each feature segment length must be no greater than the maximum segment length.
1057          my %queryParms = (forward => [$contigID, '+', $start - $maximumSegmentLength + 1, $stop],          my %queryParms = (forward => [$contigID, '+', $start - $maximumSegmentLength + 1, $stop],
1058                                            reverse => [$contigID, '-', $start, $stop + $maximumSegmentLength - 1]);                                            reverse => [$contigID, '-', $start, $stop + $maximumSegmentLength - 1]);
1059          # Loop through the query parameters.          # Loop through the query parameters.
# Line 892  Line 1079 
1079                                          $found = 1;                                          $found = 1;
1080                                  }                                  }
1081                          } elsif ($dir eq '-') {                          } elsif ($dir eq '-') {
1082                                  $end = $beg - $len;                  # Note we switch things around so that the beginning is to the left of the
1083                                  if ($end <= $stop) {                  # ending.
1084                    ($beg, $end) = ($beg - $len, $beg);
1085                    if ($beg <= $stop) {
1086                                          # Denote we found a useful feature.                                          # Denote we found a useful feature.
1087                                          $found = 1;                                          $found = 1;
1088                                  }                                  }
1089                          }                          }
1090                          if ($found) {                          if ($found) {
1091                                  # 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,
1092                                  $featuresFound{$featureID} = 1;                  # get the current entry for the specified feature.
1093                                  if ($beg < $min) { $min = $beg; }                  my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :
1094                                  if ($end < $min) { $min = $end; }                                       @initialMinMax);
1095                                  if ($beg > $max) { $max = $beg; }                  # Merge the current segment's begin and end into the feature begin and end and the
1096                                  if ($end > $max) { $max = $end; }                  # global min and max.
1097                    if ($beg < $loc1) {
1098                        $loc1 = $beg;
1099                        $min = $beg if $beg < $min;
1100                    }
1101                    if ($end > $loc2) {
1102                        $loc2 = $end;
1103                        $max = $end if $end > $max;
1104                    }
1105                    # Store the entry back into the hash table.
1106                    $featuresFound{$featureID} = [$loc1, $loc2];
1107                          }                          }
1108                  }                  }
1109          }          }
1110          # 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
1111          my @list = (sort (keys %featuresFound));      # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1112        # but the result of the sort will be the same.)
1113        my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;
1114        # Now we sort by midpoint and yank out the feature IDs.
1115        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1116          # Return it along with the min and max.          # Return it along with the min and max.
1117          return (\@list, $min, $max);      return (\@retVal, $min, $max);
1118  }  }
1119    
1120  =head3 FType  =head3 FType
# Line 934  Line 1137 
1137  =back  =back
1138    
1139  =cut  =cut
1140    #: Return Type $;
1141  sub FType {  sub FType {
1142          # Get the parameters.          # Get the parameters.
1143          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1144          # Get the specified feature's type.          # Get the specified feature's type.
1145          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
1146          # Return the result.          # Return the result.
# Line 947  Line 1149 
1149    
1150  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1151    
1152  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1153    
1154  Return the annotations of a feature.  Return the annotations of a feature.
1155    
# Line 957  Line 1159 
1159    
1160  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1161    
1162    =item rawFlag
1163    
1164    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1165    will be returned in human-readable form.
1166    
1167  =item RETURN  =item RETURN
1168    
1169  Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.  Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.
# Line 972  Line 1179 
1179  =back  =back
1180    
1181  =cut  =cut
1182    #: Return Type @%;
1183  sub FeatureAnnotations {  sub FeatureAnnotations {
1184          # Get the parameters.          # Get the parameters.
1185          my $self = shift @_;      my ($self, $featureID, $rawFlag) = @_;
         my ($featureID) = @_;  
1186          # Create a query to get the feature's annotations and the associated users.          # Create a query to get the feature's annotations and the associated users.
1187          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1188                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 989  Line 1195 
1195                          $annotation->Values(['IsTargetOfAnnotation(from-link)',                          $annotation->Values(['IsTargetOfAnnotation(from-link)',
1196                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1197                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1198            # Convert the time, if necessary.
1199            if (! $rawFlag) {
1200                $timeStamp = FriendlyTimestamp($timeStamp);
1201            }
1202                  # Assemble them into a hash.                  # Assemble them into a hash.
1203                  my $annotationHash = { featureID => $featureID, timeStamp => $timeStamp,          my $annotationHash = { featureID => $featureID,
1204                                   timeStamp => $timeStamp,
1205                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1206                  # Add it to the return list.                  # Add it to the return list.
1207                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1004  Line 1215 
1215  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>
1216    
1217  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
1218  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,
1219  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
1220  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,
1221  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.
1222  features only have a small number of annotations.  Finally, if a single user has multiple functional assignments, we will only keep the most
1223    recent one.
1224    
1225  =over 4  =over 4
1226    
# Line 1016  Line 1228 
1228    
1229  ID of the feature whose functional assignments are desired.  ID of the feature whose functional assignments are desired.
1230    
1231    =item RETURN
1232    
1233    Returns a hash mapping the user IDs to functional assignment IDs.
1234    
1235  =back  =back
1236    
1237  =cut  =cut
1238    #: Return Type %;
1239  sub AllFunctionsOf {  sub AllFunctionsOf {
1240          # Get the parameters.          # Get the parameters.
1241          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1242          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1243          my @query = $self->GetFlat(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1244                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1245                                                          [$featureID], 'Annotation(annotation)');                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1246                                               'MadeAnnotation(from-link)']);
1247          # Declare the return hash.          # Declare the return hash.
1248          my %retVal;          my %retVal;
1249        # Now we sort the assignments by timestamp in reverse.
1250        my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1251          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1252          for my $text (@query) {      for my $annotation (@sortedQuery) {
1253            # Get the annotation fields.
1254            my ($timeStamp, $text, $user) = @{$annotation};
1255                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1256                  my ($user, $function) = ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1257                  if ($user) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1258                          # Here it is, so stuff it in the return hash.              # Here it is a functional assignment and there has been no
1259                          $retVal{$function} = $user;              # previous assignment for this user, so we stuff it in the
1260                # return hash.
1261                $retVal{$actualUser} = $function;
1262                  }                  }
1263          }          }
1264          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1047  Line 1269 
1269    
1270  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>
1271    
1272  Return the most recently-determined functional assignment of a particular feature. A functional  Return the most recently-determined functional assignment of a particular feature.
1273  assignment is a type of annotation. It has the format "XXXX\nset XXXX function to\nYYYYY". In this  
1274  instance, XXXX is the user ID and YYYYY is the functional assignment text. Its worth noting that  The functional assignment is handled differently depending on the type of feature. If
1275  we cannot filter on the content of the annotation itself because it's a text field; however, this  the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1276  is not a big problem because most features only have a small number of annotations.  assignment is a type of annotation. The format of an assignment is described in
1277    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1278    annotation itself because it's a text field; however, this is not a big problem because
1279    most features only have a small number of annotations.
1280    
1281    Each user has an associated list of trusted users. The assignment returned will be the most
1282    recent one by at least one of the trusted users. If no trusted user list is available, then
1283    the specified user and FIG are considered trusted. If the user ID is omitted, only FIG
1284    is trusted.
1285    
1286    If the feature is B<not> identified by a FIG ID, then the functional assignment
1287    information is taken from the B<ExternalAliasFunc> table. If the table does
1288    not contain an entry for the feature, an undefined value is returned.
1289    
1290  =over 4  =over 4
1291    
# Line 1061  Line 1295 
1295    
1296  =item userID (optional)  =item userID (optional)
1297    
1298  ID of the user whose function determination is desired. If omitted, C<FIG> is assumed.  ID of the user whose function determination is desired. If omitted, only the latest
1299    C<FIG> assignment will be returned.
1300    
1301  =item RETURN  =item RETURN
1302    
# Line 1070  Line 1305 
1305  =back  =back
1306    
1307  =cut  =cut
1308    #: Return Type $;
1309  sub FunctionOf {  sub FunctionOf {
1310          # Get the parameters.          # Get the parameters.
1311          my $self = shift @_;      my ($self, $featureID, $userID) = @_;
1312          my ($featureID, $userID) = @_;      # Declare the return value.
         if (!$userID) { $userID = 'FIG'; }  
         # Build a query for all of the feature's annotation, sorted by date.  
         my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],  
                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);  
         # Declare the return value. We'll set this to the most recent annotation for the  
         # specified user.  
1313          my $retVal;          my $retVal;
1314        # Determine the ID type.
1315        if ($featureID =~ m/^fig\|/) {
1316            # Here we have a FIG feature ID. We must build the list of trusted
1317            # users.
1318            my %trusteeTable = ();
1319            # Check the user ID.
1320            if (!$userID) {
1321                # No user ID, so only FIG is trusted.
1322                $trusteeTable{FIG} = 1;
1323            } else {
1324                # Add this user's ID.
1325                $trusteeTable{$userID} = 1;
1326                # Look for the trusted users in the database.
1327                my @trustees = $self->GetFlat(['IsTrustedBy'], 'IsTrustedBy(from-link) = ?', [$userID], 'IsTrustedBy(to-link)');
1328                if (! @trustees) {
1329                    # None were found, so build a default list.
1330                    $trusteeTable{FIG} = 1;
1331                } else {
1332                    # Otherwise, put all the trustees in.
1333                    for my $trustee (@trustees) {
1334                        $trusteeTable{$trustee} = 1;
1335                    }
1336                }
1337            }
1338            # Build a query for all of the feature's annotations, sorted by date.
1339            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1340                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1341                                   [$featureID]);
1342          my $timeSelected = 0;          my $timeSelected = 0;
1343          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1344          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1345                  # Get the annotation text.                  # Get the annotation text.
1346                  my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);              my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1347                  # Check to see if this is a functional assignment for the desired user.                                                       'Annotation(time)', 'MadeAnnotation(from-link)']);
1348                  my ($user, $type, $function) = split(/\n/, $text);              # Check to see if this is a functional assignment for a trusted user.
1349                  if ($type =~ m/^set $userID function to$/i) {              my ($actualUser, $function) = _ParseAssignment($user, $text);
1350                          # Here it is, so we check the time and save the assignment value.              Trace("Assignment user is $actualUser, text is $function.") if T(4);
1351                          if ($time > $timeSelected) {              if ($actualUser) {
1352                    # Here it is a functional assignment. Check the time and the user
1353                    # name. The time must be recent and the user must be trusted.
1354                    if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1355                                  $retVal = $function;                                  $retVal = $function;
1356                                  $timeSelected = $time;                                  $timeSelected = $time;
1357                          }                          }
1358                  }                  }
1359          }          }
1360        } else {
1361            # Here we have a non-FIG feature ID. In this case the user ID does not
1362            # matter. We simply get the information from the External Alias Function
1363            # table.
1364            ($retVal) = $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']);
1365        }
1366          # Return the assignment found.          # Return the assignment found.
1367          return $retVal;          return $retVal;
1368  }  }
1369    
1370    =head3 FunctionsOf
1371    
1372    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1373    
1374    Return the functional assignments of a particular feature.
1375    
1376    The functional assignment is handled differently depending on the type of feature. If
1377    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1378    assignment is a type of annotation. The format of an assignment is described in
1379    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1380    annotation itself because it's a text field; however, this is not a big problem because
1381    most features only have a small number of annotations.
1382    
1383    If the feature is B<not> identified by a FIG ID, then the functional assignment
1384    information is taken from the B<ExternalAliasFunc> table. If the table does
1385    not contain an entry for the feature, an empty list is returned.
1386    
1387    =over 4
1388    
1389    =item featureID
1390    
1391    ID of the feature whose functional assignments are desired.
1392    
1393    =item RETURN
1394    
1395    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1396    that user.
1397    
1398    =back
1399    
1400    =cut
1401    #: Return Type @@;
1402    sub FunctionsOf {
1403        # Get the parameters.
1404        my ($self, $featureID) = @_;
1405        # Declare the return value.
1406        my @retVal = ();
1407        # Determine the ID type.
1408        if ($featureID =~ m/^fig\|/) {
1409            # Here we have a FIG feature ID. We must build the list of trusted
1410            # users.
1411            my %trusteeTable = ();
1412            # Build a query for all of the feature's annotations, sorted by date.
1413            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1414                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1415                                   [$featureID]);
1416            my $timeSelected = 0;
1417            # Loop until we run out of annotations.
1418            while (my $annotation = $query->Fetch()) {
1419                # Get the annotation text.
1420                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1421                                                                'Annotation(time)',
1422                                                                'MadeAnnotation(user)']);
1423                # Check to see if this is a functional assignment for a trusted user.
1424                my ($actualUser, $function) = _ParseAssignment($user, $text);
1425                if ($actualUser) {
1426                    # Here it is a functional assignment.
1427                    push @retVal, [$actualUser, $function];
1428                }
1429            }
1430        } else {
1431            # Here we have a non-FIG feature ID. In this case the user ID does not
1432            # matter. We simply get the information from the External Alias Function
1433            # table.
1434            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1435                                                     ['ExternalAliasFunc(func)']);
1436            push @retVal, map { ['master', $_] } @assignments;
1437        }
1438        # Return the assignments found.
1439        return @retVal;
1440    }
1441    
1442  =head3 BBHList  =head3 BBHList
1443    
1444  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1120  Line 1458 
1458    
1459  =item RETURN  =item RETURN
1460    
1461  Returns a reference to a hash that maps the IDs of the incoming features to the IDs of  Returns a reference to a hash that maps the IDs of the incoming features to the best hits
1462  their best hits.  on the target genome.
1463    
1464  =back  =back
1465    
1466  =cut  =cut
1467    #: Return Type %;
1468  sub BBHList {  sub BBHList {
1469          # Get the parameters.          # Get the parameters.
1470          my $self = shift @_;      my ($self, $genomeID, $featureList) = @_;
         my ($genomeID, $featureList) = @_;  
1471          # Create the return structure.          # Create the return structure.
1472          my %retVal = ();          my %retVal = ();
1473          # Loop through the incoming features.          # Loop through the incoming features.
# Line 1139  Line 1476 
1476                  my $query = $self->Get(['IsBidirectionalBestHitOf'],                  my $query = $self->Get(['IsBidirectionalBestHitOf'],
1477                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",
1478                                                             [$featureID, $genomeID]);                                                             [$featureID, $genomeID]);
1479                  # Look for the best hit.          # Peel off the BBHs found.
1480                  my $bbh = $query->Fetch;          my @found = ();
1481                  if ($bbh) {          while (my $bbh = $query->Fetch) {
1482                          my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');
                         $retVal{$featureID} = $targetFeature;  
1483                  }                  }
1484            $retVal{$featureID} = \@found;
1485          }          }
1486          # Return the mapping.          # Return the mapping.
1487          return \%retVal;          return \%retVal;
1488  }  }
1489    
1490    =head3 SimList
1491    
1492    C<< my %similarities = $sprout->SimList($featureID, $count); >>
1493    
1494    Return a list of the similarities to the specified feature.
1495    
1496    Sprout does not support real similarities, so this method just returns the bidirectional
1497    best hits.
1498    
1499    =over 4
1500    
1501    =item featureID
1502    
1503    ID of the feature whose similarities are desired.
1504    
1505    =item count
1506    
1507    Maximum number of similar features to be returned, or C<0> to return them all.
1508    
1509    =back
1510    
1511    =cut
1512    #: Return Type %;
1513    sub SimList {
1514        # Get the parameters.
1515        my ($self, $featureID, $count) = @_;
1516        # Ask for the best hits.
1517        my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],
1518                                  "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",
1519                                  [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],
1520                                  $count);
1521        # Create the return value.
1522        my %retVal = ();
1523        for my $tuple (@lists) {
1524            $retVal{$tuple->[0]} = $tuple->[1];
1525        }
1526        # Return the result.
1527        return %retVal;
1528    }
1529    
1530    
1531    
1532    =head3 IsComplete
1533    
1534    C<< my $flag = $sprout->IsComplete($genomeID); >>
1535    
1536    Return TRUE if the specified genome is complete, else FALSE.
1537    
1538    =over 4
1539    
1540    =item genomeID
1541    
1542    ID of the genome whose completeness status is desired.
1543    
1544    =item RETURN
1545    
1546    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1547    not found.
1548    
1549    =back
1550    
1551    =cut
1552    #: Return Type $;
1553    sub IsComplete {
1554        # Get the parameters.
1555        my ($self, $genomeID) = @_;
1556        # Declare the return variable.
1557        my $retVal;
1558        # Get the genome's data.
1559        my $genomeData = $self->GetEntity('Genome', $genomeID);
1560        if ($genomeData) {
1561            # The genome exists, so get the completeness flag.
1562            ($retVal) = $genomeData->Value('Genome(complete)');
1563        }
1564        # Return the result.
1565        return $retVal;
1566    }
1567    
1568  =head3 FeatureAliases  =head3 FeatureAliases
1569    
1570  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
# Line 1170  Line 1585 
1585  =back  =back
1586    
1587  =cut  =cut
1588    #: Return Type @;
1589  sub FeatureAliases {  sub FeatureAliases {
1590          # Get the parameters.          # Get the parameters.
1591          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1592          # Get the desired feature's aliases          # Get the desired feature's aliases
1593          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);
1594          # Return the result.          # Return the result.
# Line 1185  Line 1599 
1599    
1600  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1601    
1602  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1603    
1604  =over 4  =over 4
1605    
1606  =item featureID  =item featureID
1607    
1608  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1609    
1610  =item RETURN  =item RETURN
1611    
1612  Returns the ID of the genome for the specified feature. If the feature is not found, returns  Returns the ID of the genome for the specified feature or contig. If the feature or contig is not
1613  an undefined value.  found, returns an undefined value.
1614    
1615  =back  =back
1616    
1617  =cut  =cut
1618    #: Return Type $;
1619  sub GenomeOf {  sub GenomeOf {
1620          # Get the parameters.          # Get the parameters.
1621          my $self = shift @_;      my ($self, $featureID) = @_;
1622          my ($featureID) = @_;      # Create a query to find the genome associated with the incoming ID.
1623          # Create a query to find the genome associated with the feature.      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1624          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);                             [$featureID, $featureID]);
1625          # Declare the return value.          # Declare the return value.
1626          my $retVal;          my $retVal;
1627          # Get the genome ID.          # Get the genome ID.
# Line 1238  Line 1652 
1652  =back  =back
1653    
1654  =cut  =cut
1655    #: Return Type %;
1656  sub CoupledFeatures {  sub CoupledFeatures {
1657          # Get the parameters.          # Get the parameters.
1658          my $self = shift @_;      my ($self, $featureID) = @_;
1659          my ($featureID) = @_;      # Create a query to retrieve the functionally-coupled features.
1660          # Create a query to retrieve the functionally-coupled features. Note that we depend on the      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1661          # fact that the functional coupling is physically paired. If (A,B) is in the database, then                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);
         # (B,A) will also be found.  
         my $query = $self->Get(['IsClusteredOnChromosomeWith'],  
                                                    "IsClusteredOnChromosomeWith(from-link) = ?", [$featureID]);  
1662          # 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.
1663          my $found = 0;          my $found = 0;
1664          # Create the return hash.          # Create the return hash.
1665          my %retVal = ();          my %retVal = ();
1666          # Retrieve the relationship records and store them in the hash.          # Retrieve the relationship records and store them in the hash.
1667          while (my $clustering = $query->Fetch()) {          while (my $clustering = $query->Fetch()) {
1668                  my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',          # Get the ID and score of the coupling.
1669                                                                      'IsClusteredOnChromosomeWith(score)']);          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1670                                                            'Coupling(score)']);
1671            # Get the other feature that participates in the coupling.
1672            my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],
1673                                               "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",
1674                                               [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');
1675            # Attach the other feature's score to its ID.
1676                  $retVal{$otherFeatureID} = $score;                  $retVal{$otherFeatureID} = $score;
1677                  $found = 1;                  $found = 1;
1678          }          }
# Line 1268  Line 1685 
1685          return %retVal;          return %retVal;
1686  }  }
1687    
1688  =head3 GetEntityTypes  =head3 CouplingEvidence
1689    
1690  C<< my @entityList = $sprout->GetEntityTypes(); >>  C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1691    
1692  Return the list of supported entity types.  Return the evidence for a functional coupling.
1693    
1694    A pair of features is considered evidence of a coupling between two other
1695    features if they occur close together on a contig and both are similar to
1696    the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1697    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1698    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1699    similar to B<A2>.
1700    
1701    The score of a coupling is determined by the number of pieces of evidence
1702    that are considered I<representative>. If several evidence items belong to
1703    a group of genomes that are close to each other, only one of those items
1704    is considered representative. The other evidence items are presumed to be
1705    there because of the relationship between the genomes rather than because
1706    the two proteins generated by the features have a related functionality.
1707    
1708    Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1709    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1710    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1711    and FALSE otherwise.
1712    
1713    =over 4
1714    
1715    =item peg1
1716    
1717    ID of the feature of interest.
1718    
1719    =item peg2
1720    
1721    ID of a feature functionally coupled to the feature of interest.
1722    
1723    =item RETURN
1724    
1725    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1726    of interest, a feature similar to the functionally coupled feature, and a flag
1727    that is TRUE for a representative piece of evidence and FALSE otherwise.
1728    
1729    =back
1730    
1731  =cut  =cut
1732    #: Return Type @@;
1733    sub CouplingEvidence {
1734        # Get the parameters.
1735        my ($self, $peg1, $peg2) = @_;
1736        # Declare the return variable.
1737        my @retVal = ();
1738        # Our first task is to find out the nature of the coupling: whether or not
1739        # it exists, its score, and whether the features are stored in the same
1740        # order as the ones coming in.
1741        my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1742        # Only proceed if a coupling exists.
1743        if ($couplingID) {
1744            # Determine the ordering to place on the evidence items. If we're
1745            # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1746            # we want feature 1 before feature 2 (normal).
1747            Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);
1748            my $ordering = ($inverted ? "DESC" : "");
1749            # Get the coupling evidence.
1750            my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
1751                                              "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",
1752                                              [$couplingID],
1753                                              ['PCH(used)', 'UsesAsEvidence(to-link)']);
1754            # Loop through the evidence items. Each piece of evidence is represented by two
1755            # positions in the evidence list, one for each feature on the other side of the
1756            # evidence link. If at some point we want to generalize to couplings with
1757            # more than two positions, this section of code will need to be re-done.
1758            while (@evidenceList > 0) {
1759                my $peg1Data = shift @evidenceList;
1760                my $peg2Data = shift @evidenceList;
1761                Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1762                push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1763            }
1764            Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1765        }
1766        # Return the result.
1767        return @retVal;
1768    }
1769    
1770  sub GetEntityTypes {  =head3 GetCoupling
1771    
1772    C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>
1773    
1774    Return the coupling (if any) for the specified pair of PEGs. If a coupling
1775    exists, we return the coupling ID along with an indicator of whether the
1776    coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.
1777    In the second case, we say the coupling is I<inverted>. The importance of an
1778    inverted coupling is that the PEGs in the evidence will appear in reverse order.
1779    
1780    =over 4
1781    
1782    =item peg1
1783    
1784    ID of the feature of interest.
1785    
1786    =item peg2
1787    
1788    ID of the potentially coupled feature.
1789    
1790    =item RETURN
1791    
1792    Returns a three-element list. The first element contains the database ID of
1793    the coupling. The second element is FALSE if the coupling is stored in the
1794    database in the caller specified order and TRUE if it is stored in the
1795    inverted order. The third element is the coupling's score. If the coupling
1796    does not exist, all three list elements will be C<undef>.
1797    
1798    =back
1799    
1800    =cut
1801    #: Return Type $%@;
1802    sub GetCoupling {
1803          # Get the parameters.          # Get the parameters.
1804          my $self = shift @_;      my ($self, $peg1, $peg2) = @_;
1805          # Get the underlying database object.      # Declare the return values. We'll start with the coupling ID and undefine the
1806          my $erdb = $self->{_erdb};      # flag and score until we have more information.
1807          # Get its entity type list.      my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);
1808          my @retVal = $erdb->GetEntityTypes();      # Find the coupling data.
1809        my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1810                                     "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1811                                     [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1812        # Check to see if we found anything.
1813        if (!@pegs) {
1814            Trace("No coupling found.") if T(Coupling => 4);
1815            # No coupling, so undefine the return value.
1816            $retVal = undef;
1817        } else {
1818            # We have a coupling! Get the score and check for inversion.
1819            $score = $pegs[0]->[1];
1820            my $firstFound = $pegs[0]->[0];
1821            $inverted = ($firstFound ne $peg1);
1822            Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1823        }
1824        # Return the result.
1825        return ($retVal, $inverted, $score);
1826    }
1827    
1828    =head3 CouplingID
1829    
1830    C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>
1831    
1832    Return the coupling ID for a pair of feature IDs.
1833    
1834    The coupling ID is currently computed by joining the feature IDs in
1835    sorted order with a space. Client modules (that is, modules which
1836    use Sprout) should not, however, count on this always being the
1837    case. This method provides a way for abstracting the concept of a
1838    coupling ID. All that we know for sure about it is that it can be
1839    generated easily from the feature IDs and the order of the IDs
1840    in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>
1841    will have the same value as C<CouplingID("b1", "a1")>.
1842    
1843    =over 4
1844    
1845    =item peg1
1846    
1847    First feature of interest.
1848    
1849    =item peg2
1850    
1851    Second feature of interest.
1852    
1853    =item RETURN
1854    
1855    Returns the ID that would be used to represent a functional coupling of
1856    the two specified PEGs.
1857    
1858    =back
1859    
1860    =cut
1861    #: Return Type $;
1862    sub CouplingID {
1863        return join " ", sort @_;
1864  }  }
1865    
1866  =head3 ReadFasta  =head3 ReadFasta
# Line 1310  Line 1888 
1888  =back  =back
1889    
1890  =cut  =cut
1891    #: Return Type %;
1892  sub ReadFasta {  sub ReadFasta {
1893          # Get the parameters.          # Get the parameters.
1894          my ($fileName, $prefix) = @_;          my ($fileName, $prefix) = @_;
# Line 1329  Line 1907 
1907                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1908                          # 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.
1909                          if ($id) {                          if ($id) {
1910                                  $retVal{$id} = $sequence;                  $retVal{$id} = lc $sequence;
1911                          }                          }
1912                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
1913                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
1914                  } else {                  } else {
1915                          # 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.
1916                          # First, we get the actual data out.              # First, we get the actual data out. Note that we normalize to lower
1917                # case.
1918                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
1919                          $sequence .= $1;                          $sequence .= $1;
1920                  }                  }
1921          }          }
1922          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
1923          if ($sequence) {          if ($sequence) {
1924                  $retVal {$id} = $sequence;          $retVal{$id} = lc $sequence;
1925          }          }
1926        # Close the file.
1927        close FASTAFILE;
1928          # Return the hash constructed from the file.          # Return the hash constructed from the file.
1929          return %retVal;          return %retVal;
1930  }  }
# Line 1354  Line 1935 
1935    
1936  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
1937  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
1938  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,
1939    it will not be changed; otherwise, it will be converted. This method can also be used to
1940    perform the reverse task-- insuring that all the locations are in the old format.
1941    
1942  =over 4  =over 4
1943    
# Line 1378  Line 1961 
1961  =back  =back
1962    
1963  =cut  =cut
1964    #: Return Type @;
1965  sub FormatLocations {  sub FormatLocations {
1966          # Get the parameters.          # Get the parameters.
1967          my $self = shift @_;      my ($self, $prefix, $locations, $oldFormat) = @_;
         my ($prefix, $locations, $oldFormat) = @_;  
1968          # Create the return list.          # Create the return list.
1969          my @retVal = ();          my @retVal = ();
1970          # Check to see if any locations were passed in.          # Check to see if any locations were passed in.
1971          if ($locations eq '') {          if ($locations eq '') {
1972              confess "No locations specified.";          Confess("No locations specified.");
1973          } else {          } else {
1974                  # Loop through the locations, converting them to the new format.                  # Loop through the locations, converting them to the new format.
1975                  for my $location (@{$locations}) {                  for my $location (@{$locations}) {
# Line 1422  Line 2004 
2004    
2005  sub DumpData {  sub DumpData {
2006          # Get the parameters.          # Get the parameters.
2007          my $self = shift @_;      my ($self) = @_;
2008          # Get the data directory name.          # Get the data directory name.
2009          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
2010          # Dump the relations.          # Dump the relations.
2011          $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2012  }  }
2013    
2014  =head3 XMLFileName  =head3 XMLFileName
# Line 1436  Line 2018 
2018  Return the name of this database's XML definition file.  Return the name of this database's XML definition file.
2019    
2020  =cut  =cut
2021    #: Return Type $;
2022  sub XMLFileName {  sub XMLFileName {
2023          my $self = shift @_;      my ($self) = @_;
2024          return $self->{_xmlName};          return $self->{_xmlName};
2025  }  }
2026    
# Line 1458  Line 2040 
2040  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
2041  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>.
2042    
2043  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'}); >>
2044    
2045  =over 4  =over 4
2046    
# Line 1473  Line 2055 
2055  =back  =back
2056    
2057  =cut  =cut
2058    #: Return Type ;
2059  sub Insert {  sub Insert {
2060          # Get the parameters.          # Get the parameters.
2061          my $self = shift @_;      my ($self, $objectType, $fieldHash) = @_;
         my ($objectType, $fieldHash) = @_;  
2062          # Call the underlying method.          # Call the underlying method.
2063          $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2064  }  }
2065    
2066  =head3 Annotate  =head3 Annotate
# Line 1515  Line 2096 
2096  =back  =back
2097    
2098  =cut  =cut
2099    #: Return Type $;
2100  sub Annotate {  sub Annotate {
2101          # Get the parameters.          # Get the parameters.
2102          my $self = shift @_;      my ($self, $fid, $timestamp, $user, $text) = @_;
         my ($fid, $timestamp, $user, $text) = @_;  
2103          # Create the annotation ID.          # Create the annotation ID.
2104          my $aid = "$fid:$timestamp";          my $aid = "$fid:$timestamp";
2105          # Insert the Annotation object.          # Insert the Annotation object.
# Line 1539  Line 2119 
2119    
2120  =head3 AssignFunction  =head3 AssignFunction
2121    
2122  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function); >>  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>
2123    
2124  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
2125  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.  
2126    
2127  =over 4  =over 4
2128    
# Line 1553  Line 2132 
2132    
2133  =item user  =item user
2134    
2135  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>.
2136    
2137  =item function  =item function
2138    
2139  Text of the function being assigned.  Text of the function being assigned.
2140    
2141    =item assigningUser (optional)
2142    
2143    Name of the individual user making the assignment. If omitted, defaults to the user group.
2144    
2145  =item RETURN  =item RETURN
2146    
2147  Returns 1 if successful, 0 if an error occurred.  Returns 1 if successful, 0 if an error occurred.
# Line 1566  Line 2149 
2149  =back  =back
2150    
2151  =cut  =cut
2152    #: Return Type $;
2153  sub AssignFunction {  sub AssignFunction {
2154          # Get the parameters.          # Get the parameters.
2155          my $self = shift @_;      my ($self, $featureID, $user, $function, $assigningUser) = @_;
2156          my ($featureID, $user, $function) = @_;      # Default the assigning user.
2157        if (! $assigningUser) {
2158            $assigningUser = $user;
2159        }
2160          # Create an annotation string from the parameters.          # Create an annotation string from the parameters.
2161          my $annotationText = "$user\nset $user function to\n$function";      my $annotationText = "$assigningUser\nset $user function to\n$function";
2162          # Get the current time.          # Get the current time.
2163          my $now = time;          my $now = time;
2164          # Declare the return variable.          # Declare the return variable.
# Line 1614  Line 2200 
2200  =back  =back
2201    
2202  =cut  =cut
2203    #: Return Type @;
2204  sub FeaturesByAlias {  sub FeaturesByAlias {
2205          # Get the parameters.          # Get the parameters.
2206          my $self = shift @_;      my ($self, $alias) = @_;
         my ($alias) = @_;  
2207          # Declare the return variable.          # Declare the return variable.
2208          my @retVal = ();          my @retVal = ();
2209          # Parse the alias.          # Parse the alias.
# Line 1634  Line 2219 
2219          return @retVal;          return @retVal;
2220  }  }
2221    
 =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  
   
 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;  
 }  
   
2222  =head3 FeatureTranslation  =head3 FeatureTranslation
2223    
2224  C<< my $translation = $sprout->FeatureTranslation($featureID); >>  C<< my $translation = $sprout->FeatureTranslation($featureID); >>
# Line 1688  Line 2238 
2238  =back  =back
2239    
2240  =cut  =cut
2241    #: Return Type $;
2242  sub FeatureTranslation {  sub FeatureTranslation {
2243          # Get the parameters.          # Get the parameters.
2244          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2245          # Get the specified feature's translation.          # Get the specified feature's translation.
2246          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
2247          return $retVal;          return $retVal;
# Line 1721  Line 2270 
2270  =back  =back
2271    
2272  =cut  =cut
2273    #: Return Type @;
2274  sub Taxonomy {  sub Taxonomy {
2275          # Get the parameters.          # Get the parameters.
2276          my $self = shift @_;      my ($self, $genome) = @_;
         my ($genome) = @_;  
2277          # Find the specified genome's taxonomy string.          # Find the specified genome's taxonomy string.
2278          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);
2279          # Declare the return variable.          # Declare the return variable.
# Line 1765  Line 2313 
2313  =back  =back
2314    
2315  =cut  =cut
2316    #: Return Type $;
2317  sub CrudeDistance {  sub CrudeDistance {
2318          # Get the parameters.          # Get the parameters.
2319          my $self = shift @_;      my ($self, $genome1, $genome2) = @_;
         my ($genome1, $genome2) = @_;  
2320          # Insure that the distance is commutative by sorting the genome IDs.          # Insure that the distance is commutative by sorting the genome IDs.
2321          my ($genomeA, $genomeB);          my ($genomeA, $genomeB);
2322          if ($genome2 < $genome2) {          if ($genome2 < $genome2) {
# Line 1813  Line 2360 
2360  =back  =back
2361    
2362  =cut  =cut
2363    #: Return Type $;
2364  sub RoleName {  sub RoleName {
2365          # Get the parameters.          # Get the parameters.
2366          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2367          # Get the specified role's name.          # Get the specified role's name.
2368          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);
2369          # Use the ID if the role has no name.          # Use the ID if the role has no name.
# Line 1838  Line 2384 
2384    
2385  =item roleID  =item roleID
2386    
2387  ID of the role whose diagrams are desired.  ID of the role whose diagrams are desired.
2388    
2389    =item RETURN
2390    
2391    Returns a list of the IDs for the diagrams that contain the specified functional role.
2392    
2393    =back
2394    
2395    =cut
2396    #: Return Type @;
2397    sub RoleDiagrams {
2398        # Get the parameters.
2399        my ($self, $roleID) = @_;
2400        # Query for the diagrams.
2401        my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2402                                    'RoleOccursIn(to-link)');
2403        # Return the result.
2404        return @retVal;
2405    }
2406    
2407    =head3 GetProperties
2408    
2409    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2410    
2411    Return a list of the properties with the specified characteristics.
2412    
2413    Properties are arbitrary key-value pairs associated with a feature. (At some point they
2414    will also be associated with genomes.) A property value is represented by a 4-tuple of
2415    the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2416    
2417    =over 4
2418    
2419    =item fid
2420    
2421    ID of the feature possessing the property.
2422    
2423    =item key
2424    
2425    Name or key of the property.
2426    
2427    =item value
2428    
2429    Value of the property.
2430    
2431    =item url
2432    
2433    URL of the document that indicated the property should have this particular value, or an
2434    empty string if no such document exists.
2435    
2436    =back
2437    
2438    The parameters act as a filter for the desired data. Any non-null parameter will
2439    automatically match all the tuples returned. So, specifying just the I<$fid> will
2440    return all the properties of the specified feature; similarly, specifying the I<$key>
2441    and I<$value> parameters will return all the features having the specified property
2442    value.
2443    
2444    A single property key can have many values, representing different ideas about the
2445    feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2446    virulent, and another may declare that it is not virulent. A query about the virulence of
2447    C<fig|83333.1.peg.10> would be coded as
2448    
2449  =item RETURN      my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2450    
2451  Returns a list of the IDs for the diagrams that contain the specified functional role.  Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2452    not to be filtered. The tuples returned would be
2453    
2454  =back      ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2455        ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2456    
2457  =cut  =cut
2458    #: Return Type @@;
2459  sub RoleDiagrams {  sub GetProperties {
2460          # Get the parameters.          # Get the parameters.
2461          my $self = shift @_;      my ($self, @parms) = @_;
2462          my ($roleID) = @_;      # Declare the return variable.
2463          # Query for the diagrams.      my @retVal = ();
2464          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],      # Now we need to create a WHERE clause that will get us the data we want. First,
2465                                                                  'RoleOccursIn(to-link)');      # we create a list of the columns containing the data for each parameter.
2466        my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2467                        'Property(property-value)', 'HasProperty(evidence)');
2468        # Now we build the WHERE clause and the list of parameter values.
2469        my @where = ();
2470        my @values = ();
2471        for (my $i = 0; $i <= $#colNames; $i++) {
2472            my $parm = $parms[$i];
2473            if (defined $parm && ($parm ne '')) {
2474                push @where, "$colNames[$i] = ?";
2475                push @values, $parm;
2476            }
2477        }
2478        # Format the WHERE clause.
2479        my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2480        # Ask for all the propertie values with the desired characteristics.
2481        my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2482        while (my $valueObject = $query->Fetch()) {
2483            my @tuple = $valueObject->Values(\@colNames);
2484            push @retVal, \@tuple;
2485        }
2486          # Return the result.          # Return the result.
2487          return @retVal;          return @retVal;
2488  }  }
# Line 1885  Line 2513 
2513  =back  =back
2514    
2515  =cut  =cut
2516    #: Return Type @@;
2517  sub FeatureProperties {  sub FeatureProperties {
2518          # Get the parameters.          # Get the parameters.
2519          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2520          # Get the properties.          # Get the properties.
2521          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],
2522                                                          ['Property(property-name)', 'Property(property-value)',                                                          ['Property(property-name)', 'Property(property-value)',
# Line 1917  Line 2544 
2544  =back  =back
2545    
2546  =cut  =cut
2547    #: Return Type $;
2548  sub DiagramName {  sub DiagramName {
2549          # Get the parameters.          # Get the parameters.
2550          my $self = shift @_;      my ($self, $diagramID) = @_;
         my ($diagramID) = @_;  
2551          # Get the specified diagram's name and return it.          # Get the specified diagram's name and return it.
2552          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);
2553          return $retVal;          return $retVal;
# Line 1950  Line 2576 
2576  =back  =back
2577    
2578  =cut  =cut
2579    #: Return Type @;
2580  sub MergedAnnotations {  sub MergedAnnotations {
2581          # Get the parameters.          # Get the parameters.
2582          my $self = shift @_;      my ($self, $list) = @_;
         my ($list) = @_;  
2583          # Create a list to hold the annotation tuples found.          # Create a list to hold the annotation tuples found.
2584          my @tuples = ();          my @tuples = ();
2585          # Loop through the features in the input list.          # Loop through the features in the input list.
# Line 1969  Line 2594 
2594          }          }
2595          # Sort the result list by timestamp.          # Sort the result list by timestamp.
2596          my @retVal = sort { $a->[1] <=> $b->[1] } @tuples;          my @retVal = sort { $a->[1] <=> $b->[1] } @tuples;
2597        # Loop through and make the time stamps friendly.
2598        for my $tuple (@retVal) {
2599            $tuple->[1] = FriendlyTimestamp($tuple->[1]);
2600        }
2601          # Return the sorted list.          # Return the sorted list.
2602          return @retVal;          return @retVal;
2603  }  }
# Line 1995  Line 2624 
2624  =back  =back
2625    
2626  =cut  =cut
2627    #: Return Type @;
2628  sub RoleNeighbors {  sub RoleNeighbors {
2629          # Get the parameters.          # Get the parameters.
2630          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2631          # Get all the diagrams containing this role.          # Get all the diagrams containing this role.
2632          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2633                                                                    'RoleOccursIn(to-link)');                                                                    'RoleOccursIn(to-link)');
# Line 2038  Line 2666 
2666  =back  =back
2667    
2668  =cut  =cut
2669    #: Return Type @;
2670  sub FeatureLinks {  sub FeatureLinks {
2671          # Get the parameters.          # Get the parameters.
2672          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2673          # Get the feature's links.          # Get the feature's links.
2674          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);
2675          # Return the feature's links.          # Return the feature's links.
# Line 2054  Line 2681 
2681  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2682    
2683  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
2684  to the role the feature performs.  to the roles the feature performs.
2685    
2686  =over 4  =over 4
2687    
# Line 2064  Line 2691 
2691    
2692  =item RETURN  =item RETURN
2693    
2694  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.
2695    
2696  =back  =back
2697    
2698  =cut  =cut
2699    #: Return Type %@;
2700  sub SubsystemsOf {  sub SubsystemsOf {
2701          # Get the parameters.          # Get the parameters.
2702          my $self = shift @_;      my ($self, $featureID) = @_;
2703          my ($featureID) = @_;      # Get the subsystem list.
         # Use the SSCell to connect features to subsystems.  
2704          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2705                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2706                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2707          # Create the return value.          # Create the return value.
2708          my %retVal = ();          my %retVal = ();
2709        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2710        # in two spreadsheet cells.
2711        my %dupHash = ();
2712          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
2713          for my $record (@subsystems) {          for my $record (@subsystems) {
2714                  $retVal{$record->[0]} = $record->[1];          # Get this subsystem and role.
2715            my ($subsys, $role) = @{$record};
2716            # Insure it's the first time for both.
2717            my $dupKey = "$subsys\n$role";
2718            if (! exists $dupHash{"$subsys\n$role"}) {
2719                $dupHash{$dupKey} = 1;
2720                push @{$retVal{$subsys}}, $role;
2721            }
2722          }          }
2723          # Return the hash.          # Return the hash.
2724          return %retVal;          return %retVal;
2725  }  }
2726    
2727    =head3 SubsystemList
2728    
2729    C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2730    
2731    Return a list containing the names of the subsystems in which the specified
2732    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2733    subsystem names, not the roles.
2734    
2735    =over 4
2736    
2737    =item featureID
2738    
2739    ID of the feature whose subsystem names are desired.
2740    
2741    =item RETURN
2742    
2743    Returns a list of the names of the subsystems in which the feature participates.
2744    
2745    =back
2746    
2747    =cut
2748    #: Return Type @;
2749    sub SubsystemList {
2750        # Get the parameters.
2751        my ($self, $featureID) = @_;
2752        # Get the list of names.
2753        my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",
2754                                    [$featureID], 'HasSSCell(from-link)');
2755        # Return the result.
2756        return @retVal;
2757    }
2758    
2759  =head3 RelatedFeatures  =head3 RelatedFeatures
2760    
2761  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2118  Line 2786 
2786  =back  =back
2787    
2788  =cut  =cut
2789    #: Return Type @;
2790  sub RelatedFeatures {  sub RelatedFeatures {
2791          # Get the parameters.          # Get the parameters.
2792          my $self = shift @_;      my ($self, $featureID, $function, $userID) = @_;
         my ($featureID, $function, $userID) = @_;  
2793          # 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.
2794          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],
2795                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],
# Line 2167  Line 2834 
2834  =back  =back
2835    
2836  =cut  =cut
2837    #: Return Type @;
2838  sub TaxonomySort {  sub TaxonomySort {
2839          # Get the parameters.          # Get the parameters.
2840          my $self = shift @_;      my ($self, $featureIDs) = @_;
         my ($featureIDs) = @_;  
2841          # Create the working hash table.          # Create the working hash table.
2842          my %hashBuffer = ();          my %hashBuffer = ();
2843          # Loop through the features.          # Loop through the features.
# Line 2180  Line 2846 
2846                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
2847                                                                                  [$fid], 'Genome(taxonomy)');                                                                                  [$fid], 'Genome(taxonomy)');
2848                  # Add this feature to the hash buffer.                  # Add this feature to the hash buffer.
2849                  if (exists $hashBuffer{$taxonomy}) {          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);
                         push @{$hashBuffer{$taxonomy}}, $fid;  
                 } else {  
                         $hashBuffer{$taxonomy} = [$fid];  
                 }  
2850          }          }
2851          # Sort the keys and get the elements.          # Sort the keys and get the elements.
2852          my @retVal = ();          my @retVal = ();
# Line 2195  Line 2857 
2857          return @retVal;          return @retVal;
2858  }  }
2859    
 =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  
   
 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  
   
 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;  
 }  
   
2860  =head3 Protein  =head3 Protein
2861    
2862  C<< my $protein = Sprout::Protein($sequence, $table); >>  C<< my $protein = Sprout::Protein($sequence, $table); >>
# Line 2423  Line 2951 
2951  to load the entire database.  to load the entire database.
2952    
2953  =cut  =cut
2954    #: Return Type @;
2955  sub LoadInfo {  sub LoadInfo {
2956          # Get the parameters.          # Get the parameters.
2957          my $self = shift @_;      my ($self) = @_;
2958          # 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.
2959          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
2960          # Concatenate the table names.          # Concatenate the table names.
2961          push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
2962          # Return the result.          # Return the result.
2963          return @retVal;          return @retVal;
2964  }  }
2965    
2966  =head3 LowBBHs  =head3 LowBBHs
2967    
2968  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
2969    
2970  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
2971  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 2460  Line 2988 
2988  =back  =back
2989    
2990  =cut  =cut
2991    #: Return Type %;
2992  sub LowBBHs {  sub LowBBHs {
2993          # Get the parsameters.          # Get the parsameters.
2994          my $self = shift @_;      my ($self, $featureID, $cutoff) = @_;
         my ($featureID, $cutoff) = @_;  
2995          # Create the return hash.          # Create the return hash.
2996          my %retVal = ();          my %retVal = ();
2997          # Create a query to get the desired BBHs.          # Create a query to get the desired BBHs.
# Line 2480  Line 3007 
3007          return %retVal;          return %retVal;
3008  }  }
3009    
3010    =head3 Sims
3011    
3012    C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>
3013    
3014    Get a list of similarities for a specified feature. Similarity information is not kept in the
3015    Sprout database; rather, they are retrieved from a network server. The similarities are
3016    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3017    so that its elements can be accessed by name.
3018    
3019    Similarities can be either raw or expanded. The raw similarities are basic
3020    hits between features with similar DNA. Expanding a raw similarity drags in any
3021    features considered substantially identical. So, for example, if features B<A1>,
3022    B<A2>, and B<A3> are all substatially identical to B<A>, then a raw similarity
3023    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3024    
3025    =over 4
3026    
3027    =item fid
3028    
3029    ID of the feature whose similarities are desired.
3030    
3031    =item maxN
3032    
3033    Maximum number of similarities to return.
3034    
3035    =item maxP
3036    
3037    Minumum allowable similarity score.
3038    
3039    =item select
3040    
3041    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3042    means only similarities to FIG features are returned; C<all> means all expanded
3043    similarities are returned; and C<figx> means similarities are expanded until the
3044    number of FIG features equals the maximum.
3045    
3046    =item max_expand
3047    
3048    The maximum number of features to expand.
3049    
3050    =item filters
3051    
3052    Reference to a hash containing filter information, or a subroutine that can be
3053    used to filter the sims.
3054    
3055    =item RETURN
3056    
3057    Returns a reference to a list of similarity objects, or C<undef> if an error
3058    occurred.
3059    
3060    =back
3061    
3062    =cut
3063    
3064    sub Sims {
3065        # Get the parameters.
3066        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3067        # Create the shim object to test for deleted FIDs.
3068        my $shim = FidCheck->new($self);
3069        # Ask the network for sims.
3070        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3071        # Return the result.
3072        return $retVal;
3073    }
3074    
3075    =head3 GetGroups
3076    
3077    C<< my %groups = $sprout->GetGroups(\@groupList); >>
3078    
3079    Return a hash mapping each group to the IDs of the genomes in the group.
3080    A list of groups may be specified, in which case only those groups will be
3081    shown. Alternatively, if no parameter is supplied, all groups will be
3082    included. Genomes that are not in any group are omitted.
3083    
3084    =cut
3085    #: Return Type %@;
3086    sub GetGroups {
3087        # Get the parameters.
3088        my ($self, $groupList) = @_;
3089        # Declare the return value.
3090        my %retVal = ();
3091        # Determine whether we are getting all the groups or just some.
3092        if (defined $groupList) {
3093            # Here we have a group list. Loop through them individually,
3094            # getting a list of the relevant genomes.
3095            for my $group (@{$groupList}) {
3096                my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",
3097                    [$group], "Genome(id)");
3098                $retVal{$group} = \@genomeIDs;
3099            }
3100        } else {
3101            # Here we need all of the groups. In this case, we run through all
3102            # of the genome records, putting each one found into the appropriate
3103            # group. Note that we use a filter clause to insure that only genomes
3104            # in groups are included in the return set.
3105            my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],
3106                                        ['Genome(id)', 'Genome(group-name)']);
3107            # Loop through the genomes found.
3108            for my $genome (@genomes) {
3109                # Pop this genome's ID off the current list.
3110                my @groups = @{$genome};
3111                my $genomeID = shift @groups;
3112                # Loop through the groups, adding the genome ID to each group's
3113                # list.
3114                for my $group (@groups) {
3115                    Tracer::AddToListMap(\%retVal, $group, $genomeID);
3116                }
3117            }
3118        }
3119        # Return the hash we just built.
3120        return %retVal;
3121    }
3122    
3123    =head3 MyGenomes
3124    
3125    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
3126    
3127    Return a list of the genomes to be included in the Sprout.
3128    
3129    This method is provided for use during the Sprout load. It presumes the Genome load file has
3130    already been created. (It will be in the Sprout data directory and called either C<Genome>
3131    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3132    IDs.
3133    
3134    =over 4
3135    
3136    =item dataDir
3137    
3138    Directory containing the Sprout load files.
3139    
3140    =back
3141    
3142    =cut
3143    #: Return Type @;
3144    sub MyGenomes {
3145        # Get the parameters.
3146        my ($dataDir) = @_;
3147        # Compute the genome file name.
3148        my $genomeFileName = LoadFileName($dataDir, "Genome");
3149        # Extract the genome IDs from the files.
3150        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3151        # Return the result.
3152        return @retVal;
3153    }
3154    
3155    =head3 LoadFileName
3156    
3157    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3158    
3159    Return the name of the load file for the specified table in the specified data
3160    directory.
3161    
3162    =over 4
3163    
3164    =item dataDir
3165    
3166    Directory containing the Sprout load files.
3167    
3168    =item tableName
3169    
3170    Name of the table whose load file is desired.
3171    
3172    =item RETURN
3173    
3174    Returns the name of the file containing the load data for the specified table, or
3175    C<undef> if no load file is present.
3176    
3177    =back
3178    
3179    =cut
3180    #: Return Type $;
3181    sub LoadFileName {
3182        # Get the parameters.
3183        my ($dataDir, $tableName) = @_;
3184        # Declare the return variable.
3185        my $retVal;
3186        # Check for the various file names.
3187        if (-e "$dataDir/$tableName") {
3188            $retVal = "$dataDir/$tableName";
3189        } elsif (-e "$dataDir/$tableName.dtx") {
3190            $retVal = "$dataDir/$tableName.dtx";
3191        }
3192        # Return the result.
3193        return $retVal;
3194    }
3195    
3196    =head3 DeleteGenome
3197    
3198    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3199    
3200    Delete a genome from the database.
3201    
3202    =over 4
3203    
3204    =item genomeID
3205    
3206    ID of the genome to delete
3207    
3208    =item testFlag
3209    
3210    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3211    
3212    =item RETURN
3213    
3214    Returns a statistics object describing the rows deleted.
3215    
3216    =back
3217    
3218    =cut
3219    #: Return Type $%;
3220    sub DeleteGenome {
3221        # Get the parameters.
3222        my ($self, $genomeID, $testFlag) = @_;
3223        # Perform the delete for the genome's features.
3224        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);
3225        # Perform the delete for the primary genome data.
3226        my $stats = $self->Delete('Genome', $genomeID, $testFlag);
3227        $retVal->Accumulate($stats);
3228        # Return the result.
3229        return $retVal;
3230    }
3231    
3232  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3233    
3234  =head3 ParseAssignment  =head3 ParseAssignment
3235    
3236  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,
3237  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
3238  will be returned.  isn't, an empty list will be returned.
3239    
3240    A functional assignment is always of the form
3241    
3242        C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3243    
3244    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3245    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3246    not always the case.
3247    
3248    In addition, the functional role may contain extra data that is stripped, such as
3249    terminating spaces or a comment separated from the rest of the text by a tab.
3250    
3251  This is a static method.  This is a static method.
3252    
3253  =over 4  =over 4
3254    
3255    =item user
3256    
3257    Name of the assigning user.
3258    
3259  =item text  =item text
3260    
3261  Text of the annotation.  Text of the annotation.
# Line 2505  Line 3269 
3269    
3270  =cut  =cut
3271    
3272  sub ParseAssignment {  sub _ParseAssignment {
3273          # Get the parameters.          # Get the parameters.
3274          my ($text) = @_;      my ($user, $text) = @_;
3275          # Declare the return value.          # Declare the return value.
3276          my @retVal = ();          my @retVal = ();
3277          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3278          my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3279          if ($type =~ m/^set $user function to$/i) {      if ($type =~ m/^set function to$/i) {
3280                  # 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.
3281                  @retVal = ($user, $function);                  @retVal = ($user, $function);
3282        } elsif ($type =~ m/^set (\S+) function to$/i) {
3283            # Here we have an assignment with a user that is passed back to the caller.
3284            @retVal = ($1, $function);
3285        }
3286        # If we have an assignment, we need to clean the function text. There may be
3287        # extra junk at the end added as a note from the user.
3288        if (@retVal) {
3289            $retVal[1] =~ s/(\t\S)?\s*$//;
3290          }          }
3291          # Return the result list.          # Return the result list.
3292          return @retVal;          return @retVal;
3293  }  }
3294    
3295    =head3 FriendlyTimestamp
3296    
3297    Convert a time number to a user-friendly time stamp for display.
3298    
3299    This is a static method.
3300    
3301    =over 4
3302    
3303    =item timeValue
3304    
3305    Numeric time value.
3306    
3307    =item RETURN
3308    
3309    Returns a string containing the same time in user-readable format.
3310    
3311    =back
3312    
3313    =cut
3314    
3315    sub FriendlyTimestamp {
3316        my ($timeValue) = @_;
3317        my $retVal = localtime($timeValue);
3318        return $retVal;
3319    }
3320    
3321    =head3 AddProperty
3322    
3323    C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>
3324    
3325    Add a new attribute value (Property) to a feature. In the SEED system, attributes can
3326    be added to almost any object. In Sprout, they can only be added to features. In
3327    Sprout, attributes are implemented using I<properties>. A property represents a key/value
3328    pair. If the particular key/value pair coming in is not already in the database, a new
3329    B<Property> record is created to hold it.
3330    
3331    =over 4
3332    
3333    =item peg
3334    
3335    ID of the feature to which the attribute is to be replied.
3336    
3337    =item key
3338    
3339    Name of the attribute (key).
3340    
3341    =item value
3342    
3343    Value of the attribute.
3344    
3345    =item url
3346    
3347    URL or text citation from which the property was obtained.
3348    
3349    =back
3350    
3351    =cut
3352    #: Return Type ;
3353    sub AddProperty {
3354        # Get the parameters.
3355        my ($self, $featureID, $key, $value, $url) = @_;
3356        # Declare the variable to hold the desired property ID.
3357        my $propID;
3358        # Attempt to find a property record for this key/value pair.
3359        my @properties = $self->GetFlat(['Property'],
3360                                       "Property(property-name) = ? AND Property(property-value) = ?",
3361                                       [$key, $value], 'Property(id)');
3362        if (@properties) {
3363            # Here the property is already in the database. We save its ID.
3364            $propID = $properties[0];
3365            # Here the property value does not exist. We need to generate an ID. It will be set
3366            # to a number one greater than the maximum value in the database. This call to
3367            # GetAll will stop after one record.
3368            my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],
3369                                            1);
3370            $propID = $maxProperty[0]->[0] + 1;
3371            # Insert the new property value.
3372            $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });
3373        }
3374        # Now we connect the incoming feature to the property.
3375        $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3376    }
3377    
3378    
3379  1;  1;

Legend:
Removed from v.1.2  
changed lines
  Added in v.1.71

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3