[Bio] / Sprout / Sprout.pm Repository:
ViewVC logotype

Diff of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.5, Tue Jan 25 03:02:07 2005 UTC revision 1.78, Wed Jul 26 14:47:03 2006 UTC
# Line 1  Line 1 
1  package Sprout;  package Sprout;
2    
3        require Exporter;
4        use ERDB;
5        @ISA = qw(Exporter ERDB);
6          use Data::Dumper;          use Data::Dumper;
7          use strict;          use strict;
8          use Carp;          use Carp;
# Line 7  Line 10 
10          use XML::Simple;          use XML::Simple;
11          use DBQuery;          use DBQuery;
12          use DBObject;          use DBObject;
         use ERDB;  
13          use Tracer;          use Tracer;
14          use FIGRules;          use FIGRules;
15        use FidCheck;
16          use Stats;          use Stats;
17      use POSIX qw(strftime);      use POSIX qw(strftime);
18        use BasicLocation;
19    
20  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
21    
# Line 32  Line 35 
35  query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and  query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and
36  L</dna_seq> returns the DNA sequence for a specified genome location.  L</dna_seq> returns the DNA sequence for a specified genome location.
37    
38    The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.
39    
40  =cut  =cut
41    
42  #: Constructor SFXlate->new_sprout_only();  #: Constructor SFXlate->new_sprout_only();
43    
   
44  =head2 Public Methods  =head2 Public Methods
45    
46  =head3 new  =head3 new
# Line 63  Line 67 
67    
68  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)
69    
70  * B<userData> user name and password, delimited by a slash (default C<root/>)  * B<userData> user name and password, delimited by a slash (default same as SEED)
71    
72  * B<port> connection port (default C<0>)  * B<port> connection port (default C<0>)
73    
74    * B<sock> connection socket (default same as SEED)
75    
76  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
77    
78  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
79    
80    * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
81    
82  =back  =back
83    
84  For example, the following constructor call specifies a database named I<Sprout> and a user name of  For example, the following constructor call specifies a database named I<Sprout> and a user name of
# Line 84  Line 92 
92  sub new {  sub new {
93          # Get the parameters.          # Get the parameters.
94          my ($class, $dbName, $options) = @_;          my ($class, $dbName, $options) = @_;
95        # Compute the DBD directory.
96        my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
97                                                      $FIG_Config::fig );
98          # Compute the options. We do this by starting with a table of defaults and overwriting with          # Compute the options. We do this by starting with a table of defaults and overwriting with
99          # the incoming data.          # the incoming data.
100          my $optionTable = Tracer::GetOptions({          my $optionTable = Tracer::GetOptions({
101                                             dbType               => 'mysql',                     # database type                         dbType       => $FIG_Config::dbms,
102                                             dataDir              => 'Data',                      # data file directory                                                          # database type
103                                             xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
104                                             userData             => 'root/',                     # user name and password                                                          # data file directory
105                                             port                 => 0,                           # database connection port                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
106                                                            # database definition file name
107                           userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
108                                                            # user name and password
109                           port         => $FIG_Config::dbport,
110                                                            # database connection port
111                           sock         => $FIG_Config::dbsock,
112                                             maxSegmentLength => 4500,            # maximum feature segment length                                             maxSegmentLength => 4500,            # maximum feature segment length
113                                             maxSequenceLength => 8000,           # maximum contig sequence length                                             maxSequenceLength => 8000,           # maximum contig sequence length
114                           noDBOpen     => 0,               # 1 to suppress the database open
115                                            }, $options);                                            }, $options);
116          # Get the data directory.          # Get the data directory.
117          my $dataDir = $optionTable->{dataDir};          my $dataDir = $optionTable->{dataDir};
# Line 101  Line 119 
119          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
120          my ($userName, $password) = ($1, $2);          my ($userName, $password) = ($1, $2);
121          # Connect to the database.          # Connect to the database.
122          my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
123        if (! $optionTable->{noDBOpen}) {
124            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
125                                    $password, $optionTable->{port}, undef, $optionTable->{sock});
126        }
127          # Create the ERDB object.          # Create the ERDB object.
128          my $xmlFileName = "$optionTable->{xmlFileName}";          my $xmlFileName = "$optionTable->{xmlFileName}";
129          my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
130          # Create this object.      # Add the option table and XML file name.
131          my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
132          # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
133          bless $self;      # Return it.
134          return $self;      return $retVal;
135  }  }
136    
137  =head3 MaxSegment  =head3 MaxSegment
# Line 125  Line 147 
147  =cut  =cut
148  #: Return Type $;  #: Return Type $;
149  sub MaxSegment {  sub MaxSegment {
150          my $self = shift @_;      my ($self) = @_;
151          return $self->{_options}->{maxSegmentLength};          return $self->{_options}->{maxSegmentLength};
152  }  }
153    
# Line 140  Line 162 
162  =cut  =cut
163  #: Return Type $;  #: Return Type $;
164  sub MaxSequence {  sub MaxSequence {
165          my $self = shift @_;      my ($self) = @_;
166          return $self->{_options}->{maxSequenceLength};          return $self->{_options}->{maxSequenceLength};
167  }  }
168    
169  =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]); >>  
170    
171  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.  
172    
173  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.
174    
175  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
176  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
177  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
178    extension are used in preference to the files with an extension.
179    
180  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
181  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
182  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
183  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.  
184    
185  =over 4  =over 4
186    
187  =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  
188    
189  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
190    
191  =item RETURN  =item RETURN
192    
193  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,
194    the number of errors, and a list of the error messages.
195    
196  =back  =back
197    
198  =cut  =cut
199    #: Return Type %;
200  sub Get {  sub Load {
201          # Get the parameters.          # Get the parameters.
202          my $self = shift @_;      my ($self, $rebuild) = @_;
203          my ($objectNames, $filterClause, $parameterList) = @_;      # Load the tables from the data directory.
204          # 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);
205          # rather than a list of parameters. The next step is to convert the parameters from a reference      # Return the statistics.
206          # 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);  
207  }  }
208    
209  =head3 GetEntity  =head3 LoadUpdate
210    
211  C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
212    
213  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
214    or two tables without reloading the whole database. For each table, there must be a corresponding
215    file in the data directory, either with the same name as the table, or with a C<.dtx> suffix. So,
216    for example, to make updates to the B<FeatureTranslation> relation, there must be a
217    C<FeatureTranslation.dtx> file in the data directory. Unlike a full load, files without an extension
218    are not examined. This allows update files to co-exist with files from an original load.
219    
220  =over 4  =over 4
221    
222  =item entityType  =item truncateFlag
223    
224  Entity type name.  TRUE if the tables should be rebuilt before loading, else FALSE. A value of TRUE therefore causes
225    current data and schema of the tables to be replaced, while a value of FALSE means the new data
226    is added to the existing data in the various relations.
227    
228  =item ID  =item tableList
229    
230  ID of the desired entity.  List of the tables to be updated.
231    
232  =item RETURN  =item RETURN
233    
234  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,
235  instance is found with the specified key.  the number of errors encountered, and a list of error messages.
236    
237  =back  =back
238    
239  =cut  =cut
240    #: Return Type $%;
241  sub GetEntity {  sub LoadUpdate {
242          # Get the parameters.          # Get the parameters.
243          my $self = shift @_;      my ($self, $truncateFlag, $tableList) = @_;
244          my ($entityType, $ID) = @_;      # Declare the return value.
245          # Create a query.      my $retVal = Stats->new();
246          my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);      # Get the data directory.
247          # Get the first (and only) object.      my $optionTable = $self->{_options};
248          my $retVal = $query->Fetch();      my $dataDir = $optionTable->{dataDir};
249          # Return the result.      # Loop through the incoming table names.
250        for my $tableName (@{$tableList}) {
251            # Find the table's file.
252            my $fileName = LoadFileName($dataDir, $tableName);
253            if (! $fileName) {
254                Trace("No load file found for $tableName in $dataDir.") if T(0);
255            } else {
256                # Attempt to load this table.
257                my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);
258                # Accumulate the resulting statistics.
259                $retVal->Accumulate($result);
260            }
261        }
262        # Return the statistics.
263          return $retVal;          return $retVal;
264  }  }
265    
266  =head3 GetEntityValues  =head3 GenomeCounts
267    
268  C<< my @values = GetEntityValues($entityType, $ID, \@fields); >>  C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>
269    
270  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
271    genomes will be included in the counts.
272    
273  =over 4  =over 4
274    
275  =item entityType  =item complete
276    
277  Entity type name.  TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
278    counted
 =item ID  
   
 ID of the desired entity.  
   
 =item fields  
   
 List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.  
279    
280  =item RETURN  =item RETURN
281    
282  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--
283    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
284    
285  =back  =back
286    
287  =cut  =cut
288  #: Return Type @;  
289  sub GetEntityValues {  sub GenomeCounts {
290          # Get the parameters.          # Get the parameters.
291          my $self = shift @_;      my ($self, $complete) = @_;
292          my ($entityType, $ID, $fields) = @_;      # Set the filter based on the completeness flag.
293          # Get the specified entity.      my $filter = ($complete ? "Genome(complete) = 1" : "");
294          my $entity = $self->GetEntity($entityType, $ID);      # Get all the genomes and the related taxonomy information.
295          # Declare the return list.      my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
296          my @retVal = ();      # Clear the counters.
297          # 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);
298          if ($entity) {      # Loop through, counting the domains.
299                  push @retVal, $entity->Values($fields);      for my $genome (@genomes) {
300            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
301            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
302            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
303            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
304            elsif ($genome->[1] =~ /^env/i)      { ++$env }
305            else  { ++$unk }
306          }          }
307          # Return the result.      # Return the counts.
308          return @retVal;      return ($arch, $bact, $euk, $vir, $env, $unk);
309  }  }
310    
311  =head3 ShowMetaData  =head3 ContigCount
312    
313  C<< $sprout->ShowMetaData($fileName); >>  C<< my $count = $sprout->ContigCount($genomeID); >>
314    
315  This method outputs a description of the database to an HTML file in the data directory.  Return the number of contigs for the specified genome ID.
316    
317  =over 4  =over 4
318    
319  =item fileName  =item genomeID
   
 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);  
 }  
   
 =head3 Load  
   
 C<< $sprout->Load($rebuild); >>;  
   
 Load the database from files in the data directory, optionally re-creating the tables.  
   
 This method always deletes the data from the database before loading, even if the tables are not  
 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.  
   
 The files are loaded based on the presumption that each line of the file is a record in the  
 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.  
   
 =over 4  
   
 =item rebuild  
