[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.6, Wed Jan 26 17:41:53 2005 UTC revision 1.63, Sun Jun 18 07:03:00 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 Stats;          use Stats;
# Line 32  Line 34 
34  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
35  L</dna_seq> returns the DNA sequence for a specified genome location.  L</dna_seq> returns the DNA sequence for a specified genome location.
36    
37    The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.
38    
39  =cut  =cut
40    
41  #: Constructor SFXlate->new_sprout_only();  #: Constructor SFXlate->new_sprout_only();
# Line 62  Line 66 
66    
67  * 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>)
68    
69  * 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)
70    
71  * B<port> connection port (default C<0>)  * B<port> connection port (default C<0>)
72    
73    * B<sock> connection socket (default same as SEED)
74    
75  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
76    
77  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
78    
79    * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
80    
81  =back  =back
82    
83  For example, the following constructor call specifies a database named I<Sprout> and a user name of  For example, the following constructor call specifies a database named I<Sprout> and a user name of
# Line 86  Line 94 
94          # 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
95          # the incoming data.          # the incoming data.
96          my $optionTable = Tracer::GetOptions({          my $optionTable = Tracer::GetOptions({
97                                             dbType               => 'mysql',                     # database type                         dbType       => $FIG_Config::dbms,
98                                             dataDir              => 'Data',                      # data file directory                                                          # database type
99                                             xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
100                                             userData             => 'root/',                     # user name and password                                                          # data file directory
101                                             port                 => 0,                           # database connection port                         xmlFileName  => "$FIG_Config::fig/SproutDBD.xml",
102                                                            # database definition file name
103                           userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
104                                                            # user name and password
105                           port         => $FIG_Config::dbport,
106                                                            # database connection port
107                           sock         => $FIG_Config::dbsock,
108                                             maxSegmentLength => 4500,            # maximum feature segment length                                             maxSegmentLength => 4500,            # maximum feature segment length
109                                             maxSequenceLength => 8000,           # maximum contig sequence length                                             maxSequenceLength => 8000,           # maximum contig sequence length
110                           noDBOpen     => 0,               # 1 to suppress the database open
111                                            }, $options);                                            }, $options);
112          # Get the data directory.          # Get the data directory.
113          my $dataDir = $optionTable->{dataDir};          my $dataDir = $optionTable->{dataDir};
# Line 100  Line 115 
115          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
116          my ($userName, $password) = ($1, $2);          my ($userName, $password) = ($1, $2);
117          # Connect to the database.          # Connect to the database.
118          my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
119        if (! $optionTable->{noDBOpen}) {
120            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
121                                    $password, $optionTable->{port}, undef, $optionTable->{sock});
122        }
123          # Create the ERDB object.          # Create the ERDB object.
124          my $xmlFileName = "$optionTable->{xmlFileName}";          my $xmlFileName = "$optionTable->{xmlFileName}";
125          my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
126          # Create this object.      # Add the option table and XML file name.
127          my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
128          # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
129          bless $self;      # Return it.
130          return $self;      return $retVal;
131  }  }
132    
133  =head3 MaxSegment  =head3 MaxSegment
# Line 124  Line 143 
143  =cut  =cut
144  #: Return Type $;  #: Return Type $;
145  sub MaxSegment {  sub MaxSegment {
146          my $self = shift @_;      my ($self) = @_;
147          return $self->{_options}->{maxSegmentLength};          return $self->{_options}->{maxSegmentLength};
148  }  }
149    
# Line 139  Line 158 
158  =cut  =cut
159  #: Return Type $;  #: Return Type $;
160  sub MaxSequence {  sub MaxSequence {
161          my $self = shift @_;      my ($self) = @_;
162          return $self->{_options}->{maxSequenceLength};          return $self->{_options}->{maxSequenceLength};
163  }  }
164    
165  =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]); >>  
166    
167  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.  
168    
169  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.
170    
171  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
172  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
173  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
174    extension are used in preference to the files with an extension.
175    
176  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
177  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
178  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
179  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.  
180    
181  =over 4  =over 4
182    
183  =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  
184    
185  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
186    
187  =item RETURN  =item RETURN
188    
189  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,
190    the number of errors, and a list of the error messages.
191    
192  =back  =back
193    
194  =cut  =cut
195    #: Return Type %;
196  sub Get {  sub Load {
197          # Get the parameters.          # Get the parameters.
198          my $self = shift @_;      my ($self, $rebuild) = @_;
199          my ($objectNames, $filterClause, $parameterList) = @_;      # Load the tables from the data directory.
200          # 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);
201          # rather than a list of parameters. The next step is to convert the parameters from a reference      # Return the statistics.
202          # 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);  
203  }  }
204    
205  =head3 GetEntity  =head3 LoadUpdate
206    
207  C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
208    
209  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
210    or two tables without reloading the whole database. For each table, there must be a corresponding
211    file in the data directory, either with the same name as the table, or with a C<.dtx> suffix. So,
212    for example, to make updates to the B<FeatureTranslation> relation, there must be a
213    C<FeatureTranslation.dtx> file in the data directory. Unlike a full load, files without an extension
214    are not examined. This allows update files to co-exist with files from an original load.
215    
216  =over 4  =over 4
217    
218  =item entityType  =item truncateFlag
219    
220  Entity type name.  TRUE if the tables should be rebuilt before loading, else FALSE. A value of TRUE therefore causes
221    current data and schema of the tables to be replaced, while a value of FALSE means the new data
222    is added to the existing data in the various relations.
223    
224  =item ID  =item tableList
225    
226  ID of the desired entity.  List of the tables to be updated.
227    
228  =item RETURN  =item RETURN
229    
230  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,
231  instance is found with the specified key.  the number of errors encountered, and a list of error messages.
232    
233  =back  =back
234    
235  =cut  =cut
236    #: Return Type $%;
237  sub GetEntity {  sub LoadUpdate {
238          # Get the parameters.          # Get the parameters.
239          my $self = shift @_;      my ($self, $truncateFlag, $tableList) = @_;
240          my ($entityType, $ID) = @_;      # Declare the return value.
241          # Create a query.      my $retVal = Stats->new();
242          my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);      # Get the data directory.
243          # Get the first (and only) object.      my $optionTable = $self->{_options};
244          my $retVal = $query->Fetch();      my $dataDir = $optionTable->{dataDir};
245          # Return the result.      # Loop through the incoming table names.
246        for my $tableName (@{$tableList}) {
247            # Find the table's file.
248            my $fileName = LoadFileName($dataDir, $tableName);
249            if (! $fileName) {
250                Trace("No load file found for $tableName in $dataDir.") if T(0);
251            } else {
252                # Attempt to load this table.
253                my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);
254                # Accumulate the resulting statistics.
255                $retVal->Accumulate($result);
256            }
257        }
258        # Return the statistics.
259          return $retVal;          return $retVal;
260  }  }
261    
262  =head3 GetEntityValues  =head3 GenomeCounts
263    
264  C<< my @values = GetEntityValues($entityType, $ID, \@fields); >>  C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>
265    
266  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
267    genomes will be included in the counts.
268    
269  =over 4  =over 4
270    
271  =item entityType  =item complete
   
 Entity type name.  
   
 =item ID  
   
 ID of the desired entity.  
272    
273  =item fields  TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
274    counted
 List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.  
275    
276  =item RETURN  =item RETURN
277    
278  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--
279    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
 =back  
   
 =cut  
 #: Return Type @;  
 sub GetEntityValues {  
         # Get the parameters.  
         my $self = shift @_;  
         my ($entityType, $ID, $fields) = @_;  
         # Get the specified entity.  
         my $entity = $self->GetEntity($entityType, $ID);  
         # Declare the return list.  
         my @retVal = ();  
         # If we found the entity, push the values into the return list.  
         if ($entity) {  
                 push @retVal, $entity->Values($fields);  
         }  
         # Return the result.  
         return @retVal;  
 }  
   
 =head3 ShowMetaData  
   
 C<< $sprout->ShowMetaData($fileName); >>  
   
 This method outputs a description of the database to an HTML file in the data directory.  
   
 =over 4  
   
 =item fileName  
   
 Fully-qualified name to give to the output file.  
280    
281  =back  =back
282    
283  =cut  =cut
284    
285  sub ShowMetaData {  sub GenomeCounts {
286          # Get the parameters.          # Get the parameters.
287          my $self = shift @_;      my ($self, $complete) = @_;
288          my ($fileName) = @_;      # Set the filter based on the completeness flag.
289          # Compute the file name.      my $filter = ($complete ? "Genome(complete) = 1" : "");
290          my $options = $self->{_options};      # Get all the genomes and the related taxonomy information.
291          # Call the show method on the underlying ERDB object.      my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
292          $self->{_erdb}->ShowMetaData($fileName);      # Clear the counters.
293        my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
294        # Loop through, counting the domains.
295        for my $genome (@genomes) {
296            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
297            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
298            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
299            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
300            elsif ($genome->[1] =~ /^env/i)      { ++$env }
301            else  { ++$unk }
302        }
303        # Return the counts.
304        return ($arch, $bact, $euk, $vir, $env, $unk);
305  }  }
306    
307  =head3 Load  =head3 ContigCount
   
 C<< $sprout->Load($rebuild); >>;  
   
 Load the database from files in the data directory, optionally re-creating the tables.  
308    
309  This method always deletes the data from the database before loading, even if the tables are not  C<< my $count = $sprout->ContigCount($genomeID); >>
 re-created. The data is loaded into the relations from files in the data directory either having the  
 same name as the target relation with no extension or with an extension of C<.dtx>. Files without an  
 extension are used in preference to the files with an extension.  
310    
311  The files are loaded based on the presumption that each line of the file is a record in the  Return the number of contigs for the specified genome ID.
 relation, and the individual fields are delimited by tabs. Tab and new-line characters inside  
 fields must be represented by the escape sequences C<\t> and C<\n>, respectively. The fields must  
 be presented in the order given in the relation tables produced by the L</ShowMetaData> method.  
