[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.7, Wed Jan 26 22:26:09 2005 UTC revision 1.95, Wed Nov 29 20:31:32 2006 UTC
# Line 1  Line 1 
1  package Sprout;  package Sprout;
2    
3        require Exporter;
4        use ERDB;
5        @ISA = qw(Exporter ERDB);
6          use Data::Dumper;          use Data::Dumper;
7          use strict;          use strict;
8          use Carp;          use Carp;
# Line 7  Line 10 
10          use XML::Simple;          use XML::Simple;
11          use DBQuery;          use DBQuery;
12          use DBObject;          use DBObject;
         use ERDB;  
13          use Tracer;          use Tracer;
14          use FIGRules;          use FIGRules;
15        use FidCheck;
16          use Stats;          use Stats;
17      use POSIX qw(strftime);      use POSIX qw(strftime);
18        use BasicLocation;
19    
20  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
21    
# Line 32  Line 35 
35  query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and  query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and
36  L</dna_seq> returns the DNA sequence for a specified genome location.  L</dna_seq> returns the DNA sequence for a specified genome location.
37    
38    The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.
39    
40  =cut  =cut
41    
42  #: Constructor SFXlate->new_sprout_only();  #: Constructor SFXlate->new_sprout_only();
# Line 62  Line 67 
67    
68  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)
69    
70  * B<userData> user name and password, delimited by a slash (default C<root/>)  * B<userData> user name and password, delimited by a slash (default same as SEED)
71    
72  * B<port> connection port (default C<0>)  * B<port> connection port (default C<0>)
73    
74    * B<sock> connection socket (default same as SEED)
75    
76  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
77    
78  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
79    
80    * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
81    
82  =back  =back
83    
84  For example, the following constructor call specifies a database named I<Sprout> and a user name of  For example, the following constructor call specifies a database named I<Sprout> and a user name of
# Line 83  Line 92 
92  sub new {  sub new {
93          # Get the parameters.          # Get the parameters.
94          my ($class, $dbName, $options) = @_;          my ($class, $dbName, $options) = @_;
95        # Compute the DBD directory.
96        my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
97                                                      $FIG_Config::fig );
98          # Compute the options. We do this by starting with a table of defaults and overwriting with          # Compute the options. We do this by starting with a table of defaults and overwriting with
99          # the incoming data.          # the incoming data.
100          my $optionTable = Tracer::GetOptions({          my $optionTable = Tracer::GetOptions({
101                                             dbType               => 'mysql',                     # database type                         dbType       => $FIG_Config::dbms,
102                                             dataDir              => 'Data',                      # data file directory                                                          # database type
103                                             xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
104                                             userData             => 'root/',                     # user name and password                                                          # data file directory
105                                             port                 => 0,                           # database connection port                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
106                                                            # database definition file name
107                           userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
108                                                            # user name and password
109                           port         => $FIG_Config::dbport,
110                                                            # database connection port
111                           sock         => $FIG_Config::dbsock,
112                           host         => $FIG_Config::dbhost,
113                                             maxSegmentLength => 4500,            # maximum feature segment length                                             maxSegmentLength => 4500,            # maximum feature segment length
114                                             maxSequenceLength => 8000,           # maximum contig sequence length                                             maxSequenceLength => 8000,           # maximum contig sequence length
115                           noDBOpen     => 0,               # 1 to suppress the database open
116                                            }, $options);                                            }, $options);
117          # Get the data directory.          # Get the data directory.
118          my $dataDir = $optionTable->{dataDir};          my $dataDir = $optionTable->{dataDir};
# Line 100  Line 120 
120          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
121          my ($userName, $password) = ($1, $2);          my ($userName, $password) = ($1, $2);
122          # Connect to the database.          # Connect to the database.
123          my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
124        if (! $optionTable->{noDBOpen}) {
125            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
126                                    $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
127        }
128          # Create the ERDB object.          # Create the ERDB object.
129          my $xmlFileName = "$optionTable->{xmlFileName}";          my $xmlFileName = "$optionTable->{xmlFileName}";
130          my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
131          # Create this object.      # Add the option table and XML file name.
132          my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
133          # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
134          bless $self;      # Set up space for the group file data.
135          return $self;      $retVal->{groupHash} = undef;
136        # Return it.
137        return $retVal;
138  }  }
139    
140  =head3 MaxSegment  =head3 MaxSegment
# Line 124  Line 150 
150  =cut  =cut
151  #: Return Type $;  #: Return Type $;
152  sub MaxSegment {  sub MaxSegment {
153          my $self = shift @_;      my ($self) = @_;
154          return $self->{_options}->{maxSegmentLength};          return $self->{_options}->{maxSegmentLength};
155  }  }
156    
# Line 139  Line 165 
165  =cut  =cut
166  #: Return Type $;  #: Return Type $;
167  sub MaxSequence {  sub MaxSequence {
168          my $self = shift @_;      my ($self) = @_;
169          return $self->{_options}->{maxSequenceLength};          return $self->{_options}->{maxSequenceLength};
170  }  }
171    
172  =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]); >>  
173    
174  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.  
175    
176  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.
177    
178  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
179  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
180  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
181    extension are used in preference to the files with an extension.
182    
183  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
184  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
185  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
186  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.  
187    
188  =over 4  =over 4
189    
190  =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  
191    
192  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
193    
194  =item RETURN  =item RETURN
195    
196  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,
197    the number of errors, and a list of the error messages.
198    
199  =back  =back
200    
201  =cut  =cut
202    #: Return Type %;
203  sub Get {  sub Load {
204          # Get the parameters.          # Get the parameters.
205          my $self = shift @_;      my ($self, $rebuild) = @_;
206          my ($objectNames, $filterClause, $parameterList) = @_;      # Load the tables from the data directory.
207          # 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);
208          # rather than a list of parameters. The next step is to convert the parameters from a reference      # Return the statistics.
209          # 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);  
210  }  }
211    
212  =head3 GetEntity  =head3 LoadUpdate
213    
214  C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
215    
216  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
217    or two tables without reloading the whole database. For each table, there must be a corresponding
218    file in the data directory, either with the same name as the table, or with a C<.dtx> suffix. So,
219    for example, to make updates to the B<FeatureTranslation> relation, there must be a
220    C<FeatureTranslation.dtx> file in the data directory. Unlike a full load, files without an extension
221    are not examined. This allows update files to co-exist with files from an original load.
222    
223  =over 4  =over 4
224    
225  =item entityType  =item truncateFlag
226    
227  Entity type name.  TRUE if the tables should be rebuilt before loading, else FALSE. A value of TRUE therefore causes
228    current data and schema of the tables to be replaced, while a value of FALSE means the new data
229    is added to the existing data in the various relations.
230    
231  =item ID  =item tableList
232    
233  ID of the desired entity.  List of the tables to be updated.
234    
235  =item RETURN  =item RETURN
236    
237  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,
238  instance is found with the specified key.  the number of errors encountered, and a list of error messages.
239    
240  =back  =back
241    
242  =cut  =cut
243    #: Return Type $%;
244  sub GetEntity {  sub LoadUpdate {
245          # Get the parameters.          # Get the parameters.
246          my $self = shift @_;      my ($self, $truncateFlag, $tableList) = @_;
247          my ($entityType, $ID) = @_;      # Declare the return value.
248          # Create a query.      my $retVal = Stats->new();
249          my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);      # Get the data directory.
250          # Get the first (and only) object.      my $optionTable = $self->{_options};
251          my $retVal = $query->Fetch();      my $dataDir = $optionTable->{dataDir};
252          # Return the result.      # Loop through the incoming table names.
253        for my $tableName (@{$tableList}) {
254            # Find the table's file.
255            my $fileName = LoadFileName($dataDir, $tableName);
256            if (! $fileName) {
257                Trace("No load file found for $tableName in $dataDir.") if T(0);
258            } else {
259                # Attempt to load this table.
260                my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);
261                # Accumulate the resulting statistics.
262                $retVal->Accumulate($result);
263            }
264        }
265        # Return the statistics.
266          return $retVal;          return $retVal;
267  }  }
268    
269  =head3 GetEntityValues  =head3 GenomeCounts
270    
271  C<< my @values = GetEntityValues($entityType, $ID, \@fields); >>  C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>
272    
273  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
274    genomes will be included in the counts.
275    
276  =over 4  =over 4
277    
278  =item entityType  =item complete
279    
280  Entity type name.  TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
281    counted
 =item ID  
   
 ID of the desired entity.  
   
 =item fields  
   
 List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.  
282    
283  =item RETURN  =item RETURN
284    
285  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--
286    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
287    
288  =back  =back
289    
290  =cut  =cut
291  #: Return Type @;  
292  sub GetEntityValues {  sub GenomeCounts {
293          # Get the parameters.          # Get the parameters.
294          my $self = shift @_;      my ($self, $complete) = @_;
295          my ($entityType, $ID, $fields) = @_;      # Set the filter based on the completeness flag.
296          # Get the specified entity.      my $filter = ($complete ? "Genome(complete) = 1" : "");
297          my $entity = $self->GetEntity($entityType, $ID);      # Get all the genomes and the related taxonomy information.
298          # Declare the return list.      my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
299          my @retVal = ();      # Clear the counters.
300          # If we found the entity, push the values into the return list.      my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
301          if ($entity) {      # Loop through, counting the domains.
302                  push @retVal, $entity->Values($fields);      for my $genome (@genomes) {
303            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
304            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
305            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
306            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
307            elsif ($genome->[1] =~ /^env/i)      { ++$env }
308            else  { ++$unk }
309          }          }
310          # Return the result.      # Return the counts.
311          return @retVal;      return ($arch, $bact, $euk, $vir, $env, $unk);
312  }  }
313    
314  =head3 ShowMetaData  =head3 ContigCount
315    
316  C<< $sprout->ShowMetaData($fileName); >>  C<< my $count = $sprout->ContigCount($genomeID); >>
317    
318  This method outputs a description of the database to an HTML file in the data directory.  Return the number of contigs for the specified genome ID.
319    
320  =over 4  =over 4
321    
322  =item fileName  =item genomeID
323    
324    ID of the genome whose contig count is desired.
325    
326  Fully-qualified name to give to the output file.  =item RETURN
327    
328    Returns the number of contigs for the specified genome.
329    
330  =back  =back
331    
332  =cut  =cut
333    
334  sub ShowMetaData {  sub ContigCount {
335          # Get the parameters.          # Get the parameters.
336          my $self = shift @_;      my ($self, $genomeID) = @_;
337          my ($fileName) = @_;      # Get the contig count.
338          # Compute the file name.      my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
339          my $options = $self->{_options};      # Return the result.
340          # Call the show method on the underlying ERDB object.      return $retVal;
         $self->{_erdb}->ShowMetaData($fileName);  
341  }  }
342    
343  =head3 Load  =head3 GeneMenu
   
 C<< $sprout->Load($rebuild); >>;  
   
 Load the database from files in the data directory, optionally re-creating the tables.  
344    
345  This method always deletes the data from the database before loading, even if the tables are not  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected); >>
 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.  
346    
347  The files are loaded based on the presumption that each line of the file is a record in the  Return an HTML select menu of genomes. Each genome will be an option in the menu,
348  relation, and the individual fields are delimited by tabs. Tab and new-line characters inside  and will be displayed by name with the ID and a contig count attached. The selection
349  fields must be represented by the escape sequences C<\t> and C<\n>, respectively. The fields must  value will be the genome ID. The genomes will be sorted by genus/species name.
 be presented in the order given in the relation tables produced by the L</ShowMetaData> method.  
350    
351  =over 4  =over 4
352    
353  =item rebuild  =item attributes
   
 TRUE if the data tables need to be created or re-created, else FALSE  
   
 =item RETURN  
   
 Returns a statistical object containing the number of records read, the number of duplicates found,  
 the number of errors, and a list of the error messages.  
   
 =back  
354    
355  =cut  Reference to a hash mapping attributes to values for the SELECT tag generated.
 #: Return Type %;  
 sub Load {  
         # Get the parameters.  
         my $self = shift @_;  
         my ($rebuild) = @_;  
         # Get the database object.  
         my $erdb = $self->{_erdb};  
         # Load the tables from the data directory.  
         my $retVal = $erdb->LoadTables($self->{_options}->{dataDir}, $rebuild);  
         # Return the statistics.  
         return $retVal;  
 }  
356    
357  =head3 LoadUpdate  =item filterString
358    
359  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  A filter string for use in selecting the genomes. The filter string must conform
360    to the rules for the C<< ERDB->Get >> method.
361    
362  Load updates to one or more database tables. This method enables the client to make changes to one  =item params
 or two tables without reloading the whole database. For each table, there must be a corresponding  
 file in the data directory, either with the same name as the table, or with a C<.dtx> suffix. So,  
 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.  
363    
364  =over 4  Reference to a list of values to be substituted in for the parameter marks in
365    the filter string.
366    
367  =item truncateFlag  =item selected (optional)
368    
369  TRUE if the tables should be rebuilt before loading, else FALSE. A value of TRUE therefore causes  ID of the genome to be initially selected.
 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.  