320    
321  TRUE if the data tables need to be created or re-created, else FALSE  ID of the genome whose contig count is desired.
322    
323  =item RETURN  =item RETURN
324    
325  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.  
326    
327  =back  =back
328    
329  =cut  =cut
330  #: Return Type %;  
331  sub Load {  sub ContigCount {
332          # Get the parameters.          # Get the parameters.
333          my $self = shift @_;      my ($self, $genomeID) = @_;
334          my ($rebuild) = @_;      # Get the contig count.
335          # Get the database object.      my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
336          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.  
337          return $retVal;          return $retVal;
338  }  }
339    
340  =head3 LoadUpdate  =head3 GeneMenu
341    
342  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params); >>
343    
344  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,
345  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
346  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.  
347    
348  =over 4  =over 4
349    
350  =item truncateFlag  =item attributes
351    
352  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.  
353    
354  =item tableList  =item filterString
355    
356  List of the tables to be updated.  A filter string for use in selecting the genomes. The filter string must conform
357    to the rules for the C<< ERDB->Get >> method.
358    
359    =item params
360    
361    Reference to a list of values to be substituted in for the parameter marks in
362    the filter string.
363    
364  =item RETURN  =item RETURN
365    
366  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.  
367    
368  =back  =back
369    
370  =cut  =cut
371  #: Return Type %;  
372  sub LoadUpdate {  sub GeneMenu {
373          # Get the parameters.          # Get the parameters.
374          my $self = shift @_;      my ($self, $attributes, $filterString, $params) = @_;
375          my ($truncateFlag, $tableList) = @_;      # Start the menu.
376          # Get the database object.      my $retVal = "<select " .
377          my $erdb = $self->{_erdb};          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
378          # Declare the return value.          ">\n";
379          my $retVal = Stats->new();      # Get the genomes.
380          # Get the data directory.      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
381          my $optionTable = $self->{_options};                                                                       'Genome(genus)',
382          my $dataDir = $optionTable->{dataDir};                                                                       'Genome(species)',
383          # Loop through the incoming table names.                                                                       'Genome(unique-characterization)']);
384          for my $tableName (@{$tableList}) {      # Sort them by name.
385                  # Find the table's file.      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
386                  my $fileName = "$dataDir/$tableName";      # Loop through the genomes, creating the option tags.
387                  if (! -e $fileName) {      for my $genomeData (@sorted) {
388                          $fileName = "$fileName.dtx";          # Get the data for this genome.
389                  }          my ($genomeID, $genus, $species, $strain) = @{$genomeData};
390                  # Attempt to load this table.          # Get the contig count.
391                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);          my $count = $self->ContigCount($genomeID);
392                  # Accumulate the resulting statistics.          my $counting = ($count == 1 ? "contig" : "contigs");
393                  $retVal->Accumulate($result);          # Build the option tag.
394            $retVal .= "<option value=\"$genomeID\">$genus $species $strain ($genomeID) [$count $counting]</option>\n";
395            Trace("Option tag built for $genomeID: $genus $species $strain.") if T(3);
396          }          }
397          # Return the statistics.      # Close the SELECT tag.
398        $retVal .= "</select>\n";
399        # Return the result.
400          return $retVal;          return $retVal;
401  }  }
   