312    
313  =over 4  =over 4
314    
315  =item rebuild  =item genomeID
316    
317  TRUE if the data tables need to be created or re-created, else FALSE  ID of the genome whose contig count is desired.
318    
319  =item RETURN  =item RETURN
320    
321  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.  
322    
323  =back  =back
324    
325  =cut  =cut
326  #: Return Type %;  
327  sub Load {  sub ContigCount {
328          # Get the parameters.          # Get the parameters.
329          my $self = shift @_;      my ($self, $genomeID) = @_;
330          my ($rebuild) = @_;      # Get the contig count.
331          # Get the database object.      my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
332          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.  
333          return $retVal;          return $retVal;
334  }  }
335    
336  =head3 LoadUpdate  =head3 GeneMenu
337    
338  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params); >>
339    
340  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,
341  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
342  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.  
343    
344  =over 4  =over 4
345    
346  =item truncateFlag  =item attributes
347    
348  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.  
349    
350  =item tableList  =item filterString
351    
352  List of the tables to be updated.  A filter string for use in selecting the genomes. The filter string must conform
353    to the rules for the C<< ERDB->Get >> method.
354    
355    =item params
356    
357    Reference to a list of values to be substituted in for the parameter marks in
358    the filter string.
359    
360  =item RETURN  =item RETURN
361    
362  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.  
363    
364  =back  =back
365    
366  =cut  =cut
367  #: Return Type %;  
368  sub LoadUpdate {  sub GeneMenu {
369          # Get the parameters.          # Get the parameters.
370          my $self = shift @_;      my ($self, $attributes, $filterString, $params) = @_;
371          my ($truncateFlag, $tableList) = @_;      # Start the menu.
372          # Get the database object.      my $retVal = "<select " .
373          my $erdb = $self->{_erdb};          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
374          # Declare the return value.          ">\n";
375          my $retVal = Stats->new();      # Get the genomes.
376          # Get the data directory.      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
377          my $optionTable = $self->{_options};                                                                       'Genome(genus)',
378          my $dataDir = $optionTable->{dataDir};                                                                       'Genome(species)']);
379          # Loop through the incoming table names.      # Sort them by name.
380          for my $tableName (@{$tableList}) {      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
381                  # Find the table's file.      # Loop through the genomes, creating the option tags.
382                  my $fileName = "$dataDir/$tableName";      for my $genomeData (@sorted) {
383                  if (! -e $fileName) {          # Get the data for this genome.
384                          $fileName = "$fileName.dtx";          my ($genomeID, $genus, $species) = @{$genomeData};
385            # Get the contig count.
386            my $count = $self->ContigCount($genomeID);
387            my $counting = ($count == 1 ? "contig" : "contigs");
388            # Build the option tag.
389            $retVal .= "<option value=\"$genomeID\">$genus $species ($genomeID) [$count $counting]</option>\n";
390                  }                  }
391                  # Attempt to load this table.      # Close the SELECT tag.
392                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);      $retVal .= "</select>\n";
393                  # Accumulate the resulting statistics.      # Return the result.
                 $retVal->Accumulate($result);  
         }  
         # Return the statistics.  
394          return $retVal;          return $retVal;
395  }  }
   