370    
371  =item tableList  =item fast (optional)
372    
373  List of the tables to be updated.  If specified and TRUE, the contig counts will be omitted to improve performance.
374    
375  =item RETURN  =item RETURN
376    
377  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.  
378    
379  =back  =back
380    
381  =cut  =cut
382  #: Return Type $%;  
383  sub LoadUpdate {  sub GeneMenu {
384          # Get the parameters.          # Get the parameters.
385          my $self = shift @_;      my ($self, $attributes, $filterString, $params, $selected, $fast) = @_;
386          my ($truncateFlag, $tableList) = @_;      my $slowMode = ! $fast;
387          # Get the database object.      # Default to nothing selected. This prevents an execution warning if "$selected"
388          my $erdb = $self->{_erdb};      # is undefined.
389          # Declare the return value.      $selected = "" unless defined $selected;
390          my $retVal = Stats->new();      Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3);
391          # Get the data directory.      # Start the menu.
392          my $optionTable = $self->{_options};      my $retVal = "<select " .
393          my $dataDir = $optionTable->{dataDir};          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
394          # Loop through the incoming table names.          ">\n";
395          for my $tableName (@{$tableList}) {      # Get the genomes.
396                  # Find the table's file.      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
397                  my $fileName = "$dataDir/$tableName";                                                                       'Genome(genus)',
398                  if (! -e $fileName) {                                                                       'Genome(species)',
399                          $fileName = "$fileName.dtx";                                                                       'Genome(unique-characterization)']);
400                  }      # Sort them by name.
401                  # Attempt to load this table.      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
402                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);      # Loop through the genomes, creating the option tags.
403                  # Accumulate the resulting statistics.      for my $genomeData (@sorted) {
404                  $retVal->Accumulate($result);          # Get the data for this genome.
405            my ($genomeID, $genus, $species, $strain) = @{$genomeData};
406            # Get the contig count.
407            my $contigInfo = "";
408            if ($slowMode) {
409                my $count = $self->ContigCount($genomeID);
410                my $counting = ($count == 1 ? "contig" : "contigs");
411                $contigInfo = "[$count $counting]";
412            }
413            # Find out if we're selected.
414            my $selectOption = ($selected eq $genomeID ? " selected" : "");
415            # Build the option tag.
416            $retVal .= "<option value=\"$genomeID\"$selectOption>$genus $species $strain ($genomeID)$contigInfo</option>\n";
417          }          }
418          # Return the statistics.      # Close the SELECT tag.
419        $retVal .= "</select>\n";
420        # Return the result.
421          return $retVal;          return $retVal;
422  }  }
423    
# Line 463  Line 433 
433  #: Return Type ;  #: Return Type ;
434  sub Build {  sub Build {
435          # Get the parameters.          # Get the parameters.
436          my $self = shift @_;      my ($self) = @_;
437          # Create the tables.          # Create the tables.
438          $self->{_erdb}->CreateTables;      $self->CreateTables();
439  }  }
440    
441  =head3 Genomes  =head3 Genomes
# Line 478  Line 448 
448  #: Return Type @;  #: Return Type @;
449  sub Genomes {  sub Genomes {
450          # Get the parameters.          # Get the parameters.
451          my $self = shift @_;      my ($self) = @_;
452          # Get all the genomes.          # Get all the genomes.
453          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');
454          # Return the list of IDs.          # Return the list of IDs.
# Line 508  Line 478 
478  #: Return Type $;  #: Return Type $;
479  sub GenusSpecies {  sub GenusSpecies {
480          # Get the parameters.          # Get the parameters.
481          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
482          # Get the data for the specified genome.          # Get the data for the specified genome.
483          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',
484                                                                                                                            'Genome(unique-characterization)']);                                                                                                                            'Genome(unique-characterization)']);
# Line 545  Line 514 
514  #: Return Type @;  #: Return Type @;
515  sub FeaturesOf {  sub FeaturesOf {
516          # Get the parameters.          # Get the parameters.
517          my $self = shift @_;      my ($self, $genomeID,$ftype) = @_;
         my ($genomeID,$ftype) = @_;  
518          # Get the features we want.          # Get the features we want.
519          my @features;          my @features;
520          if (!$ftype) {          if (!$ftype) {
# Line 590  Line 558 
558  =item RETURN  =item RETURN
559    
560  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
561  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context.
562    
563  =back  =back
564    
# Line 599  Line 567 
567  #: Return Type $;  #: Return Type $;
568  sub FeatureLocation {  sub FeatureLocation {
569          # Get the parameters.          # Get the parameters.
570          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
571          # Create a query for the feature locations.          # Create a query for the feature locations.
572          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",
573                                                     [$featureID]);                                                     [$featureID]);
# Line 618  Line 585 
585                  if ($prevContig eq $contigID && $dir eq $prevDir) {                  if ($prevContig eq $contigID && $dir eq $prevDir) {
586                          # 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
587                          # new segment's beginning is next to the old segment's end.                          # new segment's beginning is next to the old segment's end.
588                          if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||              if ($dir eq "-" && $beg + $len == $prevBeg) {
589                                  ($dir eq "+" && $beg == $prevBeg + $prevLen)) {                  # Here we're merging two backward blocks, so we keep the new begin point
590                                  # Here we need to merge two segments. Adjust the beginning and length values                  # and adjust the length.
591                                  # to include both segments.                  $len += $prevLen;
592                    # Pop the old segment off. The new one will replace it later.
593                    pop @retVal;
594                } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {
595                    # Here we need to merge two forward blocks. Adjust the beginning and
596                    # length values to include both segments.
597                                  $beg = $prevBeg;                                  $beg = $prevBeg;
598                                  $len += $prevLen;                                  $len += $prevLen;
599                                  # 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 602 
602                  }                  }
603                  # Remember this specifier for the adjacent-segment test the next time through.                  # Remember this specifier for the adjacent-segment test the next time through.
604                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);                  ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);
605            # Compute the initial base pair.
606            my $start = ($dir eq "+" ? $beg : $beg + $len - 1);
607                  # Add the specifier to the list.                  # Add the specifier to the list.
608                  push @retVal, "${contigID}_$beg$dir$len";          push @retVal, "${contigID}_$start$dir$len";
609          }          }
610          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
611          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
612  }  }
613    
614  =head3 ParseLocation  =head3 ParseLocation
# Line 660  Line 634 
634  =cut  =cut
635  #: Return Type @;  #: Return Type @;
636  sub ParseLocation {  sub ParseLocation {
637          # Get the parameter.      # Get the parameter. Note that if we're called as an instance method, we ignore
638        # the first parameter.
639        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
640          my ($location) = @_;          my ($location) = @_;
641          # Parse it into segments.          # Parse it into segments.
642          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
643          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
644          # If the direction is an underscore, convert it to a + or -.          # If the direction is an underscore, convert it to a + or -.
645          if ($dir eq "_") {          if ($dir eq "_") {
# Line 679  Line 655 
655          return ($contigID, $start, $dir, $len);          return ($contigID, $start, $dir, $len);
656  }  }
657    
658    
659    
660    =head3 PointLocation
661    
662    C<< my $found = Sprout::PointLocation($location, $point); >>
663    
664    Return the offset into the specified location of the specified point on the contig. If
665    the specified point is before the location, a negative value will be returned. If it is
666    beyond the location, an undefined value will be returned. It is assumed that the offset
667    is for the location's contig. The location can either be new-style (using a C<+> or C<->
668    and a length) or old-style (using C<_> and start and end positions.
669    
670    =over 4
671    
672    =item location
673    
674    A location specifier (see L</FeatureLocation> for a description).
675    
676    =item point
677    
678    The offset into the contig of the point in which we're interested.
679    
680    =item RETURN
681    
682    Returns the offset inside the specified location of the specified point, a negative
683    number if the point is before the location, or an undefined value if the point is past
684    the location. If the length of the location is 0, this method will B<always> denote
685    that it is outside the location. The offset will always be relative to the left-most
686    position in the location.
687    
688    =back
689    
690    =cut
691    #: Return Type $;
692    sub PointLocation {
693        # Get the parameter. Note that if we're called as an instance method, we ignore
694        # the first parameter.
695        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
696        my ($location, $point) = @_;
697        # Parse out the location elements. Note that this works on both old-style and new-style
698        # locations.
699        my ($contigID, $start, $dir, $len) = ParseLocation($location);
700        # Declare the return variable.
701        my $retVal;
702        # Compute the offset. The computation is dependent on the direction of the location.
703        my $offset = (($dir == '+') ? $point - $start : $point - ($start - $len + 1));
704        # Return the offset if it's valid.
705        if ($offset < $len) {
706            $retVal = $offset;
707        }
708        # Return the offset found.
709        return $retVal;
710    }
711    
712  =head3 DNASeq  =head3 DNASeq
713    
714  C<< my $sequence = $sprout->DNASeq(\@locationList); >>  C<< my $sequence = $sprout->DNASeq(\@locationList); >>
# Line 687  Line 717 
717  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,
718  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>.
719    
720    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
721    between positions 1401 and 1532, inclusive.
722    
723        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
724    
725  =over 4  =over 4
726    
727  =item locationList  =item locationList
728    
729  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
730  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
731    
732  =item RETURN  =item RETURN
733    
# Line 704  Line 739 
739  #: Return Type $;  #: Return Type $;
740  sub DNASeq {  sub DNASeq {
741          # Get the parameters.          # Get the parameters.
742          my $self = shift @_;      my ($self, $locationList) = @_;
         my ($locationList) = @_;  
743          # Create the return string.          # Create the return string.
744          my $retVal = "";          my $retVal = "";
745          # Loop through the locations.          # Loop through the locations.
# Line 720  Line 754 
754                  # 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
755                  # before putting it in the return value.                  # before putting it in the return value.
756                  my ($start, $stop);                  my ($start, $stop);
757            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
758                  if ($dir eq "+") {                  if ($dir eq "+") {
759                          $start = $beg;                          $start = $beg;
760                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
761                  } else {                  } else {
762                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
763                          $stop = $beg;                          $stop = $beg;
764                  }                  }
765            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
766                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
767                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
768                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 738  Line 774 
774                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
775                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
776                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
777                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
778                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
779                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
780                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
781                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
782                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
783                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
784                  }                  }
785                  # 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.
786                  if ($dir eq '+') {                  if ($dir eq '+') {
787                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
788                  } else {                  } else {
789                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
790                  }                  }
791          }          }
792          # Return the result.          # Return the result.
# Line 778  Line 815 
815  #: Return Type @;  #: Return Type @;
816  sub AllContigs {  sub AllContigs {
817          # Get the parameters.          # Get the parameters.
818          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
819          # Ask for the genome's Contigs.          # Ask for the genome's Contigs.
820          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],
821                                                                  'HasContig(to-link)');                                                                  'HasContig(to-link)');
# Line 787  Line 823 
823          return @retVal;          return @retVal;
824  }  }
825    
826  =head3 ContigLength  =head3 GenomeLength
827    
828  C<< my $length = $sprout->ContigLength($contigID); >>  C<< my $length = $sprout->GenomeLength($genomeID); >>
829    
830  Compute the length of a contig.  Return the length of the specified genome in base pairs.
831    
832  =over 4  =over 4
833    
834  =item contigID  =item genomeID
835    
836  ID of the contig whose length is desired.  ID of the genome whose base pair count is desired.
837    
838  =item RETURN  =item RETURN
839    
840  Returns the number of positions in the contig.  Returns the number of base pairs in all the contigs of the specified
841    genome.
842    
843  =back  =back
844    
845  =cut  =cut
846  #: Return Type $;  
847  sub ContigLength {  sub GenomeLength {
848          # Get the parameters.          # Get the parameters.
849          my $self = shift @_;      my ($self, $genomeID) = @_;
850          my ($contigID) = @_;      # Declare the return variable.
         # Get the contig's last sequence.  
         my $query = $self->Get(['IsMadeUpOf'],  
                 "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",  
                 [$contigID]);  
         my $sequence = $query->Fetch();  
         # Declare the return value.  
851          my $retVal = 0;          my $retVal = 0;
852          # Set it from the sequence data, if any.      # Get the genome's contig sequence lengths.
853          if ($sequence) {      my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
854                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);                         [$genomeID], 'IsMadeUpOf(len)');
855                  $retVal = $start + $len;      # Sum the lengths.
856          }      map { $retVal += $_ } @lens;
857          # Return the result.          # Return the result.
858          return $retVal;          return $retVal;
859  }  }
860    
861  =head3 GenesInRegion  =head3 FeatureCount
862    
863  C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>  C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
864    
865  List the features which overlap a specified region in a contig.  Return the number of features of the specified type in the specified genome.
866    
867  =over 4  =over 4
868    
869  =item contigID  =item genomeID
870    
871  ID of the contig containing the region of interest.  ID of the genome whose feature count is desired.
872    
873  =item start  =item type
874    
875  Offset of the first residue in the region of interest.  Type of feature to count (eg. C<peg>, C<rna>, etc.).
876    
877  =item stop  =item RETURN
878    
879  Offset of the last residue in the region of interest.  Returns the number of features of the specified type for the specified genome.
880    
881    =back
882    
883    =cut
884    
885    sub FeatureCount {
886        # Get the parameters.
887        my ($self, $genomeID, $type) = @_;
888        # Compute the count.
889        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
890                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
891                                    [$genomeID, $type]);
892        # Return the result.
893        return $retVal;
894    }
895    
896    =head3 GenomeAssignments
897    
898    C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
899    
900    Return a list of a genome's assigned features. The return hash will contain each
901    assigned feature of the genome mapped to the text of its most recent functional
902    assignment.
903    
904    =over 4
905    
906    =item genomeID
907    
908    ID of the genome whose functional assignments are desired.
909    
910  =item RETURN  =item RETURN
911    
912  Returns a three-element list. The first element is a list of feature IDs for the features that  Returns a reference to a hash which maps each feature to its most recent
913  overlap the region of interest. The second and third elements are the minimum and maximum  functional assignment.
 locations of the features provided on the specified contig. These may extend outside  
 the start and stop values.  