402  =head3 Build  =head3 Build
403    
404  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 464  Line 411 
411  #: Return Type ;  #: Return Type ;
412  sub Build {  sub Build {
413          # Get the parameters.          # Get the parameters.
414          my $self = shift @_;      my ($self) = @_;
415          # Create the tables.          # Create the tables.
416          $self->{_erdb}->CreateTables;      $self->CreateTables();
417  }  }
418    
419  =head3 Genomes  =head3 Genomes
# Line 479  Line 426 
426  #: Return Type @;  #: Return Type @;
427  sub Genomes {  sub Genomes {
428          # Get the parameters.          # Get the parameters.
429          my $self = shift @_;      my ($self) = @_;
430          # Get all the genomes.          # Get all the genomes.
431          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');
432          # Return the list of IDs.          # Return the list of IDs.
# Line 509  Line 456 
456  #: Return Type $;  #: Return Type $;
457  sub GenusSpecies {  sub GenusSpecies {
458          # Get the parameters.          # Get the parameters.
459          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
460          # Get the data for the specified genome.          # Get the data for the specified genome.
461          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',
462                                                                                                                            'Genome(unique-characterization)']);                                                                                                                            'Genome(unique-characterization)']);
# Line 546  Line 492 
492  #: Return Type @;  #: Return Type @;
493  sub FeaturesOf {  sub FeaturesOf {
494          # Get the parameters.          # Get the parameters.
495          my $self = shift @_;      my ($self, $genomeID,$ftype) = @_;
         my ($genomeID,$ftype) = @_;  
496          # Get the features we want.          # Get the features we want.
497          my @features;          my @features;
498          if (!$ftype) {          if (!$ftype) {
# Line 591  Line 536 
536  =item RETURN  =item RETURN
537    
538  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
539  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context.
540    
541  =back  =back
542    
# Line 600  Line 545 
545  #: Return Type $;  #: Return Type $;
546  sub FeatureLocation {  sub FeatureLocation {
547          # Get the parameters.          # Get the parameters.
548          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
549          # Create a query for the feature locations.          # Create a query for the feature locations.
550          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",
551                                                     [$featureID]);                                                     [$featureID]);
# Line 619  Line 563 
563                  if ($prevContig eq $contigID && $dir eq $prevDir) {                  if ($prevContig eq $contigID && $dir eq $prevDir) {
564                          # Here the new segment is in the same direction on the same contig. Insure the                          # Here the new segment is in the same direction on the same contig. Insure the
565                          # new segment's beginning is next to the old segment's end.                          # new segment's beginning is next to the old segment's end.
566                          if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||              if ($dir eq "-" && $beg + $len == $prevBeg) {
567                                  ($dir eq "+" && $beg == $prevBeg + $prevLen)) {                  # Here we're merging two backward blocks, so we keep the new begin point
568                                  # Here we need to merge two segments. Adjust the beginning and length values                  # and adjust the length.
569                                  # to include both segments.                  $len += $prevLen;
570                    # Pop the old segment off. The new one will replace it later.
571                    pop @retVal;
572                } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
573                    # Here we need to merge two forward blocks. Adjust the beginning and
574                    # length values to include both segments.
575                                  $beg = $prevBeg;                                  $beg = $prevBeg;
576                                  $len += $prevLen;                                  $len += $prevLen;
577                                  # Pop the old segment off. The new one will replace it later.                                  # Pop the old segment off. The new one will replace it later.
# Line 631  Line 580 
580                  }                  }
581                  # Remember this specifier for the adjacent-segment test the next time through.                  # Remember this specifier for the adjacent-segment test the next time through.
582                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
583            # Compute the initial base pair.
584            my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
585                  # Add the specifier to the list.                  # Add the specifier to the list.
586                  push @retVal, "${contigID}_$beg$dir$len";          push @retVal, "${contigID}_$start$dir$len";
587          }          }
588          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
589          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
590  }  }
591    
592  =head3 ParseLocation  =head3 ParseLocation
# Line 661  Line 612 
612  =cut  =cut
613  #: Return Type @;  #: Return Type @;
614  sub ParseLocation {  sub ParseLocation {
615          # Get the parameter.      # Get the parameter. Note that if we're called as an instance method, we ignore
616        # the first parameter.
617        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
618          my ($location) = @_;          my ($location) = @_;
619          # Parse it into segments.          # Parse it into segments.
620          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
621          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
622          # If the direction is an underscore, convert it to a + or -.          # If the direction is an underscore, convert it to a + or -.
623          if ($dir eq "_") {          if ($dir eq "_") {
# Line 680  Line 633 
633          return ($contigID, $start, $dir, $len);          return ($contigID, $start, $dir, $len);
634  }  }
635    
636    =head3 PointLocation
637    
638    C<< my $found = Sprout::PointLocation($location, $point); >>
639    
640    Return the offset into the specified location of the specified point on the contig. If
641    the specified point is before the location, a negative value will be returned. If it is
642    beyond the location, an undefined value will be returned. It is assumed that the offset
643    is for the location's contig. The location can either be new-style (using a C<+> or C<->
644    and a length) or old-style (using C<_> and start and end positions.
645    
646    =over 4
647    
648    =item location
649    
650    A location specifier (see L</FeatureLocation> for a description).
651    
652    =item point
653    
654    The offset into the contig of the point in which we're interested.
655    
656    =item RETURN
657    
658    Returns the offset inside the specified location of the specified point, a negative
659    number if the point is before the location, or an undefined value if the point is past
660    the location. If the length of the location is 0, this method will B<always> denote
661    that it is outside the location. The offset will always be relative to the left-most
662    position in the location.
663    
664    =back
665    
666    =cut
667    #: Return Type $;
668    sub PointLocation {
669        # Get the parameter. Note that if we're called as an instance method, we ignore
670        # the first parameter.
671        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
672        my ($location, $point) = @_;
673        # Parse out the location elements. Note that this works on both old-style and new-style
674        # locations.
675        my ($contigID, $start, $dir, $len) = ParseLocation($location);
676        # Declare the return variable.
677        my $retVal;
678        # Compute the offset. The computation is dependent on the direction of the location.
679        my $offset = (($dir == '+') ? $point - $start : $point - ($start - $len + 1));
680        # Return the offset if it's valid.
681        if ($offset < $len) {
682            $retVal = $offset;
683        }
684        # Return the offset found.
685        return $retVal;
686    }
687    
688  =head3 DNASeq  =head3 DNASeq
689    
690  C<< my $sequence = $sprout->DNASeq(\@locationList); >>  C<< my $sequence = $sprout->DNASeq(\@locationList); >>
# Line 688  Line 693 
693  should be of the form returned by L</featureLocation> when in a list context. In other words,  should be of the form returned by L</featureLocation> when in a list context. In other words,
694  each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.  each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.
695    
696    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
697    between positions 1401 and 1532, inclusive.
698    
699        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
700    
701  =over 4  =over 4
702    
703  =item locationList  =item locationList
704    
705  List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<end> (see  List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<len> or
706  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
707    
708  =item RETURN  =item RETURN
709    
# Line 705  Line 715 
715  #: Return Type $;  #: Return Type $;
716  sub DNASeq {  sub DNASeq {
717          # Get the parameters.          # Get the parameters.
718          my $self = shift @_;      my ($self, $locationList) = @_;
         my ($locationList) = @_;  
719          # Create the return string.          # Create the return string.
720          my $retVal = "";          my $retVal = "";
721          # Loop through the locations.          # Loop through the locations.
# Line 721  Line 730 
730                  # 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
731                  # before putting it in the return value.                  # before putting it in the return value.
732                  my ($start, $stop);                  my ($start, $stop);
733            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
734                  if ($dir eq "+") {                  if ($dir eq "+") {
735                          $start = $beg;                          $start = $beg;
736                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
737                  } else {                  } else {
738                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
739                          $stop = $beg;                          $stop = $beg;
740                  }                  }
741            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
742                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
743                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
744                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 739  Line 750 
750                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
751                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
752                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
753                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
754                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
755                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
756                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
757                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
758                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
759                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
760                  }                  }
761                  # 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.
762                  if ($dir eq '+') {                  if ($dir eq '+') {
763                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
764                  } else {                  } else {
765                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
766                  }                  }
767          }          }
768          # Return the result.          # Return the result.
# Line 779  Line 791 
791  #: Return Type @;  #: Return Type @;
792  sub AllContigs {  sub AllContigs {
793          # Get the parameters.          # Get the parameters.
794          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
795          # Ask for the genome's Contigs.          # Ask for the genome's Contigs.
796          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],
797                                                                  'HasContig(to-link)');                                                                  'HasContig(to-link)');
# Line 788  Line 799 
799          return @retVal;          return @retVal;
800  }  }
801    
802    =head3 GenomeLength
803    
804    C<< my $length = $sprout->GenomeLength($genomeID); >>
805    
806    Return the length of the specified genome in base pairs.
807    
808    =over 4
809    
810    =item genomeID
811    
812    ID of the genome whose base pair count is desired.
813    
814    =item RETURN
815    
816    Returns the number of base pairs in all the contigs of the specified
817    genome.
818    
819    =back
820    
821    =cut
822    
823    sub GenomeLength {
824        # Get the parameters.
825        my ($self, $genomeID) = @_;
826        # Declare the return variable.
827        my $retVal = 0;
828        # Get the genome's contig sequence lengths.
829        my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
830                           [$genomeID], 'IsMadeUpOf(len)');
831        # Sum the lengths.
832        map { $retVal += $_ } @lens;
833        # Return the result.
834        return $retVal;
835    }
836    
837    =head3 FeatureCount
838    
839    C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
840    
841    Return the number of features of the specified type in the specified genome.
842    
843    =over 4
844    
845    =item genomeID
846    
847    ID of the genome whose feature count is desired.
848    
849    =item type
850    
851    Type of feature to count (eg. C<peg>, C<rna>, etc.).
852    
853    =item RETURN
854    
855    Returns the number of features of the specified type for the specified genome.
856    
857    =back
858    
859    =cut
860    
861    sub FeatureCount {
862        # Get the parameters.
863        my ($self, $genomeID, $type) = @_;
864        # Compute the count.
865        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
866                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
867                                    [$genomeID, $type]);
868        # Return the result.
869        return $retVal;
870    }
871    
872    =head3 GenomeAssignments
873    
874    C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
875    
876    Return a list of a genome's assigned features. The return hash will contain each
877    assigned feature of the genome mapped to the text of its most recent functional
878    assignment.
879    
880    =over 4
881    
882    =item genomeID
883    
884    ID of the genome whose functional assignments are desired.
885    
886    =item RETURN
887    
888    Returns a reference to a hash which maps each feature to its most recent
889    functional assignment.
890    
891    =back
892    
893    =cut
894    
895    sub GenomeAssignments {
896        # Get the parameters.
897        my ($self, $genomeID) = @_;
898        # Declare the return variable.
899        my $retVal = {};
900        # Query the genome's features and annotations. We'll put the oldest annotations
901        # first so that the last assignment to go into the hash will be the correct one.
902        my $query = $self->Get(['HasFeature', 'IsTargetOfAnnotation', 'Annotation'],
903                               "HasFeature(from-link) = ? ORDER BY Annotation(time)",
904                               [$genomeID]);
905        # Loop through the annotations.
906        while (my $data = $query->Fetch) {
907            # Get the feature ID and annotation text.
908            my ($fid, $annotation) = $data->Values(['HasFeature(to-link)',
909                                                    'Annotation(annotation)']);
910            # Check to see if this is an assignment. Note that the user really
911            # doesn't matter to us, other than we use it to determine whether or
912            # not this is an assignment.
913            my ($user, $assignment) = _ParseAssignment('fig', $annotation);
914            if ($user) {
915                # Here it's an assignment. We put it in the return hash, overwriting
916                # any older assignment that might be present.
917                $retVal->{$fid} = $assignment;
918            }
919        }
920        # Return the result.
921        return $retVal;
922    }
923    
924  =head3 ContigLength  =head3 ContigLength
925    
926  C<< my $length = $sprout->ContigLength($contigID); >>  C<< my $length = $sprout->ContigLength($contigID); >>
# Line 796  Line 929 
929    
930  =over 4  =over 4
931    
932  =item contigID  =item contigID
933    
934    ID of the contig whose length is desired.
935    
936    =item RETURN
937    
938    Returns the number of positions in the contig.
939    
940    =back
941    
942    =cut
943    #: Return Type $;
944    sub ContigLength {
945        # Get the parameters.
946        my ($self, $contigID) = @_;
947        # Get the contig's last sequence.
948        my $query = $self->Get(['IsMadeUpOf'],
949            "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
950            [$contigID]);
951        my $sequence = $query->Fetch();
952        # Declare the return value.
953        my $retVal = 0;
954        # Set it from the sequence data, if any.
955        if ($sequence) {
956            my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
957            $retVal = $start + $len - 1;
958        }
959        # Return the result.
960        return $retVal;
961    }
962    
963    =head3 ClusterPEGs
964    
965    C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
966    
967    Cluster the PEGs in a list according to the cluster coding scheme of the specified
968    subsystem. In order for this to work properly, the subsystem object must have
969    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
970    This causes the cluster numbers to be pulled into the subsystem's color hash.
971    If a PEG is not found in the color hash, it will not appear in the output
972    sequence.
973    
974    =over 4
975    
976    =item sub
977    
978    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
979    method.
980    
981    =item pegs
982    
983  ID of the contig whose length is desired.  Reference to the list of PEGs to be clustered.
984    
985  =item RETURN  =item RETURN
986    
987  Returns the number of positions in the contig.  Returns a list of the PEGs, grouped into smaller lists by cluster number.
988    
989  =back  =back
990    
991  =cut  =cut
992  #: Return Type $;  #: Return Type $@@;
993  sub ContigLength {  sub ClusterPEGs {
994          # Get the parameters.          # Get the parameters.
995          my $self = shift @_;      my ($self, $sub, $pegs) = @_;
996          my ($contigID) = @_;      # Declare the return variable.
997          # Get the contig's last sequence.      my $retVal = [];
998          my $query = $self->Get(['IsMadeUpOf'],      # Loop through the PEGs, creating arrays for each cluster.
999                  "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",      for my $pegID (@{$pegs}) {
1000                  [$contigID]);          my $clusterNumber = $sub->get_cluster_number($pegID);
1001          my $sequence = $query->Fetch();          # Only proceed if the PEG is in a cluster.
1002          # Declare the return value.          if ($clusterNumber >= 0) {
1003          my $retVal = 0;              # Push this PEG onto the sub-list for the specified cluster number.
1004          # Set it from the sequence data, if any.              push @{$retVal->[$clusterNumber]}, $pegID;
1005          if ($sequence) {          }
                 my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);  
                 $retVal = $start + $len;  
1006          }          }
1007          # Return the result.          # Return the result.
1008          return $retVal;          return $retVal;
# Line 853  Line 1033 
1033  Returns a three-element list. The first element is a list of feature IDs for the features that  Returns a three-element list. The first element is a list of feature IDs for the features that
1034  overlap the region of interest. The second and third elements are the minimum and maximum  overlap the region of interest. The second and third elements are the minimum and maximum
1035  locations of the features provided on the specified contig. These may extend outside  locations of the features provided on the specified contig. These may extend outside
1036  the start and stop values.  the start and stop values. The first element (that is, the list of features) is sorted
1037    roughly by location.
1038    
1039  =back  =back
1040    
1041  =cut  =cut
1042  #: Return Type @;  #: Return Type @@;
1043  sub GenesInRegion {  sub GenesInRegion {
1044          # Get the parameters.          # Get the parameters.
1045          my $self = shift @_;      my ($self, $contigID, $start, $stop) = @_;
         my ($contigID, $start, $stop) = @_;  
1046          # Get the maximum segment length.          # Get the maximum segment length.
1047          my $maximumSegmentLength = $self->MaxSegment;          my $maximumSegmentLength = $self->MaxSegment;
1048          # Create a hash to receive the feature list. We use a hash so that we can eliminate          # Create a hash to receive the feature list. We use a hash so that we can eliminate
1049          # duplicates easily.      # duplicates easily. The hash key will be the feature ID. The value will be a two-element
1050        # containing the minimum and maximum offsets. We will use the offsets to sort the results
1051        # when we're building the result set.
1052          my %featuresFound = ();          my %featuresFound = ();
1053          # Prime the values we'll use for the returned beginning and end.          # Prime the values we'll use for the returned beginning and end.
1054          my ($min, $max) = ($self->ContigLength($contigID), 0);      my @initialMinMax = ($self->ContigLength($contigID), 0);
1055        my ($min, $max) = @initialMinMax;
1056          # Create a table of parameters for each query. Each query looks for features travelling in          # Create a table of parameters for each query. Each query looks for features travelling in
1057          # a particular direction. The query parameters include the contig ID, the feature direction,          # a particular direction. The query parameters include the contig ID, the feature direction,
1058          # the lowest possible start position, and the highest possible start position. This works          # the lowest possible start position, and the highest possible start position. This works
# Line 899  Line 1082 
1082                                          $found = 1;                                          $found = 1;
1083                                  }                                  }
1084                          } elsif ($dir eq '-') {                          } elsif ($dir eq '-') {
1085                                  $end = $beg - $len;                  # Note we switch things around so that the beginning is to the left of the
1086                                  if ($end <= $stop) {                  # ending.
1087                    ($beg, $end) = ($beg - $len, $beg);
1088                    if ($beg <= $stop) {
1089                                          # Denote we found a useful feature.                                          # Denote we found a useful feature.
1090                                          $found = 1;                                          $found = 1;
1091                                  }                                  }
1092                          }                          }
1093                          if ($found) {                          if ($found) {
1094                                  # 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,
1095                                  $featuresFound{$featureID} = 1;                  # get the current entry for the specified feature.
1096                                  if ($beg < $min) { $min = $beg; }                  my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :
1097                                  if ($end < $min) { $min = $end; }                                       @initialMinMax);
1098                                  if ($beg > $max) { $max = $beg; }                  # Merge the current segment's begin and end into the feature begin and end and the
1099                                  if ($end > $max) { $max = $end; }                  # global min and max.
1100                    if ($beg < $loc1) {
1101                        $loc1 = $beg;
1102                        $min = $beg if $beg < $min;
1103                    }
1104                    if ($end > $loc2) {
1105                        $loc2 = $end;
1106                        $max = $end if $end > $max;
1107                    }
1108                    # Store the entry back into the hash table.
1109                    $featuresFound{$featureID} = [$loc1, $loc2];
1110                          }                          }
1111                  }                  }
1112          }          }
1113          # 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
1114          my @list = (sort (keys %featuresFound));      # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1115        # but the result of the sort will be the same.)
1116        my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;
1117        # Now we sort by midpoint and yank out the feature IDs.
1118        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1119          # Return it along with the min and max.          # Return it along with the min and max.
1120          return (\@list, $min, $max);      return (\@retVal, $min, $max);
1121  }  }
1122    
1123  =head3 FType  =head3 FType
# Line 944  Line 1143 
1143  #: Return Type $;  #: Return Type $;
1144  sub FType {  sub FType {
1145          # Get the parameters.          # Get the parameters.
1146          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1147          # Get the specified feature's type.          # Get the specified feature's type.
1148          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
1149          # Return the result.          # Return the result.
# Line 954  Line 1152 
1152    
1153  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1154    
1155  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1156    
1157  Return the annotations of a feature.  Return the annotations of a feature.
1158    
# Line 964  Line 1162 
1162    
1163  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1164    
1165    =item rawFlag
1166    
1167    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1168    will be returned in human-readable form.
1169    
1170  =item RETURN  =item RETURN
1171    
1172  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.
1173    
1174  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1175    
1176  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1177    
1178  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1179    
# Line 982  Line 1185 
1185  #: Return Type @%;  #: Return Type @%;
1186  sub FeatureAnnotations {  sub FeatureAnnotations {
1187          # Get the parameters.          # Get the parameters.
1188          my $self = shift @_;      my ($self, $featureID, $rawFlag) = @_;
         my ($featureID) = @_;  
1189          # 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.
1190          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1191                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 996  Line 1198 
1198                          $annotation->Values(['IsTargetOfAnnotation(from-link)',                          $annotation->Values(['IsTargetOfAnnotation(from-link)',
1199                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1200                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1201            # Convert the time, if necessary.
1202            if (! $rawFlag) {
1203                $timeStamp = FriendlyTimestamp($timeStamp);
1204            }
1205                  # Assemble them into a hash.                  # Assemble them into a hash.
1206          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1207                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1208                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1209                  # Add it to the return list.                  # Add it to the return list.
1210                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1012  Line 1218 
1218  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>
1219    
1220  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
1221  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,
1222  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
1223  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,
1224  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.
1225  features only have a small number of annotations. Finally, if a single user has multiple  Finally, if a single user has multiple functional assignments, we will only keep the most
1226  functional assignments, we will only keep the most recent one.  recent one.
1227    
1228  =over 4  =over 4
1229    
# Line 1027  Line 1233 
1233    
1234  =item RETURN  =item RETURN
1235    
1236  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1237    
1238  =back  =back
1239    
# Line 1035  Line 1241 
1241  #: Return Type %;  #: Return Type %;
1242  sub AllFunctionsOf {  sub AllFunctionsOf {
1243          # Get the parameters.          # Get the parameters.
1244          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1245          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1246      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1247                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1248                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1249                                               'MadeAnnotation(from-link)']);
1250          # Declare the return hash.          # Declare the return hash.
1251          my %retVal;          my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1252      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1253      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1254          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1255      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1256          # Get the annotation fields.          # Get the annotation fields.
1257          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1258                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1259                  my ($user, $function) = ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1260          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1261              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1262              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1263              # return hash.              # return hash.
1264                          $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1265                  }                  }
1266          }          }
1267          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1074  Line 1276 
1276    
1277  The functional assignment is handled differently depending on the type of feature. If  The functional assignment is handled differently depending on the type of feature. If
1278  the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional  the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1279  assignment is a type of annotation. It has the format "XXXX\nset XXXX function to\nYYYYY". In this  assignment is a type of annotation. The format of an assignment is described in
1280  instance, XXXX is the user ID and YYYYY is the functional assignment text. Its worth noting that  L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1281  we cannot filter on the content of the annotation itself because it's a text field; however, this  annotation itself because it's a text field; however, this is not a big problem because
1282  is not a big problem because most features only have a small number of annotations.  most features only have a small number of annotations.
1283    
1284  Each user has an associated list of trusted users. The assignment returned will be the most  Each user has an associated list of trusted users. The assignment returned will be the most
1285  recent one by at least one of the trusted users. If no trusted user list is available, then  recent one by at least one of the trusted users. If no trusted user list is available, then
# Line 1109  Line 1311 
1311  #: Return Type $;  #: Return Type $;
1312  sub FunctionOf {  sub FunctionOf {
1313          # Get the parameters.          # Get the parameters.
1314          my $self = shift @_;      my ($self, $featureID, $userID) = @_;
         my ($featureID, $userID) = @_;  
1315      # Declare the return value.      # Declare the return value.
1316      my $retVal;      my $retVal;
1317      # Determine the ID type.      # Determine the ID type.
# Line 1138  Line 1339 
1339              }              }
1340          }          }
1341          # Build a query for all of the feature's annotations, sorted by date.          # Build a query for all of the feature's annotations, sorted by date.
1342          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1343                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1344                                 [$featureID]);                                 [$featureID]);
1345          my $timeSelected = 0;          my $timeSelected = 0;
1346          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1347          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1348              # Get the annotation text.              # Get the annotation text.
1349              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);              my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1350                                                         'Annotation(time)', 'MadeAnnotation(from-link)']);
1351              # Check to see if this is a functional assignment for a trusted user.              # Check to see if this is a functional assignment for a trusted user.
1352              my ($user, $type, $function) = split(/\n/, $text);              my ($actualUser, $function) = _ParseAssignment($user, $text);
1353              if ($type =~ m/^set $user function to$/i) {              Trace("Assignment user is $actualUser, text is $function.") if T(4);
1354                if ($actualUser) {
1355                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1356                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1357                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                  if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1358                      $retVal = $function;                      $retVal = $function;
1359                      $timeSelected = $time;                      $timeSelected = $time;
1360                  }                  }
# Line 1167  Line 1370 
1370          return $retVal;          return $retVal;
1371  }  }
1372    
1373    =head3 FunctionsOf
1374    
1375    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1376    
1377    Return the functional assignments of a particular feature.
1378    
1379    The functional assignment is handled differently depending on the type of feature. If
1380    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1381    assignment is a type of annotation. The format of an assignment is described in
1382    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1383    annotation itself because it's a text field; however, this is not a big problem because
1384    most features only have a small number of annotations.
1385    
1386    If the feature is B<not> identified by a FIG ID, then the functional assignment
1387    information is taken from the B<ExternalAliasFunc> table. If the table does
1388    not contain an entry for the feature, an empty list is returned.
1389    
1390    =over 4
1391    
1392    =item featureID
1393    
1394    ID of the feature whose functional assignments are desired.
1395    
1396    =item RETURN
1397    
1398    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1399    that user.
1400    
1401    =back
1402    
1403    =cut
1404    #: Return Type @@;
1405    sub FunctionsOf {
1406        # Get the parameters.
1407        my ($self, $featureID) = @_;
1408        # Declare the return value.
1409        my @retVal = ();
1410        # Determine the ID type.
1411        if ($featureID =~ m/^fig\|/) {
1412            # Here we have a FIG feature ID. We must build the list of trusted
1413            # users.
1414            my %trusteeTable = ();
1415            # Build a query for all of the feature's annotations, sorted by date.
1416            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1417                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1418                                   [$featureID]);
1419            my $timeSelected = 0;
1420            # Loop until we run out of annotations.
1421            while (my $annotation = $query->Fetch()) {
1422                # Get the annotation text.
1423                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1424                                                                'Annotation(time)',
1425                                                                'MadeAnnotation(user)']);
1426                # Check to see if this is a functional assignment for a trusted user.
1427                my ($actualUser, $function) = _ParseAssignment($user, $text);
1428                if ($actualUser) {
1429                    # Here it is a functional assignment.
1430                    push @retVal, [$actualUser, $function];
1431                }
1432            }
1433        } else {
1434            # Here we have a non-FIG feature ID. In this case the user ID does not
1435            # matter. We simply get the information from the External Alias Function
1436            # table.
1437            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1438                                                     ['ExternalAliasFunc(func)']);
1439            push @retVal, map { ['master', $_] } @assignments;
1440        }
1441        # Return the assignments found.
1442        return @retVal;
1443    }
1444    
1445  =head3 BBHList  =head3 BBHList
1446    
1447  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1186  Line 1461 
1461    
1462  =item RETURN  =item RETURN
1463    
1464  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
1465  their best hits.  on the target genome.
1466    
1467  =back  =back
1468    
# Line 1195  Line 1470 
1470  #: Return Type %;  #: Return Type %;
1471  sub BBHList {  sub BBHList {
1472          # Get the parameters.          # Get the parameters.
1473          my $self = shift @_;      my ($self, $genomeID, $featureList) = @_;
         my ($genomeID, $featureList) = @_;  
1474          # Create the return structure.          # Create the return structure.
1475          my %retVal = ();          my %retVal = ();
1476          # Loop through the incoming features.          # Loop through the incoming features.
# Line 1205  Line 1479 
1479                  my $query = $self->Get(['IsBidirectionalBestHitOf'],                  my $query = $self->Get(['IsBidirectionalBestHitOf'],
1480                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",
1481                                                             [$featureID, $genomeID]);                                                             [$featureID, $genomeID]);
1482                  # Look for the best hit.          # Peel off the BBHs found.
1483                  my $bbh = $query->Fetch;          my @found = ();
1484                  if ($bbh) {          while (my $bbh = $query->Fetch) {
1485                          my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');
                         $retVal{$featureID} = $targetFeature;  
1486                  }                  }
1487            $retVal{$featureID} = \@found;
1488          }          }
1489          # Return the mapping.          # Return the mapping.
1490          return \%retVal;          return \%retVal;
1491  }  }
1492    
1493    =head3 SimList
1494    
1495    C<< my %similarities = $sprout->SimList($featureID, $count); >>
1496    
1497    Return a list of the similarities to the specified feature.
1498    
1499    Sprout does not support real similarities, so this method just returns the bidirectional
1500    best hits.
1501    
1502    =over 4
1503    
1504    =item featureID
1505    
1506    ID of the feature whose similarities are desired.
1507    
1508    =item count
1509    
1510    Maximum number of similar features to be returned, or C<0> to return them all.
1511    
1512    =back
1513    
1514    =cut
1515    #: Return Type %;
1516    sub SimList {
1517        # Get the parameters.
1518        my ($self, $featureID, $count) = @_;
1519        # Ask for the best hits.
1520        my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],
1521                                  "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",
1522                                  [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],
1523                                  $count);
1524        # Create the return value.
1525        my %retVal = ();
1526        for my $tuple (@lists) {
1527            $retVal{$tuple->[0]} = $tuple->[1];
1528        }
1529        # Return the result.
1530        return %retVal;
1531    }
1532    
1533    
1534    
1535    =head3 IsComplete
1536    
1537    C<< my $flag = $sprout->IsComplete($genomeID); >>
1538    
1539    Return TRUE if the specified genome is complete, else FALSE.
1540    
1541    =over 4
1542    
1543    =item genomeID
1544    
1545    ID of the genome whose completeness status is desired.
1546    
1547    =item RETURN
1548    
1549    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1550    not found.
1551    
1552    =back
1553    
1554    =cut
1555    #: Return Type $;
1556    sub IsComplete {
1557        # Get the parameters.
1558        my ($self, $genomeID) = @_;
1559        # Declare the return variable.
1560        my $retVal;
1561        # Get the genome's data.
1562        my $genomeData = $self->GetEntity('Genome', $genomeID);
1563        if ($genomeData) {
1564            # The genome exists, so get the completeness flag.
1565            ($retVal) = $genomeData->Value('Genome(complete)');
1566        }
1567        # Return the result.
1568        return $retVal;
1569    }
1570    
1571  =head3 FeatureAliases  =head3 FeatureAliases
1572    
1573  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
# Line 1239  Line 1591 
1591  #: Return Type @;  #: Return Type @;
1592  sub FeatureAliases {  sub FeatureAliases {
1593          # Get the parameters.          # Get the parameters.
1594          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1595          # Get the desired feature's aliases          # Get the desired feature's aliases
1596          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);
1597          # Return the result.          # Return the result.
# Line 1251  Line 1602 
1602    
1603  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1604    
1605  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1606    
1607  =over 4  =over 4
1608    
1609  =item featureID  =item featureID
1610    
1611  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1612    
1613  =item RETURN  =item RETURN
1614    
1615  Returns the ID of the genome for the specified feature. If the feature is not found, returns  Returns the ID of the genome for the specified feature or contig. If the feature or contig is not
1616  an undefined value.  found, returns an undefined value.
1617    
1618  =back  =back
1619    
# Line 1270  Line 1621 
1621  #: Return Type $;  #: Return Type $;
1622  sub GenomeOf {  sub GenomeOf {
1623          # Get the parameters.          # Get the parameters.
1624          my $self = shift @_;      my ($self, $featureID) = @_;
1625          my ($featureID) = @_;      # Create a query to find the genome associated with the incoming ID.
1626          # Create a query to find the genome associated with the feature.      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1627          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);                             [$featureID, $featureID]);
1628          # Declare the return value.          # Declare the return value.
1629          my $retVal;          my $retVal;
1630          # Get the genome ID.          # Get the genome ID.
# Line 1307  Line 1658 
1658  #: Return Type %;  #: Return Type %;
1659  sub CoupledFeatures {  sub CoupledFeatures {
1660          # Get the parameters.          # Get the parameters.
1661          my $self = shift @_;      my ($self, $featureID) = @_;
1662          my ($featureID) = @_;      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1663          # Create a query to retrieve the functionally-coupled features. Note that we depend on the      # Create a query to retrieve the functionally-coupled features.
1664          # fact that the functional coupling is physically paired. If (A,B) is in the database, then      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1665          # (B,A) will also be found.                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);
         my $query = $self->Get(['IsClusteredOnChromosomeWith'],  
                                                    "IsClusteredOnChromosomeWith(from-link) = ?", [$featureID]);  
1666          # 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.
1667          my $found = 0;          my $found = 0;
1668          # Create the return hash.          # Create the return hash.
1669          my %retVal = ();          my %retVal = ();
1670          # Retrieve the relationship records and store them in the hash.          # Retrieve the relationship records and store them in the hash.
1671          while (my $clustering = $query->Fetch()) {          while (my $clustering = $query->Fetch()) {
1672                  my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',          # Get the ID and score of the coupling.
1673                                                                      'IsClusteredOnChromosomeWith(score)']);          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1674                                                            'Coupling(score)']);
1675            Trace("$featureID coupled with score $score to ID $couplingID.") if T(coupling => 4);
1676            # Get the other feature that participates in the coupling.
1677            my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],
1678                                               "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",
1679                                               [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');
1680            Trace("$couplingID target feature is $otherFeatureID.") if T(coupling => 4);
1681            # Attach the other feature's score to its ID.
1682                  $retVal{$otherFeatureID} = $score;                  $retVal{$otherFeatureID} = $score;
1683                  $found = 1;                  $found = 1;
1684          }          }
# Line 1334  Line 1691 
1691          return %retVal;          return %retVal;
1692  }  }
1693    
1694  =head3 GetEntityTypes  =head3 CouplingEvidence
1695    
1696    C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1697    
1698    Return the evidence for a functional coupling.
1699    
1700    A pair of features is considered evidence of a coupling between two other
1701    features if they occur close together on a contig and both are similar to
1702    the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1703    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1704    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1705    similar to B<A2>.
1706    
1707    The score of a coupling is determined by the number of pieces of evidence
1708    that are considered I<representative>. If several evidence items belong to
1709    a group of genomes that are close to each other, only one of those items
1710    is considered representative. The other evidence items are presumed to be
1711    there because of the relationship between the genomes rather than because
1712    the two proteins generated by the features have a related functionality.
1713    
1714    Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1715    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1716    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1717    and FALSE otherwise.
1718    
1719    =over 4
1720    
1721    =item peg1
1722    
1723    ID of the feature of interest.
1724    
1725    =item peg2
1726    
1727    ID of a feature functionally coupled to the feature of interest.
1728    
1729    =item RETURN
1730    
1731    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1732    of interest, a feature similar to the functionally coupled feature, and a flag
1733    that is TRUE for a representative piece of evidence and FALSE otherwise.
1734    
1735    =back
1736    
1737    =cut
1738    #: Return Type @@;
1739    sub CouplingEvidence {
1740        # Get the parameters.
1741        my ($self, $peg1, $peg2) = @_;
1742        # Declare the return variable.
1743        my @retVal = ();
1744        # Our first task is to find out the nature of the coupling: whether or not
1745        # it exists, its score, and whether the features are stored in the same
1746        # order as the ones coming in.
1747        my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1748        # Only proceed if a coupling exists.
1749        if ($couplingID) {
1750            # Determine the ordering to place on the evidence items. If we're
1751            # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1752            # we want feature 1 before feature 2 (normal).
1753            Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);
1754            my $ordering = ($inverted ? "DESC" : "");
1755            # Get the coupling evidence.
1756            my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
1757                                              "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",
1758                                              [$couplingID],
1759                                              ['PCH(used)', 'UsesAsEvidence(to-link)']);
1760            # Loop through the evidence items. Each piece of evidence is represented by two
1761            # positions in the evidence list, one for each feature on the other side of the
1762            # evidence link. If at some point we want to generalize to couplings with
1763            # more than two positions, this section of code will need to be re-done.
1764            while (@evidenceList > 0) {
1765                my $peg1Data = shift @evidenceList;
1766                my $peg2Data = shift @evidenceList;
1767                Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1768                push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1769            }
1770            Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1771        }
1772        # Return the result.
1773        return @retVal;
1774    }
1775    
1776    =head3 GetCoupling
1777    
1778    C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>
1779    
1780    Return the coupling (if any) for the specified pair of PEGs. If a coupling
1781    exists, we return the coupling ID along with an indicator of whether the
1782    coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.
1783    In the second case, we say the coupling is I<inverted>. The importance of an
1784    inverted coupling is that the PEGs in the evidence will appear in reverse order.
1785    
1786    =over 4
1787    
1788    =item peg1
1789    
1790    ID of the feature of interest.
1791    
1792    =item peg2
1793    
1794    ID of the potentially coupled feature.
1795    
1796    =item RETURN
1797    
1798    Returns a three-element list. The first element contains the database ID of
1799    the coupling. The second element is FALSE if the coupling is stored in the
1800    database in the caller specified order and TRUE if it is stored in the
1801    inverted order. The third element is the coupling's score. If the coupling
1802    does not exist, all three list elements will be C<undef>.
1803    
1804    =back
1805    
1806    =cut
1807    #: Return Type $%@;
1808    sub GetCoupling {
1809        # Get the parameters.
1810        my ($self, $peg1, $peg2) = @_;
1811        # Declare the return values. We'll start with the coupling ID and undefine the
1812        # flag and score until we have more information.
1813        my ($retVal, $inverted, $score) = ($self->CouplingID($peg1, $peg2), undef, undef);
1814        # Find the coupling data.
1815        my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1816                                     "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1817                                     [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1818        # Check to see if we found anything.
1819        if (!@pegs) {
1820            Trace("No coupling found.") if T(Coupling => 4);
1821            # No coupling, so undefine the return value.
1822            $retVal = undef;
1823        } else {
1824            # We have a coupling! Get the score and check for inversion.
1825            $score = $pegs[0]->[1];
1826            my $firstFound = $pegs[0]->[0];
1827            $inverted = ($firstFound ne $peg1);
1828            Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1829        }
1830        # Return the result.
1831        return ($retVal, $inverted, $score);
1832    }
1833    
1834    =head3 GetSynonymGroup
1835    
1836    C<< my $id = $sprout->GetSynonymGroup($fid); >>
1837    
1838    Return the synonym group name for the specified feature.
1839    
1840    =over 4
1841    
1842    =item fid
1843    
1844    ID of the feature whose synonym group is desired.
1845    
1846    =item RETURN
1847    
1848  C<< my @entityList = $sprout->GetEntityTypes(); >>  The name of the synonym group to which the feature belongs. If the feature does
1849    not belong to a synonym group, the feature ID itself is returned.
1850    
1851  Return the list of supported entity types.  =back
1852    
1853  =cut  =cut
1854  #: Return Type @;  
1855  sub GetEntityTypes {  sub GetSynonymGroup {
1856        # Get the parameters.
1857        my ($self, $fid) = @_;
1858        # Declare the return variable.
1859        my $retVal;
1860        # Find the synonym group.
1861        my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1862                                       [$fid], 'IsSynonymGroupFor(from-link)');
1863        # Check to see if we found anything.
1864        if (@groups) {
1865            $retVal = $groups[0];
1866        } else {
1867            $retVal = $fid;
1868        }
1869        # Return the result.
1870        return $retVal;
1871    }
1872    
1873    =head3 GetBoundaries
1874    
1875    C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>
1876    
1877    Determine the begin and end boundaries for the locations in a list. All of the
1878    locations must belong to the same contig and have mostly the same direction in
1879    order for this method to produce a meaningful result. The resulting
1880    begin/end pair will contain all of the bases in any of the locations.
1881    
1882    =over 4
1883    
1884    =item locList
1885    
1886    List of locations to process.
1887    
1888    =item RETURN
1889    
1890    Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1891    and the ending boundary. The beginning boundary will be left of the
1892    end for mostly-forward locations and right of the end for mostly-backward
1893    locations.
1894    
1895    =back
1896    
1897    =cut
1898    
1899    sub GetBoundaries {
1900          # Get the parameters.          # Get the parameters.
1901          my $self = shift @_;      my ($self, @locList) = @_;
1902          # Get the underlying database object.      # Set up the counters used to determine the most popular direction.
1903          my $erdb = $self->{_erdb};      my %counts = ( '+' => 0, '-' => 0 );
1904          # Get its entity type list.      # Get the last location and parse it.
1905          my @retVal = $erdb->GetEntityTypes();      my $locObject = BasicLocation->new(pop @locList);
1906        # Prime the loop with its data.
1907        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
1908        # Count its direction.
1909        $counts{$locObject->Dir}++;
1910        # Loop through the remaining locations. Note that in most situations, this loop
1911        # will not iterate at all, because most of the time we will be dealing with a
1912        # singleton list.
1913        for my $loc (@locList) {
1914            # Create a location object.
1915            my $locObject = BasicLocation->new($loc);
1916            # Count the direction.
1917            $counts{$locObject->Dir}++;
1918            # Get the left end and the right end.
1919            my $left = $locObject->Left;
1920            my $right = $locObject->Right;
1921            # Merge them into the return variables.
1922            if ($left < $beg) {
1923                $beg = $left;
1924            }
1925            if ($right > $end) {
1926                $end = $right;
1927            }
1928        }
1929        # If the most common direction is reverse, flip the begin and end markers.
1930        if ($counts{'-'} > $counts{'+'}) {
1931            ($beg, $end) = ($end, $beg);
1932        }
1933        # Return the result.
1934        return ($contig, $beg, $end);
1935    }
1936    
1937    =head3 CouplingID
1938    
1939    C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >>
1940    
1941    Return the coupling ID for a pair of feature IDs.
1942    
1943    The coupling ID is currently computed by joining the feature IDs in
1944    sorted order with a space. Client modules (that is, modules which
1945    use Sprout) should not, however, count on this always being the
1946    case. This method provides a way for abstracting the concept of a
1947    coupling ID. All that we know for sure about it is that it can be
1948    generated easily from the feature IDs and the order of the IDs
1949    in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>
1950    will have the same value as C<CouplingID("b1", "a1")>.
1951    
1952    =over 4
1953    
1954    =item peg1
1955    
1956    First feature of interest.
1957    
1958    =item peg2
1959    
1960    Second feature of interest.
1961    
1962    =item RETURN
1963    
1964    Returns the ID that would be used to represent a functional coupling of
1965    the two specified PEGs.
1966    
1967    =back
1968    
1969    =cut
1970    #: Return Type $;
1971    sub CouplingID {
1972        my ($self, @pegs) = @_;
1973        return $self->DigestKey(join " ", sort @pegs);
1974  }  }
1975    
1976  =head3 ReadFasta  =head3 ReadFasta
# Line 1395  Line 2017 
2017                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
2018                          # 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.
2019                          if ($id) {                          if ($id) {
2020                                  $retVal{$id} = $sequence;                  $retVal{$id} = lc $sequence;
2021                          }                          }
2022                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
2023                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
2024                  } else {                  } else {
2025                          # 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.
2026                          # First, we get the actual data out.              # First, we get the actual data out. Note that we normalize to lower
2027                # case.
2028                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
2029                          $sequence .= $1;                          $sequence .= $1;
2030                  }                  }
2031          }          }
2032          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
2033          if ($sequence) {          if ($sequence) {
2034                  $retVal {$id} = $sequence;          $retVal{$id} = lc $sequence;
2035          }          }
2036        # Close the file.
2037        close FASTAFILE;
2038          # Return the hash constructed from the file.          # Return the hash constructed from the file.
2039          return %retVal;          return %retVal;
2040  }  }
# Line 1420  Line 2045 
2045    
2046  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
2047  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
2048  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,
2049    it will not be changed; otherwise, it will be converted. This method can also be used to
2050    perform the reverse task-- insuring that all the locations are in the old format.
2051    
2052  =over 4  =over 4
2053    
# Line 1447  Line 2074 
2074  #: Return Type @;  #: Return Type @;
2075  sub FormatLocations {  sub FormatLocations {
2076          # Get the parameters.          # Get the parameters.
2077          my $self = shift @_;      my ($self, $prefix, $locations, $oldFormat) = @_;
         my ($prefix, $locations, $oldFormat) = @_;  
2078          # Create the return list.          # Create the return list.
2079          my @retVal = ();          my @retVal = ();
2080          # Check to see if any locations were passed in.          # Check to see if any locations were passed in.
2081          if ($locations eq '') {          if ($locations eq '') {
2082              confess "No locations specified.";          Confess("No locations specified.");
2083          } else {          } else {
2084                  # Loop through the locations, converting them to the new format.                  # Loop through the locations, converting them to the new format.
2085                  for my $location (@{$locations}) {                  for my $location (@{$locations}) {
# Line 1488  Line 2114 
2114    
2115  sub DumpData {  sub DumpData {
2116          # Get the parameters.          # Get the parameters.
2117          my $self = shift @_;      my ($self) = @_;
2118          # Get the data directory name.          # Get the data directory name.
2119          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
2120          # Dump the relations.          # Dump the relations.
2121          $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2122  }  }
2123    
2124  =head3 XMLFileName  =head3 XMLFileName
# Line 1504  Line 2130 
2130  =cut  =cut
2131  #: Return Type $;  #: Return Type $;
2132  sub XMLFileName {  sub XMLFileName {
2133          my $self = shift @_;      my ($self) = @_;
2134          return $self->{_xmlName};          return $self->{_xmlName};
2135  }  }
2136    
# Line 1524  Line 2150 
2150  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
2151  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>.
2152    
2153  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'}); >>
2154    
2155  =over 4  =over 4
2156    
# Line 1542  Line 2168 
2168  #: Return Type ;  #: Return Type ;
2169  sub Insert {  sub Insert {
2170          # Get the parameters.          # Get the parameters.
2171          my $self = shift @_;      my ($self, $objectType, $fieldHash) = @_;
         my ($objectType, $fieldHash) = @_;  
2172          # Call the underlying method.          # Call the underlying method.
2173          $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2174  }  }
2175    
2176  =head3 Annotate  =head3 Annotate
# Line 1584  Line 2209 
2209  #: Return Type $;  #: Return Type $;
2210  sub Annotate {  sub Annotate {
2211          # Get the parameters.          # Get the parameters.
2212          my $self = shift @_;      my ($self, $fid, $timestamp, $user, $text) = @_;
         my ($fid, $timestamp, $user, $text) = @_;  
2213          # Create the annotation ID.          # Create the annotation ID.
2214          my $aid = "$fid:$timestamp";          my $aid = "$fid:$timestamp";
2215          # Insert the Annotation object.          # Insert the Annotation object.
# Line 1605  Line 2229 
2229    
2230  =head3 AssignFunction  =head3 AssignFunction
2231    
2232  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function); >>  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>
2233    
2234  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
2235  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.  
2236    
2237  =over 4  =over 4
2238    
# Line 1619  Line 2242 
2242    
2243  =item user  =item user
2244    
2245  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>.
2246    
2247  =item function  =item function
2248    
2249  Text of the function being assigned.  Text of the function being assigned.
2250    
2251    =item assigningUser (optional)
2252    
2253    Name of the individual user making the assignment. If omitted, defaults to the user group.
2254    
2255  =item RETURN  =item RETURN
2256    
2257  Returns 1 if successful, 0 if an error occurred.  Returns 1 if successful, 0 if an error occurred.
# Line 1635  Line 2262 
2262  #: Return Type $;  #: Return Type $;
2263  sub AssignFunction {  sub AssignFunction {
2264          # Get the parameters.          # Get the parameters.
2265          my $self = shift @_;      my ($self, $featureID, $user, $function, $assigningUser) = @_;
2266          my ($featureID, $user, $function) = @_;      # Default the assigning user.
2267        if (! $assigningUser) {
2268            $assigningUser = $user;
2269        }
2270          # Create an annotation string from the parameters.          # Create an annotation string from the parameters.
2271          my $annotationText = "$user\nset $user function to\n$function";      my $annotationText = "$assigningUser\nset $user function to\n$function";
2272          # Get the current time.          # Get the current time.
2273          my $now = time;          my $now = time;
2274          # Declare the return variable.          # Declare the return variable.
# Line 1683  Line 2313 
2313  #: Return Type @;  #: Return Type @;
2314  sub FeaturesByAlias {  sub FeaturesByAlias {
2315          # Get the parameters.          # Get the parameters.
2316          my $self = shift @_;      my ($self, $alias) = @_;
         my ($alias) = @_;  
2317          # Declare the return variable.          # Declare the return variable.
2318          my @retVal = ();          my @retVal = ();
2319          # Parse the alias.          # Parse the alias.
# Line 1694  Line 2323 
2323                  push @retVal, $mappedAlias;                  push @retVal, $mappedAlias;
2324          } else {          } else {
2325                  # Here we have a non-FIG alias. Get the features with the normalized alias.                  # Here we have a non-FIG alias. Get the features with the normalized alias.
2326                  @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');          @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');
2327          }      }
2328          # Return the result.      # Return the result.
2329          return @retVal;      return @retVal;
 }  
   
 =head3 Exists  
   
 C<< my $found = $sprout->Exists($entityName, $entityID); >>  
   
 Return TRUE if an entity exists, else FALSE.  
   
 =over 4  
   
 =item entityName  
   
 Name of the entity type (e.g. C<Feature>) relevant to the existence check.  
   
 =item entityID  
   
 ID of the entity instance whose existence is to be checked.  
   
 =item RETURN  
   
 Returns TRUE if the entity instance exists, else FALSE.  
   
 =back  
   
 =cut  
 #: Return Type $;  
 sub Exists {  
         # Get the parameters.  
         my $self = shift @_;  
         my ($entityName, $entityID) = @_;  
         # Check for the entity instance.  
         my $testInstance = $self->GetEntity($entityName, $entityID);  
         # Return an existence indicator.  
         my $retVal = ($testInstance ? 1 : 0);  
         return $retVal;  
2330  }  }
2331    
2332  =head3 FeatureTranslation  =head3 FeatureTranslation
# Line 1757  Line 2351 
2351  #: Return Type $;  #: Return Type $;
2352  sub FeatureTranslation {  sub FeatureTranslation {
2353          # Get the parameters.          # Get the parameters.
2354          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2355          # Get the specified feature's translation.          # Get the specified feature's translation.
2356          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
2357          return $retVal;          return $retVal;
# Line 1790  Line 2383 
2383  #: Return Type @;  #: Return Type @;
2384  sub Taxonomy {  sub Taxonomy {
2385          # Get the parameters.          # Get the parameters.
2386          my $self = shift @_;      my ($self, $genome) = @_;
         my ($genome) = @_;  
2387          # Find the specified genome's taxonomy string.          # Find the specified genome's taxonomy string.
2388          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);
2389          # Declare the return variable.          # Declare the return variable.
# Line 1834  Line 2426 
2426  #: Return Type $;  #: Return Type $;
2427  sub CrudeDistance {  sub CrudeDistance {
2428          # Get the parameters.          # Get the parameters.
2429          my $self = shift @_;      my ($self, $genome1, $genome2) = @_;
         my ($genome1, $genome2) = @_;  
2430          # Insure that the distance is commutative by sorting the genome IDs.          # Insure that the distance is commutative by sorting the genome IDs.
2431          my ($genomeA, $genomeB);          my ($genomeA, $genomeB);
2432          if ($genome2 < $genome2) {          if ($genome2 < $genome2) {
# Line 1882  Line 2473 
2473  #: Return Type $;  #: Return Type $;
2474  sub RoleName {  sub RoleName {
2475          # Get the parameters.          # Get the parameters.
2476          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2477          # Get the specified role's name.          # Get the specified role's name.
2478          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);
2479          # Use the ID if the role has no name.          # Use the ID if the role has no name.
# Line 1916  Line 2506 
2506  #: Return Type @;  #: Return Type @;
2507  sub RoleDiagrams {  sub RoleDiagrams {
2508          # Get the parameters.          # Get the parameters.
2509          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2510          # Query for the diagrams.          # Query for the diagrams.
2511          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2512                                                                  'RoleOccursIn(to-link)');                                                                  'RoleOccursIn(to-link)');
# Line 1925  Line 2514 
2514          return @retVal;          return @retVal;
2515  }  }
2516    
2517    =head3 GetProperties
2518    
2519    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2520    
2521    Return a list of the properties with the specified characteristics.
2522    
2523    Properties are arbitrary key-value pairs associated with a feature. (At some point they
2524    will also be associated with genomes.) A property value is represented by a 4-tuple of
2525    the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2526    
2527    =over 4
2528    
2529    =item fid
2530    
2531    ID of the feature possessing the property.
2532    
2533    =item key
2534    
2535    Name or key of the property.
2536    
2537    =item value
2538    
2539    Value of the property.
2540    
2541    =item url
2542    
2543    URL of the document that indicated the property should have this particular value, or an
2544    empty string if no such document exists.
2545    
2546    =back
2547    
2548    The parameters act as a filter for the desired data. Any non-null parameter will
2549    automatically match all the tuples returned. So, specifying just the I<$fid> will
2550    return all the properties of the specified feature; similarly, specifying the I<$key>
2551    and I<$value> parameters will return all the features having the specified property
2552    value.
2553    
2554    A single property key can have many values, representing different ideas about the
2555    feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2556    virulent, and another may declare that it is not virulent. A query about the virulence of
2557    C<fig|83333.1.peg.10> would be coded as
2558    
2559        my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2560    
2561    Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2562    not to be filtered. The tuples returned would be
2563    
2564        ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2565        ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2566    
2567    =cut
2568    #: Return Type @@;
2569    sub GetProperties {
2570        # Get the parameters.
2571        my ($self, @parms) = @_;
2572        # Declare the return variable.
2573        my @retVal = ();
2574        # Now we need to create a WHERE clause that will get us the data we want. First,
2575        # we create a list of the columns containing the data for each parameter.
2576        my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2577                        'Property(property-value)', 'HasProperty(evidence)');
2578        # Now we build the WHERE clause and the list of parameter values.
2579        my @where = ();
2580        my @values = ();
2581        for (my $i = 0; $i <= $#colNames; $i++) {
2582            my $parm = $parms[$i];
2583            if (defined $parm && ($parm ne '')) {
2584                push @where, "$colNames[$i] = ?";
2585                push @values, $parm;
2586            }
2587        }
2588        # Format the WHERE clause.
2589        my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2590        # Ask for all the propertie values with the desired characteristics.
2591        my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2592        while (my $valueObject = $query->Fetch()) {
2593            my @tuple = $valueObject->Values(\@colNames);
2594            push @retVal, \@tuple;
2595        }
2596        # Return the result.
2597        return @retVal;
2598    }
2599    
2600  =head3 FeatureProperties  =head3 FeatureProperties
2601    
2602  C<< my @properties = $sprout->FeatureProperties($featureID); >>  C<< my @properties = $sprout->FeatureProperties($featureID); >>
# Line 1954  Line 2626 
2626  #: Return Type @@;  #: Return Type @@;
2627  sub FeatureProperties {  sub FeatureProperties {
2628          # Get the parameters.          # Get the parameters.
2629          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2630          # Get the properties.          # Get the properties.
2631          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],
2632                                                          ['Property(property-name)', 'Property(property-value)',                                                          ['Property(property-name)', 'Property(property-value)',
# Line 1986  Line 2657 
2657  #: Return Type $;  #: Return Type $;
2658  sub DiagramName {  sub DiagramName {
2659          # Get the parameters.          # Get the parameters.
2660          my $self = shift @_;      my ($self, $diagramID) = @_;
         my ($diagramID) = @_;  
2661          # Get the specified diagram's name and return it.          # Get the specified diagram's name and return it.
2662          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);
2663          return $retVal;          return $retVal;
# Line 2019  Line 2689 
2689  #: Return Type @;  #: Return Type @;
2690  sub MergedAnnotations {  sub MergedAnnotations {
2691          # Get the parameters.          # Get the parameters.
2692          my $self = shift @_;      my ($self, $list) = @_;
         my ($list) = @_;  
2693          # Create a list to hold the annotation tuples found.          # Create a list to hold the annotation tuples found.
2694          my @tuples = ();          my @tuples = ();
2695          # Loop through the features in the input list.          # Loop through the features in the input list.
# Line 2068  Line 2737 
2737  #: Return Type @;  #: Return Type @;
2738  sub RoleNeighbors {  sub RoleNeighbors {
2739          # Get the parameters.          # Get the parameters.
2740          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2741          # Get all the diagrams containing this role.          # Get all the diagrams containing this role.
2742          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2743                                                                    'RoleOccursIn(to-link)');                                                                    'RoleOccursIn(to-link)');
# Line 2111  Line 2779 
2779  #: Return Type @;  #: Return Type @;
2780  sub FeatureLinks {  sub FeatureLinks {
2781          # Get the parameters.          # Get the parameters.
2782          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2783          # Get the feature's links.          # Get the feature's links.
2784          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);
2785          # Return the feature's links.          # Return the feature's links.
# Line 2124  Line 2791 
2791  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2792    
2793  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
2794  to the role the feature performs.  to the roles the feature performs.
2795    
2796  =over 4  =over 4
2797    
# Line 2134  Line 2801 
2801    
2802  =item RETURN  =item RETURN
2803    
2804  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.
2805    
2806  =back  =back
2807    
2808  =cut  =cut
2809  #: Return Type %;  #: Return Type %@;
2810  sub SubsystemsOf {  sub SubsystemsOf {
2811          # Get the parameters.          # Get the parameters.
2812          my $self = shift @_;      my ($self, $featureID) = @_;
2813          my ($featureID) = @_;      # Get the subsystem list.
         # Use the SSCell to connect features to subsystems.  
2814          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2815                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2816                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2817          # Create the return value.          # Create the return value.
2818          my %retVal = ();          my %retVal = ();
2819        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2820        # in two spreadsheet cells.
2821        my %dupHash = ();
2822          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
2823          for my $record (@subsystems) {          for my $record (@subsystems) {
2824                  $retVal{$record->[0]} = $record->[1];          # Get this subsystem and role.
2825            my ($subsys, $role) = @{$record};
2826            # Insure it's the first time for both.
2827            my $dupKey = "$subsys\n$role";
2828            if (! exists $dupHash{"$subsys\n$role"}) {
2829                $dupHash{$dupKey} = 1;
2830                push @{$retVal{$subsys}}, $role;
2831            }
2832          }          }
2833          # Return the hash.          # Return the hash.
2834          return %retVal;          return %retVal;
2835  }  }
2836    
2837    =head3 SubsystemList
2838    
2839    C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2840    
2841    Return a list containing the names of the subsystems in which the specified
2842    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2843    subsystem names, not the roles.
2844    
2845    =over 4
2846    
2847    =item featureID
2848    
2849    ID of the feature whose subsystem names are desired.
2850    
2851    =item RETURN
2852    
2853    Returns a list of the names of the subsystems in which the feature participates.
2854    
2855    =back
2856    
2857    =cut
2858    #: Return Type @;
2859    sub SubsystemList {
2860        # Get the parameters.
2861        my ($self, $featureID) = @_;
2862        # Get the list of names.
2863        my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",
2864                                    [$featureID], 'HasSSCell(from-link)');
2865        # Return the result.
2866        return @retVal;
2867    }
2868    
2869  =head3 RelatedFeatures  =head3 RelatedFeatures
2870    
2871  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2191  Line 2899 
2899  #: Return Type @;  #: Return Type @;
2900  sub RelatedFeatures {  sub RelatedFeatures {
2901          # Get the parameters.          # Get the parameters.
2902          my $self = shift @_;      my ($self, $featureID, $function, $userID) = @_;
         my ($featureID, $function, $userID) = @_;  
2903          # 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.
2904          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],
2905                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],
# Line 2240  Line 2947 
2947  #: Return Type @;  #: Return Type @;
2948  sub TaxonomySort {  sub TaxonomySort {
2949          # Get the parameters.          # Get the parameters.
2950          my $self = shift @_;      my ($self, $featureIDs) = @_;
         my ($featureIDs) = @_;  
2951          # Create the working hash table.          # Create the working hash table.
2952          my %hashBuffer = ();          my %hashBuffer = ();
2953          # Loop through the features.          # Loop through the features.
# Line 2250  Line 2956 
2956                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
2957                                                                                  [$fid], 'Genome(taxonomy)');                                                                                  [$fid], 'Genome(taxonomy)');
2958                  # Add this feature to the hash buffer.                  # Add this feature to the hash buffer.
2959                  if (exists $hashBuffer{$taxonomy}) {          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);
                         push @{$hashBuffer{$taxonomy}}, $fid;  
                 } else {  
                         $hashBuffer{$taxonomy} = [$fid];  
                 }  
2960          }          }
2961          # Sort the keys and get the elements.          # Sort the keys and get the elements.
2962          my @retVal = ();          my @retVal = ();
# Line 2265  Line 2967 
2967          return @retVal;          return @retVal;
2968  }  }
2969    
 =head3 GetAll  
   
 C<< my @list = $sprout->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>  
   
 Return a list of values taken from the objects returned by a query. The first three  
 parameters correspond to the parameters of the L</Get> method. The final parameter is  
 a list of the fields desired from each record found by the query. The field name  
 syntax is the standard syntax used for fields in the B<ERDB> system--  
 B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity  
 or relationship and I<fieldName> is the name of the field.  
   
 The list returned will be a list of lists. Each element of the list will contain  
 the values returned for the fields specified in the fourth parameter. If one of the  
 fields specified returns multiple values, they are flattened in with the rest. For  
 example, the following call will return a list of the features in a particular  
 spreadsheet cell, and each feature will be represented by a list containing the  
 feature ID followed by all of its aliases.  
   
 C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item fields  
   
 List of the fields to be returned in each element of the list returned.  
   
 =item count  
   
 Maximum number of records to return. If omitted or 0, all available records will be returned.  
   
 =item RETURN  
   
 Returns a list of list references. Each element of the return list contains the values for the  
 fields specified in the B<fields> parameter.  
   
 =back  
   
 =cut  
 #: Return Type @@;  
 sub GetAll {  
         # Get the parameters.  
         my $self = shift @_;  
         my ($objectNames, $filterClause, $parameterList, $fields, $count) = @_;  
         # Create the query.  
         my $query = $self->Get($objectNames, $filterClause, $parameterList);  
         # Set up a counter of the number of records read.  
         my $fetched = 0;  
         # Insure the counter has a value.  
         if (!defined $count) {  
                 $count = 0;  
         }  
         # Loop through the records returned, extracting the fields. Note that if the  
         # counter is non-zero, we stop when the number of records read hits the count.  
         my @retVal = ();  
         while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {  
                 my @rowData = $row->Values($fields);  
                 push @retVal, \@rowData;  
                 $fetched++;  
         }  
         # Return the resulting list.  
         return @retVal;  
 }  
   
 =head3 GetFlat  
   
 C<< my @list = $sprout->GetFlat(\@objectNames, $filterClause, $parameterList, $field); >>  
   
 This is a variation of L</GetAll> that asks for only a single field per record and  
 returns a single flattened list.  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item field  
   
 Name of the field to be used to get the elements of the list returned.  
   
 =item RETURN  
   
 Returns a list of values.  
   
 =back  
   
 =cut  
 #: Return Type @;  
 sub GetFlat {  
         # Get the parameters.  
         my $self = shift @_;  
         my ($objectNames, $filterClause, $parameterList, $field) = @_;  
         # Construct the query.  
         my $query = $self->Get($objectNames, $filterClause, $parameterList);  
         # Create the result list.  
         my @retVal = ();  
         # Loop through the records, adding the field values found to the result list.  
         while (my $row = $query->Fetch()) {  
                 push @retVal, $row->Value($field);  
         }  
         # Return the list created.  
         return @retVal;  
 }  
   
2970  =head3 Protein  =head3 Protein
2971    
2972  C<< my $protein = Sprout::Protein($sequence, $table); >>  C<< my $protein = Sprout::Protein($sequence, $table); >>
# Line 2496  Line 3064 
3064  #: Return Type @;  #: Return Type @;
3065  sub LoadInfo {  sub LoadInfo {
3066          # Get the parameters.          # Get the parameters.
3067          my $self = shift @_;      my ($self) = @_;
3068          # Create the return list, priming it with the name of the data directory.          # Create the return list, priming it with the name of the data directory.
3069          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
3070          # Concatenate the table names.          # Concatenate the table names.
3071          push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
3072          # Return the result.          # Return the result.
3073          return @retVal;          return @retVal;
3074  }  }
3075    
3076  =head3 LowBBHs  =head3 LowBBHs
3077    
3078  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
3079    
3080  Return the bidirectional best hits of a feature whose score is no greater than a  Return the bidirectional best hits of a feature whose score is no greater than a
3081  specified cutoff value. A higher cutoff value will allow inclusion of hits with  specified cutoff value. A higher cutoff value will allow inclusion of hits with
# Line 2533  Line 3101 
3101  #: Return Type %;  #: Return Type %;
3102  sub LowBBHs {  sub LowBBHs {
3103          # Get the parsameters.          # Get the parsameters.
3104          my $self = shift @_;      my ($self, $featureID, $cutoff) = @_;
         my ($featureID, $cutoff) = @_;  
3105          # Create the return hash.          # Create the return hash.
3106          my %retVal = ();          my %retVal = ();
3107          # Create a query to get the desired BBHs.          # Create a query to get the desired BBHs.
# Line 2550  Line 3117 
3117          return %retVal;          return %retVal;
3118  }  }
3119    
3120    =head3 Sims
3121    
3122    C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>
3123    
3124    Get a list of similarities for a specified feature. Similarity information is not kept in the
3125    Sprout database; rather, they are retrieved from a network server. The similarities are
3126    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3127    so that its elements can be accessed by name.
3128    
3129    Similarities can be either raw or expanded. The raw similarities are basic
3130    hits between features with similar DNA. Expanding a raw similarity drags in any
3131    features considered substantially identical. So, for example, if features B<A1>,
3132    B<A2>, and B<A3> are all substatially identical to B<A>, then a raw similarity
3133    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3134    
3135    =over 4
3136    
3137    =item fid
3138    
3139    ID of the feature whose similarities are desired.
3140    
3141    =item maxN
3142    
3143    Maximum number of similarities to return.
3144    
3145    =item maxP
3146    
3147    Minumum allowable similarity score.
3148    
3149    =item select
3150    
3151    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3152    means only similarities to FIG features are returned; C<all> means all expanded
3153    similarities are returned; and C<figx> means similarities are expanded until the
3154    number of FIG features equals the maximum.
3155    
3156    =item max_expand
3157    
3158    The maximum number of features to expand.
3159    
3160    =item filters
3161    
3162    Reference to a hash containing filter information, or a subroutine that can be
3163    used to filter the sims.
3164    
3165    =item RETURN
3166    
3167    Returns a reference to a list of similarity objects, or C<undef> if an error
3168    occurred.
3169    
3170    =back
3171    
3172    =cut
3173    
3174    sub Sims {
3175        # Get the parameters.
3176        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3177        # Create the shim object to test for deleted FIDs.
3178        my $shim = FidCheck->new($self);
3179        # Ask the network for sims.
3180        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3181        # Return the result.
3182        return $retVal;
3183    }
3184    
3185    =head3 GetGroups
3186    
3187    C<< my %groups = $sprout->GetGroups(\@groupList); >>
3188    
3189    Return a hash mapping each group to the IDs of the genomes in the group.
3190    A list of groups may be specified, in which case only those groups will be
3191    shown. Alternatively, if no parameter is supplied, all groups will be
3192    included. Genomes that are not in any group are omitted.
3193    
3194    =cut
3195    #: Return Type %@;
3196    sub GetGroups {
3197        # Get the parameters.
3198        my ($self, $groupList) = @_;
3199        # Declare the return value.
3200        my %retVal = ();
3201        # Determine whether we are getting all the groups or just some.
3202        if (defined $groupList) {
3203            # Here we have a group list. Loop through them individually,
3204            # getting a list of the relevant genomes.
3205            for my $group (@{$groupList}) {
3206                my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",
3207                    [$group], "Genome(id)");
3208                $retVal{$group} = \@genomeIDs;
3209            }
3210        } else {
3211            # Here we need all of the groups. In this case, we run through all
3212            # of the genome records, putting each one found into the appropriate
3213            # group. Note that we use a filter clause to insure that only genomes
3214            # in groups are included in the return set.
3215            my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],
3216                                        ['Genome(id)', 'Genome(group-name)']);
3217            # Loop through the genomes found.
3218            for my $genome (@genomes) {
3219                # Pop this genome's ID off the current list.
3220                my @groups = @{$genome};
3221                my $genomeID = shift @groups;
3222                # Loop through the groups, adding the genome ID to each group's
3223                # list.
3224                for my $group (@groups) {
3225                    Tracer::AddToListMap(\%retVal, $group, $genomeID);
3226                }
3227            }
3228        }
3229        # Return the hash we just built.
3230        return %retVal;
3231    }
3232    
3233    =head3 MyGenomes
3234    
3235    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
3236    
3237    Return a list of the genomes to be included in the Sprout.
3238    
3239    This method is provided for use during the Sprout load. It presumes the Genome load file has
3240    already been created. (It will be in the Sprout data directory and called either C<Genome>
3241    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3242    IDs.
3243    
3244    =over 4
3245    
3246    =item dataDir
3247    
3248    Directory containing the Sprout load files.
3249    
3250    =back
3251    
3252    =cut
3253    #: Return Type @;
3254    sub MyGenomes {
3255        # Get the parameters.
3256        my ($dataDir) = @_;
3257        # Compute the genome file name.
3258        my $genomeFileName = LoadFileName($dataDir, "Genome");
3259        # Extract the genome IDs from the files.
3260        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3261        # Return the result.
3262        return @retVal;
3263    }
3264    
3265    =head3 LoadFileName
3266    
3267    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3268    
3269    Return the name of the load file for the specified table in the specified data
3270    directory.
3271    
3272    =over 4
3273    
3274    =item dataDir
3275    
3276    Directory containing the Sprout load files.
3277    
3278    =item tableName
3279    
3280    Name of the table whose load file is desired.
3281    
3282    =item RETURN
3283    
3284    Returns the name of the file containing the load data for the specified table, or
3285    C<undef> if no load file is present.
3286    
3287    =back
3288    
3289    =cut
3290    #: Return Type $;
3291    sub LoadFileName {
3292        # Get the parameters.
3293        my ($dataDir, $tableName) = @_;
3294        # Declare the return variable.
3295        my $retVal;
3296        # Check for the various file names.
3297        if (-e "$dataDir/$tableName") {
3298            $retVal = "$dataDir/$tableName";
3299        } elsif (-e "$dataDir/$tableName.dtx") {
3300            $retVal = "$dataDir/$tableName.dtx";
3301        }
3302        # Return the result.
3303        return $retVal;
3304    }
3305    
3306    =head3 DeleteGenome
3307    
3308    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3309    
3310    Delete a genome from the database.
3311    
3312    =over 4
3313    
3314    =item genomeID
3315    
3316    ID of the genome to delete
3317    
3318    =item testFlag
3319    
3320    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3321    
3322    =item RETURN
3323    
3324    Returns a statistics object describing the rows deleted.
3325    
3326    =back
3327    
3328    =cut
3329    #: Return Type $%;
3330    sub DeleteGenome {
3331        # Get the parameters.
3332        my ($self, $genomeID, $testFlag) = @_;
3333        # Perform the delete for the genome's features.
3334        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);
3335        # Perform the delete for the primary genome data.
3336        my $stats = $self->Delete('Genome', $genomeID, $testFlag);
3337        $retVal->Accumulate($stats);
3338        # Return the result.
3339        return $retVal;
3340    }
3341    
3342  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3343    
3344  =head3 ParseAssignment  =head3 ParseAssignment
3345    
3346  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,
3347  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
3348  will be returned.  isn't, an empty list will be returned.
3349    
3350    A functional assignment is always of the form
3351    
3352        C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3353    
3354    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3355    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3356    not always the case.
3357    
3358    In addition, the functional role may contain extra data that is stripped, such as
3359    terminating spaces or a comment separated from the rest of the text by a tab.
3360    
3361  This is a static method.  This is a static method.
3362    
3363  =over 4  =over 4
3364    
3365    =item user
3366    
3367    Name of the assigning user.
3368    
3369  =item text  =item text
3370    
3371  Text of the annotation.  Text of the annotation.
# Line 2575  Line 3379 
3379    
3380  =cut  =cut
3381    
3382  sub ParseAssignment {  sub _ParseAssignment {
3383          # Get the parameters.          # Get the parameters.
3384          my ($text) = @_;      my ($user, $text) = @_;
3385          # Declare the return value.          # Declare the return value.
3386          my @retVal = ();          my @retVal = ();
3387          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3388          my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3389          if ($type =~ m/^set $user function to$/i) {      if ($type =~ m/^set function to$/i) {
3390                  # 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.
3391                  @retVal = ($user, $function);                  @retVal = ($user, $function);
3392        } elsif ($type =~ m/^set (\S+) function to$/i) {
3393            # Here we have an assignment with a user that is passed back to the caller.
3394            @retVal = ($1, $function);
3395        }
3396        # If we have an assignment, we need to clean the function text. There may be
3397        # extra junk at the end added as a note from the user.
3398        if (@retVal) {
3399            $retVal[1] =~ s/(\t\S)?\s*$//;
3400          }          }
3401          # Return the result list.          # Return the result list.
3402          return @retVal;          return @retVal;
# Line 2612  Line 3424 
3424    
3425  sub FriendlyTimestamp {  sub FriendlyTimestamp {
3426      my ($timeValue) = @_;      my ($timeValue) = @_;
3427      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
3428      return $retVal;      return $retVal;
3429  }  }
3430    
3431    =head3 AddProperty
3432    
3433    C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>
3434    
3435    Add a new attribute value (Property) to a feature. In the SEED system, attributes can
3436    be added to almost any object. In Sprout, they can only be added to features. In
3437    Sprout, attributes are implemented using I<properties>. A property represents a key/value
3438    pair. If the particular key/value pair coming in is not already in the database, a new
3439    B<Property> record is created to hold it.
3440    
3441    =over 4
3442    
3443    =item peg
3444    
3445    ID of the feature to which the attribute is to be replied.
3446    
3447    =item key
3448    
3449    Name of the attribute (key).
3450    
3451    =item value
3452    
3453    Value of the attribute.
3454    
3455    =item url
3456    
3457    URL or text citation from which the property was obtained.
3458    
3459    =back
3460    
3461    =cut
3462    #: Return Type ;
3463    sub AddProperty {
3464        # Get the parameters.
3465        my ($self, $featureID, $key, $value, $url) = @_;
3466        # Declare the variable to hold the desired property ID.
3467        my $propID;
3468        # Attempt to find a property record for this key/value pair.
3469        my @properties = $self->GetFlat(['Property'],
3470                                       "Property(property-name) = ? AND Property(property-value) = ?",
3471                                       [$key, $value], 'Property(id)');
3472        if (@properties) {
3473            # Here the property is already in the database. We save its ID.
3474            $propID = $properties[0];
3475            # Here the property value does not exist. We need to generate an ID. It will be set
3476            # to a number one greater than the maximum value in the database. This call to
3477            # GetAll will stop after one record.
3478            my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],
3479                                            1);
3480            $propID = $maxProperty[0]->[0] + 1;
3481            # Insert the new property value.
3482            $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });
3483        }
3484        # Now we connect the incoming feature to the property.
3485        $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3486    }
3487    
3488    
3489  1;  1;

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3