396  =head3 Build  =head3 Build
397    
398  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 463  Line 405 
405  #: Return Type ;  #: Return Type ;
406  sub Build {  sub Build {
407          # Get the parameters.          # Get the parameters.
408          my $self = shift @_;      my ($self) = @_;
409          # Create the tables.          # Create the tables.
410          $self->{_erdb}->CreateTables;      $self->CreateTables();
411  }  }
412    
413  =head3 Genomes  =head3 Genomes
# Line 478  Line 420 
420  #: Return Type @;  #: Return Type @;
421  sub Genomes {  sub Genomes {
422          # Get the parameters.          # Get the parameters.
423          my $self = shift @_;      my ($self) = @_;
424          # Get all the genomes.          # Get all the genomes.
425          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');
426          # Return the list of IDs.          # Return the list of IDs.
# Line 508  Line 450 
450  #: Return Type $;  #: Return Type $;
451  sub GenusSpecies {  sub GenusSpecies {
452          # Get the parameters.          # Get the parameters.
453          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
454          # Get the data for the specified genome.          # Get the data for the specified genome.
455          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',
456                                                                                                                            'Genome(unique-characterization)']);                                                                                                                            'Genome(unique-characterization)']);
# Line 545  Line 486 
486  #: Return Type @;  #: Return Type @;
487  sub FeaturesOf {  sub FeaturesOf {
488          # Get the parameters.          # Get the parameters.
489          my $self = shift @_;      my ($self, $genomeID,$ftype) = @_;
         my ($genomeID,$ftype) = @_;  
490          # Get the features we want.          # Get the features we want.
491          my @features;          my @features;
492          if (!$ftype) {          if (!$ftype) {
# Line 590  Line 530 
530  =item RETURN  =item RETURN
531    
532  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
533  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context.
534    
535  =back  =back
536    
# Line 599  Line 539 
539  #: Return Type $;  #: Return Type $;
540  sub FeatureLocation {  sub FeatureLocation {
541          # Get the parameters.          # Get the parameters.
542          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
543          # Create a query for the feature locations.          # Create a query for the feature locations.
544          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",
545                                                     [$featureID]);                                                     [$featureID]);
# Line 618  Line 557 
557                  if ($prevContig eq $contigID && $dir eq $prevDir) {                  if ($prevContig eq $contigID && $dir eq $prevDir) {
558                          # 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
559                          # new segment's beginning is next to the old segment's end.                          # new segment's beginning is next to the old segment's end.
560                          if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||              if ($dir eq "-" && $beg + $len == $prevBeg) {
561                                  ($dir eq "+" && $beg == $prevBeg + $prevLen)) {                  # Here we're merging two backward blocks, so we keep the new begin point
562                                  # Here we need to merge two segments. Adjust the beginning and length values                  # and adjust the length.
563                                  # to include both segments.                  $len += $prevLen;
564                    # Pop the old segment off. The new one will replace it later.
565                    pop @retVal;
566                } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
567                    # Here we need to merge two forward blocks. Adjust the beginning and
568                    # length values to include both segments.
569                                  $beg = $prevBeg;                                  $beg = $prevBeg;
570                                  $len += $prevLen;                                  $len += $prevLen;
571                                  # 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 630  Line 574 
574                  }                  }
575                  # Remember this specifier for the adjacent-segment test the next time through.                  # Remember this specifier for the adjacent-segment test the next time through.
576                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
577            # Compute the initial base pair.
578            my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
579                  # Add the specifier to the list.                  # Add the specifier to the list.
580                  push @retVal, "${contigID}_$beg$dir$len";          push @retVal, "${contigID}_$start$dir$len";
581          }          }
582          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
583          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
584  }  }
585    
586  =head3 ParseLocation  =head3 ParseLocation
# Line 660  Line 606 
606  =cut  =cut
607  #: Return Type @;  #: Return Type @;
608  sub ParseLocation {  sub ParseLocation {
609          # Get the parameter.      # Get the parameter. Note that if we're called as an instance method, we ignore
610        # the first parameter.
611        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
612          my ($location) = @_;          my ($location) = @_;
613          # Parse it into segments.          # Parse it into segments.
614          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
615          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
616          # If the direction is an underscore, convert it to a + or -.          # If the direction is an underscore, convert it to a + or -.
617          if ($dir eq "_") {          if ($dir eq "_") {
# Line 679  Line 627 
627          return ($contigID, $start, $dir, $len);          return ($contigID, $start, $dir, $len);
628  }  }
629    
630    =head3 PointLocation
631    
632    C<< my $found = Sprout::PointLocation($location, $point); >>
633    
634    Return the offset into the specified location of the specified point on the contig. If
635    the specified point is before the location, a negative value will be returned. If it is
636    beyond the location, an undefined value will be returned. It is assumed that the offset
637    is for the location's contig. The location can either be new-style (using a C<+> or C<->
638    and a length) or old-style (using C<_> and start and end positions.
639    
640    =over 4
641    
642    =item location
643    
644    A location specifier (see L</FeatureLocation> for a description).
645    
646    =item point
647    
648    The offset into the contig of the point in which we're interested.
649    
650    =item RETURN
651    
652    Returns the offset inside the specified location of the specified point, a negative
653    number if the point is before the location, or an undefined value if the point is past
654    the location. If the length of the location is 0, this method will B<always> denote
655    that it is outside the location. The offset will always be relative to the left-most
656    position in the location.
657    
658    =back
659    
660    =cut
661    #: Return Type $;
662    sub PointLocation {
663        # Get the parameter. Note that if we're called as an instance method, we ignore
664        # the first parameter.
665        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
666        my ($location, $point) = @_;
667        # Parse out the location elements. Note that this works on both old-style and new-style
668        # locations.
669        my ($contigID, $start, $dir, $len) = ParseLocation($location);
670        # Declare the return variable.
671        my $retVal;
672        # Compute the offset. The computation is dependent on the direction of the location.
673        my $offset = (($dir == '+') ? $point - $start : $point - ($start - $len + 1));
674        # Return the offset if it's valid.
675        if ($offset < $len) {
676            $retVal = $offset;
677        }
678        # Return the offset found.
679        return $retVal;
680    }
681    
682  =head3 DNASeq  =head3 DNASeq
683    
684  C<< my $sequence = $sprout->DNASeq(\@locationList); >>  C<< my $sequence = $sprout->DNASeq(\@locationList); >>
# Line 687  Line 687 
687  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,
688  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>.
689    
690    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
691    between positions 1401 and 1532, inclusive.
692    
693        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
694    
695  =over 4  =over 4
696    
697  =item locationList  =item locationList
698    
699  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
700  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
701    
702  =item RETURN  =item RETURN
703    
# Line 704  Line 709 
709  #: Return Type $;  #: Return Type $;
710  sub DNASeq {  sub DNASeq {
711          # Get the parameters.          # Get the parameters.
712          my $self = shift @_;      my ($self, $locationList) = @_;
         my ($locationList) = @_;  
713          # Create the return string.          # Create the return string.
714          my $retVal = "";          my $retVal = "";
715          # Loop through the locations.          # Loop through the locations.
# Line 720  Line 724 
724                  # 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
725                  # before putting it in the return value.                  # before putting it in the return value.
726                  my ($start, $stop);                  my ($start, $stop);
727            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
728                  if ($dir eq "+") {                  if ($dir eq "+") {
729                          $start = $beg;                          $start = $beg;
730                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
731                  } else {                  } else {
732                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
733                          $stop = $beg;                          $stop = $beg;
734                  }                  }
735            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
736                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
737                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
738                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 738  Line 744 
744                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
745                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
746                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
747                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
748                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
749                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
750                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
751                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
752                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
753                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
754                  }                  }
755                  # 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.
756                  if ($dir eq '+') {                  if ($dir eq '+') {
757                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
758                  } else {                  } else {
759                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
760                  }                  }
761          }          }
762          # Return the result.          # Return the result.
# Line 778  Line 785 
785  #: Return Type @;  #: Return Type @;
786  sub AllContigs {  sub AllContigs {
787          # Get the parameters.          # Get the parameters.
788          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
789          # Ask for the genome's Contigs.          # Ask for the genome's Contigs.
790          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],
791                                                                  'HasContig(to-link)');                                                                  'HasContig(to-link)');
# Line 787  Line 793 
793          return @retVal;          return @retVal;
794  }  }
795    
796    =head3 GenomeLength
797    
798    C<< my $length = $sprout->GenomeLength($genomeID); >>
799    
800    Return the length of the specified genome in base pairs.
801    
802    =over 4
803    
804    =item genomeID
805    
806    ID of the genome whose base pair count is desired.
807    
808    =item RETURN
809    
810    Returns the number of base pairs in all the contigs of the specified
811    genome.
812    
813    =back
814    
815    =cut
816    
817    sub GenomeLength {
818        # Get the parameters.
819        my ($self, $genomeID) = @_;
820        # Declare the return variable.
821        my $retVal = 0;
822        # Get the genome's contig sequence lengths.
823        my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
824                           [$genomeID], 'IsMadeUpOf(len)');
825        # Sum the lengths.
826        map { $retVal += $_ } @lens;
827        # Return the result.
828        return $retVal;
829    }
830    
831    =head3 FeatureCount
832    
833    C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
834    
835    Return the number of features of the specified type in the specified genome.
836    
837    =over 4
838    
839    =genomeID
840    
841    ID of the genome whose feature count is desired.
842    
843    =item type
844    
845    Type of feature to count (eg. C<peg>, C<rna>, etc.).
846    
847    =item RETURN
848    
849    Returns the number of features of the specified type for the specified genome.
850    
851    =back
852    
853    =cut
854    
855    sub FeatureCount {
856        # Get the parameters.
857        my ($self, $genomeID, $type) = @_;
858        # Compute the count.
859        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
860                                    "HasFeature(from-link) = ? AND Feature(type) = ?",
861                                    [$genomeID, $type]);
862        # Return the result.
863        return $retVal;
864    }
865    
866    =head3 GenomeAssignments
867    
868    C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
869    
870    Return a list of a genome's assigned features. The return hash will contain each
871    assigned feature of the genome mapped to the text of its most recent functional
872    assignment.
873    
874    =over 4
875    
876    =item genomeID
877    
878    ID of the genome whose functional assignments are desired.
879    
880    =item RETURN
881    
882    Returns a reference to a hash which maps each feature to its most recent
883    functional assignment.
884    
885    =back
886    
887    =cut
888    
889    sub GenomeAssignments {
890        # Get the parameters.
891        my ($self, $genomeID) = @_;
892        # Declare the return variable.
893        my $retVal = {};
894        # Query the genome's features and annotations. We'll put the oldest annotations
895        # first so that the last assignment to go into the hash will be the correct one.
896        my $query = $self->Get(['HasFeature', 'IsTargetOfAnnotation', 'Annotation'],
897                               "HasFeature(from-link) = ? ORDER BY Annotation(time)",
898                               [$genomeID]);
899        # Loop through the annotations.
900        while (my $data = $query->Fetch) {
901            # Get the feature ID and annotation text.
902            my ($fid, $annotation) = $data->Values(['HasFeature(from-link)',
903                                                    'Annotation(text)']);
904            # Check to see if this is an assignment. Note that the user really
905            # doesn't matter to us, other than we use it to determine whether or
906            # not this is an assignment.
907            my ($user, $assignment) = $self->_ParseAssignment('fig', $annotation);
908            if ($user) {
909                # Here it's an assignment. We put it in the return hash, overwriting
910                # any older assignment that might be present.
911                $retVal->{$fid} = $assignment;
912            }
913        }
914        # Return the result.
915        return $retVal;
916    }
917    
918  =head3 ContigLength  =head3 ContigLength
919    
920  C<< my $length = $sprout->ContigLength($contigID); >>  C<< my $length = $sprout->ContigLength($contigID); >>
# Line 809  Line 937 
937  #: Return Type $;  #: Return Type $;
938  sub ContigLength {  sub ContigLength {
939          # Get the parameters.          # Get the parameters.
940          my $self = shift @_;      my ($self, $contigID) = @_;
         my ($contigID) = @_;  
941          # Get the contig's last sequence.          # Get the contig's last sequence.
942          my $query = $self->Get(['IsMadeUpOf'],          my $query = $self->Get(['IsMadeUpOf'],
943                  "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",                  "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
# Line 821  Line 948 
948          # Set it from the sequence data, if any.          # Set it from the sequence data, if any.
949          if ($sequence) {          if ($sequence) {
950                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
951                  $retVal = $start + $len;          $retVal = $start + $len - 1;
952        }
953        # Return the result.
954        return $retVal;
955    }
956    
957    =head3 ClusterPEGs
958    
959    C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
960    
961    Cluster the PEGs in a list according to the cluster coding scheme of the specified
962    subsystem. In order for this to work properly, the subsystem object must have
963    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
964    This causes the cluster numbers to be pulled into the subsystem's color hash.
965    If a PEG is not found in the color hash, it will not appear in the output
966    sequence.
967    
968    =over 4
969    
970    =item sub
971    
972    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
973    method.
974    
975    =item pegs
976    
977    Reference to the list of PEGs to be clustered.
978    
979    =item RETURN
980    
981    Returns a list of the PEGs, grouped into smaller lists by cluster number.
982    
983    =back
984    
985    =cut
986    #: Return Type $@@;
987    sub ClusterPEGs {
988        # Get the parameters.
989        my ($self, $sub, $pegs) = @_;
990        # Declare the return variable.
991        my $retVal = [];
992        # Loop through the PEGs, creating arrays for each cluster.
993        for my $pegID (@{$pegs}) {
994            my $clusterNumber = $sub->get_cluster_number($pegID);
995            # Only proceed if the PEG is in a cluster.
996            if ($clusterNumber >= 0) {
997                # Push this PEG onto the sub-list for the specified cluster number.
998                push @{$retVal->[$clusterNumber]}, $pegID;
999            }
1000          }          }
1001          # Return the result.          # Return the result.
1002          return $retVal;          return $retVal;
# Line 852  Line 1027 
1027  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
1028  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
1029  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
1030  the start and stop values.  the start and stop values. The first element (that is, the list of features) is sorted
1031    roughly by location.
1032    
1033  =back  =back
1034    
1035  =cut  =cut
1036  #: Return Type @;  #: Return Type @@;
1037  sub GenesInRegion {  sub GenesInRegion {
1038          # Get the parameters.          # Get the parameters.
1039          my $self = shift @_;      my ($self, $contigID, $start, $stop) = @_;
         my ($contigID, $start, $stop) = @_;  
1040          # Get the maximum segment length.          # Get the maximum segment length.
1041          my $maximumSegmentLength = $self->MaxSegment;          my $maximumSegmentLength = $self->MaxSegment;
1042          # 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
1043          # duplicates easily.      # duplicates easily. The hash key will be the feature ID. The value will be a two-element
1044        # containing the minimum and maximum offsets. We will use the offsets to sort the results
1045        # when we're building the result set.
1046          my %featuresFound = ();          my %featuresFound = ();
1047          # Prime the values we'll use for the returned beginning and end.          # Prime the values we'll use for the returned beginning and end.
1048          my ($min, $max) = ($self->ContigLength($contigID), 0);      my @initialMinMax = ($self->ContigLength($contigID), 0);
1049        my ($min, $max) = @initialMinMax;
1050          # 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
1051          # 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,
1052          # 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 898  Line 1076 
1076                                          $found = 1;                                          $found = 1;
1077                                  }                                  }
1078                          } elsif ($dir eq '-') {                          } elsif ($dir eq '-') {
1079                                  $end = $beg - $len;                  # Note we switch things around so that the beginning is to the left of the
1080                                  if ($end <= $stop) {                  # ending.
1081                    ($beg, $end) = ($beg - $len, $beg);
1082                    if ($beg <= $stop) {
1083                                          # Denote we found a useful feature.                                          # Denote we found a useful feature.
1084                                          $found = 1;                                          $found = 1;
1085                                  }                                  }
1086                          }                          }
1087                          if ($found) {                          if ($found) {
1088                                  # 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,
1089                                  $featuresFound{$featureID} = 1;                  # get the current entry for the specified feature.
1090                                  if ($beg < $min) { $min = $beg; }                  my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :
1091                                  if ($end < $min) { $min = $end; }                                       @initialMinMax);
1092                                  if ($beg > $max) { $max = $beg; }                  # Merge the current segment's begin and end into the feature begin and end and the
1093                                  if ($end > $max) { $max = $end; }                  # global min and max.
1094                    if ($beg < $loc1) {
1095                        $loc1 = $beg;
1096                        $min = $beg if $beg < $min;
1097                    }
1098                    if ($end > $loc2) {
1099                        $loc2 = $end;
1100                        $max = $end if $end > $max;
1101                    }
1102                    # Store the entry back into the hash table.
1103                    $featuresFound{$featureID} = [$loc1, $loc2];
1104                          }                          }
1105                  }                  }
1106          }          }
1107          # 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
1108          my @list = (sort (keys %featuresFound));      # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1109        # but the result of the sort will be the same.)
1110        my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;
1111        # Now we sort by midpoint and yank out the feature IDs.
1112        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1113          # Return it along with the min and max.          # Return it along with the min and max.
1114          return (\@list, $min, $max);      return (\@retVal, $min, $max);
1115  }  }
1116    
1117  =head3 FType  =head3 FType
# Line 943  Line 1137 
1137  #: Return Type $;  #: Return Type $;
1138  sub FType {  sub FType {
1139          # Get the parameters.          # Get the parameters.
1140          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1141          # Get the specified feature's type.          # Get the specified feature's type.
1142          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
1143          # Return the result.          # Return the result.
# Line 953  Line 1146 
1146    
1147  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1148    
1149  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1150    
1151  Return the annotations of a feature.  Return the annotations of a feature.
1152    
# Line 963  Line 1156 
1156    
1157  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1158    
1159    =item rawFlag
1160    
1161    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1162    will be returned in human-readable form.
1163    
1164  =item RETURN  =item RETURN
1165    
1166  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.
1167    
1168  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1169    
1170  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1171    
1172  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1173    
# Line 981  Line 1179 
1179  #: Return Type @%;  #: Return Type @%;
1180  sub FeatureAnnotations {  sub FeatureAnnotations {
1181          # Get the parameters.          # Get the parameters.
1182          my $self = shift @_;      my ($self, $featureID, $rawFlag) = @_;
         my ($featureID) = @_;  
1183          # 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.
1184          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1185                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 995  Line 1192 
1192                          $annotation->Values(['IsTargetOfAnnotation(from-link)',                          $annotation->Values(['IsTargetOfAnnotation(from-link)',
1193                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1194                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1195            # Convert the time, if necessary.
1196            if (! $rawFlag) {
1197                $timeStamp = FriendlyTimestamp($timeStamp);
1198            }
1199                  # Assemble them into a hash.                  # Assemble them into a hash.
1200          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1201                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1202                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1203                  # Add it to the return list.                  # Add it to the return list.
1204                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1011  Line 1212 
1212  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>
1213    
1214  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
1215  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,
1216  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
1217  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,
1218  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.
1219  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
1220  functional assignments, we will only keep the most recent one.  recent one.
1221    
1222  =over 4  =over 4
1223    
# Line 1026  Line 1227 
1227    
1228  =item RETURN  =item RETURN
1229    
1230  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1231    
1232  =back  =back
1233    
# Line 1034  Line 1235 
1235  #: Return Type %;  #: Return Type %;
1236  sub AllFunctionsOf {  sub AllFunctionsOf {
1237          # Get the parameters.          # Get the parameters.
1238          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1239          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1240      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1241                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1242                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1243                                               'MadeAnnotation(from-link)']);
1244          # Declare the return hash.          # Declare the return hash.
1245          my %retVal;          my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1246      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1247      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1248          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1249      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1250          # Get the annotation fields.          # Get the annotation fields.
1251          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1252                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1253                  my ($user, $function) = ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1254          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1255              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1256              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1257              # return hash.              # return hash.
1258                          $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1259                  }                  }
1260          }          }
1261          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1073  Line 1270 
1270    
1271  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
1272  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
1273  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
1274  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
1275  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
1276  is not a big problem because most features only have a small number of annotations.  most features only have a small number of annotations.
1277    
1278  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
1279  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 1108  Line 1305 
1305  #: Return Type $;  #: Return Type $;
1306  sub FunctionOf {  sub FunctionOf {
1307          # Get the parameters.          # Get the parameters.
1308          my $self = shift @_;      my ($self, $featureID, $userID) = @_;
         my ($featureID, $userID) = @_;  
1309      # Declare the return value.      # Declare the return value.
1310      my $retVal;      my $retVal;
1311      # Determine the ID type.      # Determine the ID type.
# Line 1137  Line 1333 
1333              }              }
1334          }          }
1335          # 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.
1336          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1337                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1338                                 [$featureID]);                                 [$featureID]);
1339          my $timeSelected = 0;          my $timeSelected = 0;
1340          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1341          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1342              # Get the annotation text.              # Get the annotation text.
1343              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);              my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1344                                                         'Annotation(time)', 'MadeAnnotation(from-link)']);
1345              # 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.
1346              my ($user, $type, $function) = split(/\n/, $text);              my ($actualUser, $function) = _ParseAssignment($user, $text);
1347              if ($type =~ m/^set $user function to$/i) {              Trace("Assignment user is $actualUser, text is $function.") if T(4);
1348                if ($actualUser) {
1349                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1350                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1351                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                  if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1352                      $retVal = $function;                      $retVal = $function;
1353                      $timeSelected = $time;                      $timeSelected = $time;
1354                  }                  }
# Line 1166  Line 1364 
1364          return $retVal;          return $retVal;
1365  }  }
1366    
1367    =head3 FunctionsOf
1368    
1369    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1370    
1371    Return the functional assignments of a particular feature.
1372    
1373    The functional assignment is handled differently depending on the type of feature. If
1374    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1375    assignment is a type of annotation. The format of an assignment is described in
1376    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1377    annotation itself because it's a text field; however, this is not a big problem because
1378    most features only have a small number of annotations.
1379    
1380    If the feature is B<not> identified by a FIG ID, then the functional assignment
1381    information is taken from the B<ExternalAliasFunc> table. If the table does
1382    not contain an entry for the feature, an empty list is returned.
1383    
1384    =over 4
1385    
1386    =item featureID
1387    
1388    ID of the feature whose functional assignments are desired.
1389    
1390    =item RETURN
1391    
1392    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1393    that user.
1394    
1395    =back
1396    
1397    =cut
1398    #: Return Type @@;
1399    sub FunctionsOf {
1400        # Get the parameters.
1401        my ($self, $featureID) = @_;
1402        # Declare the return value.
1403        my @retVal = ();
1404        # Determine the ID type.
1405        if ($featureID =~ m/^fig\|/) {
1406            # Here we have a FIG feature ID. We must build the list of trusted
1407            # users.
1408            my %trusteeTable = ();
1409            # Build a query for all of the feature's annotations, sorted by date.
1410            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1411                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1412                                   [$featureID]);
1413            my $timeSelected = 0;
1414            # Loop until we run out of annotations.
1415            while (my $annotation = $query->Fetch()) {
1416                # Get the annotation text.
1417                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1418                                                                'Annotation(time)',
1419                                                                'MadeAnnotation(user)']);
1420                # Check to see if this is a functional assignment for a trusted user.
1421                my ($actualUser, $function) = _ParseAssignment($user, $text);
1422                if ($actualUser) {
1423                    # Here it is a functional assignment.
1424                    push @retVal, [$actualUser, $function];
1425                }
1426            }
1427        } else {
1428            # Here we have a non-FIG feature ID. In this case the user ID does not
1429            # matter. We simply get the information from the External Alias Function
1430            # table.
1431            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1432                                                     ['ExternalAliasFunc(func)']);
1433            push @retVal, map { ['master', $_] } @assignments;
1434        }
1435        # Return the assignments found.
1436        return @retVal;
1437    }
1438    
1439  =head3 BBHList  =head3 BBHList
1440    
1441  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1185  Line 1455 
1455    
1456  =item RETURN  =item RETURN
1457    
1458  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
1459  their best hits.  on the target genome.
1460    
1461  =back  =back
1462    
# Line 1194  Line 1464 
1464  #: Return Type %;  #: Return Type %;
1465  sub BBHList {  sub BBHList {
1466          # Get the parameters.          # Get the parameters.
1467          my $self = shift @_;      my ($self, $genomeID, $featureList) = @_;
         my ($genomeID, $featureList) = @_;  
1468          # Create the return structure.          # Create the return structure.
1469          my %retVal = ();          my %retVal = ();
1470          # Loop through the incoming features.          # Loop through the incoming features.
# Line 1204  Line 1473 
1473                  my $query = $self->Get(['IsBidirectionalBestHitOf'],                  my $query = $self->Get(['IsBidirectionalBestHitOf'],
1474                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",
1475                                                             [$featureID, $genomeID]);                                                             [$featureID, $genomeID]);
1476                  # Look for the best hit.          # Peel off the BBHs found.
1477                  my $bbh = $query->Fetch;          my @found = ();
1478                  if ($bbh) {          while (my $bbh = $query->Fetch) {
1479                          my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');
                         $retVal{$featureID} = $targetFeature;  
1480                  }                  }
1481            $retVal{$featureID} = \@found;
1482          }          }
1483          # Return the mapping.          # Return the mapping.
1484          return \%retVal;          return \%retVal;
1485  }  }
1486    
1487    =head3 SimList
1488    
1489    C<< my %similarities = $sprout->SimList($featureID, $count); >>
1490    
1491    Return a list of the similarities to the specified feature.
1492    
1493    Sprout does not support real similarities, so this method just returns the bidirectional
1494    best hits.
1495    
1496    =over 4
1497    
1498    =item featureID
1499    
1500    ID of the feature whose similarities are desired.
1501    
1502    =item count
1503    
1504    Maximum number of similar features to be returned, or C<0> to return them all.
1505    
1506    =back
1507    
1508    =cut
1509    #: Return Type %;
1510    sub SimList {
1511        # Get the parameters.
1512        my ($self, $featureID, $count) = @_;
1513        # Ask for the best hits.
1514        my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],
1515                                  "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",
1516                                  [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],
1517                                  $count);
1518        # Create the return value.
1519        my %retVal = ();
1520        for my $tuple (@lists) {
1521            $retVal{$tuple->[0]} = $tuple->[1];
1522        }
1523        # Return the result.
1524        return %retVal;
1525    }
1526    
1527    
1528    
1529    =head3 IsComplete
1530    
1531    C<< my $flag = $sprout->IsComplete($genomeID); >>
1532    
1533    Return TRUE if the specified genome is complete, else FALSE.
1534    
1535    =over 4
1536    
1537    =item genomeID
1538    
1539    ID of the genome whose completeness status is desired.
1540    
1541    =item RETURN
1542    
1543    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1544    not found.
1545    
1546    =back
1547    
1548    =cut
1549    #: Return Type $;
1550    sub IsComplete {
1551        # Get the parameters.
1552        my ($self, $genomeID) = @_;
1553        # Declare the return variable.
1554        my $retVal;
1555        # Get the genome's data.
1556        my $genomeData = $self->GetEntity('Genome', $genomeID);
1557        if ($genomeData) {
1558            # The genome exists, so get the completeness flag.
1559            ($retVal) = $genomeData->Value('Genome(complete)');
1560        }
1561        # Return the result.
1562        return $retVal;
1563    }
1564    
1565  =head3 FeatureAliases  =head3 FeatureAliases
1566    
1567  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
# Line 1238  Line 1585 
1585  #: Return Type @;  #: Return Type @;
1586  sub FeatureAliases {  sub FeatureAliases {
1587          # Get the parameters.          # Get the parameters.
1588          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1589          # Get the desired feature's aliases          # Get the desired feature's aliases
1590          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);
1591          # Return the result.          # Return the result.
# Line 1250  Line 1596 
1596    
1597  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1598    
1599  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1600    
1601  =over 4  =over 4
1602    
1603  =item featureID  =item featureID
1604    
1605  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1606    
1607  =item RETURN  =item RETURN
1608    
1609  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
1610  an undefined value.  found, returns an undefined value.
1611    
1612  =back  =back
1613    
# Line 1269  Line 1615 
1615  #: Return Type $;  #: Return Type $;
1616  sub GenomeOf {  sub GenomeOf {
1617          # Get the parameters.          # Get the parameters.
1618          my $self = shift @_;      my ($self, $featureID) = @_;
1619          my ($featureID) = @_;      # Create a query to find the genome associated with the incoming ID.
1620          # Create a query to find the genome associated with the feature.      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1621          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);                             [$featureID, $featureID]);
1622          # Declare the return value.          # Declare the return value.
1623          my $retVal;          my $retVal;
1624          # Get the genome ID.          # Get the genome ID.
# Line 1296  Line 1642 
1642    
1643  ID of the feature whose functionally-coupled brethren are desired.  ID of the feature whose functionally-coupled brethren are desired.
1644    
1645  =item RETURN  =item RETURN
1646    
1647    A hash mapping the functionally-coupled feature IDs to the coupling score.
1648    
1649    =back
1650    
1651    =cut
1652    #: Return Type %;
1653    sub CoupledFeatures {
1654        # Get the parameters.
1655        my ($self, $featureID) = @_;
1656        # Create a query to retrieve the functionally-coupled features.
1657        my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1658                               "ParticipatesInCoupling(from-link) = ?", [$featureID]);
1659        # This value will be set to TRUE if we find at least one coupled feature.
1660        my $found = 0;
1661        # Create the return hash.
1662        my %retVal = ();
1663        # Retrieve the relationship records and store them in the hash.
1664        while (my $clustering = $query->Fetch()) {
1665            # Get the ID and score of the coupling.
1666            my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1667                                                            'Coupling(score)']);
1668            # Get the other feature that participates in the coupling.
1669            my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],
1670                                               "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",
1671                                               [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');
1672            # Attach the other feature's score to its ID.
1673            $retVal{$otherFeatureID} = $score;
1674            $found = 1;
1675        }
1676        # Functional coupling is reflexive. If we found at least one coupled feature, we must add
1677        # the incoming feature as well.
1678        if ($found) {
1679            $retVal{$featureID} = 9999;
1680        }
1681        # Return the hash.
1682        return %retVal;
1683    }
1684    
1685    =head3 CouplingEvidence
1686    
1687    C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1688    
1689    Return the evidence for a functional coupling.
1690    
1691    A pair of features is considered evidence of a coupling between two other
1692    features if they occur close together on a contig and both are similar to
1693    the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1694    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1695    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1696    similar to B<A2>.
1697    
1698    The score of a coupling is determined by the number of pieces of evidence
1699    that are considered I<representative>. If several evidence items belong to
1700    a group of genomes that are close to each other, only one of those items
1701    is considered representative. The other evidence items are presumed to be
1702    there because of the relationship between the genomes rather than because
1703    the two proteins generated by the features have a related functionality.
1704    
1705    Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1706    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1707    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1708    and FALSE otherwise.
1709    
1710    =over 4
1711    
1712    =item peg1
1713    
1714    ID of the feature of interest.
1715    
1716    =item peg2
1717    
1718    ID of a feature functionally coupled to the feature of interest.
1719    
1720    =item RETURN
1721    
1722    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1723    of interest, a feature similar to the functionally coupled feature, and a flag
1724    that is TRUE for a representative piece of evidence and FALSE otherwise.
1725    
1726    =back
1727    
1728    =cut
1729    #: Return Type @@;
1730    sub CouplingEvidence {
1731        # Get the parameters.
1732        my ($self, $peg1, $peg2) = @_;
1733        # Declare the return variable.
1734        my @retVal = ();
1735        # Our first task is to find out the nature of the coupling: whether or not
1736        # it exists, its score, and whether the features are stored in the same
1737        # order as the ones coming in.
1738        my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1739        # Only proceed if a coupling exists.
1740        if ($couplingID) {
1741            # Determine the ordering to place on the evidence items. If we're
1742            # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1743            # we want feature 1 before feature 2 (normal).
1744            Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);
1745            my $ordering = ($inverted ? "DESC" : "");
1746            # Get the coupling evidence.
1747            my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
1748                                              "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",
1749                                              [$couplingID],
1750                                              ['PCH(used)', 'UsesAsEvidence(to-link)']);
1751            # Loop through the evidence items. Each piece of evidence is represented by two
1752            # positions in the evidence list, one for each feature on the other side of the
1753            # evidence link. If at some point we want to generalize to couplings with
1754            # more than two positions, this section of code will need to be re-done.
1755            while (@evidenceList > 0) {
1756                my $peg1Data = shift @evidenceList;
1757                my $peg2Data = shift @evidenceList;
1758                Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1759                push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1760            }
1761            Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1762        }
1763        # Return the result.
1764        return @retVal;
1765    }
1766    
1767    =head3 GetCoupling
1768    
1769    C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>
1770    
1771    Return the coupling (if any) for the specified pair of PEGs. If a coupling
1772    exists, we return the coupling ID along with an indicator of whether the
1773    coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.
1774    In the second case, we say the coupling is I<inverted>. The importance of an
1775    inverted coupling is that the PEGs in the evidence will appear in reverse order.
1776    
1777    =over 4
1778    
1779    =item peg1
1780    
1781    ID of the feature of interest.
1782    
1783    =item peg2
1784    
1785    ID of the potentially coupled feature.
1786    
1787    =item RETURN
1788    
1789    Returns a three-element list. The first element contains the database ID of
1790    the coupling. The second element is FALSE if the coupling is stored in the
1791    database in the caller specified order and TRUE if it is stored in the
1792    inverted order. The third element is the coupling's score. If the coupling
1793    does not exist, all three list elements will be C<undef>.
1794    
1795    =back
1796    
1797    =cut
1798    #: Return Type $%@;
1799    sub GetCoupling {
1800        # Get the parameters.
1801        my ($self, $peg1, $peg2) = @_;
1802        # Declare the return values. We'll start with the coupling ID and undefine the
1803        # flag and score until we have more information.
1804        my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);
1805        # Find the coupling data.
1806        my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1807                                     "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1808                                     [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1809        # Check to see if we found anything.
1810        if (!@pegs) {
1811            Trace("No coupling found.") if T(Coupling => 4);
1812            # No coupling, so undefine the return value.
1813            $retVal = undef;
1814        } else {
1815            # We have a coupling! Get the score and check for inversion.
1816            $score = $pegs[0]->[1];
1817            my $firstFound = $pegs[0]->[0];
1818            $inverted = ($firstFound ne $peg1);
1819            Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1820        }
1821        # Return the result.
1822        return ($retVal, $inverted, $score);
1823    }
1824    
1825    =head3 CouplingID
1826    
1827    C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>
1828    
1829    Return the coupling ID for a pair of feature IDs.
1830    
1831    The coupling ID is currently computed by joining the feature IDs in
1832    sorted order with a space. Client modules (that is, modules which
1833    use Sprout) should not, however, count on this always being the
1834    case. This method provides a way for abstracting the concept of a
1835    coupling ID. All that we know for sure about it is that it can be
1836    generated easily from the feature IDs and the order of the IDs
1837    in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>
1838    will have the same value as C<CouplingID("b1", "a1")>.
1839    
1840    =over 4
1841    
1842    =item peg1
1843    
1844  A hash mapping the functionally-coupled feature IDs to the coupling score.  First feature of interest.
1845    
1846  =back  =item peg2
1847    
1848  =cut  Second feature of interest.
 #: Return Type %;  
 sub CoupledFeatures {  
         # Get the parameters.  
         my $self = shift @_;  
         my ($featureID) = @_;  
         # Create a query to retrieve the functionally-coupled features. Note that we depend on the  
         # fact that the functional coupling is physically paired. If (A,B) is in the database, then  
         # (B,A) will also be found.  
         my $query = $self->Get(['IsClusteredOnChromosomeWith'],  
                                                    "IsClusteredOnChromosomeWith(from-link) = ?", [$featureID]);  
         # This value will be set to TRUE if we find at least one coupled feature.  
         my $found = 0;  
         # Create the return hash.  
         my %retVal = ();  
         # Retrieve the relationship records and store them in the hash.  
         while (my $clustering = $query->Fetch()) {  
                 my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',  
                                                                     'IsClusteredOnChromosomeWith(score)']);  
                 $retVal{$otherFeatureID} = $score;  
                 $found = 1;  
         }  
         # Functional coupling is reflexive. If we found at least one coupled feature, we must add  
         # the incoming feature as well.  
         if ($found) {  
                 $retVal{$featureID} = 9999;  
     }  
         # Return the hash.  
         return %retVal;  
 }  