914    
915  =back  =back
916    
917  =cut  =cut
918  #: Return Type @;  
919  sub GenesInRegion {  sub GenomeAssignments {
920          # Get the parameters.          # Get the parameters.
921          my $self = shift @_;      my ($self, $genomeID) = @_;
922          my ($contigID, $start, $stop) = @_;      # Declare the return variable.
923          # Get the maximum segment length.      my $retVal = {};
924          my $maximumSegmentLength = $self->MaxSegment;      # Query the genome's features.
925          # Create a hash to receive the feature list. We use a hash so that we can eliminate      my $query = $self->Get(['HasFeature', 'Feature'], "HasFeature(from-link) = ?",
926          # duplicates easily.                             [$genomeID]);
927          my %featuresFound = ();      # Loop through the features.
928          # Prime the values we'll use for the returned beginning and end.      while (my $data = $query->Fetch) {
929          my ($min, $max) = ($self->ContigLength($contigID), 0);          # Get the feature ID and assignment.
930          # Create a table of parameters for each query. Each query looks for features travelling in          my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']);
931          # a particular direction. The query parameters include the contig ID, the feature direction,          if ($assignment) {
932          # the lowest possible start position, and the highest possible start position. This works              $retVal->{$fid} = $assignment;
933            }
934        }
935        # Return the result.
936        return $retVal;
937    }
938    
939    =head3 ContigLength
940    
941    C<< my $length = $sprout->ContigLength($contigID); >>
942    
943    Compute the length of a contig.
944    
945    =over 4
946    
947    =item contigID
948    
949    ID of the contig whose length is desired.
950    
951    =item RETURN
952    
953    Returns the number of positions in the contig.
954    
955    =back
956    
957    =cut
958    #: Return Type $;
959    sub ContigLength {
960        # Get the parameters.
961        my ($self, $contigID) = @_;
962        # Get the contig's last sequence.
963        my $query = $self->Get(['IsMadeUpOf'],
964            "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
965            [$contigID]);
966        my $sequence = $query->Fetch();
967        # Declare the return value.
968        my $retVal = 0;
969        # Set it from the sequence data, if any.
970        if ($sequence) {
971            my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
972            $retVal = $start + $len - 1;
973        }
974        # Return the result.
975        return $retVal;
976    }
977    
978    =head3 ClusterPEGs
979    
980    C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
981    
982    Cluster the PEGs in a list according to the cluster coding scheme of the specified
983    subsystem. In order for this to work properly, the subsystem object must have
984    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
985    This causes the cluster numbers to be pulled into the subsystem's color hash.
986    If a PEG is not found in the color hash, it will not appear in the output
987    sequence.
988    
989    =over 4
990    
991    =item sub
992    
993    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
994    method.
995    
996    =item pegs
997    
998    Reference to the list of PEGs to be clustered.
999    
1000    =item RETURN
1001    
1002    Returns a list of the PEGs, grouped into smaller lists by cluster number.
1003    
1004    =back
1005    
1006    =cut
1007    #: Return Type $@@;
1008    sub ClusterPEGs {
1009        # Get the parameters.
1010        my ($self, $sub, $pegs) = @_;
1011        # Declare the return variable.
1012        my $retVal = [];
1013        # Loop through the PEGs, creating arrays for each cluster.
1014        for my $pegID (@{$pegs}) {
1015            my $clusterNumber = $sub->get_cluster_number($pegID);
1016            # Only proceed if the PEG is in a cluster.
1017            if ($clusterNumber >= 0) {
1018                # Push this PEG onto the sub-list for the specified cluster number.
1019                push @{$retVal->[$clusterNumber]}, $pegID;
1020            }
1021        }
1022        # Return the result.
1023        return $retVal;
1024    }
1025    
1026    =head3 GenesInRegion
1027    
1028    C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>
1029    
1030    List the features which overlap a specified region in a contig.
1031    
1032    =over 4
1033    
1034    =item contigID
1035    
1036    ID of the contig containing the region of interest.
1037    
1038    =item start
1039    
1040    Offset of the first residue in the region of interest.
1041    
1042    =item stop
1043    
1044    Offset of the last residue in the region of interest.
1045    
1046    =item RETURN
1047    
1048    Returns a three-element list. The first element is a list of feature IDs for the features that
1049    overlap the region of interest. The second and third elements are the minimum and maximum
1050    locations of the features provided on the specified contig. These may extend outside
1051    the start and stop values. The first element (that is, the list of features) is sorted
1052    roughly by location.
1053    
1054    =back
1055    
1056    =cut
1057    #: Return Type @@;
1058    sub GenesInRegion {
1059        # Get the parameters.
1060        my ($self, $contigID, $start, $stop) = @_;
1061        # Get the maximum segment length.
1062        my $maximumSegmentLength = $self->MaxSegment;
1063        # Create a hash to receive the feature list. We use a hash so that we can eliminate
1064        # duplicates easily. The hash key will be the feature ID. The value will be a two-element
1065        # containing the minimum and maximum offsets. We will use the offsets to sort the results
1066        # when we're building the result set.
1067        my %featuresFound = ();
1068        # Prime the values we'll use for the returned beginning and end.
1069        my @initialMinMax = ($self->ContigLength($contigID), 0);
1070        my ($min, $max) = @initialMinMax;
1071        # Create a table of parameters for each query. Each query looks for features travelling in
1072        # a particular direction. The query parameters include the contig ID, the feature direction,
1073        # the lowest possible start position, and the highest possible start position. This works
1074          # because each feature segment length must be no greater than the maximum segment length.          # because each feature segment length must be no greater than the maximum segment length.
1075          my %queryParms = (forward => [$contigID, '+', $start - $maximumSegmentLength + 1, $stop],          my %queryParms = (forward => [$contigID, '+', $start - $maximumSegmentLength + 1, $stop],
1076                                            reverse => [$contigID, '-', $start, $stop + $maximumSegmentLength - 1]);                                            reverse => [$contigID, '-', $start, $stop + $maximumSegmentLength - 1]);
# Line 898  Line 1097 
1097                                          $found = 1;                                          $found = 1;
1098                                  }                                  }
1099                          } elsif ($dir eq '-') {                          } elsif ($dir eq '-') {
1100                                  $end = $beg - $len;                  # Note we switch things around so that the beginning is to the left of the
1101                                  if ($end <= $stop) {                  # ending.
1102                    ($beg, $end) = ($beg - $len, $beg);
1103                    if ($beg <= $stop) {
1104                                          # Denote we found a useful feature.                                          # Denote we found a useful feature.
1105                                          $found = 1;                                          $found = 1;
1106                                  }                                  }
1107                          }                          }
1108                          if ($found) {                          if ($found) {
1109                                  # 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,
1110                                  $featuresFound{$featureID} = 1;                  # get the current entry for the specified feature.
1111                                  if ($beg < $min) { $min = $beg; }                  my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :
1112                                  if ($end < $min) { $min = $end; }                                       @initialMinMax);
1113                                  if ($beg > $max) { $max = $beg; }                  # Merge the current segment's begin and end into the feature begin and end and the
1114                                  if ($end > $max) { $max = $end; }                  # global min and max.
1115                    if ($beg < $loc1) {
1116                        $loc1 = $beg;
1117                        $min = $beg if $beg < $min;
1118                    }
1119                    if ($end > $loc2) {
1120                        $loc2 = $end;
1121                        $max = $end if $end > $max;
1122                    }
1123                    # Store the entry back into the hash table.
1124                    $featuresFound{$featureID} = [$loc1, $loc2];
1125                          }                          }
1126                  }                  }
1127          }          }
1128          # 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
1129          my @list = (sort (keys %featuresFound));      # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1130        # but the result of the sort will be the same.)
1131        my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;
1132        # Now we sort by midpoint and yank out the feature IDs.
1133        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1134          # Return it along with the min and max.          # Return it along with the min and max.
1135          return (\@list, $min, $max);      return (\@retVal, $min, $max);
1136  }  }
1137    
1138  =head3 FType  =head3 FType
# Line 943  Line 1158 
1158  #: Return Type $;  #: Return Type $;
1159  sub FType {  sub FType {
1160          # Get the parameters.          # Get the parameters.
1161          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1162          # Get the specified feature's type.          # Get the specified feature's type.
1163          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
1164          # Return the result.          # Return the result.
# Line 953  Line 1167 
1167    
1168  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1169    
1170  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1171    
1172  Return the annotations of a feature.  Return the annotations of a feature.
1173    
# Line 963  Line 1177 
1177    
1178  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1179    
1180    =item rawFlag
1181    
1182    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1183    will be returned in human-readable form.
1184    
1185  =item RETURN  =item RETURN
1186    
1187  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.
1188    
1189  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1190    
1191  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1192    
1193  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1194    
# Line 981  Line 1200 
1200  #: Return Type @%;  #: Return Type @%;
1201  sub FeatureAnnotations {  sub FeatureAnnotations {
1202          # Get the parameters.          # Get the parameters.
1203          my $self = shift @_;      my ($self, $featureID, $rawFlag) = @_;
         my ($featureID) = @_;  
1204          # 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.
1205          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1206                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 995  Line 1213 
1213                          $annotation->Values(['IsTargetOfAnnotation(from-link)',                          $annotation->Values(['IsTargetOfAnnotation(from-link)',
1214                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1215                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1216            # Convert the time, if necessary.
1217            if (! $rawFlag) {
1218                $timeStamp = FriendlyTimestamp($timeStamp);
1219            }
1220                  # Assemble them into a hash.                  # Assemble them into a hash.
1221          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1222                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1223                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1224                  # Add it to the return list.                  # Add it to the return list.
1225                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1011  Line 1233 
1233  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>
1234    
1235  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
1236  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,
1237  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
1238  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,
1239  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.
1240  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
1241  functional assignments, we will only keep the most recent one.  recent one.
1242    
1243  =over 4  =over 4
1244    
# Line 1026  Line 1248 
1248    
1249  =item RETURN  =item RETURN
1250    
1251  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1252    
1253  =back  =back
1254    
# Line 1034  Line 1256 
1256  #: Return Type %;  #: Return Type %;
1257  sub AllFunctionsOf {  sub AllFunctionsOf {
1258          # Get the parameters.          # Get the parameters.
1259          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1260          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1261      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1262                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1263                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1264                                               'MadeAnnotation(from-link)']);
1265          # Declare the return hash.          # Declare the return hash.
1266          my %retVal;          my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1267      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1268      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1269          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1270      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1271          # Get the annotation fields.          # Get the annotation fields.
1272          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1273                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1274                  my ($user, $function) = ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1275          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1276              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1277              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1278              # return hash.              # return hash.
1279                          $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1280                  }                  }
1281          }          }
1282          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1072  Line 1290 
1290  Return the most recently-determined functional assignment of a particular feature.  Return the most recently-determined functional assignment of a particular feature.
1291    
1292  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
1293  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 the functional
1294  assignment is a type of annotation. It has the format "XXXX\nset XXXX function to\nYYYYY". In this  assignment is taken from the B<Feature> or C<Annotation> table, depending.
 instance, XXXX is the user ID and YYYYY is the functional assignment text. Its worth noting that  
 we cannot filter on the content of the annotation itself because it's a text field; however, this  
 is not a big problem because most features only have a small number of annotations.  
1295    
1296  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
1297  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 1095  Line 1310 
1310    
1311  =item userID (optional)  =item userID (optional)
1312    
1313  ID of the user whose function determination is desired. If omitted, only the latest  ID of the user whose function determination is desired. If omitted, the primary
1314  C<FIG> assignment will be returned.  functional assignment in the B<Feature> table will be returned.
1315    
1316  =item RETURN  =item RETURN
1317    
# Line 1108  Line 1323 
1323  #: Return Type $;  #: Return Type $;
1324  sub FunctionOf {  sub FunctionOf {
1325          # Get the parameters.          # Get the parameters.
1326          my $self = shift @_;      my ($self, $featureID, $userID) = @_;
         my ($featureID, $userID) = @_;  
1327      # Declare the return value.      # Declare the return value.
1328      my $retVal;      my $retVal;
1329      # Determine the ID type.      # Determine the ID type.
1330      if ($featureID =~ m/^fig\|/) {      if ($featureID =~ m/^fig\|/) {
1331          # Here we have a FIG feature ID. We must build the list of trusted          # Here we have a FIG feature ID.
1332          # users.          if (!$userID) {
1333                # Use the primary assignment.
1334                ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']);
1335            } else {
1336                # We must build the list of trusted users.
1337          my %trusteeTable = ();          my %trusteeTable = ();
1338          # Check the user ID.          # Check the user ID.
1339          if (!$userID) {          if (!$userID) {
# Line 1137  Line 1355 
1355              }              }
1356          }          }
1357          # 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.
1358          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],              my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1359                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1360                                 [$featureID]);                                 [$featureID]);
1361          my $timeSelected = 0;          my $timeSelected = 0;
1362          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1363          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1364              # Get the annotation text.              # Get the annotation text.
1365              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);                  my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1366                                                             'Annotation(time)', 'MadeAnnotation(from-link)']);
1367              # 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.
1368              my ($user, $type, $function) = split(/\n/, $text);                  my ($actualUser, $function) = _ParseAssignment($user, $text);
1369              if ($type =~ m/^set $user function to$/i) {                  Trace("Assignment user is $actualUser, text is $function.") if T(4);
1370                    if ($actualUser) {
1371                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1372                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1373                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                      if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1374                      $retVal = $function;                      $retVal = $function;
1375                      $timeSelected = $time;                      $timeSelected = $time;
1376                  }                  }
1377              }              }
1378          }          }
1379            }
1380      } else {      } else {
1381          # Here we have a non-FIG feature ID. In this case the user ID does not          # Here we have a non-FIG feature ID. In this case the user ID does not
1382          # matter. We simply get the information from the External Alias Function          # matter. We simply get the information from the External Alias Function
# Line 1166  Line 1387 
1387          return $retVal;          return $retVal;
1388  }  }
1389    
1390    =head3 FunctionsOf
1391    
1392    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1393    
1394    Return the functional assignments of a particular feature.
1395    
1396    The functional assignment is handled differently depending on the type of feature. If
1397    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1398    assignment is a type of annotation. The format of an assignment is described in
1399    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1400    annotation itself because it's a text field; however, this is not a big problem because
1401    most features only have a small number of annotations.
1402    
1403    If the feature is B<not> identified by a FIG ID, then the functional assignment
1404    information is taken from the B<ExternalAliasFunc> table. If the table does
1405    not contain an entry for the feature, an empty list is returned.
1406    
1407    =over 4
1408    
1409    =item featureID
1410    
1411    ID of the feature whose functional assignments are desired.
1412    
1413    =item RETURN
1414    
1415    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1416    that user.
1417    
1418    =back
1419    
1420    =cut
1421    #: Return Type @@;
1422    sub FunctionsOf {
1423        # Get the parameters.
1424        my ($self, $featureID) = @_;
1425        # Declare the return value.
1426        my @retVal = ();
1427        # Determine the ID type.
1428        if ($featureID =~ m/^fig\|/) {
1429            # Here we have a FIG feature ID. We must build the list of trusted
1430            # users.
1431            my %trusteeTable = ();
1432            # Build a query for all of the feature's annotations, sorted by date.
1433            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1434                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1435                                   [$featureID]);
1436            my $timeSelected = 0;
1437            # Loop until we run out of annotations.
1438            while (my $annotation = $query->Fetch()) {
1439                # Get the annotation text.
1440                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1441                                                                'Annotation(time)',
1442                                                                'MadeAnnotation(user)']);
1443                # Check to see if this is a functional assignment for a trusted user.
1444                my ($actualUser, $function) = _ParseAssignment($user, $text);
1445                if ($actualUser) {
1446                    # Here it is a functional assignment.
1447                    push @retVal, [$actualUser, $function];
1448                }
1449            }
1450        } else {
1451            # Here we have a non-FIG feature ID. In this case the user ID does not
1452            # matter. We simply get the information from the External Alias Function
1453            # table.
1454            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1455                                                     ['ExternalAliasFunc(func)']);
1456            push @retVal, map { ['master', $_] } @assignments;
1457        }
1458        # Return the assignments found.
1459        return @retVal;
1460    }
1461    
1462  =head3 BBHList  =head3 BBHList
1463    
1464  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1185  Line 1478 
1478    
1479  =item RETURN  =item RETURN
1480    
1481  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
1482  their best hits.  on the target genome.
1483    
1484  =back  =back
1485    
# Line 1194  Line 1487 
1487  #: Return Type %;  #: Return Type %;
1488  sub BBHList {  sub BBHList {
1489          # Get the parameters.          # Get the parameters.
1490          my $self = shift @_;      my ($self, $genomeID, $featureList) = @_;
         my ($genomeID, $featureList) = @_;  
1491          # Create the return structure.          # Create the return structure.
1492          my %retVal = ();          my %retVal = ();
1493          # Loop through the incoming features.          # Loop through the incoming features.
1494          for my $featureID (@{$featureList}) {          for my $featureID (@{$featureList}) {
1495                  # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1496                  my $query = $self->Get(['IsBidirectionalBestHitOf'],          my @bbhData = FIGRules::BBHData($featureID);
1497                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",          # Peel off the BBHs found.
1498                                                             [$featureID, $genomeID]);          my @found = ();
1499                  # Look for the best hit.          for my $bbh (@bbhData) {
1500                  my $bbh = $query->Fetch;              my $fid = $bbh->[0];
1501                  if ($bbh) {              my $bbGenome = $self->GenomeOf($fid);
1502                          my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              if ($bbGenome eq $genomeID) {
1503                          $retVal{$featureID} = $targetFeature;                  push @found, $fid;
1504                }
1505                  }                  }
1506            $retVal{$featureID} = \@found;
1507          }          }
1508          # Return the mapping.          # Return the mapping.
1509          return \%retVal;          return \%retVal;
1510  }  }
1511    
1512    =head3 SimList
1513    
1514    C<< my %similarities = $sprout->SimList($featureID, $count); >>
1515    
1516    Return a list of the similarities to the specified feature.
1517    
1518    This method just returns the bidirectional best hits for performance reasons.
1519    
1520    =over 4
1521    
1522    =item featureID
1523    
1524    ID of the feature whose similarities are desired.
1525    
1526    =item count
1527    
1528    Maximum number of similar features to be returned, or C<0> to return them all.
1529    
1530    =back
1531    
1532    =cut
1533    #: Return Type %;
1534    sub SimList {
1535        # Get the parameters.
1536        my ($self, $featureID, $count) = @_;
1537        # Ask for the best hits.
1538        my @lists = FIGRules::BBHData($featureID);
1539        # Create the return value.
1540        my %retVal = ();
1541        for my $tuple (@lists) {
1542            $retVal{$tuple->[0]} = $tuple->[1];
1543        }
1544        # Return the result.
1545        return %retVal;
1546    }
1547    
1548    =head3 IsComplete
1549    
1550    C<< my $flag = $sprout->IsComplete($genomeID); >>
1551    
1552    Return TRUE if the specified genome is complete, else FALSE.
1553    
1554    =over 4
1555    
1556    =item genomeID
1557    
1558    ID of the genome whose completeness status is desired.
1559    
1560    =item RETURN
1561    
1562    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1563    not found.
1564    
1565    =back
1566    
1567    =cut
1568    #: Return Type $;
1569    sub IsComplete {
1570        # Get the parameters.
1571        my ($self, $genomeID) = @_;
1572        # Declare the return variable.
1573        my $retVal;
1574        # Get the genome's data.
1575        my $genomeData = $self->GetEntity('Genome', $genomeID);
1576        if ($genomeData) {
1577            # The genome exists, so get the completeness flag.
1578            ($retVal) = $genomeData->Value('Genome(complete)');
1579        }
1580        # Return the result.
1581        return $retVal;
1582    }
1583    
1584  =head3 FeatureAliases  =head3 FeatureAliases
1585    
1586  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
# Line 1238  Line 1604 
1604  #: Return Type @;  #: Return Type @;
1605  sub FeatureAliases {  sub FeatureAliases {
1606          # Get the parameters.          # Get the parameters.
1607          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1608          # Get the desired feature's aliases          # Get the desired feature's aliases
1609          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);
1610          # Return the result.          # Return the result.
# Line 1250  Line 1615 
1615    
1616  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1617    
1618  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1619    
1620  =over 4  =over 4
1621    
1622  =item featureID  =item featureID
1623    
1624  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1625    
1626  =item RETURN  =item RETURN
1627    
1628  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
1629  an undefined value.  found, returns an undefined value.
1630    
1631  =back  =back
1632    
# Line 1269  Line 1634 
1634  #: Return Type $;  #: Return Type $;
1635  sub GenomeOf {  sub GenomeOf {
1636          # Get the parameters.          # Get the parameters.
1637          my $self = shift @_;      my ($self, $featureID) = @_;
1638          my ($featureID) = @_;      # Create a query to find the genome associated with the incoming ID.
1639          # Create a query to find the genome associated with the feature.      my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",
1640          my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);                             [$featureID, $featureID]);
1641          # Declare the return value.          # Declare the return value.
1642          my $retVal;          my $retVal;
1643          # Get the genome ID.          # Get the genome ID.
# Line 1306  Line 1671 
1671  #: Return Type %;  #: Return Type %;
1672  sub CoupledFeatures {  sub CoupledFeatures {
1673          # Get the parameters.          # Get the parameters.
1674          my $self = shift @_;      my ($self, $featureID) = @_;
1675          my ($featureID) = @_;      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1676          # Create a query to retrieve the functionally-coupled features. Note that we depend on the      # Create a query to retrieve the functionally-coupled features.
1677          # fact that the functional coupling is physically paired. If (A,B) is in the database, then      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
1678          # (B,A) will also be found.                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);
         my $query = $self->Get(['IsClusteredOnChromosomeWith'],  
                                                    "IsClusteredOnChromosomeWith(from-link) = ?", [$featureID]);  
1679          # This value will be set to TRUE if we find at least one coupled feature.          # This value will be set to TRUE if we find at least one coupled feature.
1680          my $found = 0;          my $found = 0;
1681          # Create the return hash.          # Create the return hash.
1682          my %retVal = ();          my %retVal = ();
1683          # Retrieve the relationship records and store them in the hash.          # Retrieve the relationship records and store them in the hash.
1684          while (my $clustering = $query->Fetch()) {          while (my $clustering = $query->Fetch()) {
1685                  my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',          # Get the ID and score of the coupling.
1686                                                                      'IsClusteredOnChromosomeWith(score)']);          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
1687                                                            'Coupling(score)']);
1688            Trace("$featureID coupled with score $score to ID $couplingID.") if T(coupling => 4);
1689            # Get the other feature that participates in the coupling.
1690            my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],
1691                                               "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",
1692                                               [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');
1693            Trace("$couplingID target feature is $otherFeatureID.") if T(coupling => 4);
1694            # Attach the other feature's score to its ID.
1695                  $retVal{$otherFeatureID} = $score;                  $retVal{$otherFeatureID} = $score;
1696                  $found = 1;                  $found = 1;
1697          }          }
# Line 1333  Line 1704 
1704          return %retVal;          return %retVal;
1705  }  }
1706    
1707  =head3 GetEntityTypes  =head3 CouplingEvidence
1708    
1709    C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1710    
1711    Return the evidence for a functional coupling.
1712    
1713    A pair of features is considered evidence of a coupling between two other
1714    features if they occur close together on a contig and both are similar to
1715    the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1716    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1717    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1718    similar to B<A2>.
1719    
1720    The score of a coupling is determined by the number of pieces of evidence
1721    that are considered I<representative>. If several evidence items belong to
1722    a group of genomes that are close to each other, only one of those items
1723    is considered representative. The other evidence items are presumed to be
1724    there because of the relationship between the genomes rather than because
1725    the two proteins generated by the features have a related functionality.
1726    
1727    Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1728    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1729    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1730    and FALSE otherwise.
1731    
1732    =over 4
1733    
1734    =item peg1
1735    
1736    ID of the feature of interest.
1737    
1738  C<< my @entityList = $sprout->GetEntityTypes(); >>  =item peg2
1739    
1740  Return the list of supported entity types.  ID of a feature functionally coupled to the feature of interest.
1741    
1742    =item RETURN
1743    
1744    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1745    of interest, a feature similar to the functionally coupled feature, and a flag
1746    that is TRUE for a representative piece of evidence and FALSE otherwise.
1747    
1748    =back
1749    
1750  =cut  =cut
1751  #: Return Type @;  #: Return Type @@;
1752  sub GetEntityTypes {  sub CouplingEvidence {
1753          # Get the parameters.          # Get the parameters.
1754          my $self = shift @_;      my ($self, $peg1, $peg2) = @_;
1755          # Get the underlying database object.      # Declare the return variable.
1756          my $erdb = $self->{_erdb};      my @retVal = ();
1757          # Get its entity type list.      # Our first task is to find out the nature of the coupling: whether or not
1758          my @retVal = $erdb->GetEntityTypes();      # it exists, its score, and whether the features are stored in the same
1759        # order as the ones coming in.
1760        my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
1761        # Only proceed if a coupling exists.
1762        if ($couplingID) {
1763            # Determine the ordering to place on the evidence items. If we're
1764            # inverted, we want to see feature 2 before feature 1 (descending); otherwise,
1765            # we want feature 1 before feature 2 (normal).
1766            Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);
1767            my $ordering = ($inverted ? "DESC" : "");
1768            # Get the coupling evidence.
1769            my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],
1770                                              "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",
1771                                              [$couplingID],
1772                                              ['PCH(used)', 'UsesAsEvidence(to-link)']);
1773            # Loop through the evidence items. Each piece of evidence is represented by two
1774            # positions in the evidence list, one for each feature on the other side of the
1775            # evidence link. If at some point we want to generalize to couplings with
1776            # more than two positions, this section of code will need to be re-done.
1777            while (@evidenceList > 0) {
1778                my $peg1Data = shift @evidenceList;
1779                my $peg2Data = shift @evidenceList;
1780                Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);
1781                push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];
1782            }
1783            Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);
1784        }
1785        # Return the result.
1786        return @retVal;
1787  }  }
1788    
1789  =head3 ReadFasta  =head3 GetCoupling
1790    
1791  C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>  C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>
1792    
1793  Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by  Return the coupling (if any) for the specified pair of PEGs. If a coupling
1794  one or more lines of data. The first line begins with a > character and contains an ID.  exists, we return the coupling ID along with an indicator of whether the
1795  The remaining lines contain the sequence data in order.  coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.
1796    In the second case, we say the coupling is I<inverted>. The importance of an
1797    inverted coupling is that the PEGs in the evidence will appear in reverse order.
1798    
1799  =over 4  =over 4
1800    
1801  =item fileName  =item peg1
1802    
1803  Name of the FASTA file.  ID of the feature of interest.
1804    
1805  =item prefix (optional)  =item peg2
1806    
1807  Prefix to be put in front of each ID found.  ID of the potentially coupled feature.
1808    
1809  =item RETURN  =item RETURN
1810    
1811  Returns a hash that maps each ID to its sequence.  Returns a three-element list. The first element contains the database ID of
1812    the coupling. The second element is FALSE if the coupling is stored in the
1813    database in the caller specified order and TRUE if it is stored in the
1814    inverted order. The third element is the coupling's score. If the coupling
1815    does not exist, all three list elements will be C<undef>.
1816    
1817  =back  =back
1818    
1819  =cut  =cut
1820  #: Return Type %;  #: Return Type $%@;
1821  sub ReadFasta {  sub GetCoupling {
1822          # Get the parameters.          # Get the parameters.
1823          my ($fileName, $prefix) = @_;      my ($self, $peg1, $peg2) = @_;
1824          # Create the return hash.      # Declare the return values. We'll start with the coupling ID and undefine the
1825          my %retVal = ();      # flag and score until we have more information.
1826          # Open the file for input.      my ($retVal, $inverted, $score) = ($self->CouplingID($peg1, $peg2), undef, undef);
1827          open FASTAFILE, '<', $fileName;      # Find the coupling data.
1828          # Declare the ID variable and clear the sequence accumulator.      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],
1829          my $sequence = "";                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",
1830                                     [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);
1831        # Check to see if we found anything.
1832        if (!@pegs) {
1833            Trace("No coupling found.") if T(Coupling => 4);
1834            # No coupling, so undefine the return value.
1835            $retVal = undef;
1836        } else {
1837            # We have a coupling! Get the score and check for inversion.
1838            $score = $pegs[0]->[1];
1839            my $firstFound = $pegs[0]->[0];
1840            $inverted = ($firstFound ne $peg1);
1841            Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);
1842        }
1843        # Return the result.
1844        return ($retVal, $inverted, $score);
1845    }
1846    
1847    =head3 GetSynonymGroup
1848    
1849    C<< my $id = $sprout->GetSynonymGroup($fid); >>
1850    
1851    Return the synonym group name for the specified feature.
1852    
1853    =over 4
1854    
1855    =item fid
1856    
1857    ID of the feature whose synonym group is desired.
1858    
1859    =item RETURN
1860    
1861    The name of the synonym group to which the feature belongs. If the feature does
1862    not belong to a synonym group, the feature ID itself is returned.
1863    
1864    =back
1865    
1866    =cut
1867    
1868    sub GetSynonymGroup {
1869        # Get the parameters.
1870        my ($self, $fid) = @_;
1871        # Declare the return variable.
1872        my $retVal;
1873        # Find the synonym group.
1874        my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1875                                       [$fid], 'IsSynonymGroupFor(from-link)');
1876        # Check to see if we found anything.
1877        if (@groups) {
1878            $retVal = $groups[0];
1879        } else {
1880            $retVal = $fid;
1881        }
1882        # Return the result.
1883        return $retVal;
1884    }
1885    
1886    =head3 GetBoundaries
1887    
1888    C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>
1889    
1890    Determine the begin and end boundaries for the locations in a list. All of the
1891    locations must belong to the same contig and have mostly the same direction in
1892    order for this method to produce a meaningful result. The resulting
1893    begin/end pair will contain all of the bases in any of the locations.
1894    
1895    =over 4
1896    
1897    =item locList
1898    
1899    List of locations to process.
1900    
1901    =item RETURN
1902    
1903    Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1904    and the ending boundary. The beginning boundary will be left of the
1905    end for mostly-forward locations and right of the end for mostly-backward
1906    locations.
1907    
1908    =back
1909    
1910    =cut
1911    
1912    sub GetBoundaries {
1913        # Get the parameters.
1914        my ($self, @locList) = @_;
1915        # Set up the counters used to determine the most popular direction.
1916        my %counts = ( '+' => 0, '-' => 0 );
1917        # Get the last location and parse it.
1918        my $locObject = BasicLocation->new(pop @locList);
1919        # Prime the loop with its data.
1920        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
1921        # Count its direction.
1922        $counts{$locObject->Dir}++;
1923        # Loop through the remaining locations. Note that in most situations, this loop
1924        # will not iterate at all, because most of the time we will be dealing with a
1925        # singleton list.
1926        for my $loc (@locList) {
1927            # Create a location object.
1928            my $locObject = BasicLocation->new($loc);
1929            # Count the direction.
1930            $counts{$locObject->Dir}++;
1931            # Get the left end and the right end.
1932            my $left = $locObject->Left;
1933            my $right = $locObject->Right;
1934            # Merge them into the return variables.
1935            if ($left < $beg) {
1936                $beg = $left;
1937            }
1938            if ($right > $end) {
1939                $end = $right;
1940            }
1941        }
1942        # If the most common direction is reverse, flip the begin and end markers.
1943        if ($counts{'-'} > $counts{'+'}) {
1944            ($beg, $end) = ($end, $beg);
1945        }
1946        # Return the result.
1947        return ($contig, $beg, $end);
1948    }
1949    
1950    =head3 CouplingID
1951    
1952    C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >>
1953    
1954    Return the coupling ID for a pair of feature IDs.
1955    
1956    The coupling ID is currently computed by joining the feature IDs in
1957    sorted order with a space. Client modules (that is, modules which
1958    use Sprout) should not, however, count on this always being the
1959    case. This method provides a way for abstracting the concept of a
1960    coupling ID. All that we know for sure about it is that it can be
1961    generated easily from the feature IDs and the order of the IDs
1962    in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>
1963    will have the same value as C<CouplingID("b1", "a1")>.
1964    
1965    =over 4
1966    
1967    =item peg1
1968    
1969    First feature of interest.
1970    
1971    =item peg2
1972    
1973    Second feature of interest.
1974    
1975    =item RETURN
1976    
1977    Returns the ID that would be used to represent a functional coupling of
1978    the two specified PEGs.
1979    
1980    =back
1981    
1982    =cut
1983    #: Return Type $;
1984    sub CouplingID {
1985        my ($self, @pegs) = @_;
1986        return $self->DigestKey(join " ", sort @pegs);
1987    }
1988    
1989    =head3 ReadFasta
1990    
1991    C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>
1992    
1993    Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by
1994    one or more lines of data. The first line begins with a > character and contains an ID.
1995    The remaining lines contain the sequence data in order.
1996    
1997    =over 4
1998    
1999    =item fileName
2000    
2001    Name of the FASTA file.
2002    
2003    =item prefix (optional)
2004    
2005    Prefix to be put in front of each ID found.
2006    
2007    =item RETURN
2008    
2009    Returns a hash that maps each ID to its sequence.
2010    
2011    =back
2012    
2013    =cut
2014    #: Return Type %;
2015    sub ReadFasta {
2016        # Get the parameters.
2017        my ($fileName, $prefix) = @_;
2018        # Create the return hash.
2019        my %retVal = ();
2020        # Open the file for input.
2021        open FASTAFILE, '<', $fileName;
2022        # Declare the ID variable and clear the sequence accumulator.
2023        my $sequence = "";
2024          my $id = "";          my $id = "";
2025          # Loop through the file.          # Loop through the file.
2026          while (<FASTAFILE>) {          while (<FASTAFILE>) {
# Line 1394  Line 2030 
2030                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
2031                          # 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.
2032                          if ($id) {                          if ($id) {
2033                                  $retVal{$id} = $sequence;                  $retVal{$id} = lc $sequence;
2034                          }                          }
2035                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
2036                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
2037                  } else {                  } else {
2038                          # 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.
2039                          # First, we get the actual data out.              # First, we get the actual data out. Note that we normalize to lower
2040                # case.
2041                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
2042                          $sequence .= $1;                          $sequence .= $1;
2043                  }                  }
2044          }          }
2045          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
2046          if ($sequence) {          if ($sequence) {
2047                  $retVal {$id} = $sequence;          $retVal{$id} = lc $sequence;
2048          }          }
2049        # Close the file.
2050        close FASTAFILE;
2051          # Return the hash constructed from the file.          # Return the hash constructed from the file.
2052          return %retVal;          return %retVal;
2053  }  }
# Line 1419  Line 2058 
2058    
2059  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
2060  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
2061  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,
2062    it will not be changed; otherwise, it will be converted. This method can also be used to
2063    perform the reverse task-- insuring that all the locations are in the old format.
2064    
2065  =over 4  =over 4
2066    
# Line 1446  Line 2087 
2087  #: Return Type @;  #: Return Type @;
2088  sub FormatLocations {  sub FormatLocations {
2089          # Get the parameters.          # Get the parameters.
2090          my $self = shift @_;      my ($self, $prefix, $locations, $oldFormat) = @_;
         my ($prefix, $locations, $oldFormat) = @_;  
2091          # Create the return list.          # Create the return list.
2092          my @retVal = ();          my @retVal = ();
2093          # Check to see if any locations were passed in.          # Check to see if any locations were passed in.
2094          if ($locations eq '') {          if ($locations eq '') {
2095              confess "No locations specified.";          Confess("No locations specified.");
2096          } else {          } else {
2097                  # Loop through the locations, converting them to the new format.                  # Loop through the locations, converting them to the new format.
2098                  for my $location (@{$locations}) {                  for my $location (@{$locations}) {
# Line 1487  Line 2127 
2127    
2128  sub DumpData {  sub DumpData {
2129          # Get the parameters.          # Get the parameters.
2130          my $self = shift @_;      my ($self) = @_;
2131          # Get the data directory name.          # Get the data directory name.
2132          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
2133          # Dump the relations.          # Dump the relations.
2134          $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2135  }  }
2136    
2137  =head3 XMLFileName  =head3 XMLFileName
# Line 1503  Line 2143 
2143  =cut  =cut
2144  #: Return Type $;  #: Return Type $;
2145  sub XMLFileName {  sub XMLFileName {
2146          my $self = shift @_;      my ($self) = @_;
2147          return $self->{_xmlName};          return $self->{_xmlName};
2148  }  }
2149    
# Line 1523  Line 2163 
2163  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
2164  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>.
2165    
2166  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'}); >>
2167    
2168  =over 4  =over 4
2169    
# Line 1541  Line 2181 
2181  #: Return Type ;  #: Return Type ;
2182  sub Insert {  sub Insert {
2183          # Get the parameters.          # Get the parameters.
2184          my $self = shift @_;      my ($self, $objectType, $fieldHash) = @_;
         my ($objectType, $fieldHash) = @_;  
2185          # Call the underlying method.          # Call the underlying method.
2186          $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2187  }  }
2188    
2189  =head3 Annotate  =head3 Annotate
# Line 1583  Line 2222 
2222  #: Return Type $;  #: Return Type $;
2223  sub Annotate {  sub Annotate {
2224          # Get the parameters.          # Get the parameters.
2225          my $self = shift @_;      my ($self, $fid, $timestamp, $user, $text) = @_;
         my ($fid, $timestamp, $user, $text) = @_;  
2226          # Create the annotation ID.          # Create the annotation ID.
2227          my $aid = "$fid:$timestamp";          my $aid = "$fid:$timestamp";
2228          # Insert the Annotation object.          # Insert the Annotation object.
# Line 1604  Line 2242 
2242    
2243  =head3 AssignFunction  =head3 AssignFunction
2244    
2245  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function); >>  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>
2246    
2247  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
2248  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.  
2249    
2250  =over 4  =over 4
2251    
# Line 1618  Line 2255 
2255    
2256  =item user  =item user
2257    
2258  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>.
2259    
2260  =item function  =item function
2261    
2262  Text of the function being assigned.  Text of the function being assigned.
2263    
2264    =item assigningUser (optional)
2265    
2266    Name of the individual user making the assignment. If omitted, defaults to the user group.
2267    
2268  =item RETURN  =item RETURN
2269    
2270  Returns 1 if successful, 0 if an error occurred.  Returns 1 if successful, 0 if an error occurred.
# Line 1634  Line 2275 
2275  #: Return Type $;  #: Return Type $;
2276  sub AssignFunction {  sub AssignFunction {
2277          # Get the parameters.          # Get the parameters.
2278          my $self = shift @_;      my ($self, $featureID, $user, $function, $assigningUser) = @_;
2279          my ($featureID, $user, $function) = @_;      # Default the assigning user.
2280        if (! $assigningUser) {
2281            $assigningUser = $user;
2282        }
2283          # Create an annotation string from the parameters.          # Create an annotation string from the parameters.
2284          my $annotationText = "$user\nset $user function to\n$function";      my $annotationText = "$assigningUser\nset $user function to\n$function";
2285          # Get the current time.          # Get the current time.
2286          my $now = time;          my $now = time;
2287          # Declare the return variable.          # Declare the return variable.
# Line 1682  Line 2326 
2326  #: Return Type @;  #: Return Type @;
2327  sub FeaturesByAlias {  sub FeaturesByAlias {
2328          # Get the parameters.          # Get the parameters.
2329          my $self = shift @_;      my ($self, $alias) = @_;
         my ($alias) = @_;  
2330          # Declare the return variable.          # Declare the return variable.
2331          my @retVal = ();          my @retVal = ();
2332          # Parse the alias.          # Parse the alias.
# Line 1699  Line 2342 
2342          return @retVal;          return @retVal;
2343  }  }
2344    
 =head3 Exists  
   
 C<< my $found = $sprout->Exists($entityName, $entityID); >>  
   
 Return TRUE if an entity exists, else FALSE.  
   
 =over 4  
   
 =item entityName  
   
 Name of the entity type (e.g. C<Feature>) relevant to the existence check.  
   
 =item entityID  
   
 ID of the entity instance whose existence is to be checked.  
   
 =item RETURN  
   
 Returns TRUE if the entity instance exists, else FALSE.  
   
 =back  
   
 =cut  
 #: Return Type $;  
 sub Exists {  
         # Get the parameters.  
         my $self = shift @_;  
         my ($entityName, $entityID) = @_;  
         # Check for the entity instance.  
         my $testInstance = $self->GetEntity($entityName, $entityID);  
         # Return an existence indicator.  
         my $retVal = ($testInstance ? 1 : 0);  
         return $retVal;  
 }  
   
2345  =head3 FeatureTranslation  =head3 FeatureTranslation
2346    
2347  C<< my $translation = $sprout->FeatureTranslation($featureID); >>  C<< my $translation = $sprout->FeatureTranslation($featureID); >>
# Line 1756  Line 2364 
2364  #: Return Type $;  #: Return Type $;
2365  sub FeatureTranslation {  sub FeatureTranslation {
2366          # Get the parameters.          # Get the parameters.
2367          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2368          # Get the specified feature's translation.          # Get the specified feature's translation.
2369          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
2370          return $retVal;          return $retVal;
# Line 1789  Line 2396 
2396  #: Return Type @;  #: Return Type @;
2397  sub Taxonomy {  sub Taxonomy {
2398          # Get the parameters.          # Get the parameters.
2399          my $self = shift @_;      my ($self, $genome) = @_;
         my ($genome) = @_;  
2400          # Find the specified genome's taxonomy string.          # Find the specified genome's taxonomy string.
2401          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);
2402          # Declare the return variable.          # Declare the return variable.
# Line 1833  Line 2439 
2439  #: Return Type $;  #: Return Type $;
2440  sub CrudeDistance {  sub CrudeDistance {
2441          # Get the parameters.          # Get the parameters.
2442          my $self = shift @_;      my ($self, $genome1, $genome2) = @_;
         my ($genome1, $genome2) = @_;  
2443          # Insure that the distance is commutative by sorting the genome IDs.          # Insure that the distance is commutative by sorting the genome IDs.
2444          my ($genomeA, $genomeB);          my ($genomeA, $genomeB);
2445          if ($genome2 < $genome2) {          if ($genome2 < $genome2) {
# Line 1881  Line 2486 
2486  #: Return Type $;  #: Return Type $;
2487  sub RoleName {  sub RoleName {
2488          # Get the parameters.          # Get the parameters.
2489          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2490          # Get the specified role's name.          # Get the specified role's name.
2491          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);
2492          # Use the ID if the role has no name.          # Use the ID if the role has no name.
# Line 1915  Line 2519 
2519  #: Return Type @;  #: Return Type @;
2520  sub RoleDiagrams {  sub RoleDiagrams {
2521          # Get the parameters.          # Get the parameters.
2522          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2523          # Query for the diagrams.          # Query for the diagrams.
2524          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2525                                                                  'RoleOccursIn(to-link)');                                                                  'RoleOccursIn(to-link)');
# Line 1924  Line 2527 
2527          return @retVal;          return @retVal;
2528  }  }
2529    
2530    =head3 GetProperties
2531    
2532    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2533    
2534    Return a list of the properties with the specified characteristics.
2535    
2536    Properties are arbitrary key-value pairs associated with a feature. (At some point they
2537    will also be associated with genomes.) A property value is represented by a 4-tuple of
2538    the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter
2539    
2540    =over 4
2541    
2542    =item fid
2543    
2544    ID of the feature possessing the property.
2545    
2546    =item key
2547    
2548    Name or key of the property.
2549    
2550    =item value
2551    
2552    Value of the property.
2553    
2554    =item url
2555    
2556    URL of the document that indicated the property should have this particular value, or an
2557    empty string if no such document exists.
2558    
2559    =back
2560    
2561    The parameters act as a filter for the desired data. Any non-null parameter will
2562    automatically match all the tuples returned. So, specifying just the I<$fid> will
2563    return all the properties of the specified feature; similarly, specifying the I<$key>
2564    and I<$value> parameters will return all the features having the specified property
2565    value.
2566    
2567    A single property key can have many values, representing different ideas about the
2568    feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is
2569    virulent, and another may declare that it is not virulent. A query about the virulence of
2570    C<fig|83333.1.peg.10> would be coded as
2571    
2572        my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');
2573    
2574    Here the I<$value> and I<$url> fields are left blank, indicating that those fields are
2575    not to be filtered. The tuples returned would be
2576    
2577        ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')
2578        ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')
2579    
2580    =cut
2581    #: Return Type @@;
2582    sub GetProperties {
2583        # Get the parameters.
2584        my ($self, @parms) = @_;
2585        # Declare the return variable.
2586        my @retVal = ();
2587        # Now we need to create a WHERE clause that will get us the data we want. First,
2588        # we create a list of the columns containing the data for each parameter.
2589        my @colNames = ('HasProperty(from-link)', 'Property(property-name)',
2590                        'Property(property-value)', 'HasProperty(evidence)');
2591        # Now we build the WHERE clause and the list of parameter values.
2592        my @where = ();
2593        my @values = ();
2594        for (my $i = 0; $i <= $#colNames; $i++) {
2595            my $parm = $parms[$i];
2596            if (defined $parm && ($parm ne '')) {
2597                push @where, "$colNames[$i] = ?";
2598                push @values, $parm;
2599            }
2600        }
2601        # Format the WHERE clause.
2602        my $filter = (@values > 0 ? (join " AND ", @where) : undef);
2603        # Ask for all the propertie values with the desired characteristics.
2604        my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);
2605        while (my $valueObject = $query->Fetch()) {
2606            my @tuple = $valueObject->Values(\@colNames);
2607            push @retVal, \@tuple;
2608        }
2609        # Return the result.
2610        return @retVal;
2611    }
2612    
2613  =head3 FeatureProperties  =head3 FeatureProperties
2614    
2615  C<< my @properties = $sprout->FeatureProperties($featureID); >>  C<< my @properties = $sprout->FeatureProperties($featureID); >>
# Line 1953  Line 2639 
2639  #: Return Type @@;  #: Return Type @@;
2640  sub FeatureProperties {  sub FeatureProperties {
2641          # Get the parameters.          # Get the parameters.
2642          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2643          # Get the properties.          # Get the properties.
2644          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],
2645                                                          ['Property(property-name)', 'Property(property-value)',                                                          ['Property(property-name)', 'Property(property-value)',
# Line 1985  Line 2670 
2670  #: Return Type $;  #: Return Type $;
2671  sub DiagramName {  sub DiagramName {
2672          # Get the parameters.          # Get the parameters.
2673          my $self = shift @_;      my ($self, $diagramID) = @_;
         my ($diagramID) = @_;  
2674          # Get the specified diagram's name and return it.          # Get the specified diagram's name and return it.
2675          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);
2676          return $retVal;          return $retVal;
2677  }  }
2678    
2679    =head3 PropertyID
2680    
2681    C<< my $id = $sprout->PropertyID($propName, $propValue); >>
2682    
2683    Return the ID of the specified property name and value pair, if the
2684    pair exists.
2685    
2686    =over 4
2687    
2688    =item propName
2689    
2690    Name of the desired property.
2691    
2692    =item propValue
2693    
2694    Value expected for the desired property.
2695    
2696    =item RETURN
2697    
2698    Returns the ID of the name/value pair, or C<undef> if the pair does not exist.
2699    
2700    =back
2701    
2702    =cut
2703    
2704    sub PropertyID {
2705        # Get the parameters.
2706        my ($self, $propName, $propValue) = @_;
2707        # Try to find the ID.
2708        my ($retVal) = $self->GetFlat(['Property'],
2709                                      "Property(property-name) = ? AND Property(property-value) = ?",
2710                                      [$propName, $propValue], 'Property(id)');
2711        # Return the result.
2712        return $retVal;
2713    }
2714    
2715  =head3 MergedAnnotations  =head3 MergedAnnotations
2716    
2717  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>
# Line 2018  Line 2738 
2738  #: Return Type @;  #: Return Type @;
2739  sub MergedAnnotations {  sub MergedAnnotations {
2740          # Get the parameters.          # Get the parameters.
2741          my $self = shift @_;      my ($self, $list) = @_;
         my ($list) = @_;  
2742          # Create a list to hold the annotation tuples found.          # Create a list to hold the annotation tuples found.
2743          my @tuples = ();          my @tuples = ();
2744          # Loop through the features in the input list.          # Loop through the features in the input list.
# Line 2067  Line 2786 
2786  #: Return Type @;  #: Return Type @;
2787  sub RoleNeighbors {  sub RoleNeighbors {
2788          # Get the parameters.          # Get the parameters.
2789          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2790          # Get all the diagrams containing this role.          # Get all the diagrams containing this role.
2791          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2792                                                                    'RoleOccursIn(to-link)');                                                                    'RoleOccursIn(to-link)');
# Line 2110  Line 2828 
2828  #: Return Type @;  #: Return Type @;
2829  sub FeatureLinks {  sub FeatureLinks {
2830          # Get the parameters.          # Get the parameters.
2831          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2832          # Get the feature's links.          # Get the feature's links.
2833          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);
2834          # Return the feature's links.          # Return the feature's links.
# Line 2123  Line 2840 
2840  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2841    
2842  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
2843  to the role the feature performs.  to the roles the feature performs.
2844    
2845  =over 4  =over 4
2846    
# Line 2133  Line 2850 
2850    
2851  =item RETURN  =item RETURN
2852    
2853  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.
2854    
2855  =back  =back
2856    
2857  =cut  =cut
2858  #: Return Type %;  #: Return Type %@;
2859  sub SubsystemsOf {  sub SubsystemsOf {
2860          # Get the parameters.          # Get the parameters.
2861          my $self = shift @_;      my ($self, $featureID) = @_;
2862          my ($featureID) = @_;      # Get the subsystem list.
         # Use the SSCell to connect features to subsystems.  
2863          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2864                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2865                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2866          # Create the return value.          # Create the return value.
2867          my %retVal = ();          my %retVal = ();
2868        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2869        # in two spreadsheet cells.
2870        my %dupHash = ();
2871          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
2872          for my $record (@subsystems) {          for my $record (@subsystems) {
2873                  $retVal{$record->[0]} = $record->[1];          # Get this subsystem and role.
2874            my ($subsys, $role) = @{$record};
2875            # Insure it's the first time for both.
2876            my $dupKey = "$subsys\n$role";
2877            if (! exists $dupHash{"$subsys\n$role"}) {
2878                $dupHash{$dupKey} = 1;
2879                push @{$retVal{$subsys}}, $role;
2880            }
2881          }          }
2882          # Return the hash.          # Return the hash.
2883          return %retVal;          return %retVal;
2884  }  }
2885    
2886    =head3 SubsystemList
2887    
2888    C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2889    
2890    Return a list containing the names of the subsystems in which the specified
2891    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2892    subsystem names, not the roles.
2893    
2894    =over 4
2895    
2896    =item featureID
2897    
2898    ID of the feature whose subsystem names are desired.
2899    
2900    =item RETURN
2901    
2902    Returns a list of the names of the subsystems in which the feature participates.
2903    
2904    =back
2905    
2906    =cut
2907    #: Return Type @;
2908    sub SubsystemList {
2909        # Get the parameters.
2910        my ($self, $featureID) = @_;
2911        # Get the list of names.
2912        my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?",
2913                                    [$featureID], 'HasRoleInSubsystem(to-link)');
2914        # Return the result, sorted.
2915        return sort @retVal;
2916    }
2917    
2918    =head3 GenomeSubsystemData
2919    
2920    C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>
2921    
2922    Return a hash mapping genome features to their subsystem roles.
2923    
2924    =over 4
2925    
2926    =item genomeID
2927    
2928    ID of the genome whose subsystem feature map is desired.
2929    
2930    =item RETURN
2931    
2932    Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb
2933    2-tuple contains a subsystem name followed by a role ID.
2934    
2935    =back
2936    
2937    =cut
2938    
2939    sub GenomeSubsystemData {
2940        # Get the parameters.
2941        my ($self, $genomeID) = @_;
2942        # Declare the return variable.
2943        my %retVal = ();
2944        # Get a list of the genome features that participate in subsystems. For each
2945        # feature we get its spreadsheet cells and the corresponding roles.
2946        my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],
2947                                 "HasFeature(from-link) = ?", [$genomeID],
2948                                 ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);
2949        # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems
2950        # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the
2951        # list. We use it at the beginning to get all the spreadsheet cells for the genome and
2952        # again at the end to filter out participation in subsystems with a negative variant code.
2953        my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],
2954                                     "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?",
2955                                     [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']);
2956        # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features.
2957        # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We
2958        # link these two lists together to create the result. First, we want a hash mapping
2959        # spreadsheet cells to subsystem names.
2960        my %subHash = map { $_->[0] => $_->[1] } @cellData;
2961        # We loop through @cellData to build the hash.
2962        for my $roleEntry (@roleData) {
2963            # Get the data for this feature and cell.
2964            my ($fid, $cellID, $role) = @{$roleEntry};
2965            # Check for a subsystem name.
2966            my $subsys = $subHash{$cellID};
2967            if ($subsys) {
2968                # Insure this feature has an entry in the return hash.
2969                if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
2970                # Merge in this new data.
2971                push @{$retVal{$fid}}, [$subsys, $role];
2972            }
2973        }
2974        # Return the result.
2975        return %retVal;
2976    }
2977    
2978  =head3 RelatedFeatures  =head3 RelatedFeatures
2979    
2980  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2190  Line 3008 
3008  #: Return Type @;  #: Return Type @;
3009  sub RelatedFeatures {  sub RelatedFeatures {
3010          # Get the parameters.          # Get the parameters.
3011          my $self = shift @_;      my ($self, $featureID, $function, $userID) = @_;
         my ($featureID, $function, $userID) = @_;  
3012          # 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.
3013          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
                                                                          "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],  
                                                                          'IsBidirectionalBestHitOf(to-link)');  
3014          # Now we loop through the features, pulling out the ones that have the correct          # Now we loop through the features, pulling out the ones that have the correct
3015          # functional assignment.          # functional assignment.
3016          my @retVal = ();          my @retVal = ();
# Line 2239  Line 3054 
3054  #: Return Type @;  #: Return Type @;
3055  sub TaxonomySort {  sub TaxonomySort {
3056          # Get the parameters.          # Get the parameters.
3057          my $self = shift @_;      my ($self, $featureIDs) = @_;
         my ($featureIDs) = @_;  
3058          # Create the working hash table.          # Create the working hash table.
3059          my %hashBuffer = ();          my %hashBuffer = ();
3060          # Loop through the features.          # Loop through the features.
# Line 2249  Line 3063 
3063                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
3064                                                                                  [$fid], 'Genome(taxonomy)');                                                                                  [$fid], 'Genome(taxonomy)');
3065                  # Add this feature to the hash buffer.                  # Add this feature to the hash buffer.
3066                  if (exists $hashBuffer{$taxonomy}) {          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);
                         push @{$hashBuffer{$taxonomy}}, $fid;  
                 } else {  
                         $hashBuffer{$taxonomy} = [$fid];  
                 }  
3067          }          }
3068          # Sort the keys and get the elements.          # Sort the keys and get the elements.
3069          my @retVal = ();          my @retVal = ();
# Line 2264  Line 3074 
3074          return @retVal;          return @retVal;
3075  }  }
3076    
3077  =head3 GetAll  =head3 Protein
   
 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.  
3078    
3079  The list returned will be a list of lists. Each element of the list will contain  C<< my $protein = Sprout::Protein($sequence, $table); >>
 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.  
3080    
3081  C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>  Translate a DNA sequence into a protein sequence.
3082    
3083  =over 4  =over 4
3084    
3085  =item objectNames  =item sequence
   
 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  
3086    
3087  List of the fields to be returned in each element of the list returned.  DNA sequence to translate.
3088    
3089  =item count  =item table (optional)
3090    
3091  Maximum number of records to return. If omitted or 0, all available records will be returned.  Reference to a Hash that translates DNA triples to proteins. A triple that does not
3092    appear in the hash will be translated automatically to C<X>.
3093    
3094  =item RETURN  =item RETURN
3095    
3096  Returns a list of list references. Each element of the return list contains the values for the  Returns the protein sequence that would be created by the DNA sequence.
 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;  
 }  
   
 =head3 Protein  
   
 C<< my $protein = Sprout::Protein($sequence, $table); >>  
   
 Translate a DNA sequence into a protein sequence.  
   
 =over 4  
   
 =item sequence  
   
 DNA sequence to translate.  
   
 =item table (optional)  
   
 Reference to a Hash that translates DNA triples to proteins. A triple that does not  
 appear in the hash will be translated automatically to C<X>.  
   
 =item RETURN  
   
 Returns the protein sequence that would be created by the DNA sequence.  
3097    
3098  =back  =back
3099    
# Line 2470  Line 3146 
3146          # Loop through the input triples.          # Loop through the input triples.
3147          my $n = length $sequence;          my $n = length $sequence;
3148          for (my $i = 0; $i < $n; $i += 3) {          for (my $i = 0; $i < $n; $i += 3) {
3149                  # Get the current triple from the sequence.          # Get the current triple from the sequence. Note we convert to
3150                  my $triple = substr($sequence, $i, 3);          # upper case to insure a match.
3151            my $triple = uc substr($sequence, $i, 3);
3152                  # Translate it using the table.                  # Translate it using the table.
3153                  my $protein = "X";                  my $protein = "X";
3154                  if (exists $table->{$triple}) { $protein = $table->{$triple}; }                  if (exists $table->{$triple}) { $protein = $table->{$triple}; }
# Line 2495  Line 3172 
3172  #: Return Type @;  #: Return Type @;
3173  sub LoadInfo {  sub LoadInfo {
3174          # Get the parameters.          # Get the parameters.
3175          my $self = shift @_;      my ($self) = @_;
3176          # 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.
3177          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
3178          # Concatenate the table names.          # Concatenate the table names.
3179          push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
3180          # Return the result.          # Return the result.
3181          return @retVal;          return @retVal;
3182  }  }
3183    
3184  =head3 LowBBHs  =head3 LowBBHs
3185    
3186  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
3187    
3188  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
3189  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 3209 
3209  #: Return Type %;  #: Return Type %;
3210  sub LowBBHs {  sub LowBBHs {
3211          # Get the parsameters.          # Get the parsameters.
3212          my $self = shift @_;      my ($self, $featureID, $cutoff) = @_;
         my ($featureID, $cutoff) = @_;  
3213          # Create the return hash.          # Create the return hash.
3214          my %retVal = ();          my %retVal = ();
3215          # Create a query to get the desired BBHs.      # Query for the desired BBHs.
3216          my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BBHData($featureID, $cutoff);
                                                                 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',  
                                                                 [$cutoff, $featureID],  
                                                                 ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);  
3217          # Form the results into the return hash.          # Form the results into the return hash.
3218          for my $pair (@bbhList) {          for my $pair (@bbhList) {
3219                  $retVal{$pair->[0]} = $pair->[1];          my $fid = $pair->[0];
3220            if ($self->Exists('Feature', $fid)) {
3221                $retVal{$fid} = $pair->[1];
3222            }
3223          }          }
3224          # Return the result.          # Return the result.
3225          return %retVal;          return %retVal;
3226  }  }
3227    
3228    =head3 Sims
3229    
3230    C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>
3231    
3232    Get a list of similarities for a specified feature. Similarity information is not kept in the
3233    Sprout database; rather, they are retrieved from a network server. The similarities are
3234    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3235    so that its elements can be accessed by name.
3236    
3237    Similarities can be either raw or expanded. The raw similarities are basic
3238    hits between features with similar DNA. Expanding a raw similarity drags in any
3239    features considered substantially identical. So, for example, if features B<A1>,
3240    B<A2>, and B<A3> are all substatially identical to B<A>, then a raw similarity
3241    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3242    
3243    =over 4
3244    
3245    =item fid
3246    
3247    ID of the feature whose similarities are desired.
3248    
3249    =item maxN
3250    
3251    Maximum number of similarities to return.
3252    
3253    =item maxP
3254    
3255    Minumum allowable similarity score.
3256    
3257    =item select
3258    
3259    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3260    means only similarities to FIG features are returned; C<all> means all expanded
3261    similarities are returned; and C<figx> means similarities are expanded until the
3262    number of FIG features equals the maximum.
3263    
3264    =item max_expand
3265    
3266    The maximum number of features to expand.
3267    
3268    =item filters
3269    
3270    Reference to a hash containing filter information, or a subroutine that can be
3271    used to filter the sims.
3272    
3273    =item RETURN
3274    
3275    Returns a reference to a list of similarity objects, or C<undef> if an error
3276    occurred.
3277    
3278    =back
3279    
3280    =cut
3281    
3282    sub Sims {
3283        # Get the parameters.
3284        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3285        # Create the shim object to test for deleted FIDs.
3286        my $shim = FidCheck->new($self);
3287        # Ask the network for sims.
3288        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3289        # Return the result.
3290        return $retVal;
3291    }
3292    
3293    =head3 IsAllGenomes
3294    
3295    C<< my $flag = $sprout->IsAllGenomes(\@list, \@checkList); >>
3296    
3297    Return TRUE if all genomes in the second list are represented in the first list at
3298    least one. Otherwise, return FALSE. If the second list is omitted, the first list is
3299    compared to a list of all the genomes.
3300    
3301    =over 4
3302    
3303    =item list
3304    
3305    Reference to the list to be compared to the second list.
3306    
3307    =item checkList (optional)
3308    
3309    Reference to the comparison target list. Every genome ID in this list must occur at
3310    least once in the first list. If this parameter is omitted, a list of all the genomes
3311    is used.
3312    
3313    =item RETURN
3314    
3315    Returns TRUE if every item in the second list appears at least once in the
3316    first list, else FALSE.
3317    
3318    =back
3319    
3320    =cut
3321    
3322    sub IsAllGenomes {
3323        # Get the parameters.
3324        my ($self, $list, $checkList) = @_;
3325        # Supply the checklist if it was omitted.
3326        $checkList = [$self->Genomes()] if ! defined($checkList);
3327        # Create a hash of the original list.
3328        my %testList = map { $_ => 1 } @{$list};
3329        # Declare the return variable. We assume that the representation
3330        # is complete and stop at the first failure.
3331        my $retVal = 1;
3332        my $n = scalar @{$checkList};
3333        for (my $i = 0; $retVal && $i < $n; $i++) {
3334            if (! $testList{$checkList->[$i]}) {
3335                $retVal = 0;
3336            }
3337        }
3338        # Return the result.
3339        return $retVal;
3340    }
3341    
3342  =head3 GetGroups  =head3 GetGroups
3343    
3344    C<< my %groups = $sprout->GetGroups(\@groupList); >>
3345    
3346    Return a hash mapping each group to the IDs of the genomes in the group.
3347    A list of groups may be specified, in which case only those groups will be
3348    shown. Alternatively, if no parameter is supplied, all groups will be
3349    included. Genomes that are not in any group are omitted.
3350    
3351  =cut  =cut
3352  #: Return Type %@;  #: Return Type %@;
3353  sub GetGroups {  sub GetGroups {
3354        # Get the parameters.
3355        my ($self, $groupList) = @_;
3356        # Declare the return value.
3357        my %retVal = ();
3358        # Determine whether we are getting all the groups or just some.
3359        if (defined $groupList) {
3360            # Here we have a group list. Loop through them individually,
3361            # getting a list of the relevant genomes.
3362            for my $group (@{$groupList}) {
3363                my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3364                    [$group], "Genome(id)");
3365                $retVal{$group} = \@genomeIDs;
3366            }
3367        } else {
3368            # Here we need all of the groups. In this case, we run through all
3369            # of the genome records, putting each one found into the appropriate
3370            # group. Note that we use a filter clause to insure that only genomes
3371            # in real NMPDR groups are included in the return set.
3372            my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3373                                        [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3374            # Loop through the genomes found.
3375            for my $genome (@genomes) {
3376                # Pop this genome's ID off the current list.
3377                my @groups = @{$genome};
3378                my $genomeID = shift @groups;
3379                # Loop through the groups, adding the genome ID to each group's
3380                # list.
3381                for my $group (@groups) {
3382                    Tracer::AddToListMap(\%retVal, $group, $genomeID);
3383                }
3384            }
3385        }
3386        # Return the hash we just built.
3387        return %retVal;
3388    }
3389    
3390    =head3 MyGenomes
3391    
3392    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
3393    
3394    Return a list of the genomes to be included in the Sprout.
3395    
3396    This method is provided for use during the Sprout load. It presumes the Genome load file has
3397    already been created. (It will be in the Sprout data directory and called either C<Genome>
3398    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3399    IDs.
3400    
3401    =over 4
3402    
3403    =item dataDir
3404    
3405    Directory containing the Sprout load files.
3406    
3407    =back
3408    
3409    =cut
3410    #: Return Type @;
3411    sub MyGenomes {
3412        # Get the parameters.
3413        my ($dataDir) = @_;
3414        # Compute the genome file name.
3415        my $genomeFileName = LoadFileName($dataDir, "Genome");
3416        # Extract the genome IDs from the files.
3417        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3418        # Return the result.
3419        return @retVal;
3420    }
3421    
3422    =head3 LoadFileName
3423    
3424    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3425    
3426    Return the name of the load file for the specified table in the specified data
3427    directory.
3428    
3429    =over 4
3430    
3431    =item dataDir
3432    
3433    Directory containing the Sprout load files.
3434    
3435    =item tableName
3436    
3437    Name of the table whose load file is desired.
3438    
3439    =item RETURN
3440    
3441    Returns the name of the file containing the load data for the specified table, or
3442    C<undef> if no load file is present.
3443    
3444    =back
3445    
3446    =cut
3447    #: Return Type $;
3448    sub LoadFileName {
3449        # Get the parameters.
3450        my ($dataDir, $tableName) = @_;
3451        # Declare the return variable.
3452        my $retVal;
3453        # Check for the various file names.
3454        if (-e "$dataDir/$tableName") {
3455            $retVal = "$dataDir/$tableName";
3456        } elsif (-e "$dataDir/$tableName.dtx") {
3457            $retVal = "$dataDir/$tableName.dtx";
3458        }
3459        # Return the result.
3460        return $retVal;
3461    }
3462    
3463    =head3 DeleteGenome
3464    
3465    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3466    
3467    Delete a genome from the database.
3468    
3469    =over 4
3470    
3471    =item genomeID
3472    
3473    ID of the genome to delete
3474    
3475    =item testFlag
3476    
3477    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3478    
3479    =item RETURN
3480    
3481    Returns a statistics object describing the rows deleted.
3482    
3483    =back
3484    
3485    =cut
3486    #: Return Type $%;
3487    sub DeleteGenome {
3488        # Get the parameters.
3489        my ($self, $genomeID, $testFlag) = @_;
3490        # Perform the delete for the genome's features.
3491        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", testMode => $testFlag);
3492        # Perform the delete for the primary genome data.
3493        my $stats = $self->Delete('Genome', $genomeID, testMode => $testFlag);
3494        $retVal->Accumulate($stats);
3495        # Return the result.
3496        return $retVal;
3497    }
3498    
3499    =head3 Fix
3500    
3501    C<< my %fixedHash = Sprout::Fix(%groupHash); >>
3502    
3503    Prepare a genome group hash (like that returned by L</GetGroups> for processing.
3504    Groups with the same primary name will be combined. The primary name is the
3505    first capitalized word in the group name.
3506    
3507    =over 4
3508    
3509    =item groupHash
3510    
3511    Hash to be fixed up.
3512    
3513    =item RETURN
3514    
3515    Returns a fixed-up version of the hash.
3516    
3517    =back
3518    
3519    =cut
3520    
3521    sub Fix {
3522        # Get the parameters.
3523        my (%groupHash) = @_;
3524        # Create the result hash.
3525        my %retVal = ();
3526        # Copy over the genomes.
3527        for my $groupID (keys %groupHash) {
3528            # Make a safety copy of the group ID.
3529            my $realGroupID = $groupID;
3530            # Yank the primary name.
3531            if ($groupID =~ /([A-Z]\w+)/) {
3532                $realGroupID = $1;
3533            }
3534            # Append this group's genomes into the result hash.
3535            Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}});
3536        }
3537        # Return the result hash.
3538        return %retVal;
3539    }
3540    
3541    =head3 GroupPageName
3542    
3543    C<< my $name = $sprout->GroupPageName($group); >>
3544    
3545    Return the name of the page for the specified NMPDR group.
3546    
3547    =over 4
3548    
3549    =item group
3550    
3551    Name of the relevant group.
3552    
3553    =item RETURN
3554    
3555    Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3556    memory it will be read in.
3557    
3558    =back
3559    
3560    =cut
3561    
3562    sub GroupPageName {
3563        # Get the parameters.
3564        my ($self, $group) = @_;
3565        # Declare the return variable.
3566        my $retVal;
3567        # Check for the group file data.
3568        if (! defined $self->{groupHash}) {
3569            # Read the group file.
3570            my %groupData = Sprout::ReadGroupFile($self->{_options}->{dataDir} . "/groups.tbl");
3571            # Store it in our object.
3572            $self->{groupHash} = \%groupData;
3573        }
3574        # Compute the real group name.
3575        my $realGroup = $group;
3576        if ($group =~ /([A-Z]\w+)/) {
3577            $realGroup = $1;
3578        }
3579        # Return the page name.
3580        $retVal = "../content/" . $self->{groupHash}->{$realGroup}->[1];
3581        # Return the result.
3582        return $retVal;
3583    }
3584    
3585    =head3 ReadGroupFile
3586    
3587    C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >>
3588    
3589    Read in the data from the specified group file. The group file contains information
3590    about each of the NMPDR groups.
3591    
3592    =over 4
3593    
3594    =item name
3595    
3596    Name of the group.
3597    
3598    =item page
3599    
3600    Name of the group's page on the web site (e.g. C<campy.php> for
3601    Campylobacter)
3602    
3603    =item genus
3604    
3605    Genus of the group
3606    
3607    =item species
3608    
3609    Species of the group, or an empty string if the group is for an entire
3610    genus. If the group contains more than one species, the species names
3611    should be separated by commas.
3612    
3613    =back
3614    
3615    The parameters to this method are as follows
3616    
3617    =over 4
3618    
3619    =item groupFile
3620    
3621    Name of the file containing the group data.
3622    
3623    =item RETURN
3624    
3625    Returns a hash keyed on group name. The value of each hash
3626    
3627    =back
3628    
3629    =cut
3630    
3631    sub ReadGroupFile {
3632        # Get the parameters.
3633        my ($groupFileName) = @_;
3634        # Declare the return variable.
3635        my %retVal;
3636        # Read the group file.
3637        my @groupLines = Tracer::GetFile($groupFileName);
3638        for my $groupLine (@groupLines) {
3639            my ($name, $page, $genus, $species) = split(/\t/, $groupLine);
3640            $retVal{$name} = [$page, $genus, $species];
3641        }
3642        # Return the result.
3643        return %retVal;
3644    }
3645    
3646    =head3 AddProperty
3647    
3648    C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>
3649    
3650    Add a new attribute value (Property) to a feature. In the SEED system, attributes can
3651    be added to almost any object. In Sprout, they can only be added to features. In
3652    Sprout, attributes are implemented using I<properties>. A property represents a key/value
3653    pair. If the particular key/value pair coming in is not already in the database, a new
3654    B<Property> record is created to hold it.
3655    
3656    =over 4
3657    
3658    =item peg
3659    
3660    ID of the feature to which the attribute is to be replied.
3661    
3662    =item key
3663    
3664    Name of the attribute (key).
3665    
3666    =item value
3667    
3668    Value of the attribute.
3669    
3670    =item url
3671    
3672    URL or text citation from which the property was obtained.
3673    
3674    =back
3675    
3676    =cut
3677    #: Return Type ;
3678    sub AddProperty {
3679        # Get the parameters.
3680        my ($self, $featureID, $key, $value, $url) = @_;
3681        # Declare the variable to hold the desired property ID.
3682        my $propID;
3683        # Attempt to find a property record for this key/value pair.
3684        my @properties = $self->GetFlat(['Property'],
3685                                       "Property(property-name) = ? AND Property(property-value) = ?",
3686                                       [$key, $value], 'Property(id)');
3687        if (@properties) {
3688            # Here the property is already in the database. We save its ID.
3689            $propID = $properties[0];
3690            # Here the property value does not exist. We need to generate an ID. It will be set
3691            # to a number one greater than the maximum value in the database. This call to
3692            # GetAll will stop after one record.
3693            my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],
3694                                            1);
3695            $propID = $maxProperty[0]->[0] + 1;
3696            # Insert the new property value.
3697            $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });
3698        }
3699        # Now we connect the incoming feature to the property.
3700        $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });
3701    }
3702    
3703    =head2 Virtual Methods
3704    
3705    =head3 CleanKeywords
3706    
3707    C<< my $cleanedString = $sprout->CleanKeywords($searchExpression); >>
3708    
3709    Clean up a search expression or keyword list. This involves converting the periods
3710    in EC numbers to underscores, converting non-leading minus signs to underscores,
3711    a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
3712    characters. In addition, any extra spaces are removed.
3713    
3714    =over 4
3715    
3716    =item searchExpression
3717    
3718    Search expression or keyword list to clean. Note that a search expression may
3719    contain boolean operators which need to be preserved. This includes leading
3720    minus signs.
3721    
3722    =item RETURN
3723    
3724    Cleaned expression or keyword list.
3725    
3726    =back
3727    
3728    =cut
3729    
3730    sub CleanKeywords {
3731        # Get the parameters.
3732        my ($self, $searchExpression) = @_;
3733        # Perform the standard cleanup.
3734        my $retVal = $self->ERDB::CleanKeywords($searchExpression);
3735        # Fix the periods in EC and TC numbers.
3736        $retVal =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g;
3737        # Fix non-trailing periods.
3738        $retVal =~ s/\.(\w)/_$1/g;
3739        # Fix non-leading minus signs.
3740        $retVal =~ s/(\w)[\-]/$1_/g;
3741        # Fix the vertical bars and colons
3742        $retVal =~ s/(\w)[|:](\w)/$1'$2/g;
3743        # Return the result.
3744        return $retVal;
3745  }  }
3746    
3747  =head2 Internal Utility Methods  =head2 Internal Utility Methods
# Line 2561  Line 3749 
3749  =head3 ParseAssignment  =head3 ParseAssignment
3750    
3751  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,
3752  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
3753  will be returned.  isn't, an empty list will be returned.
3754    
3755    A functional assignment is always of the form
3756    
3757        C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3758    
3759    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3760    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3761    not always the case.
3762    
3763    In addition, the functional role may contain extra data that is stripped, such as
3764    terminating spaces or a comment separated from the rest of the text by a tab.
3765    
3766  This is a static method.  This is a static method.
3767    
3768  =over 4  =over 4
3769    
3770    =item user
3771    
3772    Name of the assigning user.
3773    
3774  =item text  =item text
3775    
3776  Text of the annotation.  Text of the annotation.
# Line 2581  Line 3784 
3784    
3785  =cut  =cut
3786    
3787  sub ParseAssignment {  sub _ParseAssignment {
3788          # Get the parameters.          # Get the parameters.
3789          my ($text) = @_;      my ($user, $text) = @_;
3790          # Declare the return value.          # Declare the return value.
3791          my @retVal = ();          my @retVal = ();
3792          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3793          my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3794          if ($type =~ m/^set $user function to$/i) {      if ($type =~ m/^set function to$/i) {
3795                  # 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.
3796                  @retVal = ($user, $function);                  @retVal = ($user, $function);
3797        } elsif ($type =~ m/^set (\S+) function to$/i) {
3798            # Here we have an assignment with a user that is passed back to the caller.
3799            @retVal = ($1, $function);
3800        }
3801        # If we have an assignment, we need to clean the function text. There may be
3802        # extra junk at the end added as a note from the user.
3803        if (defined( $retVal[1] )) {
3804            $retVal[1] =~ s/(\t\S)?\s*$//;
3805          }          }
3806          # Return the result list.          # Return the result list.
3807          return @retVal;          return @retVal;
# Line 2618  Line 3829 
3829    
3830  sub FriendlyTimestamp {  sub FriendlyTimestamp {
3831      my ($timeValue) = @_;      my ($timeValue) = @_;
3832      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
3833      return $retVal;      return $retVal;
3834  }  }
3835    
3836    
3837  1;  1;

Legend:
Removed from v.1.7  
changed lines
  Added in v.1.95

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3