1849    
1850  =head3 GetEntityTypes  =item RETURN
1851    
1852  C<< my @entityList = $sprout->GetEntityTypes(); >>  Returns the ID that would be used to represent a functional coupling of
1853    the two specified PEGs.
1854    
1855  Return the list of supported entity types.  =back
1856    
1857  =cut  =cut
1858  #: Return Type @;  #: Return Type $;
1859  sub GetEntityTypes {  sub CouplingID {
1860          # Get the parameters.      return join " ", sort @_;
         my $self = shift @_;  
         # Get the underlying database object.  
         my $erdb = $self->{_erdb};  
         # Get its entity type list.  
         my @retVal = $erdb->GetEntityTypes();  
1861  }  }
1862    
1863  =head3 ReadFasta  =head3 ReadFasta
# Line 1394  Line 1904 
1904                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1905                          # 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.
1906                          if ($id) {                          if ($id) {
1907                                  $retVal{$id} = $sequence;                  $retVal{$id} = lc $sequence;
1908                          }                          }
1909                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
1910                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
1911                  } else {                  } else {
1912                          # 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.
1913                          # First, we get the actual data out.              # First, we get the actual data out. Note that we normalize to lower
1914                # case.
1915                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
1916                          $sequence .= $1;                          $sequence .= $1;
1917                  }                  }
1918          }          }
1919          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
1920          if ($sequence) {          if ($sequence) {
1921                  $retVal {$id} = $sequence;          $retVal{$id} = lc $sequence;
1922          }          }
1923        # Close the file.
1924        close FASTAFILE;
1925          # Return the hash constructed from the file.          # Return the hash constructed from the file.
1926          return %retVal;          return %retVal;
1927  }  }
# Line 1419  Line 1932 
1932    
1933  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
1934  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
1935  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,
1936    it will not be changed; otherwise, it will be converted. This method can also be used to
1937    perform the reverse task-- insuring that all the locations are in the old format.
1938    
1939  =over 4  =over 4
1940    
# Line 1446  Line 1961 
1961  #: Return Type @;  #: Return Type @;
1962  sub FormatLocations {  sub FormatLocations {
1963          # Get the parameters.          # Get the parameters.
1964          my $self = shift @_;      my ($self, $prefix, $locations, $oldFormat) = @_;
         my ($prefix, $locations, $oldFormat) = @_;  
1965          # Create the return list.          # Create the return list.
1966          my @retVal = ();          my @retVal = ();
1967          # Check to see if any locations were passed in.          # Check to see if any locations were passed in.
1968          if ($locations eq '') {          if ($locations eq '') {
1969              confess "No locations specified.";          Confess("No locations specified.");
1970          } else {          } else {
1971                  # Loop through the locations, converting them to the new format.                  # Loop through the locations, converting them to the new format.
1972                  for my $location (@{$locations}) {                  for my $location (@{$locations}) {
# Line 1487  Line 2001 
2001    
2002  sub DumpData {  sub DumpData {
2003          # Get the parameters.          # Get the parameters.
2004          my $self = shift @_;      my ($self) = @_;
2005          # Get the data directory name.          # Get the data directory name.
2006          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
2007          # Dump the relations.          # Dump the relations.
2008          $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2009  }  }
2010    
2011  =head3 XMLFileName  =head3 XMLFileName
# Line 1503  Line 2017 
2017  =cut  =cut
2018  #: Return Type $;  #: Return Type $;
2019  sub XMLFileName {  sub XMLFileName {
2020          my $self = shift @_;      my ($self) = @_;
2021          return $self->{_xmlName};          return $self->{_xmlName};
2022  }  }
2023    
# Line 1523  Line 2037 
2037  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
2038  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>.
2039    
2040  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'}); >>
2041    
2042  =over 4  =over 4
2043    
# Line 1541  Line 2055 
2055  #: Return Type ;  #: Return Type ;
2056  sub Insert {  sub Insert {
2057          # Get the parameters.          # Get the parameters.
2058          my $self = shift @_;      my ($self, $objectType, $fieldHash) = @_;
         my ($objectType, $fieldHash) = @_;  
2059          # Call the underlying method.          # Call the underlying method.
2060          $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2061  }  }
2062    
2063  =head3 Annotate  =head3 Annotate
# Line 1583  Line 2096 
2096  #: Return Type $;  #: Return Type $;
2097  sub Annotate {  sub Annotate {
2098          # Get the parameters.          # Get the parameters.
2099          my $self = shift @_;      my ($self, $fid, $timestamp, $user, $text) = @_;
         my ($fid, $timestamp, $user, $text) = @_;  
2100          # Create the annotation ID.          # Create the annotation ID.
2101          my $aid = "$fid:$timestamp";          my $aid = "$fid:$timestamp";
2102          # Insert the Annotation object.          # Insert the Annotation object.
# Line 1604  Line 2116 
2116    
2117  =head3 AssignFunction  =head3 AssignFunction
2118    
2119  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function); >>  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>
2120    
2121  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
2122  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.  
2123    
2124  =over 4  =over 4
2125    
# Line 1618  Line 2129 
2129    
2130  =item user  =item user
2131    
2132  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>.
2133    
2134  =item function  =item function
2135    
2136  Text of the function being assigned.  Text of the function being assigned.
2137    
2138    =item assigningUser (optional)
2139    
2140    Name of the individual user making the assignment. If omitted, defaults to the user group.
2141    
2142  =item RETURN  =item RETURN
2143    
2144  Returns 1 if successful, 0 if an error occurred.  Returns 1 if successful, 0 if an error occurred.
# Line 1634  Line 2149 
2149  #: Return Type $;  #: Return Type $;
2150  sub AssignFunction {  sub AssignFunction {
2151          # Get the parameters.          # Get the parameters.
2152          my $self = shift @_;      my ($self, $featureID, $user, $function, $assigningUser) = @_;
2153          my ($featureID, $user, $function) = @_;      # Default the assigning user.
2154        if (! $assigningUser) {
2155            $assigningUser = $user;
2156        }
2157          # Create an annotation string from the parameters.          # Create an annotation string from the parameters.
2158          my $annotationText = "$user\nset $user function to\n$function";      my $annotationText = "$assigningUser\nset $user function to\n$function";
2159          # Get the current time.          # Get the current time.
2160          my $now = time;          my $now = time;
2161          # Declare the return variable.          # Declare the return variable.
# Line 1682  Line 2200 
2200  #: Return Type @;  #: Return Type @;
2201  sub FeaturesByAlias {  sub FeaturesByAlias {
2202          # Get the parameters.          # Get the parameters.
2203          my $self = shift @_;      my ($self, $alias) = @_;
         my ($alias) = @_;  
2204          # Declare the return variable.          # Declare the return variable.
2205          my @retVal = ();          my @retVal = ();
2206          # Parse the alias.          # Parse the alias.
# Line 1725  Line 2242 
2242  #: Return Type $;  #: Return Type $;
2243  sub Exists {  sub Exists {
2244          # Get the parameters.          # Get the parameters.
2245          my $self = shift @_;      my ($self, $entityName, $entityID) = @_;
         my ($entityName, $entityID) = @_;  
2246          # Check for the entity instance.          # Check for the entity instance.
2247        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
2248          my $testInstance = $self->GetEntity($entityName, $entityID);          my $testInstance = $self->GetEntity($entityName, $entityID);
2249          # Return an existence indicator.          # Return an existence indicator.
2250          my $retVal = ($testInstance ? 1 : 0);          my $retVal = ($testInstance ? 1 : 0);
# Line 1756  Line 2273 
2273  #: Return Type $;  #: Return Type $;
2274  sub FeatureTranslation {  sub FeatureTranslation {
2275          # Get the parameters.          # Get the parameters.
2276          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2277          # Get the specified feature's translation.          # Get the specified feature's translation.
2278          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
2279          return $retVal;          return $retVal;
# Line 1789  Line 2305 
2305  #: Return Type @;  #: Return Type @;
2306  sub Taxonomy {  sub Taxonomy {
2307          # Get the parameters.          # Get the parameters.
2308          my $self = shift @_;      my ($self, $genome) = @_;
         my ($genome) = @_;  
2309          # Find the specified genome's taxonomy string.          # Find the specified genome's taxonomy string.
2310          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);
2311          # Declare the return variable.          # Declare the return variable.
# Line 1833  Line 2348 
2348  #: Return Type $;  #: Return Type $;
2349  sub CrudeDistance {  sub CrudeDistance {
2350          # Get the parameters.          # Get the parameters.
2351          my $self = shift @_;      my ($self, $genome1, $genome2) = @_;
         my ($genome1, $genome2) = @_;  
2352          # Insure that the distance is commutative by sorting the genome IDs.          # Insure that the distance is commutative by sorting the genome IDs.
2353          my ($genomeA, $genomeB);          my ($genomeA, $genomeB);
2354          if ($genome2 < $genome2) {          if ($genome2 < $genome2) {
# Line 1881  Line 2395 
2395  #: Return Type $;  #: Return Type $;
2396  sub RoleName {  sub RoleName {
2397          # Get the parameters.          # Get the parameters.
2398          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2399          # Get the specified role's name.          # Get the specified role's name.
2400          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);
2401          # Use the ID if the role has no name.          # Use the ID if the role has no name.
# Line 1915  Line 2428 
2428  #: Return Type @;  #: Return Type @;
2429  sub RoleDiagrams {  sub RoleDiagrams {
2430          # Get the parameters.          # Get the parameters.
2431          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2432          # Query for the diagrams.          # Query for the diagrams.
2433          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2434                                                                  'RoleOccursIn(to-link)');                                                                  'RoleOccursIn(to-link)');
# Line 1924  Line 2436 
2436          return @retVal;          return @retVal;
2437  }  }
2438    
2439    =head3 GetProperties
2440    
2441    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2442    
2443    Return a list of the properties with the specified characteristics.
2444    
2445    Properties are arbitrary key-value pairs associated with a feature. (At some point they
2446    will also be associated with genomes.) A property value is represented by a 4-tuple of
2447    the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2448    
2449    =over 4
2450    
2451    =item fid
2452    
2453    ID of the feature possessing the property.
2454    
2455    =item key
2456    
2457    Name or key of the property.
2458    
2459    =item value
2460    
2461    Value of the property.
2462    
2463    =item url
2464    
2465    URL of the document that indicated the property should have this particular value, or an
2466    empty string if no such document exists.
2467    
2468    =back
2469    
2470    The parameters act as a filter for the desired data. Any non-null parameter will
2471    automatically match all the tuples returned. So, specifying just the I<$fid> will
2472    return all the properties of the specified feature; similarly, specifying the I<$key>
2473    and I<$value> parameters will return all the features having the specified property
2474    value.
2475    
2476    A single property key can have many values, representing different ideas about the
2477    feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2478    virulent, and another may declare that it is not virulent. A query about the virulence of
2479    C<fig|83333.1.peg.10> would be coded as
2480    
2481        my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2482    
2483    Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2484    not to be filtered. The tuples returned would be
2485    
2486        ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2487        ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2488    
2489    =cut
2490    #: Return Type @@;
2491    sub GetProperties {
2492        # Get the parameters.
2493        my ($self, @parms) = @_;
2494        # Declare the return variable.
2495        my @retVal = ();
2496        # Now we need to create a WHERE clause that will get us the data we want. First,
2497        # we create a list of the columns containing the data for each parameter.
2498        my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2499                        'Property(property-value)', 'HasProperty(evidence)');
2500        # Now we build the WHERE clause and the list of parameter values.
2501        my @where = ();
2502        my @values = ();
2503        for (my $i = 0; $i <= $#colNames; $i++) {
2504            my $parm = $parms[$i];
2505            if (defined $parm && ($parm ne '')) {
2506                push @where, "$colNames[$i] = ?";
2507                push @values, $parm;
2508            }
2509        }
2510        # Format the WHERE clause.
2511        my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2512        # Ask for all the propertie values with the desired characteristics.
2513        my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2514        while (my $valueObject = $query->Fetch()) {
2515            my @tuple = $valueObject->Values(\@colNames);
2516            push @retVal, \@tuple;
2517        }
2518        # Return the result.
2519        return @retVal;
2520    }
2521    
2522  =head3 FeatureProperties  =head3 FeatureProperties
2523    
2524  C<< my @properties = $sprout->FeatureProperties($featureID); >>  C<< my @properties = $sprout->FeatureProperties($featureID); >>
# Line 1953  Line 2548 
2548  #: Return Type @@;  #: Return Type @@;
2549  sub FeatureProperties {  sub FeatureProperties {
2550          # Get the parameters.          # Get the parameters.
2551          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2552          # Get the properties.          # Get the properties.
2553          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],
2554                                                          ['Property(property-name)', 'Property(property-value)',                                                          ['Property(property-name)', 'Property(property-value)',
# Line 1985  Line 2579 
2579  #: Return Type $;  #: Return Type $;
2580  sub DiagramName {  sub DiagramName {
2581          # Get the parameters.          # Get the parameters.
2582          my $self = shift @_;      my ($self, $diagramID) = @_;
         my ($diagramID) = @_;  
2583          # Get the specified diagram's name and return it.          # Get the specified diagram's name and return it.
2584          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);
2585          return $retVal;          return $retVal;
# Line 2018  Line 2611 
2611  #: Return Type @;  #: Return Type @;
2612  sub MergedAnnotations {  sub MergedAnnotations {
2613          # Get the parameters.          # Get the parameters.
2614          my $self = shift @_;      my ($self, $list) = @_;
         my ($list) = @_;  
2615          # Create a list to hold the annotation tuples found.          # Create a list to hold the annotation tuples found.
2616          my @tuples = ();          my @tuples = ();
2617          # Loop through the features in the input list.          # Loop through the features in the input list.
# Line 2067  Line 2659 
2659  #: Return Type @;  #: Return Type @;
2660  sub RoleNeighbors {  sub RoleNeighbors {
2661          # Get the parameters.          # Get the parameters.
2662          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2663          # Get all the diagrams containing this role.          # Get all the diagrams containing this role.
2664          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2665                                                                    'RoleOccursIn(to-link)');                                                                    'RoleOccursIn(to-link)');
# Line 2110  Line 2701 
2701  #: Return Type @;  #: Return Type @;
2702  sub FeatureLinks {  sub FeatureLinks {
2703          # Get the parameters.          # Get the parameters.
2704          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2705          # Get the feature's links.          # Get the feature's links.
2706          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);
2707          # Return the feature's links.          # Return the feature's links.
# Line 2123  Line 2713 
2713  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2714    
2715  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
2716  to the role the feature performs.  to the roles the feature performs.
2717    
2718  =over 4  =over 4
2719    
# Line 2133  Line 2723 
2723    
2724  =item RETURN  =item RETURN
2725    
2726  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.
2727    
2728  =back  =back
2729    
2730  =cut  =cut
2731  #: Return Type %;  #: Return Type %@;
2732  sub SubsystemsOf {  sub SubsystemsOf {
2733          # Get the parameters.          # Get the parameters.
2734          my $self = shift @_;      my ($self, $featureID) = @_;
2735          my ($featureID) = @_;      # Get the subsystem list.
         # Use the SSCell to connect features to subsystems.  
2736          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2737                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2738                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2739          # Create the return value.          # Create the return value.
2740          my %retVal = ();          my %retVal = ();
2741        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2742        # in two spreadsheet cells.
2743        my %dupHash = ();
2744          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
2745          for my $record (@subsystems) {          for my $record (@subsystems) {
2746                  $retVal{$record->[0]} = $record->[1];          # Get this subsystem and role.
2747            my ($subsys, $role) = @{$record};
2748            # Insure it's the first time for both.
2749            my $dupKey = "$subsys\n$role";
2750            if (! exists $dupHash{"$subsys\n$role"}) {
2751                $dupHash{$dupKey} = 1;
2752                push @{$retVal{$subsys}}, $role;
2753            }
2754          }          }
2755          # Return the hash.          # Return the hash.
2756          return %retVal;          return %retVal;
2757  }  }
2758    
2759    =head3 SubsystemList
2760    
2761    C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2762    
2763    Return a list containing the names of the subsystems in which the specified
2764    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2765    subsystem names, not the roles.
2766    
2767    =over 4
2768    
2769    =item featureID
2770    
2771    ID of the feature whose subsystem names are desired.
2772    
2773    =item RETURN
2774    
2775    Returns a list of the names of the subsystems in which the feature participates.
2776    
2777    =back
2778    
2779    =cut
2780    #: Return Type @;
2781    sub SubsystemList {
2782        # Get the parameters.
2783        my ($self, $featureID) = @_;
2784        # Get the list of names.
2785        my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",
2786                                    [$featureID], 'HasSSCell(from-link)');
2787        # Return the result.
2788        return @retVal;
2789    }
2790    
2791    
2792    
2793  =head3 RelatedFeatures  =head3 RelatedFeatures
2794    
2795  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2190  Line 2823 
2823  #: Return Type @;  #: Return Type @;
2824  sub RelatedFeatures {  sub RelatedFeatures {
2825          # Get the parameters.          # Get the parameters.
2826          my $self = shift @_;      my ($self, $featureID, $function, $userID) = @_;
         my ($featureID, $function, $userID) = @_;  
2827          # 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.
2828          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],
2829                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],
# Line 2239  Line 2871 
2871  #: Return Type @;  #: Return Type @;
2872  sub TaxonomySort {  sub TaxonomySort {
2873          # Get the parameters.          # Get the parameters.
2874          my $self = shift @_;      my ($self, $featureIDs) = @_;
         my ($featureIDs) = @_;  
2875          # Create the working hash table.          # Create the working hash table.
2876          my %hashBuffer = ();          my %hashBuffer = ();
2877          # Loop through the features.          # Loop through the features.
# Line 2249  Line 2880 
2880                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
2881                                                                                  [$fid], 'Genome(taxonomy)');                                                                                  [$fid], 'Genome(taxonomy)');
2882                  # Add this feature to the hash buffer.                  # Add this feature to the hash buffer.
2883                  if (exists $hashBuffer{$taxonomy}) {          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);
                         push @{$hashBuffer{$taxonomy}}, $fid;  
                 } else {  
                         $hashBuffer{$taxonomy} = [$fid];  
                 }  
2884          }          }
2885          # Sort the keys and get the elements.          # Sort the keys and get the elements.
2886          my @retVal = ();          my @retVal = ();
# Line 2264  Line 2891 
2891          return @retVal;          return @retVal;
2892  }  }
2893    
 =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;  
 }  
   
2894  =head3 Protein  =head3 Protein
2895    
2896  C<< my $protein = Sprout::Protein($sequence, $table); >>  C<< my $protein = Sprout::Protein($sequence, $table); >>
# Line 2495  Line 2988 
2988  #: Return Type @;  #: Return Type @;
2989  sub LoadInfo {  sub LoadInfo {
2990          # Get the parameters.          # Get the parameters.
2991          my $self = shift @_;      my ($self) = @_;
2992          # 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.
2993          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
2994          # Concatenate the table names.          # Concatenate the table names.
2995          push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
2996          # Return the result.          # Return the result.
2997          return @retVal;          return @retVal;
2998  }  }
2999    
3000  =head3 LowBBHs  =head3 LowBBHs
3001    
3002  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
3003    
3004  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
3005  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 2532  Line 3025 
3025  #: Return Type %;  #: Return Type %;
3026  sub LowBBHs {  sub LowBBHs {
3027          # Get the parsameters.          # Get the parsameters.
3028          my $self = shift @_;      my ($self, $featureID, $cutoff) = @_;
         my ($featureID, $cutoff) = @_;  
3029          # Create the return hash.          # Create the return hash.
3030          my %retVal = ();          my %retVal = ();
3031          # Create a query to get the desired BBHs.          # Create a query to get the desired BBHs.
# Line 2549  Line 3041 
3041          return %retVal;          return %retVal;
3042  }  }
3043    
3044    =head3 GetGroups
3045    
3046    C<< my %groups = $sprout->GetGroups(\@groupList); >>
3047    
3048    Return a hash mapping each group to the IDs of the genomes in the group.
3049    A list of groups may be specified, in which case only those groups will be
3050    shown. Alternatively, if no parameter is supplied, all groups will be
3051    included. Genomes that are not in any group are omitted.
3052    
3053    =cut
3054    #: Return Type %@;
3055    sub GetGroups {
3056        # Get the parameters.
3057        my ($self, $groupList) = @_;
3058        # Declare the return value.
3059        my %retVal = ();
3060        # Determine whether we are getting all the groups or just some.
3061        if (defined $groupList) {
3062            # Here we have a group list. Loop through them individually,
3063            # getting a list of the relevant genomes.
3064            for my $group (@{$groupList}) {
3065                my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",
3066                    [$group], "Genome(id)");
3067                $retVal{$group} = \@genomeIDs;
3068            }
3069        } else {
3070            # Here we need all of the groups. In this case, we run through all
3071            # of the genome records, putting each one found into the appropriate
3072            # group. Note that we use a filter clause to insure that only genomes
3073            # in groups are included in the return set.
3074            my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],
3075                                        ['Genome(id)', 'Genome(group-name)']);
3076            # Loop through the genomes found.
3077            for my $genome (@genomes) {
3078                # Pop this genome's ID off the current list.
3079                my @groups = @{$genome};
3080                my $genomeID = shift @groups;
3081                # Loop through the groups, adding the genome ID to each group's
3082                # list.
3083                for my $group (@groups) {
3084                    Tracer::AddToListMap(\%retVal, $group, $genomeID);
3085                }
3086            }
3087        }
3088        # Return the hash we just built.
3089        return %retVal;
3090    }
3091    
3092    =head3 MyGenomes
3093    
3094    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
3095    
3096    Return a list of the genomes to be included in the Sprout.
3097    
3098    This method is provided for use during the Sprout load. It presumes the Genome load file has
3099    already been created. (It will be in the Sprout data directory and called either C<Genome>
3100    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3101    IDs.
3102    
3103    =over 4
3104    
3105    =item dataDir
3106    
3107    Directory containing the Sprout load files.
3108    
3109    =back
3110    
3111    =cut
3112    #: Return Type @;
3113    sub MyGenomes {
3114        # Get the parameters.
3115        my ($dataDir) = @_;
3116        # Compute the genome file name.
3117        my $genomeFileName = LoadFileName($dataDir, "Genome");
3118        # Extract the genome IDs from the files.
3119        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3120        # Return the result.
3121        return @retVal;
3122    }
3123    
3124    =head3 LoadFileName
3125    
3126    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3127    
3128    Return the name of the load file for the specified table in the specified data
3129    directory.
3130    
3131    =over 4
3132    
3133    =item dataDir
3134    
3135    Directory containing the Sprout load files.
3136    
3137    =item tableName
3138    
3139    Name of the table whose load file is desired.
3140    
3141    =item RETURN
3142    
3143    Returns the name of the file containing the load data for the specified table, or
3144    C<undef> if no load file is present.
3145    
3146    =back
3147    
3148    =cut
3149    #: Return Type $;
3150    sub LoadFileName {
3151        # Get the parameters.
3152        my ($dataDir, $tableName) = @_;
3153        # Declare the return variable.
3154        my $retVal;
3155        # Check for the various file names.
3156        if (-e "$dataDir/$tableName") {
3157            $retVal = "$dataDir/$tableName";
3158        } elsif (-e "$dataDir/$tableName.dtx") {
3159            $retVal = "$dataDir/$tableName.dtx";
3160        }
3161        # Return the result.
3162        return $retVal;
3163    }
3164    
3165    =head3 DeleteGenome
3166    
3167    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3168    
3169    Delete a genome from the database.
3170    
3171    =over 4
3172    
3173    =item genomeID
3174    
3175    ID of the genome to delete
3176    
3177    =item testFlag
3178    
3179    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3180    
3181    =item RETURN
3182    
3183    Returns a statistics object describing the rows deleted.
3184    
3185    =back
3186    
3187    =cut
3188    #: Return Type $%;
3189    sub DeleteGenome {
3190        # Get the parameters.
3191        my ($self, $genomeID, $testFlag) = @_;
3192        # Perform the delete for the genome's features.
3193        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);
3194        # Perform the delete for the primary genome data.
3195        my $stats = $self->Delete('Genome', $genomeID, $testFlag);
3196        $retVal->Accumulate($stats);
3197        # Return the result.
3198        return $retVal;
3199    }
3200    
3201  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3202    
3203  =head3 ParseAssignment  =head3 ParseAssignment
3204    
3205  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,
3206  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
3207  will be returned.  isn't, an empty list will be returned.
3208    
3209    A functional assignment is always of the form
3210    
3211        C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3212    
3213    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3214    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3215    not always the case.
3216    
3217    In addition, the functional role may contain extra data that is stripped, such as
3218    terminating spaces or a comment separated from the rest of the text by a tab.
3219    
3220  This is a static method.  This is a static method.
3221    
3222  =over 4  =over 4
3223    
3224    =item user
3225    
3226    Name of the assigning user.
3227    
3228  =item text  =item text
3229    
3230  Text of the annotation.  Text of the annotation.
# Line 2574  Line 3238 
3238    
3239  =cut  =cut
3240    
3241  sub ParseAssignment {  sub _ParseAssignment {
3242          # Get the parameters.          # Get the parameters.
3243          my ($text) = @_;      my ($user, $text) = @_;
3244          # Declare the return value.          # Declare the return value.
3245          my @retVal = ();          my @retVal = ();
3246          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3247          my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3248          if ($type =~ m/^set $user function to$/i) {      if ($type =~ m/^set function to$/i) {
3249                  # 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.
3250                  @retVal = ($user, $function);                  @retVal = ($user, $function);
3251        } elsif ($type =~ m/^set (\S+) function to$/i) {
3252            # Here we have an assignment with a user that is passed back to the caller.
3253            @retVal = ($1, $function);
3254        }
3255        # If we have an assignment, we need to clean the function text. There may be
3256        # extra junk at the end added as a note from the user.
3257        if (@retVal) {
3258            $retVal[1] =~ s/(\t\S)?\s*$//;
3259          }          }
3260          # Return the result list.          # Return the result list.
3261          return @retVal;          return @retVal;
# Line 2611  Line 3283 
3283    
3284  sub FriendlyTimestamp {  sub FriendlyTimestamp {
3285      my ($timeValue) = @_;      my ($timeValue) = @_;
3286      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
3287      return $retVal;      return $retVal;
3288  }  }
3289    
3290    =head3 AddProperty
3291    
3292    C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>
3293    
3294    Add a new attribute value (Property) to a feature. In the SEED system, attributes can
3295    be added to almost any object. In Sprout, they can only be added to features. In
3296    Sprout, attributes are implemented using I<properties>. A property represents a key/value
3297    pair. If the particular key/value pair coming in is not already in the database, a new
3298    B<Property> record is created to hold it.
3299    
3300    =over 4
3301    
3302    =item peg
3303    
3304    ID of the feature to which the attribute is to be replied.
3305    
3306    =item key
3307    
3308    Name of the attribute (key).
3309    
3310    =item value
3311    
3312    Value of the attribute.
3313    
3314    =item url
3315    
3316    URL or text citation from which the property was obtained.
3317    
3318    =back
3319    
3320    =cut
3321    #: Return Type ;
3322    sub AddProperty {
3323        # Get the parameters.
3324        my ($self, $featureID, $key, $value, $url) = @_;
3325        # Declare the variable to hold the desired property ID.
3326        my $propID;
3327        # Attempt to find a property record for this key/value pair.
3328        my @properties = $self->GetFlat(['Property'],
3329                                       "Property(property-name) = ? AND Property(property-value) = ?",
3330                                       [$key, $value], 'Property(id)');
3331        if (@properties) {
3332            # Here the property is already in the database. We save its ID.
3333            $propID = $properties[0];
3334            # Here the property value does not exist. We need to generate an ID. It will be set
3335            # to a number one greater than the maximum value in the database. This call to
3336            # GetAll will stop after one record.
3337            my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],
3338                                            1);
3339            $propID = $maxProperty[0]->[0] + 1;
3340            # Insert the new property value.
3341            $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });
3342        }
3343        # Now we connect the incoming feature to the property.
3344        $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3345    }
3346    
3347    
3348  1;  1;

Legend:
Removed from v.1.6  
changed lines
  Added in v.1.63

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3