[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.3, Tue Jan 25 01:00:20 2005 UTC revision 1.101, Mon Aug 20 23:29:24 2007 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;
         use Carp;  
8          use DBKernel;          use DBKernel;
9          use XML::Simple;          use XML::Simple;
10          use DBQuery;          use DBQuery;
11          use DBObject;      use ERDBObject;
         use ERDB;  
12          use Tracer;          use Tracer;
13          use FIGRules;          use FIGRules;
14        use FidCheck;
15          use Stats;          use Stats;
16      use POSIX qw(strftime);      use POSIX qw(strftime);
17        use BasicLocation;
18        use CustomAttributes;
19        use RemoteCustomAttributes;
20    
21  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
22    
# Line 32  Line 36 
36  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
37  L</dna_seq> returns the DNA sequence for a specified genome location.  L</dna_seq> returns the DNA sequence for a specified genome location.
38    
39    The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.
40    
41  =cut  =cut
42    
43  #: Constructor SFXlate->new_sprout_only();  #: Constructor SFXlate->new_sprout_only();
44    
   
45  =head2 Public Methods  =head2 Public Methods
46    
47  =head3 new  =head3 new
# Line 63  Line 68 
68    
69  * 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>)
70    
71  * 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)
72    
73  * B<port> connection port (default C<0>)  * B<port> connection port (default C<0>)
74    
75    * B<sock> connection socket (default same as SEED)
76    
77  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
78    
79  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
80    
81    * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
82    
83  =back  =back
84    
85  For example, the following constructor call specifies a database named I<Sprout> and a user name of  For example, the following constructor call specifies a database named I<Sprout> and a user name of
# Line 84  Line 93 
93  sub new {  sub new {
94          # Get the parameters.          # Get the parameters.
95          my ($class, $dbName, $options) = @_;          my ($class, $dbName, $options) = @_;
96        # Compute the DBD directory.
97        my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
98                                                      $FIG_Config::fig );
99          # 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
100          # the incoming data.          # the incoming data.
101          my $optionTable = Tracer::GetOptions({          my $optionTable = Tracer::GetOptions({
102                                             dbType               => 'mysql',                     # database type                         dbType       => $FIG_Config::dbms,
103                                             dataDir              => 'Data',                      # data file directory                                                          # database type
104                                             xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
105                                             userData             => 'root/',                     # user name and password                                                          # data file directory
106                                             port                 => 0,                           # database connection port                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
107                                                            # database definition file name
108                           userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
109                                                            # user name and password
110                           port         => $FIG_Config::dbport,
111                                                            # database connection port
112                           sock         => $FIG_Config::dbsock,
113                           host         => $FIG_Config::dbhost,
114                                             maxSegmentLength => 4500,            # maximum feature segment length                                             maxSegmentLength => 4500,            # maximum feature segment length
115                                             maxSequenceLength => 8000,           # maximum contig sequence length                                             maxSequenceLength => 8000,           # maximum contig sequence length
116                           noDBOpen     => 0,               # 1 to suppress the database open
117                                            }, $options);                                            }, $options);
118          # Get the data directory.          # Get the data directory.
119          my $dataDir = $optionTable->{dataDir};          my $dataDir = $optionTable->{dataDir};
# Line 101  Line 121 
121          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
122          my ($userName, $password) = ($1, $2);          my ($userName, $password) = ($1, $2);
123          # Connect to the database.          # Connect to the database.
124          my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
125        if (! $optionTable->{noDBOpen}) {
126            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
127                                    $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
128        }
129          # Create the ERDB object.          # Create the ERDB object.
130          my $xmlFileName = "$optionTable->{xmlFileName}";          my $xmlFileName = "$optionTable->{xmlFileName}";
131          my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
132          # Create this object.      # Add the option table and XML file name.
133          my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
134          # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
135          bless $self;      # Set up space for the group file data.
136          return $self;      $retVal->{groupHash} = undef;
137        # Set up space for the genome hash. We use this to identify NMPDR genomes.
138        $retVal->{genomeHash} = undef;
139        # Connect to the attributes.
140        if ($FIG_Config::attrURL) {
141            Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);
142            $retVal->{_ca} = RemoteCustomAttributes->new($FIG_Config::attrURL);
143        } elsif ($FIG_Config::attrDbName) {
144            Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);
145            my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));
146            $retVal->{_ca} = CustomAttributes->new(user => $user);
147        }
148        # Return it.
149        return $retVal;
150  }  }
151    
152  =head3 MaxSegment  =head3 MaxSegment
# Line 125  Line 162 
162  =cut  =cut
163  #: Return Type $;  #: Return Type $;
164  sub MaxSegment {  sub MaxSegment {
165          my $self = shift @_;      my ($self) = @_;
166          return $self->{_options}->{maxSegmentLength};          return $self->{_options}->{maxSegmentLength};
167  }  }
168    
# Line 140  Line 177 
177  =cut  =cut
178  #: Return Type $;  #: Return Type $;
179  sub MaxSequence {  sub MaxSequence {
180          my $self = shift @_;      my ($self) = @_;
181          return $self->{_options}->{maxSequenceLength};          return $self->{_options}->{maxSequenceLength};
182  }  }
183    
184  =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]); >>  
185    
186  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.  
187    
188  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.
189    
190  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
191  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
192  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
193    extension are used in preference to the files with an extension.
194    
195  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
196  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
197  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
198  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.  
199    
200  =over 4  =over 4
201    
202  =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  
203    
204  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
205    
206  =item RETURN  =item RETURN
207    
208  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,
209    the number of errors, and a list of the error messages.
210    
211  =back  =back
212    
213  =cut  =cut
214    #: Return Type %;
215  sub Get {  sub Load {
216          # Get the parameters.          # Get the parameters.
217          my $self = shift @_;      my ($self, $rebuild) = @_;
218          my ($objectNames, $filterClause, $parameterList) = @_;      # Load the tables from the data directory.
219          # 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);
220          # rather than a list of parameters. The next step is to convert the parameters from a reference      # Return the statistics.
221          # 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);  
222  }  }
223    
224  =head3 GetEntity  =head3 LoadUpdate
225    
226  C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
227    
228  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
229    or two tables without reloading the whole database. For each table, there must be a corresponding
230    file in the data directory, either with the same name as the table, or with a C<.dtx> suffix. So,
231    for example, to make updates to the B<FeatureTranslation> relation, there must be a
232    C<FeatureTranslation.dtx> file in the data directory. Unlike a full load, files without an extension
233    are not examined. This allows update files to co-exist with files from an original load.
234    
235  =over 4  =over 4
236    
237  =item entityType  =item truncateFlag
238    
239  Entity type name.  TRUE if the tables should be rebuilt before loading, else FALSE. A value of TRUE therefore causes
240    current data and schema of the tables to be replaced, while a value of FALSE means the new data
241    is added to the existing data in the various relations.
242    
243  =item ID  =item tableList
244    
245  ID of the desired entity.  List of the tables to be updated.
246    
247  =item RETURN  =item RETURN
248    
249  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,
250  instance is found with the specified key.  the number of errors encountered, and a list of error messages.
251    
252  =back  =back
253    
254  =cut  =cut
255    #: Return Type $%;
256  sub GetEntity {  sub LoadUpdate {
257          # Get the parameters.          # Get the parameters.
258          my $self = shift @_;      my ($self, $truncateFlag, $tableList) = @_;
259          my ($entityType, $ID) = @_;      # Declare the return value.
260          # Create a query.      my $retVal = Stats->new();
261          my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);      # Get the data directory.
262          # Get the first (and only) object.      my $optionTable = $self->{_options};
263          my $retVal = $query->Fetch();      my $dataDir = $optionTable->{dataDir};
264          # Return the result.      # Loop through the incoming table names.
265        for my $tableName (@{$tableList}) {
266            # Find the table's file.
267            my $fileName = LoadFileName($dataDir, $tableName);
268            if (! $fileName) {
269                Trace("No load file found for $tableName in $dataDir.") if T(0);
270            } else {
271                # Attempt to load this table.
272                my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);
273                # Accumulate the resulting statistics.
274                $retVal->Accumulate($result);
275            }
276        }
277        # Return the statistics.
278          return $retVal;          return $retVal;
279  }  }
280    
281  =head3 GetEntityValues  =head3 GenomeCounts
282    
283  C<< my @values = GetEntityValues($entityType, $ID, \@fields); >>  C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>
284    
285  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
286    genomes will be included in the counts.
287    
288  =over 4  =over 4
289    
290  =item entityType  =item complete
   
 Entity type name.  
   
 =item ID  
   
 ID of the desired entity.  
291    
292  =item fields  TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
293    counted
 List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.  
294    
295  =item RETURN  =item RETURN
296    
297  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--
298    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
299    
300  =back  =back
301    
302  =cut  =cut
303  #: Return Type @;  
304  sub GetEntityValues {  sub GenomeCounts {
305          # Get the parameters.          # Get the parameters.
306          my $self = shift @_;      my ($self, $complete) = @_;
307          my ($entityType, $ID, $fields) = @_;      # Set the filter based on the completeness flag.
308          # Get the specified entity.      my $filter = ($complete ? "Genome(complete) = 1" : "");
309          my $entity = $self->GetEntity($entityType, $ID);      # Get all the genomes and the related taxonomy information.
310          # Declare the return list.      my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
311          my @retVal = ();      # Clear the counters.
312          # 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);
313          if ($entity) {      # Loop through, counting the domains.
314                  push @retVal, $entity->Values($fields);      for my $genome (@genomes) {
315            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
316            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
317            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
318            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
319            elsif ($genome->[1] =~ /^env/i)      { ++$env }
320            else  { ++$unk }
321          }          }
322          # Return the result.      # Return the counts.
323          return @retVal;      return ($arch, $bact, $euk, $vir, $env, $unk);
324  }  }
325    
326  =head3 ShowMetaData  =head3 ContigCount
327    
328  C<< $sprout->ShowMetaData($fileName); >>  C<< my $count = $sprout->ContigCount($genomeID); >>
329    
330  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.
331    
332  =over 4  =over 4
333    
334  =item fileName  =item genomeID
335    
336  Fully-qualified name to give to the output file.  ID of the genome whose contig count is desired.
337    
338    =item RETURN
339    
340    Returns the number of contigs for the specified genome.
341    
342  =back  =back
343    
344  =cut  =cut
345    
346  sub ShowMetaData {  sub ContigCount {
347          # Get the parameters.          # Get the parameters.
348          my $self = shift @_;      my ($self, $genomeID) = @_;
349          my ($fileName) = @_;      # Get the contig count.
350          # Compute the file name.      my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
351          my $options = $self->{_options};      # Return the result.
352          # Call the show method on the underlying ERDB object.      return $retVal;
         $self->{_erdb}->ShowMetaData($fileName);  
353  }  }
354    
355  =head3 Load  =head3 GeneMenu
   
 C<< $sprout->Load($rebuild); >>;  
   
 Load the database from files in the data directory, optionally re-creating the tables.  
356    
357  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.  
358    
359  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,
360  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
361  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.  
362    
363  =over 4  =over 4
364    
365  =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  
366    
367  =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;  
 }  
368    
369  =head3 LoadUpdate  =item filterString
370    
371  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  A filter string for use in selecting the genomes. The filter string must conform
372    to the rules for the C<< ERDB->Get >> method.
373    
374  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.  
375    
376  =over 4  Reference to a list of values to be substituted in for the parameter marks in
377    the filter string.
378    
379  =item truncateFlag  =item selected (optional)
380    
381  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.  
382    
383  =item tableList  =item fast (optional)
384    
385  List of the tables to be updated.  If specified and TRUE, the contig counts will be omitted to improve performance.
386    
387  =item RETURN  =item RETURN
388    
389  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.  
390    
391  =back  =back
392    
393  =cut  =cut
394  #: Return Type %;  
395  sub LoadUpdate {  sub GeneMenu {
396          # Get the parameters.          # Get the parameters.
397          my $self = shift @_;      my ($self, $attributes, $filterString, $params, $selected, $fast) = @_;
398          my ($truncateFlag, $tableList) = @_;      my $slowMode = ! $fast;
399          # Get the database object.      # Default to nothing selected. This prevents an execution warning if "$selected"
400          my $erdb = $self->{_erdb};      # is undefined.
401          # Declare the return value.      $selected = "" unless defined $selected;
402          my $retVal = Stats->new();      Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3);
403          # Get the data directory.      # Start the menu.
404          my $optionTable = $self->{_options};      my $retVal = "<select " .
405          my $dataDir = $optionTable->{dataDir};          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
406          # Loop through the incoming table names.          ">\n";
407          for my $tableName (@{$tableList}) {      # Get the genomes.
408                  # Find the table's file.      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
409                  my $fileName = "$dataDir/$tableName";                                                                       'Genome(genus)',
410                  if (! -e $fileName) {                                                                       'Genome(species)',
411                          $fileName = "$fileName.dtx";                                                                       'Genome(unique-characterization)']);
412                  }      # Sort them by name.
413                  # Attempt to load this table.      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
414                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);      # Loop through the genomes, creating the option tags.
415                  # Accumulate the resulting statistics.      for my $genomeData (@sorted) {
416                  $retVal->Accumulate($result);          # Get the data for this genome.
417            my ($genomeID, $genus, $species, $strain) = @{$genomeData};
418            # Get the contig count.
419            my $contigInfo = "";
420            if ($slowMode) {
421                my $count = $self->ContigCount($genomeID);
422                my $counting = ($count == 1 ? "contig" : "contigs");
423                $contigInfo = "[$count $counting]";
424            }
425            # Find out if we're selected.
426            my $selectOption = ($selected eq $genomeID ? " selected" : "");
427            # Build the option tag.
428            $retVal .= "<option value=\"$genomeID\"$selectOption>$genus $species $strain ($genomeID)$contigInfo</option>\n";
429          }          }
430          # Return the statistics.      # Close the SELECT tag.
431        $retVal .= "</select>\n";
432        # Return the result.
433          return $retVal;          return $retVal;
434  }  }
435    
# Line 464  Line 445 
445  #: Return Type ;  #: Return Type ;
446  sub Build {  sub Build {
447          # Get the parameters.          # Get the parameters.
448          my $self = shift @_;      my ($self) = @_;
449          # Create the tables.          # Create the tables.
450          $self->{_erdb}->CreateTables;      $self->CreateTables();
451  }  }
452    
453  =head3 Genomes  =head3 Genomes
# Line 479  Line 460 
460  #: Return Type @;  #: Return Type @;
461  sub Genomes {  sub Genomes {
462          # Get the parameters.          # Get the parameters.
463          my $self = shift @_;      my ($self) = @_;
464          # Get all the genomes.          # Get all the genomes.
465          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');          my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');
466          # Return the list of IDs.          # Return the list of IDs.
# Line 509  Line 490 
490  #: Return Type $;  #: Return Type $;
491  sub GenusSpecies {  sub GenusSpecies {
492          # Get the parameters.          # Get the parameters.
493          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
494          # Get the data for the specified genome.          # Get the data for the specified genome.
495          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',          my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',
496                                                                                                                            'Genome(unique-characterization)']);                                                                                                                            'Genome(unique-characterization)']);
# Line 546  Line 526 
526  #: Return Type @;  #: Return Type @;
527  sub FeaturesOf {  sub FeaturesOf {
528          # Get the parameters.          # Get the parameters.
529          my $self = shift @_;      my ($self, $genomeID,$ftype) = @_;
         my ($genomeID,$ftype) = @_;  
530          # Get the features we want.          # Get the features we want.
531          my @features;          my @features;
532          if (!$ftype) {          if (!$ftype) {
# Line 591  Line 570 
570  =item RETURN  =item RETURN
571    
572  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
573  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context.
574    
575  =back  =back
576    
577  =cut  =cut
578  #: Return Type @;  
 #: Return Type $;  
579  sub FeatureLocation {  sub FeatureLocation {
580          # Get the parameters.          # Get the parameters.
581          my $self = shift @_;      my ($self, $featureID) = @_;
582          my ($featureID) = @_;      # Get the feature record.
583          # Create a query for the feature locations.      my $object = $self->GetEntity('Feature', $featureID);
584          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",      Confess("Feature $featureID not found.") if ! defined($object);
585                                                     [$featureID]);      # Get the location string.
586        my $locString = $object->PrimaryValue('Feature(location-string)');
587          # Create the return list.          # Create the return list.
588          my @retVal = ();      my @retVal = split /\s*,\s*/, $locString;
         # Set up the variables used to determine if we have adjacent segments. This initial setup will  
         # not match anything.  
         my ($prevContig, $prevBeg, $prevDir, $prevLen) = ("", 0, "0", 0);  
         # Loop through the query results, creating location specifiers.  
         while (my $location = $query->Fetch()) {  
                 # Get the location parameters.  
                 my ($contigID, $beg, $dir, $len) = $location->Values(['IsLocatedIn(to-link)',  
                         'IsLocatedIn(beg)', 'IsLocatedIn(dir)', 'IsLocatedIn(len)']);  
                 # Check to see if we are adjacent to the previous segment.  
                 if ($prevContig eq $contigID && $dir eq $prevDir) {  
                         # Here the new segment is in the same direction on the same contig. Insure the  
                         # new segment's beginning is next to the old segment's end.  
                         if (($dir eq "-" && $beg == $prevBeg - $prevLen) ||  
                                 ($dir eq "+" && $beg == $prevBeg + $prevLen)) {  
                                 # Here we need to merge two segments. Adjust the beginning and length values  
                                 # to include both segments.  
                                 $beg = $prevBeg;  
                                 $len += $prevLen;  
                                 # Pop the old segment off. The new one will replace it later.  
                                 pop @retVal;  
                         }  
                 }  
                 # Remember this specifier for the adjacent-segment test the next time through.  
                 ($prevContig, $prevBeg, $prevDir, $prevLen) = ($contigID, $beg, $dir, $len);  
                 # Add the specifier to the list.  
                 push @retVal, "${contigID}_$beg$dir$len";  
         }  
589          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
590          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
591  }  }
592    
593  =head3 ParseLocation  =head3 ParseLocation
# Line 659  Line 611 
611  =back  =back
612    
613  =cut  =cut
614  #: Return Type @;  
615  sub ParseLocation {  sub ParseLocation {
616          # Get the parameter.      # Get the parameter. Note that if we're called as an instance method, we ignore
617        # the first parameter.
618        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
619          my ($location) = @_;          my ($location) = @_;
620          # Parse it into segments.          # Parse it into segments.
621          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
622          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
623          # If the direction is an underscore, convert it to a + or -.          # If the direction is an underscore, convert it to a + or -.
624          if ($dir eq "_") {          if ($dir eq "_") {
# Line 680  Line 634 
634          return ($contigID, $start, $dir, $len);          return ($contigID, $start, $dir, $len);
635  }  }
636    
637    
638    
639    =head3 PointLocation
640    
641    C<< my $found = Sprout::PointLocation($location, $point); >>
642    
643    Return the offset into the specified location of the specified point on the contig. If
644    the specified point is before the location, a negative value will be returned. If it is
645    beyond the location, an undefined value will be returned. It is assumed that the offset
646    is for the location's contig. The location can either be new-style (using a C<+> or C<->
647    and a length) or old-style (using C<_> and start and end positions.
648    
649    =over 4
650    
651    =item location
652    
653    A location specifier (see L</FeatureLocation> for a description).
654    
655    =item point
656    
657    The offset into the contig of the point in which we're interested.
658    
659    =item RETURN
660    
661    Returns the offset inside the specified location of the specified point, a negative
662    number if the point is before the location, or an undefined value if the point is past
663    the location. If the length of the location is 0, this method will B<always> denote
664    that it is outside the location. The offset will always be relative to the left-most
665    position in the location.
666    
667    =back
668    
669    =cut
670    
671    sub PointLocation {
672        # Get the parameter. Note that if we're called as an instance method, we ignore
673        # the first parameter.
674        shift if UNIVERSAL::isa($_[0],__PACKAGE__);
675        my ($location, $point) = @_;
676        # Parse out the location elements. Note that this works on both old-style and new-style
677        # locations.
678        my ($contigID, $start, $dir, $len) = ParseLocation($location);
679        # Declare the return variable.
680        my $retVal;
681        # Compute the offset. The computation is dependent on the direction of the location.
682        my $offset = (($dir == '+') ? $point - $start : $point - ($start - $len + 1));
683        # Return the offset if it's valid.
684        if ($offset < $len) {
685            $retVal = $offset;
686        }
687        # Return the offset found.
688        return $retVal;
689    }
690    
691  =head3 DNASeq  =head3 DNASeq
692    
693  C<< my $sequence = $sprout->DNASeq(\@locationList); >>  C<< my $sequence = $sprout->DNASeq(\@locationList); >>
# Line 688  Line 696 
696  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,
697  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>.
698    
699    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
700    between positions 1401 and 1532, inclusive.
701    
702        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
703    
704  =over 4  =over 4
705    
706  =item locationList  =item locationList
707    
708  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
709  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
710    
711  =item RETURN  =item RETURN
712    
# Line 705  Line 718 
718  #: Return Type $;  #: Return Type $;
719  sub DNASeq {  sub DNASeq {
720          # Get the parameters.          # Get the parameters.
721          my $self = shift @_;      my ($self, $locationList) = @_;
         my ($locationList) = @_;  
722          # Create the return string.          # Create the return string.
723          my $retVal = "";          my $retVal = "";
724          # Loop through the locations.          # Loop through the locations.
# Line 721  Line 733 
733                  # 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
734                  # before putting it in the return value.                  # before putting it in the return value.
735                  my ($start, $stop);                  my ($start, $stop);
736            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
737                  if ($dir eq "+") {                  if ($dir eq "+") {
738                          $start = $beg;                          $start = $beg;
739                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
740                  } else {                  } else {
741                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
742                          $stop = $beg;                          $stop = $beg;
743                  }                  }
744            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
745                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
746                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
747                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 739  Line 753 
753                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
754                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
755                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
756                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
757                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
758                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
759                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
760                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
761                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
762                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
763                  }                  }
764                  # 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.
765                  if ($dir eq '+') {                  if ($dir eq '+') {
766                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
767                  } else {                  } else {
768                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
769                  }                  }
770          }          }
771          # Return the result.          # Return the result.
# Line 779  Line 794 
794  #: Return Type @;  #: Return Type @;
795  sub AllContigs {  sub AllContigs {
796          # Get the parameters.          # Get the parameters.
797          my $self = shift @_;      my ($self, $genomeID) = @_;
         my ($genomeID) = @_;  
798          # Ask for the genome's Contigs.          # Ask for the genome's Contigs.
799          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],          my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],
800                                                                  'HasContig(to-link)');                                                                  'HasContig(to-link)');
# Line 788  Line 802 
802          return @retVal;          return @retVal;
803  }  }
804    
805  =head3 ContigLength  =head3 GenomeLength
806    
807  C<< my $length = $sprout->ContigLength($contigID); >>  C<< my $length = $sprout->GenomeLength($genomeID); >>
808    
809  Compute the length of a contig.  Return the length of the specified genome in base pairs.
810    
811  =over 4  =over 4
812    
813  =item contigID  =item genomeID
814    
815  ID of the contig whose length is desired.  ID of the genome whose base pair count is desired.
816    
817  =item RETURN  =item RETURN
818    
819  Returns the number of positions in the contig.  Returns the number of base pairs in all the contigs of the specified
820    genome.
821    
822  =back  =back
823    
824  =cut  =cut
825  #: Return Type $;  
826  sub ContigLength {  sub GenomeLength {
827          # Get the parameters.          # Get the parameters.
828          my $self = shift @_;      my ($self, $genomeID) = @_;
829          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.  
830          my $retVal = 0;          my $retVal = 0;
831          # Set it from the sequence data, if any.      # Get the genome's contig sequence lengths.
832          if ($sequence) {      my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
833                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);                         [$genomeID], 'IsMadeUpOf(len)');
834                  $retVal = $start + $len;      # Sum the lengths.
835          }      map { $retVal += $_ } @lens;
836          # Return the result.          # Return the result.
837          return $retVal;          return $retVal;
838  }  }
839    
840  =head3 GenesInRegion  =head3 FeatureCount
841    
842  C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>  C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
843    
844  List the features which overlap a specified region in a contig.  Return the number of features of the specified type in the specified genome.
845    
846  =over 4  =over 4
847    
848  =item contigID  =item genomeID
849    
850  ID of the contig containing the region of interest.  ID of the genome whose feature count is desired.
851    
852  =item start  =item type
853    
854  Offset of the first residue in the region of interest.  Type of feature to count (eg. C<peg>, C<rna>, etc.).
855    
856  =item stop  =item RETURN
857    
858  Offset of the last residue in the region of interest.  Returns the number of features of the specified type for the specified genome.
859    
860    =back
861    
862    =cut
863    
864    sub FeatureCount {
865        # Get the parameters.
866        my ($self, $genomeID, $type) = @_;
867        # Compute the count.
868        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
869                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
870                                    [$genomeID, $type]);
871        # Return the result.
872        return $retVal;
873    }
874    
875    =head3 GenomeAssignments
876    
877    C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
878    
879    Return a list of a genome's assigned features. The return hash will contain each
880    assigned feature of the genome mapped to the text of its most recent functional
881    assignment.
882    
883    =over 4
884    
885    =item genomeID
886    
887    ID of the genome whose functional assignments are desired.
888    
889  =item RETURN  =item RETURN
890    
891  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
892  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.  
893    
894  =back  =back
895    
896  =cut  =cut
897  #: Return Type @;  
898  sub GenesInRegion {  sub GenomeAssignments {
899          # Get the parameters.          # Get the parameters.
900          my $self = shift @_;      my ($self, $genomeID) = @_;
901          my ($contigID, $start, $stop) = @_;      # Declare the return variable.
902          # Get the maximum segment length.      my $retVal = {};
903          my $maximumSegmentLength = $self->MaxSegment;      # Query the genome's features.
904        my $query = $self->Get(['HasFeature', 'Feature'], "HasFeature(from-link) = ?",
905                               [$genomeID]);
906        # Loop through the features.
907        while (my $data = $query->Fetch) {
908            # Get the feature ID and assignment.
909            my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']);
910            if ($assignment) {
911                $retVal->{$fid} = $assignment;
912            }
913        }
914        # Return the result.
915        return $retVal;
916    }
917    
918    =head3 ContigLength
919    
920    C<< my $length = $sprout->ContigLength($contigID); >>
921    
922    Compute the length of a contig.
923    
924    =over 4
925    
926    =item contigID
927    
928    ID of the contig whose length is desired.
929    
930    =item RETURN
931    
932    Returns the number of positions in the contig.
933    
934    =back
935    
936    =cut
937    #: Return Type $;
938    sub ContigLength {
939        # Get the parameters.
940        my ($self, $contigID) = @_;
941        # Get the contig's last sequence.
942        my $query = $self->Get(['IsMadeUpOf'],
943            "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
944            [$contigID]);
945        my $sequence = $query->Fetch();
946        # Declare the return value.
947        my $retVal = 0;
948        # Set it from the sequence data, if any.
949        if ($sequence) {
950            my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
951            $retVal = $start + $len - 1;
952        }
953        # Return the result.
954        return $retVal;
955    }
956    
957    =head3 ClusterPEGs
958    
959    C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
960    
961    Cluster the PEGs in a list according to the cluster coding scheme of the specified
962    subsystem. In order for this to work properly, the subsystem object must have
963    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
964    This causes the cluster numbers to be pulled into the subsystem's color hash.
965    If a PEG is not found in the color hash, it will not appear in the output
966    sequence.
967    
968    =over 4
969    
970    =item sub
971    
972    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
973    method.
974    
975    =item pegs
976    
977    Reference to the list of PEGs to be clustered.
978    
979    =item RETURN
980    
981    Returns a list of the PEGs, grouped into smaller lists by cluster number.
982    
983    =back
984    
985    =cut
986    #: Return Type $@@;
987    sub ClusterPEGs {
988        # Get the parameters.
989        my ($self, $sub, $pegs) = @_;
990        # Declare the return variable.
991        my $retVal = [];
992        # Loop through the PEGs, creating arrays for each cluster.
993        for my $pegID (@{$pegs}) {
994            my $clusterNumber = $sub->get_cluster_number($pegID);
995            # Only proceed if the PEG is in a cluster.
996            if ($clusterNumber >= 0) {
997                # Push this PEG onto the sub-list for the specified cluster number.
998                push @{$retVal->[$clusterNumber]}, $pegID;
999            }
1000        }
1001        # Return the result.
1002        return $retVal;
1003    }
1004    
1005    =head3 GenesInRegion
1006    
1007    C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>
1008    
1009    List the features which overlap a specified region in a contig.
1010    
1011    =over 4
1012    
1013    =item contigID
1014    
1015    ID of the contig containing the region of interest.
1016    
1017    =item start
1018    
1019    Offset of the first residue in the region of interest.
1020    
1021    =item stop
1022    
1023    Offset of the last residue in the region of interest.
1024    
1025    =item RETURN
1026    
1027    Returns a three-element list. The first element is a list of feature IDs for the features that
1028    overlap the region of interest. The second and third elements are the minimum and maximum
1029    locations of the features provided on the specified contig. These may extend outside
1030    the start and stop values. The first element (that is, the list of features) is sorted
1031    roughly by location.
1032    
1033    =back
1034    
1035    =cut
1036    
1037    sub GenesInRegion {
1038        # Get the parameters.
1039        my ($self, $contigID, $start, $stop) = @_;
1040        # Get the maximum segment length.
1041        my $maximumSegmentLength = $self->MaxSegment;
1042        # Prime the values we'll use for the returned beginning and end.
1043        my @initialMinMax = ($self->ContigLength($contigID), 0);
1044        my ($min, $max) = @initialMinMax;
1045        # Get the overlapping features.
1046        my @featureObjects = $self->GeneDataInRegion($contigID, $start, $stop);
1047        # We'l use this hash to help us track the feature IDs and sort them. The key is the
1048        # feature ID and the value is a [$left,$right] pair indicating the maximum extent
1049        # of the feature's locations.
1050        my %featureMap = ();
1051        # Loop through them to do the begin/end analysis.
1052        for my $featureObject (@featureObjects) {
1053            # Get the feature's location string. This may contain multiple actual locations.
1054            my ($locations, $fid) = $featureObject->Values([qw(Feature(location-string) Feature(id))]);
1055            my @locationSegments = split /\s*,\s*/, $locations;
1056            # Loop through the locations.
1057            for my $locationSegment (@locationSegments) {
1058                # Construct an object for the location.
1059                my $locationObject = BasicLocation->new($locationSegment);
1060                # Merge the current segment's begin and end into the min and max.
1061                my ($left, $right) = ($locationObject->Left, $locationObject->Right);
1062                my ($beg, $end);
1063                if (exists $featureMap{$fid}) {
1064                    ($beg, $end) = @{$featureMap{$fid}};
1065                    $beg = $left if $left < $beg;
1066                    $end = $right if $right > $end;
1067                } else {
1068                    ($beg, $end) = ($left, $right);
1069                }
1070                $min = $beg if $beg < $min;
1071                $max = $end if $end > $max;
1072                # Store the feature's new extent back into the hash table.
1073                $featureMap{$fid} = [$beg, $end];
1074            }
1075        }
1076        # Now we must compute the list of the IDs for the features found. We start with a list
1077        # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1078        # but the result of the sort will be the same.)
1079        my @list = map { [$featureMap{$_}->[0] + $featureMap{$_}->[1], $_] } keys %featureMap;
1080        # Now we sort by midpoint and yank out the feature IDs.
1081        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1082        # Return it along with the min and max.
1083        return (\@retVal, $min, $max);
1084    }
1085    
1086    =head3 GeneDataInRegion
1087    
1088    C<< my @featureList = $sprout->GenesInRegion($contigID, $start, $stop); >>
1089    
1090    List the features which overlap a specified region in a contig.
1091    
1092    =over 4
1093    
1094    =item contigID
1095    
1096    ID of the contig containing the region of interest.
1097    
1098    =item start
1099    
1100    Offset of the first residue in the region of interest.
1101    
1102    =item stop
1103    
1104    Offset of the last residue in the region of interest.
1105    
1106    =item RETURN
1107    
1108    Returns a list of B<ERDBObjects> for the desired features. Each object will
1109    contain a B<Feature> record.
1110    
1111    =back
1112    
1113    =cut
1114    
1115    sub GeneDataInRegion {
1116        # Get the parameters.
1117        my ($self, $contigID, $start, $stop) = @_;
1118        # Get the maximum segment length.
1119        my $maximumSegmentLength = $self->MaxSegment;
1120          # Create a hash to receive the feature list. We use a hash so that we can eliminate          # Create a hash to receive the feature list. We use a hash so that we can eliminate
1121          # duplicates easily.      # duplicates easily. The hash key will be the feature ID. The value will be the feature's
1122        # ERDBObject from the query.
1123          my %featuresFound = ();          my %featuresFound = ();
1124          # Prime the values we'll use for the returned beginning and end.      # Create a table of parameters for the queries. Each query looks for features travelling in
         my ($min, $max) = ($self->ContigLength($contigID), 0);  
         # Create a table of parameters for each query. Each query looks for features travelling in  
1125          # a particular direction. The query parameters include the contig ID, the feature direction,          # a particular direction. The query parameters include the contig ID, the feature direction,
1126          # the lowest possible start position, and the highest possible start position. This works          # the lowest possible start position, and the highest possible start position. This works
1127          # 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.
# Line 879  Line 1130 
1130          # Loop through the query parameters.          # Loop through the query parameters.
1131          for my $parms (values %queryParms) {          for my $parms (values %queryParms) {
1132                  # Create the query.                  # Create the query.
1133                  my $query = $self->Get(['IsLocatedIn'],          my $query = $self->Get([qw(Feature IsLocatedIn)],
1134                          "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",                          "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
1135                          $parms);                          $parms);
1136                  # Loop through the feature segments found.                  # Loop through the feature segments found.
1137                  while (my $segment = $query->Fetch) {                  while (my $segment = $query->Fetch) {
1138                          # Get the data about this segment.                          # Get the data about this segment.
1139                          my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',              my ($featureID, $contig, $dir, $beg, $len) = $segment->Values([qw(IsLocatedIn(from-link)
1140                                  'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);                  IsLocatedIn(to-link) IsLocatedIn(dir) IsLocatedIn(beg) IsLocatedIn(len))]);
1141                          # Determine if this feature actually overlaps the region. The query insures that              # Determine if this feature segment actually overlaps the region. The query insures that
1142                          # this will be the case if the segment is the maximum length, so to fine-tune                          # this will be the case if the segment is the maximum length, so to fine-tune
1143                          # the results we insure that the inequality from the query holds using the actual                          # the results we insure that the inequality from the query holds using the actual
1144                          # length.                          # length.
1145                          my ($found, $end) = (0, 0);              my $loc = BasicLocation->new($contig, $beg, $dir, $len);
1146                          if ($dir eq '+') {              my $found = $loc->Overlap($start, $stop);
                                 $end = $beg + $len;  
                                 if ($end >= $start) {  
                                         # Denote we found a useful feature.  
                                         $found = 1;  
                                 }  
                         } elsif ($dir eq '-') {  
                                 $end = $beg - $len;  
                                 if ($end <= $stop) {  
                                         # Denote we found a useful feature.  
                                         $found = 1;  
                                 }  
                         }  
1147                          if ($found) {                          if ($found) {
1148                                  # Here we need to record the feature and update the minimum and maximum.                  # Save this feature in the result list.
1149                                  $featuresFound{$featureID} = 1;                  $featuresFound{$featureID} = $segment;
                                 if ($beg < $min) { $min = $beg; }  
                                 if ($end < $min) { $min = $end; }  
                                 if ($beg > $max) { $max = $beg; }  
                                 if ($end > $max) { $max = $end; }  
1150                          }                          }
1151                  }                  }
1152          }          }
1153          # Compute a list of the IDs for the features found.      # Return the ERDB objects for the features found.
1154          my @list = (sort (keys %featuresFound));      return values %featuresFound;
         # Return it along with the min and max.  
         return (\@list, $min, $max);  
1155  }  }
1156    
1157  =head3 FType  =head3 FType
# Line 944  Line 1177 
1177  #: Return Type $;  #: Return Type $;
1178  sub FType {  sub FType {
1179          # Get the parameters.          # Get the parameters.
1180          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1181          # Get the specified feature's type.          # Get the specified feature's type.
1182          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);          my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
1183          # Return the result.          # Return the result.
# Line 954  Line 1186 
1186    
1187  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1188    
1189  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1190    
1191  Return the annotations of a feature.  Return the annotations of a feature.
1192    
# Line 964  Line 1196 
1196    
1197  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1198    
1199    =item rawFlag
1200    
1201    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1202    will be returned in human-readable form.
1203    
1204  =item RETURN  =item RETURN
1205    
1206  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.
1207    
1208  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1209    
1210  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1211    
1212  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1213    
# Line 982  Line 1219 
1219  #: Return Type @%;  #: Return Type @%;
1220  sub FeatureAnnotations {  sub FeatureAnnotations {
1221          # Get the parameters.          # Get the parameters.
1222          my $self = shift @_;      my ($self, $featureID, $rawFlag) = @_;
         my ($featureID) = @_;  
1223          # 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.
1224          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1225                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 996  Line 1232 
1232                          $annotation->Values(['IsTargetOfAnnotation(from-link)',                          $annotation->Values(['IsTargetOfAnnotation(from-link)',
1233                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1234                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1235            # Convert the time, if necessary.
1236            if (! $rawFlag) {
1237                $timeStamp = FriendlyTimestamp($timeStamp);
1238            }
1239                  # Assemble them into a hash.                  # Assemble them into a hash.
1240          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1241                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1242                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1243                  # Add it to the return list.                  # Add it to the return list.
1244                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1012  Line 1252 
1252  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>
1253    
1254  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
1255  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,
1256  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
1257  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,
1258  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.
1259  features only have a small number of annotations.  Finally, if a single user has multiple functional assignments, we will only keep the most
1260    recent one.
1261    
1262  =over 4  =over 4
1263    
# Line 1026  Line 1267 
1267    
1268  =item RETURN  =item RETURN
1269    
1270  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1271    
1272  =back  =back
1273    
# Line 1034  Line 1275 
1275  #: Return Type %;  #: Return Type %;
1276  sub AllFunctionsOf {  sub AllFunctionsOf {
1277          # Get the parameters.          # Get the parameters.
1278          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1279          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1280          my @query = $self->GetFlat(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1281                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1282                                                          [$featureID], 'Annotation(annotation)');                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1283                                               'MadeAnnotation(from-link)']);
1284          # Declare the return hash.          # Declare the return hash.
1285          my %retVal;          my %retVal;
1286        # Now we sort the assignments by timestamp in reverse.
1287        my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1288          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1289          for my $text (@query) {      for my $annotation (@sortedQuery) {
1290            # Get the annotation fields.
1291            my ($timeStamp, $text, $user) = @{$annotation};
1292                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1293                  my ($user, $function) = ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1294                  if ($user) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1295                          # Here it is, so stuff it in the return hash.              # Here it is a functional assignment and there has been no
1296                          $retVal{$function} = $user;              # previous assignment for this user, so we stuff it in the
1297                # return hash.
1298                $retVal{$actualUser} = $function;
1299                  }                  }
1300          }          }
1301          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1062  Line 1309 
1309  Return the most recently-determined functional assignment of a particular feature.  Return the most recently-determined functional assignment of a particular feature.
1310    
1311  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
1312  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
1313  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.  
1314    
1315  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
1316  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 1085  Line 1329 
1329    
1330  =item userID (optional)  =item userID (optional)
1331    
1332  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
1333  C<FIG> assignment will be returned.  functional assignment in the B<Feature> table will be returned.
1334    
1335  =item RETURN  =item RETURN
1336    
# Line 1098  Line 1342 
1342  #: Return Type $;  #: Return Type $;
1343  sub FunctionOf {  sub FunctionOf {
1344          # Get the parameters.          # Get the parameters.
1345          my $self = shift @_;      my ($self, $featureID, $userID) = @_;
         my ($featureID, $userID) = @_;  
1346      # Declare the return value.      # Declare the return value.
1347      my $retVal;      my $retVal;
1348      # Determine the ID type.      # Determine the ID type.
1349      if ($featureID =~ m/^fig\|/) {      if ($featureID =~ m/^fig\|/) {
1350          # Here we have a FIG feature ID. We must build the list of trusted          # Here we have a FIG feature ID.
1351          # users.          if (!$userID) {
1352                # Use the primary assignment.
1353                ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']);
1354            } else {
1355                # We must build the list of trusted users.
1356          my %trusteeTable = ();          my %trusteeTable = ();
1357          # Check the user ID.          # Check the user ID.
1358          if (!$userID) {          if (!$userID) {
# Line 1127  Line 1374 
1374              }              }
1375          }          }
1376          # 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.
1377          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],              my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1378                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1379                                 [$featureID]);                                 [$featureID]);
1380          my $timeSelected = 0;          my $timeSelected = 0;
1381          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1382          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1383              # Get the annotation text.              # Get the annotation text.
1384              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);                  my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1385                                                             'Annotation(time)', 'MadeAnnotation(from-link)']);
1386              # 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.
1387              my ($user, $type, $function) = split(/\n/, $text);                  my ($actualUser, $function) = _ParseAssignment($user, $text);
1388              if ($type =~ m/^set $user function to$/i) {                  Trace("Assignment user is $actualUser, text is $function.") if T(4);
1389                    if ($actualUser) {
1390                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1391                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1392                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                      if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1393                      $retVal = $function;                      $retVal = $function;
1394                      $timeSelected = $time;                      $timeSelected = $time;
1395                  }                  }
1396              }              }
1397          }          }
1398            }
1399      } else {      } else {
1400          # 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
1401          # matter. We simply get the information from the External Alias Function          # matter. We simply get the information from the External Alias Function
1402          # table.          # table.
1403          ($retVal) = $self->GetEntityValues('ExternalAliasFunc', $featureID, ['func']);          ($retVal) = $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']);
1404      }      }
1405          # Return the assignment found.          # Return the assignment found.
1406          return $retVal;          return $retVal;
1407  }  }
1408    
1409    =head3 FunctionsOf
1410    
1411    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1412    
1413    Return the functional assignments of a particular feature.
1414    
1415    The functional assignment is handled differently depending on the type of feature. If
1416    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1417    assignment is a type of annotation. The format of an assignment is described in
1418    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1419    annotation itself because it's a text field; however, this is not a big problem because
1420    most features only have a small number of annotations.
1421    
1422    If the feature is B<not> identified by a FIG ID, then the functional assignment
1423    information is taken from the B<ExternalAliasFunc> table. If the table does
1424    not contain an entry for the feature, an empty list is returned.
1425    
1426    =over 4
1427    
1428    =item featureID
1429    
1430    ID of the feature whose functional assignments are desired.
1431    
1432    =item RETURN
1433    
1434    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1435    that user.
1436    
1437    =back
1438    
1439    =cut
1440    #: Return Type @@;
1441    sub FunctionsOf {
1442        # Get the parameters.
1443        my ($self, $featureID) = @_;
1444        # Declare the return value.
1445        my @retVal = ();
1446        # Determine the ID type.
1447        if ($featureID =~ m/^fig\|/) {
1448            # Here we have a FIG feature ID. We must build the list of trusted
1449            # users.
1450            my %trusteeTable = ();
1451            # Build a query for all of the feature's annotations, sorted by date.
1452            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1453                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1454                                   [$featureID]);
1455            my $timeSelected = 0;
1456            # Loop until we run out of annotations.
1457            while (my $annotation = $query->Fetch()) {
1458                # Get the annotation text.
1459                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1460                                                                'Annotation(time)',
1461                                                                'MadeAnnotation(user)']);
1462                # Check to see if this is a functional assignment for a trusted user.
1463                my ($actualUser, $function) = _ParseAssignment($user, $text);
1464                if ($actualUser) {
1465                    # Here it is a functional assignment.
1466                    push @retVal, [$actualUser, $function];
1467                }
1468            }
1469        } else {
1470            # Here we have a non-FIG feature ID. In this case the user ID does not
1471            # matter. We simply get the information from the External Alias Function
1472            # table.
1473            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1474                                                     ['ExternalAliasFunc(func)']);
1475            push @retVal, map { ['master', $_] } @assignments;
1476        }
1477        # Return the assignments found.
1478        return @retVal;
1479    }
1480    
1481  =head3 BBHList  =head3 BBHList
1482    
1483  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1175  Line 1497 
1497    
1498  =item RETURN  =item RETURN
1499    
1500  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
1501  their best hits.  on the target genome.
1502    
1503  =back  =back
1504    
# Line 1184  Line 1506 
1506  #: Return Type %;  #: Return Type %;
1507  sub BBHList {  sub BBHList {
1508          # Get the parameters.          # Get the parameters.
1509          my $self = shift @_;      my ($self, $genomeID, $featureList) = @_;
         my ($genomeID, $featureList) = @_;  
1510          # Create the return structure.          # Create the return structure.
1511          my %retVal = ();          my %retVal = ();
1512          # Loop through the incoming features.          # Loop through the incoming features.
1513          for my $featureID (@{$featureList}) {          for my $featureID (@{$featureList}) {
1514                  # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1515                  my $query = $self->Get(['IsBidirectionalBestHitOf'],          my @bbhData = FIGRules::BBHData($featureID);
1516                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",          # Peel off the BBHs found.
1517                                                             [$featureID, $genomeID]);          my @found = ();
1518                  # Look for the best hit.          for my $bbh (@bbhData) {
1519                  my $bbh = $query->Fetch;              my $fid = $bbh->[0];
1520                  if ($bbh) {              my $bbGenome = $self->GenomeOf($fid);
1521                          my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              if ($bbGenome eq $genomeID) {
1522                          $retVal{$featureID} = $targetFeature;                  push @found, $fid;
1523                }
1524                  }                  }
1525            $retVal{$featureID} = \@found;
1526          }          }
1527          # Return the mapping.          # Return the mapping.
1528          return \%retVal;          return \%retVal;
1529  }  }
1530    
1531    =head3 SimList
1532    
1533    C<< my %similarities = $sprout->SimList($featureID, $count); >>
1534    
1535    Return a list of the similarities to the specified feature.
1536    
1537    This method just returns the bidirectional best hits for performance reasons.
1538    
1539    =over 4
1540    
1541    =item featureID
1542    
1543    ID of the feature whose similarities are desired.
1544    
1545    =item count
1546    
1547    Maximum number of similar features to be returned, or C<0> to return them all.
1548    
1549    =back
1550    
1551    =cut
1552    #: Return Type %;
1553    sub SimList {
1554        # Get the parameters.
1555        my ($self, $featureID, $count) = @_;
1556        # Ask for the best hits.
1557        my @lists = FIGRules::BBHData($featureID);
1558        # Create the return value.
1559        my %retVal = ();
1560        for my $tuple (@lists) {
1561            $retVal{$tuple->[0]} = $tuple->[1];
1562        }
1563        # Return the result.
1564        return %retVal;
1565    }
1566    
1567    =head3 IsComplete
1568    
1569    C<< my $flag = $sprout->IsComplete($genomeID); >>
1570    
1571    Return TRUE if the specified genome is complete, else FALSE.
1572    
1573    =over 4
1574    
1575    =item genomeID
1576    
1577    ID of the genome whose completeness status is desired.
1578    
1579    =item RETURN
1580    
1581    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1582    not found.
1583    
1584    =back
1585    
1586    =cut
1587    #: Return Type $;
1588    sub IsComplete {
1589        # Get the parameters.
1590        my ($self, $genomeID) = @_;
1591        # Declare the return variable.
1592        my $retVal;
1593        # Get the genome's data.
1594        my $genomeData = $self->GetEntity('Genome', $genomeID);
1595        if ($genomeData) {
1596            # The genome exists, so get the completeness flag.
1597            $retVal = $genomeData->PrimaryValue('Genome(complete)');
1598        }
1599        # Return the result.
1600        return $retVal;
1601    }
1602    
1603  =head3 FeatureAliases  =head3 FeatureAliases
1604    
1605  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>
# Line 1228  Line 1623 
1623  #: Return Type @;  #: Return Type @;
1624  sub FeatureAliases {  sub FeatureAliases {
1625          # Get the parameters.          # Get the parameters.
1626          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
1627          # Get the desired feature's aliases          # Get the desired feature's aliases
1628          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);      my @retVal = $self->GetFlat(['IsAliasOf'], "IsAliasOf(to-link) = ?", [$featureID], 'IsAliasOf(from-link)');
1629          # Return the result.          # Return the result.
1630          return @retVal;          return @retVal;
1631  }  }
# Line 1240  Line 1634 
1634    
1635  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1636    
1637  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1638    
1639  =over 4  =over 4
1640    
1641  =item featureID  =item featureID
1642    
1643  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1644    
1645  =item RETURN  =item RETURN
1646    
1647  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
1648  an undefined value.  found, returns an undefined value.
1649    
1650  =back  =back
1651    
# Line 1259  Line 1653 
1653  #: Return Type $;  #: Return Type $;
1654  sub GenomeOf {  sub GenomeOf {
1655          # Get the parameters.          # Get the parameters.
1656          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
         # Create a query to find the genome associated with the feature.  
         my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);  
1657          # Declare the return value.          # Declare the return value.
1658          my $retVal;          my $retVal;
1659          # Get the genome ID.      # Parse the genome ID from the feature ID.
1660          if (my $relationship = $query->Fetch()) {      if ($featureID =~ /^fig\|(\d+\.\d+)/) {
1661                  ($retVal) = $relationship->Value('HasContig(from-link)');          $retVal = $1;
1662        } else {
1663            Confess("Invalid feature ID $featureID.");
1664          }          }
1665          # Return the value found.          # Return the value found.
1666          return $retVal;          return $retVal;
# Line 1296  Line 1689 
1689  #: Return Type %;  #: Return Type %;
1690  sub CoupledFeatures {  sub CoupledFeatures {
1691          # Get the parameters.          # Get the parameters.
1692          my $self = shift @_;      my ($self, $featureID) = @_;
1693          my ($featureID) = @_;      # Ask the coupling server for the data.
1694          # Create a query to retrieve the functionally-coupled features. Note that we depend on the      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1695          # fact that the functional coupling is physically paired. If (A,B) is in the database, then      my @rawPairs = FIGRules::NetCouplingData('coupled_to', id1 => $featureID);
1696          # (B,A) will also be found.      Trace(scalar(@rawPairs) . " couplings returned.") if T(coupling => 3);
1697          my $query = $self->Get(['IsClusteredOnChromosomeWith'],      # Form them into a hash.
                                                    "IsClusteredOnChromosomeWith(from-link) = ?", [$featureID]);  
         # This value will be set to TRUE if we find at least one coupled feature.  
         my $found = 0;  
         # Create the return hash.  
1698          my %retVal = ();          my %retVal = ();
1699          # Retrieve the relationship records and store them in the hash.      for my $pair (@rawPairs) {
1700          while (my $clustering = $query->Fetch()) {          # Get the feature ID and score.
1701                  my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',          my ($featureID2, $score) = @{$pair};
1702                                                                      'IsClusteredOnChromosomeWith(score)']);          # Only proceed if the feature is in NMPDR.
1703                  $retVal{$otherFeatureID} = $score;          if ($self->_CheckFeature($featureID2)) {
1704                  $found = 1;              $retVal{$featureID2} = $score;
1705            }
1706          }          }
1707          # Functional coupling is reflexive. If we found at least one coupled feature, we must add          # Functional coupling is reflexive. If we found at least one coupled feature, we must add
1708          # the incoming feature as well.          # the incoming feature as well.
1709          if ($found) {      if (keys %retVal) {
1710                  $retVal{$featureID} = 9999;                  $retVal{$featureID} = 9999;
1711      }      }
1712          # Return the hash.          # Return the hash.
1713          return %retVal;          return %retVal;
1714  }  }
1715    
1716  =head3 GetEntityTypes  =head3 CouplingEvidence
1717    
1718  C<< my @entityList = $sprout->GetEntityTypes(); >>  C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>
1719    
1720  Return the list of supported entity types.  Return the evidence for a functional coupling.
1721    
1722  =cut  A pair of features is considered evidence of a coupling between two other
1723  #: Return Type @;  features if they occur close together on a contig and both are similar to
1724  sub GetEntityTypes {  the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1725    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1726    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1727    similar to B<A2>.
1728    
1729    The score of a coupling is determined by the number of pieces of evidence
1730    that are considered I<representative>. If several evidence items belong to
1731    a group of genomes that are close to each other, only one of those items
1732    is considered representative. The other evidence items are presumed to be
1733    there because of the relationship between the genomes rather than because
1734    the two proteins generated by the features have a related functionality.
1735    
1736    Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1737    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1738    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1739    and FALSE otherwise.
1740    
1741    =over 4
1742    
1743    =item peg1
1744    
1745    ID of the feature of interest.
1746    
1747    =item peg2
1748    
1749    ID of a feature functionally coupled to the feature of interest.
1750    
1751    =item RETURN
1752    
1753    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1754    of interest, a feature similar to the functionally coupled feature, and a flag
1755    that is TRUE for a representative piece of evidence and FALSE otherwise.
1756    
1757    =back
1758    
1759    =cut
1760    #: Return Type @@;
1761    sub CouplingEvidence {
1762        # Get the parameters.
1763        my ($self, $peg1, $peg2) = @_;
1764        # Declare the return variable.
1765        my @retVal = ();
1766        # Get the coupling and evidence data.
1767        my @rawData = FIGRules::NetCouplingData('coupling_evidence', id1 => $peg1, id2 => $peg2);
1768        # Loop through the raw data, saving the ones that are in NMPDR genomes.
1769        for my $rawTuple (@rawData) {
1770            if ($self->_CheckFeature($rawTuple->[0]) && $self->_CheckFeature($rawTuple->[1])) {
1771                push @retVal, $rawTuple;
1772            }
1773        }
1774        # Return the result.
1775        return @retVal;
1776    }
1777    
1778    =head3 GetSynonymGroup
1779    
1780    C<< my $id = $sprout->GetSynonymGroup($fid); >>
1781    
1782    Return the synonym group name for the specified feature.
1783    
1784    =over 4
1785    
1786    =item fid
1787    
1788    ID of the feature whose synonym group is desired.
1789    
1790    =item RETURN
1791    
1792    The name of the synonym group to which the feature belongs. If the feature does
1793    not belong to a synonym group, the feature ID itself is returned.
1794    
1795    =back
1796    
1797    =cut
1798    
1799    sub GetSynonymGroup {
1800        # Get the parameters.
1801        my ($self, $fid) = @_;
1802        # Declare the return variable.
1803        my $retVal;
1804        # Find the synonym group.
1805        my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1806                                       [$fid], 'IsSynonymGroupFor(from-link)');
1807        # Check to see if we found anything.
1808        if (@groups) {
1809            $retVal = $groups[0];
1810        } else {
1811            $retVal = $fid;
1812        }
1813        # Return the result.
1814        return $retVal;
1815    }
1816    
1817    =head3 GetBoundaries
1818    
1819    C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>
1820    
1821    Determine the begin and end boundaries for the locations in a list. All of the
1822    locations must belong to the same contig and have mostly the same direction in
1823    order for this method to produce a meaningful result. The resulting
1824    begin/end pair will contain all of the bases in any of the locations.
1825    
1826    =over 4
1827    
1828    =item locList
1829    
1830    List of locations to process.
1831    
1832    =item RETURN
1833    
1834    Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1835    and the ending boundary. The beginning boundary will be left of the
1836    end for mostly-forward locations and right of the end for mostly-backward
1837    locations.
1838    
1839    =back
1840    
1841    =cut
1842    
1843    sub GetBoundaries {
1844          # Get the parameters.          # Get the parameters.
1845          my $self = shift @_;      my ($self, @locList) = @_;
1846          # Get the underlying database object.      # Set up the counters used to determine the most popular direction.
1847          my $erdb = $self->{_erdb};      my %counts = ( '+' => 0, '-' => 0 );
1848          # Get its entity type list.      # Get the last location and parse it.
1849          my @retVal = $erdb->GetEntityTypes();      my $locObject = BasicLocation->new(pop @locList);
1850        # Prime the loop with its data.
1851        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
1852        # Count its direction.
1853        $counts{$locObject->Dir}++;
1854        # Loop through the remaining locations. Note that in most situations, this loop
1855        # will not iterate at all, because most of the time we will be dealing with a
1856        # singleton list.
1857        for my $loc (@locList) {
1858            # Create a location object.
1859            my $locObject = BasicLocation->new($loc);
1860            # Count the direction.
1861            $counts{$locObject->Dir}++;
1862            # Get the left end and the right end.
1863            my $left = $locObject->Left;
1864            my $right = $locObject->Right;
1865            # Merge them into the return variables.
1866            if ($left < $beg) {
1867                $beg = $left;
1868            }
1869            if ($right > $end) {
1870                $end = $right;
1871            }
1872        }
1873        # If the most common direction is reverse, flip the begin and end markers.
1874        if ($counts{'-'} > $counts{'+'}) {
1875            ($beg, $end) = ($end, $beg);
1876        }
1877        # Return the result.
1878        return ($contig, $beg, $end);
1879  }  }
1880    
1881  =head3 ReadFasta  =head3 ReadFasta
# Line 1384  Line 1922 
1922                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1923                          # 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.
1924                          if ($id) {                          if ($id) {
1925                                  $retVal{$id} = $sequence;                  $retVal{$id} = lc $sequence;
1926                          }                          }
1927                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
1928                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
1929                  } else {                  } else {
1930                          # 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.
1931                          # First, we get the actual data out.              # First, we get the actual data out. Note that we normalize to lower
1932                # case.
1933                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
1934                          $sequence .= $1;                          $sequence .= $1;
1935                  }                  }
1936          }          }
1937          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
1938          if ($sequence) {          if ($sequence) {
1939                  $retVal {$id} = $sequence;          $retVal{$id} = lc $sequence;
1940          }          }
1941        # Close the file.
1942        close FASTAFILE;
1943          # Return the hash constructed from the file.          # Return the hash constructed from the file.
1944          return %retVal;          return %retVal;
1945  }  }
# Line 1409  Line 1950 
1950    
1951  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
1952  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
1953  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,
1954    it will not be changed; otherwise, it will be converted. This method can also be used to
1955    perform the reverse task-- insuring that all the locations are in the old format.
1956    
1957  =over 4  =over 4
1958    
# Line 1436  Line 1979 
1979  #: Return Type @;  #: Return Type @;
1980  sub FormatLocations {  sub FormatLocations {
1981          # Get the parameters.          # Get the parameters.
1982          my $self = shift @_;      my ($self, $prefix, $locations, $oldFormat) = @_;
         my ($prefix, $locations, $oldFormat) = @_;  
1983          # Create the return list.          # Create the return list.
1984          my @retVal = ();          my @retVal = ();
1985          # Check to see if any locations were passed in.          # Check to see if any locations were passed in.
1986          if ($locations eq '') {          if ($locations eq '') {
1987              confess "No locations specified.";          Confess("No locations specified.");
1988          } else {          } else {
1989                  # Loop through the locations, converting them to the new format.                  # Loop through the locations, converting them to the new format.
1990                  for my $location (@{$locations}) {                  for my $location (@{$locations}) {
# Line 1477  Line 2019 
2019    
2020  sub DumpData {  sub DumpData {
2021          # Get the parameters.          # Get the parameters.
2022          my $self = shift @_;      my ($self) = @_;
2023          # Get the data directory name.          # Get the data directory name.
2024          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
2025          # Dump the relations.          # Dump the relations.
2026          $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2027  }  }
2028    
2029  =head3 XMLFileName  =head3 XMLFileName
# Line 1493  Line 2035 
2035  =cut  =cut
2036  #: Return Type $;  #: Return Type $;
2037  sub XMLFileName {  sub XMLFileName {
2038          my $self = shift @_;      my ($self) = @_;
2039          return $self->{_xmlName};          return $self->{_xmlName};
2040  }  }
2041    
# Line 1513  Line 2055 
2055  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
2056  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>.
2057    
2058  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'}); >>
2059    
2060  =over 4  =over 4
2061    
# Line 1531  Line 2073 
2073  #: Return Type ;  #: Return Type ;
2074  sub Insert {  sub Insert {
2075          # Get the parameters.          # Get the parameters.
2076          my $self = shift @_;      my ($self, $objectType, $fieldHash) = @_;
         my ($objectType, $fieldHash) = @_;  
2077          # Call the underlying method.          # Call the underlying method.
2078          $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2079  }  }
2080    
2081  =head3 Annotate  =head3 Annotate
# Line 1573  Line 2114 
2114  #: Return Type $;  #: Return Type $;
2115  sub Annotate {  sub Annotate {
2116          # Get the parameters.          # Get the parameters.
2117          my $self = shift @_;      my ($self, $fid, $timestamp, $user, $text) = @_;
         my ($fid, $timestamp, $user, $text) = @_;  
2118          # Create the annotation ID.          # Create the annotation ID.
2119          my $aid = "$fid:$timestamp";          my $aid = "$fid:$timestamp";
2120          # Insert the Annotation object.          # Insert the Annotation object.
# Line 1594  Line 2134 
2134    
2135  =head3 AssignFunction  =head3 AssignFunction
2136    
2137  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function); >>  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>
2138    
2139  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
2140  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.  
2141    
2142  =over 4  =over 4
2143    
# Line 1608  Line 2147 
2147    
2148  =item user  =item user
2149    
2150  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>.
2151    
2152  =item function  =item function
2153    
2154  Text of the function being assigned.  Text of the function being assigned.
2155    
2156    =item assigningUser (optional)
2157    
2158    Name of the individual user making the assignment. If omitted, defaults to the user group.
2159    
2160  =item RETURN  =item RETURN
2161    
2162  Returns 1 if successful, 0 if an error occurred.  Returns 1 if successful, 0 if an error occurred.
# Line 1624  Line 2167 
2167  #: Return Type $;  #: Return Type $;
2168  sub AssignFunction {  sub AssignFunction {
2169          # Get the parameters.          # Get the parameters.
2170          my $self = shift @_;      my ($self, $featureID, $user, $function, $assigningUser) = @_;
2171          my ($featureID, $user, $function) = @_;      # Default the assigning user.
2172        if (! $assigningUser) {
2173            $assigningUser = $user;
2174        }
2175          # Create an annotation string from the parameters.          # Create an annotation string from the parameters.
2176          my $annotationText = "$user\nset $user function to\n$function";      my $annotationText = "$assigningUser\nset $user function to\n$function";
2177          # Get the current time.          # Get the current time.
2178          my $now = time;          my $now = time;
2179          # Declare the return variable.          # Declare the return variable.
# Line 1672  Line 2218 
2218  #: Return Type @;  #: Return Type @;
2219  sub FeaturesByAlias {  sub FeaturesByAlias {
2220          # Get the parameters.          # Get the parameters.
2221          my $self = shift @_;      my ($self, $alias) = @_;
         my ($alias) = @_;  
2222          # Declare the return variable.          # Declare the return variable.
2223          my @retVal = ();          my @retVal = ();
2224          # Parse the alias.          # Parse the alias.
# Line 1683  Line 2228 
2228                  push @retVal, $mappedAlias;                  push @retVal, $mappedAlias;
2229          } else {          } else {
2230                  # Here we have a non-FIG alias. Get the features with the normalized alias.                  # Here we have a non-FIG alias. Get the features with the normalized alias.
2231                  @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');          @retVal = $self->GetFlat(['IsAliasOf'], 'IsAliasOf(from-link) = ?', [$mappedAlias], 'IsAliasOf(to-link)');
2232          }          }
2233          # Return the result.          # Return the result.
2234          return @retVal;          return @retVal;
2235  }  }
2236    
 =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;  
 }  
   
2237  =head3 FeatureTranslation  =head3 FeatureTranslation
2238    
2239  C<< my $translation = $sprout->FeatureTranslation($featureID); >>  C<< my $translation = $sprout->FeatureTranslation($featureID); >>
# Line 1746  Line 2256 
2256  #: Return Type $;  #: Return Type $;
2257  sub FeatureTranslation {  sub FeatureTranslation {
2258          # Get the parameters.          # Get the parameters.
2259          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2260          # Get the specified feature's translation.          # Get the specified feature's translation.
2261          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);          my ($retVal) = $self->GetEntityValues("Feature", $featureID, ['Feature(translation)']);
2262          return $retVal;          return $retVal;
# Line 1779  Line 2288 
2288  #: Return Type @;  #: Return Type @;
2289  sub Taxonomy {  sub Taxonomy {
2290          # Get the parameters.          # Get the parameters.
2291          my $self = shift @_;      my ($self, $genome) = @_;
         my ($genome) = @_;  
2292          # Find the specified genome's taxonomy string.          # Find the specified genome's taxonomy string.
2293          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);          my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);
2294          # Declare the return variable.          # Declare the return variable.
# Line 1823  Line 2331 
2331  #: Return Type $;  #: Return Type $;
2332  sub CrudeDistance {  sub CrudeDistance {
2333          # Get the parameters.          # Get the parameters.
2334          my $self = shift @_;      my ($self, $genome1, $genome2) = @_;
         my ($genome1, $genome2) = @_;  
2335          # Insure that the distance is commutative by sorting the genome IDs.          # Insure that the distance is commutative by sorting the genome IDs.
2336          my ($genomeA, $genomeB);          my ($genomeA, $genomeB);
2337          if ($genome2 < $genome2) {          if ($genome2 < $genome2) {
# Line 1871  Line 2378 
2378  #: Return Type $;  #: Return Type $;
2379  sub RoleName {  sub RoleName {
2380          # Get the parameters.          # Get the parameters.
2381          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2382          # Get the specified role's name.          # Get the specified role's name.
2383          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);          my ($retVal) = $self->GetEntityValues('Role', $roleID, ['Role(name)']);
2384          # Use the ID if the role has no name.          # Use the ID if the role has no name.
# Line 1905  Line 2411 
2411  #: Return Type @;  #: Return Type @;
2412  sub RoleDiagrams {  sub RoleDiagrams {
2413          # Get the parameters.          # Get the parameters.
2414          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2415          # Query for the diagrams.          # Query for the diagrams.
2416          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @retVal = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2417                                                                  'RoleOccursIn(to-link)');                                                                  'RoleOccursIn(to-link)');
# Line 1914  Line 2419 
2419          return @retVal;          return @retVal;
2420  }  }
2421    
2422    =head3 GetProperties
2423    
2424    C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>
2425    
2426    Return a list of the properties with the specified characteristics.
2427    
2428    Properties are the Sprout analog of the FIG attributes. The call is
2429    passed directly to the CustomAttributes or RemoteCustomAttributes object
2430    contained in this object.
2431    
2432    This method returns a series of tuples that match the specified criteria. Each tuple
2433    will contain an object ID, a key, and one or more values. The parameters to this
2434    method therefore correspond structurally to the values expected in each tuple. In
2435    addition, you can ask for a generic search by suffixing a percent sign (C<%>) to any
2436    of the parameters. So, for example,
2437    
2438        my @attributeList = $sprout->GetProperties('fig|100226.1.peg.1004', 'structure%', 1, 2);
2439    
2440    would return something like
2441    
2442        ['fig}100226.1.peg.1004', 'structure', 1, 2]
2443        ['fig}100226.1.peg.1004', 'structure1', 1, 2]
2444        ['fig}100226.1.peg.1004', 'structure2', 1, 2]
2445        ['fig}100226.1.peg.1004', 'structureA', 1, 2]
2446    
2447    Use of C<undef> in any position acts as a wild card (all values). You can also specify
2448    a list reference in the ID column. Thus,
2449    
2450        my @attributeList = $sprout->GetProperties(['100226.1', 'fig|100226.1.%'], 'PUBMED');
2451    
2452    would get the PUBMED attribute data for Streptomyces coelicolor A3(2) and all its
2453    features.
2454    
2455    In addition to values in multiple sections, a single attribute key can have multiple
2456    values, so even
2457    
2458        my @attributeList = $sprout->GetProperties($peg, 'virulent');
2459    
2460    which has no wildcard in the key or the object ID, may return multiple tuples.
2461    
2462    =over 4
2463    
2464    =item objectID
2465    
2466    ID of object whose attributes are desired. If the attributes are desired for multiple
2467    objects, this parameter can be specified as a list reference. If the attributes are
2468    desired for all objects, specify C<undef> or an empty string. Finally, you can specify
2469    attributes for a range of object IDs by putting a percent sign (C<%>) at the end.
2470    
2471    =item key
2472    
2473    Attribute key name. A value of C<undef> or an empty string will match all
2474    attribute keys. If the values are desired for multiple keys, this parameter can be
2475    specified as a list reference. Finally, you can specify attributes for a range of
2476    keys by putting a percent sign (C<%>) at the end.
2477    
2478    =item values
2479    
2480    List of the desired attribute values, section by section. If C<undef>
2481    or an empty string is specified, all values in that section will match. A
2482    generic match can be requested by placing a percent sign (C<%>) at the end.
2483    In that case, all values that match up to and not including the percent sign
2484    will match. You may also specify a regular expression enclosed
2485    in slashes. All values that match the regular expression will be returned. For
2486    performance reasons, only values have this extra capability.
2487    
2488    =item RETURN
2489    
2490    Returns a list of tuples. The first element in the tuple is an object ID, the
2491    second is an attribute key, and the remaining elements are the sections of
2492    the attribute value. All of the tuples will match the criteria set forth in
2493    the parameter list.
2494    
2495    =back
2496    
2497    =cut
2498    
2499    sub GetProperties {
2500        # Get the parameters.
2501        my ($self, @parms) = @_;
2502        # Declare the return variable.
2503        my @retVal = $self->{_ca}->GetAttributes(@parms);
2504        # Return the result.
2505        return @retVal;
2506    }
2507    
2508  =head3 FeatureProperties  =head3 FeatureProperties
2509    
2510  C<< my @properties = $sprout->FeatureProperties($featureID); >>  C<< my @properties = $sprout->FeatureProperties($featureID); >>
# Line 1922  Line 2513 
2513  that specify special characteristics of the feature. For example, a property could indicate  that specify special characteristics of the feature. For example, a property could indicate
2514  that a feature is essential to the survival of the organism or that it has benign influence  that a feature is essential to the survival of the organism or that it has benign influence
2515  on the activities of a pathogen. Each property is returned as a triple of the form  on the activities of a pathogen. Each property is returned as a triple of the form
2516  C<($key,$value,$url)>, where C<$key> is the property name, C<$value> is its value (commonly  C<($key,@values)>, where C<$key> is the property name and  C<@values> are its values.
 a 1 or a 0, but possibly a string or a floating-point value), and C<$url> is a string describing  
 the web address or citation in which the property's value for the feature was identified.  
2517    
2518  =over 4  =over 4
2519    
# Line 1934  Line 2523 
2523    
2524  =item RETURN  =item RETURN
2525    
2526  Returns a list of triples, each triple containing the property name, its value, and a URL or  Returns a list of tuples, each tuple containing the property name and its values.
 citation.  
2527    
2528  =back  =back
2529    
# Line 1943  Line 2531 
2531  #: Return Type @@;  #: Return Type @@;
2532  sub FeatureProperties {  sub FeatureProperties {
2533          # Get the parameters.          # Get the parameters.
2534          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2535          # Get the properties.          # Get the properties.
2536          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],      my @attributes = $self->{_ca}->GetAttributes($featureID);
2537                                                          ['Property(property-name)', 'Property(property-value)',      # Strip the feature ID off each tuple.
2538                                                           'HasProperty(evidence)']);      my @retVal = ();
2539        for my $attributeRow (@attributes) {
2540            shift @{$attributeRow};
2541            push @retVal, $attributeRow;
2542        }
2543          # Return the resulting list.          # Return the resulting list.
2544          return @retVal;          return @retVal;
2545  }  }
# Line 1975  Line 2566 
2566  #: Return Type $;  #: Return Type $;
2567  sub DiagramName {  sub DiagramName {
2568          # Get the parameters.          # Get the parameters.
2569          my $self = shift @_;      my ($self, $diagramID) = @_;
         my ($diagramID) = @_;  
2570          # Get the specified diagram's name and return it.          # Get the specified diagram's name and return it.
2571          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);          my ($retVal) = $self->GetEntityValues('Diagram', $diagramID, ['Diagram(name)']);
2572          return $retVal;          return $retVal;
2573  }  }
2574    
2575    =head3 PropertyID
2576    
2577    C<< my $id = $sprout->PropertyID($propName, $propValue); >>
2578    
2579    Return the ID of the specified property name and value pair, if the
2580    pair exists. Only a small subset of the FIG attributes are stored as
2581    Sprout properties, mostly for use in search optimization.
2582    
2583    =over 4
2584    
2585    =item propName
2586    
2587    Name of the desired property.
2588    
2589    =item propValue
2590    
2591    Value expected for the desired property.
2592    
2593    =item RETURN
2594    
2595    Returns the ID of the name/value pair, or C<undef> if the pair does not exist.
2596    
2597    =back
2598    
2599    =cut
2600    
2601    sub PropertyID {
2602        # Get the parameters.
2603        my ($self, $propName, $propValue) = @_;
2604        # Try to find the ID.
2605        my ($retVal) = $self->GetFlat(['Property'],
2606                                      "Property(property-name) = ? AND Property(property-value) = ?",
2607                                      [$propName, $propValue], 'Property(id)');
2608        # Return the result.
2609        return $retVal;
2610    }
2611    
2612  =head3 MergedAnnotations  =head3 MergedAnnotations
2613    
2614  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>
# Line 2008  Line 2635 
2635  #: Return Type @;  #: Return Type @;
2636  sub MergedAnnotations {  sub MergedAnnotations {
2637          # Get the parameters.          # Get the parameters.
2638          my $self = shift @_;      my ($self, $list) = @_;
         my ($list) = @_;  
2639          # Create a list to hold the annotation tuples found.          # Create a list to hold the annotation tuples found.
2640          my @tuples = ();          my @tuples = ();
2641          # Loop through the features in the input list.          # Loop through the features in the input list.
# Line 2057  Line 2683 
2683  #: Return Type @;  #: Return Type @;
2684  sub RoleNeighbors {  sub RoleNeighbors {
2685          # Get the parameters.          # Get the parameters.
2686          my $self = shift @_;      my ($self, $roleID) = @_;
         my ($roleID) = @_;  
2687          # Get all the diagrams containing this role.          # Get all the diagrams containing this role.
2688          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],          my @diagrams = $self->GetFlat(['RoleOccursIn'], "RoleOccursIn(from-link) = ?", [$roleID],
2689                                                                    'RoleOccursIn(to-link)');                                                                    'RoleOccursIn(to-link)');
# Line 2100  Line 2725 
2725  #: Return Type @;  #: Return Type @;
2726  sub FeatureLinks {  sub FeatureLinks {
2727          # Get the parameters.          # Get the parameters.
2728          my $self = shift @_;      my ($self, $featureID) = @_;
         my ($featureID) = @_;  
2729          # Get the feature's links.          # Get the feature's links.
2730          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(link)']);
2731          # Return the feature's links.          # Return the feature's links.
# Line 2113  Line 2737 
2737  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>
2738    
2739  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
2740  to the role the feature performs.  to the roles the feature performs.
2741    
2742  =over 4  =over 4
2743    
# Line 2123  Line 2747 
2747    
2748  =item RETURN  =item RETURN
2749    
2750  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.
2751    
2752  =back  =back
2753    
2754  =cut  =cut
2755  #: Return Type %;  #: Return Type %@;
2756  sub SubsystemsOf {  sub SubsystemsOf {
2757          # Get the parameters.          # Get the parameters.
2758          my $self = shift @_;      my ($self, $featureID) = @_;
2759          my ($featureID) = @_;      # Get the subsystem list.
         # Use the SSCell to connect features to subsystems.  
2760          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2761                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2762                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2763          # Create the return value.          # Create the return value.
2764          my %retVal = ();          my %retVal = ();
2765        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2766        # in two spreadsheet cells.
2767        my %dupHash = ();
2768          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
2769          for my $record (@subsystems) {          for my $record (@subsystems) {
2770                  $retVal{$record->[0]} = $record->[1];          # Get this subsystem and role.
2771            my ($subsys, $role) = @{$record};
2772            # Insure it's the first time for both.
2773            my $dupKey = "$subsys\n$role";
2774            if (! exists $dupHash{"$subsys\n$role"}) {
2775                $dupHash{$dupKey} = 1;
2776                push @{$retVal{$subsys}}, $role;
2777            }
2778          }          }
2779          # Return the hash.          # Return the hash.
2780          return %retVal;          return %retVal;
2781  }  }
2782    
2783    =head3 SubsystemList
2784    
2785    C<< my @subsystems = $sprout->SubsystemList($featureID); >>
2786    
2787    Return a list containing the names of the subsystems in which the specified
2788    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2789    subsystem names, not the roles.
2790    
2791    =over 4
2792    
2793    =item featureID
2794    
2795    ID of the feature whose subsystem names are desired.
2796    
2797    =item RETURN
2798    
2799    Returns a list of the names of the subsystems in which the feature participates.
2800    
2801    =back
2802    
2803    =cut
2804    #: Return Type @;
2805    sub SubsystemList {
2806        # Get the parameters.
2807        my ($self, $featureID) = @_;
2808        # Get the list of names.
2809        my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?",
2810                                    [$featureID], 'HasRoleInSubsystem(to-link)');
2811        # Return the result, sorted.
2812        return sort @retVal;
2813    }
2814    
2815    =head3 GenomeSubsystemData
2816    
2817    C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>
2818    
2819    Return a hash mapping genome features to their subsystem roles.
2820    
2821    =over 4
2822    
2823    =item genomeID
2824    
2825    ID of the genome whose subsystem feature map is desired.
2826    
2827    =item RETURN
2828    
2829    Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb
2830    2-tuple contains a subsystem name followed by a role ID.
2831    
2832    =back
2833    
2834    =cut
2835    
2836    sub GenomeSubsystemData {
2837        # Get the parameters.
2838        my ($self, $genomeID) = @_;
2839        # Declare the return variable.
2840        my %retVal = ();
2841        # Get a list of the genome features that participate in subsystems. For each
2842        # feature we get its spreadsheet cells and the corresponding roles.
2843        my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],
2844                                 "HasFeature(from-link) = ?", [$genomeID],
2845                                 ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);
2846        # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems
2847        # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the
2848        # list. We use it at the beginning to get all the spreadsheet cells for the genome and
2849        # again at the end to filter out participation in subsystems with a negative variant code.
2850        my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],
2851                                     "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?",
2852                                     [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']);
2853        # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features.
2854        # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We
2855        # link these two lists together to create the result. First, we want a hash mapping
2856        # spreadsheet cells to subsystem names.
2857        my %subHash = map { $_->[0] => $_->[1] } @cellData;
2858        # We loop through @cellData to build the hash.
2859        for my $roleEntry (@roleData) {
2860            # Get the data for this feature and cell.
2861            my ($fid, $cellID, $role) = @{$roleEntry};
2862            # Check for a subsystem name.
2863            my $subsys = $subHash{$cellID};
2864            if ($subsys) {
2865                # Insure this feature has an entry in the return hash.
2866                if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
2867                # Merge in this new data.
2868                push @{$retVal{$fid}}, [$subsys, $role];
2869            }
2870        }
2871        # Return the result.
2872        return %retVal;
2873    }
2874    
2875  =head3 RelatedFeatures  =head3 RelatedFeatures
2876    
2877  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>
# Line 2180  Line 2905 
2905  #: Return Type @;  #: Return Type @;
2906  sub RelatedFeatures {  sub RelatedFeatures {
2907          # Get the parameters.          # Get the parameters.
2908          my $self = shift @_;      my ($self, $featureID, $function, $userID) = @_;
         my ($featureID, $function, $userID) = @_;  
2909          # 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.
2910          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
                                                                          "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],  
                                                                          'IsBidirectionalBestHitOf(to-link)');  
2911          # 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
2912          # functional assignment.          # functional assignment.
2913          my @retVal = ();          my @retVal = ();
# Line 2229  Line 2951 
2951  #: Return Type @;  #: Return Type @;
2952  sub TaxonomySort {  sub TaxonomySort {
2953          # Get the parameters.          # Get the parameters.
2954          my $self = shift @_;      my ($self, $featureIDs) = @_;
         my ($featureIDs) = @_;  
2955          # Create the working hash table.          # Create the working hash table.
2956          my %hashBuffer = ();          my %hashBuffer = ();
2957          # Loop through the features.          # Loop through the features.
# Line 2239  Line 2960 
2960                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
2961                                                                                  [$fid], 'Genome(taxonomy)');                                                                                  [$fid], 'Genome(taxonomy)');
2962                  # Add this feature to the hash buffer.                  # Add this feature to the hash buffer.
2963                  if (exists $hashBuffer{$taxonomy}) {          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);
                         push @{$hashBuffer{$taxonomy}}, $fid;  
                 } else {  
                         $hashBuffer{$taxonomy} = [$fid];  
                 }  
2964          }          }
2965          # Sort the keys and get the elements.          # Sort the keys and get the elements.
2966          my @retVal = ();          my @retVal = ();
# Line 2254  Line 2971 
2971          return @retVal;          return @retVal;
2972  }  }
2973    
 =head3 GetAll  
   
 C<< my @list = $sprout->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>  
   
 Return a list of values taken from the objects returned by a query. The first three  
 parameters correspond to the parameters of the L</Get> method. The final parameter is  
 a list of the fields desired from each record found by the query. The field name  
 syntax is the standard syntax used for fields in the B<ERDB> system--  
 B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity  
 or relationship and I<fieldName> is the name of the field.  
   
 The list returned will be a list of lists. Each element of the list will contain  
 the values returned for the fields specified in the fourth parameter. If one of the  
 fields specified returns multiple values, they are flattened in with the rest. For  
 example, the following call will return a list of the features in a particular  
 spreadsheet cell, and each feature will be represented by a list containing the  
 feature ID followed by all of its aliases.  
   
 C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item fields  
   
 List of the fields to be returned in each element of the list returned.  
   
 =item count  
   
 Maximum number of records to return. If omitted or 0, all available records will be returned.  
   
 =item RETURN  
   
 Returns a list of list references. Each element of the return list contains the values for the  
 fields specified in the B<fields> parameter.  
   
 =back  
   
 =cut  
 #: Return Type @@;  
 sub GetAll {  
         # Get the parameters.  
         my $self = shift @_;  
         my ($objectNames, $filterClause, $parameterList, $fields, $count) = @_;  
         # Create the query.  
         my $query = $self->Get($objectNames, $filterClause, $parameterList);  
         # Set up a counter of the number of records read.  
         my $fetched = 0;  
         # Insure the counter has a value.  
         if (!defined $count) {  
                 $count = 0;  
         }  
         # Loop through the records returned, extracting the fields. Note that if the  
         # counter is non-zero, we stop when the number of records read hits the count.  
         my @retVal = ();  
         while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {  
                 my @rowData = $row->Values($fields);  
                 push @retVal, \@rowData;  
                 $fetched++;  
         }  
         # Return the resulting list.  
         return @retVal;  
 }  
   
 =head3 GetFlat  
   
 C<< my @list = $sprout->GetFlat(\@objectNames, $filterClause, $parameterList, $field); >>  
   
 This is a variation of L</GetAll> that asks for only a single field per record and  
 returns a single flattened list.  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item field  
   
 Name of the field to be used to get the elements of the list returned.  
   
 =item RETURN  
   
 Returns a list of values.  
   
 =back  
   
 =cut  
 #: Return Type @;  
 sub GetFlat {  
         # Get the parameters.  
         my $self = shift @_;  
         my ($objectNames, $filterClause, $parameterList, $field) = @_;  
         # Construct the query.  
         my $query = $self->Get($objectNames, $filterClause, $parameterList);  
         # Create the result list.  
         my @retVal = ();  
         # Loop through the records, adding the field values found to the result list.  
         while (my $row = $query->Fetch()) {  
                 push @retVal, $row->Value($field);  
         }  
         # Return the list created.  
         return @retVal;  
 }  
   
2974  =head3 Protein  =head3 Protein
2975    
2976  C<< my $protein = Sprout::Protein($sequence, $table); >>  C<< my $protein = Sprout::Protein($sequence, $table); >>
# Line 2460  Line 3043 
3043          # Loop through the input triples.          # Loop through the input triples.
3044          my $n = length $sequence;          my $n = length $sequence;
3045          for (my $i = 0; $i < $n; $i += 3) {          for (my $i = 0; $i < $n; $i += 3) {
3046                  # Get the current triple from the sequence.          # Get the current triple from the sequence. Note we convert to
3047                  my $triple = substr($sequence, $i, 3);          # upper case to insure a match.
3048            my $triple = uc substr($sequence, $i, 3);
3049                  # Translate it using the table.                  # Translate it using the table.
3050                  my $protein = "X";                  my $protein = "X";
3051                  if (exists $table->{$triple}) { $protein = $table->{$triple}; }                  if (exists $table->{$triple}) { $protein = $table->{$triple}; }
# Line 2485  Line 3069 
3069  #: Return Type @;  #: Return Type @;
3070  sub LoadInfo {  sub LoadInfo {
3071          # Get the parameters.          # Get the parameters.
3072          my $self = shift @_;      my ($self) = @_;
3073          # 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.
3074          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
3075          # Concatenate the table names.          # Concatenate the table names.
3076          push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
3077          # Return the result.          # Return the result.
3078          return @retVal;          return @retVal;
3079  }  }
3080    
3081    =head3 BBHMatrix
3082    
3083    C<< my %bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets); >>
3084    
3085    Find all the bidirectional best hits for the features of a genome in a
3086    specified list of target genomes. The return value will be a hash mapping
3087    features in the original genome to their bidirectional best hits in the
3088    target genomes.
3089    
3090    =over 4
3091    
3092    =item genomeID
3093    
3094    ID of the genome whose features are to be examined for bidirectional best hits.
3095    
3096    =item cutoff
3097    
3098    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3099    
3100    =item targets
3101    
3102    List of target genomes. Only pairs originating in the original
3103    genome and landing in one of the target genomes will be returned.
3104    
3105    =item RETURN
3106    
3107    Returns a hash mapping each feature in the original genome to a hash mapping its
3108    BBH pegs in the target genomes to their scores.
3109    
3110    =back
3111    
3112    =cut
3113    
3114    sub BBHMatrix {
3115        # Get the parameters.
3116        my ($self, $genomeID, $cutoff, @targets) = @_;
3117        # Declare the return variable.
3118        my %retVal = ();
3119        # Ask for the BBHs.
3120        my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets);
3121        # We now have a set of 4-tuples that we need to convert into a hash of hashes.
3122        for my $bbhData (@bbhList) {
3123            my ($peg1, $peg2, $score) = @{$bbhData};
3124            if (! exists $retVal{$peg1}) {
3125                $retVal{$peg1} = { $peg2 => $score };
3126            } else {
3127                $retVal{$peg1}->{$peg2} = $score;
3128            }
3129        }
3130        # Return the result.
3131        return %retVal;
3132    }
3133    
3134    
3135    =head3 SimMatrix
3136    
3137    C<< my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets); >>
3138    
3139    Find all the similarities for the features of a genome in a
3140    specified list of target genomes. The return value will be a hash mapping
3141    features in the original genome to their similarites in the
3142    target genomes.
3143    
3144    =over 4
3145    
3146    =item genomeID
3147    
3148    ID of the genome whose features are to be examined for similarities.
3149    
3150    =item cutoff
3151    
3152    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3153    
3154    =item targets
3155    
3156    List of target genomes. Only pairs originating in the original
3157    genome and landing in one of the target genomes will be returned.
3158    
3159    =item RETURN
3160    
3161    Returns a hash mapping each feature in the original genome to a hash mapping its
3162    similar pegs in the target genomes to their scores.
3163    
3164    =back
3165    
3166    =cut
3167    
3168    sub SimMatrix {
3169        # Get the parameters.
3170        my ($self, $genomeID, $cutoff, @targets) = @_;
3171        # Declare the return variable.
3172        my %retVal = ();
3173        # Get the list of features in the source organism.
3174        my @fids = $self->FeaturesOf($genomeID);
3175        # Ask for the sims. We only want similarities to fig features.
3176        my $simList = FIGRules::GetNetworkSims($self, \@fids, {}, 1000, $cutoff, "fig");
3177        if (! defined $simList) {
3178            Confess("Unable to retrieve similarities from server.");
3179        } else {
3180            Trace("Processing sims.") if T(3);
3181            # We now have a set of sims that we need to convert into a hash of hashes. First, we
3182            # Create a hash for the target genomes.
3183            my %targetHash = map { $_ => 1 } @targets;
3184            for my $simData (@{$simList}) {
3185                # Get the PEGs and the score.
3186                my ($peg1, $peg2, $score) = ($simData->id1, $simData->id2, $simData->psc);
3187                # Insure the second ID is in the target list.
3188                my ($genome2) = FIGRules::ParseFeatureID($peg2);
3189                if (exists $targetHash{$genome2}) {
3190                    # Here it is. Now we need to add it to the return hash. How we do that depends
3191                    # on whether or not $peg1 is new to us.
3192                    if (! exists $retVal{$peg1}) {
3193                        $retVal{$peg1} = { $peg2 => $score };
3194                    } else {
3195                        $retVal{$peg1}->{$peg2} = $score;
3196                    }
3197                }
3198            }
3199        }
3200        # Return the result.
3201        return %retVal;
3202    }
3203    
3204    
3205  =head3 LowBBHs  =head3 LowBBHs
3206    
3207  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
3208    
3209  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
3210  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 2522  Line 3230 
3230  #: Return Type %;  #: Return Type %;
3231  sub LowBBHs {  sub LowBBHs {
3232          # Get the parsameters.          # Get the parsameters.
3233          my $self = shift @_;      my ($self, $featureID, $cutoff) = @_;
         my ($featureID, $cutoff) = @_;  
3234          # Create the return hash.          # Create the return hash.
3235          my %retVal = ();          my %retVal = ();
3236          # Create a query to get the desired BBHs.      # Query for the desired BBHs.
3237          my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BBHData($featureID, $cutoff);
                                                                 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',  
                                                                 [$cutoff, $featureID],  
                                                                 ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);  
3238          # Form the results into the return hash.          # Form the results into the return hash.
3239          for my $pair (@bbhList) {          for my $pair (@bbhList) {
3240                  $retVal{$pair->[0]} = $pair->[1];          my $fid = $pair->[0];
3241            if ($self->Exists('Feature', $fid)) {
3242                $retVal{$fid} = $pair->[1];
3243            }
3244        }
3245        # Return the result.
3246        return %retVal;
3247    }
3248    
3249    =head3 Sims
3250    
3251    C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>
3252    
3253    Get a list of similarities for a specified feature. Similarity information is not kept in the
3254    Sprout database; rather, they are retrieved from a network server. The similarities are
3255    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3256    so that its elements can be accessed by name.
3257    
3258    Similarities can be either raw or expanded. The raw similarities are basic
3259    hits between features with similar DNA. Expanding a raw similarity drags in any
3260    features considered substantially identical. So, for example, if features B<A1>,
3261    B<A2>, and B<A3> are all substantially identical to B<A>, then a raw similarity
3262    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3263    
3264    =over 4
3265    
3266    =item fid
3267    
3268    ID of the feature whose similarities are desired, or reference to a list of IDs
3269    of features whose similarities are desired.
3270    
3271    =item maxN
3272    
3273    Maximum number of similarities to return.
3274    
3275    =item maxP
3276    
3277    Minumum allowable similarity score.
3278    
3279    =item select
3280    
3281    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3282    means only similarities to FIG features are returned; C<all> means all expanded
3283    similarities are returned; and C<figx> means similarities are expanded until the
3284    number of FIG features equals the maximum.
3285    
3286    =item max_expand
3287    
3288    The maximum number of features to expand.
3289    
3290    =item filters
3291    
3292    Reference to a hash containing filter information, or a subroutine that can be
3293    used to filter the sims.
3294    
3295    =item RETURN
3296    
3297    Returns a reference to a list of similarity objects, or C<undef> if an error
3298    occurred.
3299    
3300    =back
3301    
3302    =cut
3303    
3304    sub Sims {
3305        # Get the parameters.
3306        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3307        # Create the shim object to test for deleted FIDs.
3308        my $shim = FidCheck->new($self);
3309        # Ask the network for sims.
3310        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3311        # Return the result.
3312        return $retVal;
3313    }
3314    
3315    =head3 IsAllGenomes
3316    
3317    C<< my $flag = $sprout->IsAllGenomes(\@list, \@checkList); >>
3318    
3319    Return TRUE if all genomes in the second list are represented in the first list at
3320    least one. Otherwise, return FALSE. If the second list is omitted, the first list is
3321    compared to a list of all the genomes.
3322    
3323    =over 4
3324    
3325    =item list
3326    
3327    Reference to the list to be compared to the second list.
3328    
3329    =item checkList (optional)
3330    
3331    Reference to the comparison target list. Every genome ID in this list must occur at
3332    least once in the first list. If this parameter is omitted, a list of all the genomes
3333    is used.
3334    
3335    =item RETURN
3336    
3337    Returns TRUE if every item in the second list appears at least once in the
3338    first list, else FALSE.
3339    
3340    =back
3341    
3342    =cut
3343    
3344    sub IsAllGenomes {
3345        # Get the parameters.
3346        my ($self, $list, $checkList) = @_;
3347        # Supply the checklist if it was omitted.
3348        $checkList = [$self->Genomes()] if ! defined($checkList);
3349        # Create a hash of the original list.
3350        my %testList = map { $_ => 1 } @{$list};
3351        # Declare the return variable. We assume that the representation
3352        # is complete and stop at the first failure.
3353        my $retVal = 1;
3354        my $n = scalar @{$checkList};
3355        for (my $i = 0; $retVal && $i < $n; $i++) {
3356            if (! $testList{$checkList->[$i]}) {
3357                $retVal = 0;
3358            }
3359        }
3360        # Return the result.
3361        return $retVal;
3362    }
3363    
3364    =head3 GetGroups
3365    
3366    C<< my %groups = $sprout->GetGroups(\@groupList); >>
3367    
3368    Return a hash mapping each group to the IDs of the genomes in the group.
3369    A list of groups may be specified, in which case only those groups will be
3370    shown. Alternatively, if no parameter is supplied, all groups will be
3371    included. Genomes that are not in any group are omitted.
3372    
3373    =cut
3374    #: Return Type %@;
3375    sub GetGroups {
3376        # Get the parameters.
3377        my ($self, $groupList) = @_;
3378        # Declare the return value.
3379        my %retVal = ();
3380        # Determine whether we are getting all the groups or just some.
3381        if (defined $groupList) {
3382            # Here we have a group list. Loop through them individually,
3383            # getting a list of the relevant genomes.
3384            for my $group (@{$groupList}) {
3385                my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3386                    [$group], "Genome(id)");
3387                $retVal{$group} = \@genomeIDs;
3388            }
3389        } else {
3390            # Here we need all of the groups. In this case, we run through all
3391            # of the genome records, putting each one found into the appropriate
3392            # group. Note that we use a filter clause to insure that only genomes
3393            # in real NMPDR groups are included in the return set.
3394            my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3395                                        [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3396            # Loop through the genomes found.
3397            for my $genome (@genomes) {
3398                # Pop this genome's ID off the current list.
3399                my @groups = @{$genome};
3400                my $genomeID = shift @groups;
3401                # Loop through the groups, adding the genome ID to each group's
3402                # list.
3403                for my $group (@groups) {
3404                    Tracer::AddToListMap(\%retVal, $group, $genomeID);
3405                }
3406            }
3407        }
3408        # Return the hash we just built.
3409        return %retVal;
3410    }
3411    
3412    =head3 MyGenomes
3413    
3414    C<< my @genomes = Sprout::MyGenomes($dataDir); >>
3415    
3416    Return a list of the genomes to be included in the Sprout.
3417    
3418    This method is provided for use during the Sprout load. It presumes the Genome load file has
3419    already been created. (It will be in the Sprout data directory and called either C<Genome>
3420    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3421    IDs.
3422    
3423    =over 4
3424    
3425    =item dataDir
3426    
3427    Directory containing the Sprout load files.
3428    
3429    =back
3430    
3431    =cut
3432    #: Return Type @;
3433    sub MyGenomes {
3434        # Get the parameters.
3435        my ($dataDir) = @_;
3436        # Compute the genome file name.
3437        my $genomeFileName = LoadFileName($dataDir, "Genome");
3438        # Extract the genome IDs from the files.
3439        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3440        # Return the result.
3441        return @retVal;
3442    }
3443    
3444    =head3 LoadFileName
3445    
3446    C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>
3447    
3448    Return the name of the load file for the specified table in the specified data
3449    directory.
3450    
3451    =over 4
3452    
3453    =item dataDir
3454    
3455    Directory containing the Sprout load files.
3456    
3457    =item tableName
3458    
3459    Name of the table whose load file is desired.
3460    
3461    =item RETURN
3462    
3463    Returns the name of the file containing the load data for the specified table, or
3464    C<undef> if no load file is present.
3465    
3466    =back
3467    
3468    =cut
3469    #: Return Type $;
3470    sub LoadFileName {
3471        # Get the parameters.
3472        my ($dataDir, $tableName) = @_;
3473        # Declare the return variable.
3474        my $retVal;
3475        # Check for the various file names.
3476        if (-e "$dataDir/$tableName") {
3477            $retVal = "$dataDir/$tableName";
3478        } elsif (-e "$dataDir/$tableName.dtx") {
3479            $retVal = "$dataDir/$tableName.dtx";
3480          }          }
3481          # Return the result.          # Return the result.
3482        return $retVal;
3483    }
3484    
3485    =head3 DeleteGenome
3486    
3487    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3488    
3489    Delete a genome from the database.
3490    
3491    =over 4
3492    
3493    =item genomeID
3494    
3495    ID of the genome to delete
3496    
3497    =item testFlag
3498    
3499    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3500    
3501    =item RETURN
3502    
3503    Returns a statistics object describing the rows deleted.
3504    
3505    =back
3506    
3507    =cut
3508    #: Return Type $%;
3509    sub DeleteGenome {
3510        # Get the parameters.
3511        my ($self, $genomeID, $testFlag) = @_;
3512        # Perform the delete for the genome's features.
3513        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", testMode => $testFlag);
3514        # Perform the delete for the primary genome data.
3515        my $stats = $self->Delete('Genome', $genomeID, testMode => $testFlag);
3516        $retVal->Accumulate($stats);
3517        # Return the result.
3518        return $retVal;
3519    }
3520    
3521    =head3 Fix
3522    
3523    C<< my %fixedHash = Sprout::Fix(%groupHash); >>
3524    
3525    Prepare a genome group hash (like that returned by L</GetGroups>) for processing.
3526    Groups with the same primary name will be combined. The primary name is the
3527    first capitalized word in the group name.
3528    
3529    =over 4
3530    
3531    =item groupHash
3532    
3533    Hash to be fixed up.
3534    
3535    =item RETURN
3536    
3537    Returns a fixed-up version of the hash.
3538    
3539    =back
3540    
3541    =cut
3542    
3543    sub Fix {
3544        # Get the parameters.
3545        my (%groupHash) = @_;
3546        # Create the result hash.
3547        my %retVal = ();
3548        # Copy over the genomes.
3549        for my $groupID (keys %groupHash) {
3550            # Make a safety copy of the group ID.
3551            my $realGroupID = $groupID;
3552            # Yank the primary name.
3553            if ($groupID =~ /([A-Z]\w+)/) {
3554                $realGroupID = $1;
3555            }
3556            # Append this group's genomes into the result hash.
3557            Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}});
3558        }
3559        # Return the result hash.
3560          return %retVal;          return %retVal;
3561  }  }
3562    
3563    =head3 GroupPageName
3564    
3565    C<< my $name = $sprout->GroupPageName($group); >>
3566    
3567    Return the name of the page for the specified NMPDR group.
3568    
3569    =over 4
3570    
3571    =item group
3572    
3573    Name of the relevant group.
3574    
3575    =item RETURN
3576    
3577    Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3578    memory it will be read in.
3579    
3580    =back
3581    
3582    =cut
3583    
3584    sub GroupPageName {
3585        # Get the parameters.
3586        my ($self, $group) = @_;
3587        # Declare the return variable.
3588        my $retVal;
3589        # Check for the group file data.
3590        if (! defined $self->{groupHash}) {
3591            # Read the group file.
3592            my %groupData = Sprout::ReadGroupFile($self->{_options}->{dataDir} . "/groups.tbl");
3593            # Store it in our object.
3594            $self->{groupHash} = \%groupData;
3595        }
3596        # Compute the real group name.
3597        my $realGroup = $group;
3598        if ($group =~ /([A-Z]\w+)/) {
3599            $realGroup = $1;
3600        }
3601        # Return the page name.
3602        $retVal = "../content/" . $self->{groupHash}->{$realGroup}->[1];
3603        # Return the result.
3604        return $retVal;
3605    }
3606    
3607    =head3 ReadGroupFile
3608    
3609    C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >>
3610    
3611    Read in the data from the specified group file. The group file contains information
3612    about each of the NMPDR groups.
3613    
3614    =over 4
3615    
3616    =item name
3617    
3618    Name of the group.
3619    
3620    =item page
3621    
3622    Name of the group's page on the web site (e.g. C<campy.php> for
3623    Campylobacter)
3624    
3625    =item genus
3626    
3627    Genus of the group
3628    
3629    =item species
3630    
3631    Species of the group, or an empty string if the group is for an entire
3632    genus. If the group contains more than one species, the species names
3633    should be separated by commas.
3634    
3635    =back
3636    
3637    The parameters to this method are as follows
3638    
3639    =over 4
3640    
3641    =item groupFile
3642    
3643    Name of the file containing the group data.
3644    
3645    =item RETURN
3646    
3647    Returns a hash keyed on group name. The value of each hash
3648    
3649    =back
3650    
3651    =cut
3652    
3653    sub ReadGroupFile {
3654        # Get the parameters.
3655        my ($groupFileName) = @_;
3656        # Declare the return variable.
3657        my %retVal;
3658        # Read the group file.
3659        my @groupLines = Tracer::GetFile($groupFileName);
3660        for my $groupLine (@groupLines) {
3661            my ($name, $page, $genus, $species) = split(/\t/, $groupLine);
3662            $retVal{$name} = [$page, $genus, $species];
3663        }
3664        # Return the result.
3665        return %retVal;
3666    }
3667    
3668    =head3 AddProperty
3669    
3670    C<< my  = $sprout->AddProperty($featureID, $key, @values); >>
3671    
3672    Add a new attribute value (Property) to a feature.
3673    
3674    =over 4
3675    
3676    =item peg
3677    
3678    ID of the feature to which the attribute is to be added.
3679    
3680    =item key
3681    
3682    Name of the attribute (key).
3683    
3684    =item values
3685    
3686    Values of the attribute.
3687    
3688    =back
3689    
3690    =cut
3691    #: Return Type ;
3692    sub AddProperty {
3693        # Get the parameters.
3694        my ($self, $featureID, $key, @values) = @_;
3695        # Add the property using the attached attributes object.
3696        $self->{_ca}->AddAttribute($featureID, $key, @values);
3697    }
3698    
3699    =head2 Virtual Methods
3700    
3701    =head3 CleanKeywords
3702    
3703    C<< my $cleanedString = $sprout->CleanKeywords($searchExpression); >>
3704    
3705    Clean up a search expression or keyword list. This involves converting the periods
3706    in EC numbers to underscores, converting non-leading minus signs to underscores,
3707    a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
3708    characters. In addition, any extra spaces are removed.
3709    
3710    =over 4
3711    
3712    =item searchExpression
3713    
3714    Search expression or keyword list to clean. Note that a search expression may
3715    contain boolean operators which need to be preserved. This includes leading
3716    minus signs.
3717    
3718    =item RETURN
3719    
3720    Cleaned expression or keyword list.
3721    
3722    =back
3723    
3724    =cut
3725    
3726    sub CleanKeywords {
3727        # Get the parameters.
3728        my ($self, $searchExpression) = @_;
3729        # Perform the standard cleanup.
3730        my $retVal = $self->ERDB::CleanKeywords($searchExpression);
3731        # Fix the periods in EC and TC numbers.
3732        $retVal =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g;
3733        # Fix non-trailing periods.
3734        $retVal =~ s/\.(\w)/_$1/g;
3735        # Fix non-leading minus signs.
3736        $retVal =~ s/(\w)[\-]/$1_/g;
3737        # Fix the vertical bars and colons
3738        $retVal =~ s/(\w)[|:](\w)/$1'$2/g;
3739        # Return the result.
3740        return $retVal;
3741    }
3742    
3743  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3744    
3745  =head3 ParseAssignment  =head3 ParseAssignment
3746    
3747  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,
3748  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
3749  will be returned.  isn't, an empty list will be returned.
3750    
3751    A functional assignment is always of the form
3752    
3753        C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3754    
3755    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3756    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3757    not always the case.
3758    
3759    In addition, the functional role may contain extra data that is stripped, such as
3760    terminating spaces or a comment separated from the rest of the text by a tab.
3761    
3762  This is a static method.  This is a static method.
3763    
3764  =over 4  =over 4
3765    
3766    =item user
3767    
3768    Name of the assigning user.
3769    
3770  =item text  =item text
3771    
3772  Text of the annotation.  Text of the annotation.
# Line 2564  Line 3780 
3780    
3781  =cut  =cut
3782    
3783  sub ParseAssignment {  sub _ParseAssignment {
3784          # Get the parameters.          # Get the parameters.
3785          my ($text) = @_;      my ($user, $text) = @_;
3786          # Declare the return value.          # Declare the return value.
3787          my @retVal = ();          my @retVal = ();
3788          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3789          my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3790          if ($type =~ m/^set $user function to$/i) {      if ($type =~ m/^set function to$/i) {
3791                  # 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.
3792                  @retVal = ($user, $function);                  @retVal = ($user, $function);
3793        } elsif ($type =~ m/^set (\S+) function to$/i) {
3794            # Here we have an assignment with a user that is passed back to the caller.
3795            @retVal = ($1, $function);
3796        }
3797        # If we have an assignment, we need to clean the function text. There may be
3798        # extra junk at the end added as a note from the user.
3799        if (defined( $retVal[1] )) {
3800            $retVal[1] =~ s/(\t\S)?\s*$//;
3801          }          }
3802          # Return the result list.          # Return the result list.
3803          return @retVal;          return @retVal;
3804  }  }
3805    
3806    =head3 _CheckFeature
3807    
3808    C<< my $flag = $sprout->_CheckFeature($fid); >>
3809    
3810    Return TRUE if the specified FID is probably an NMPDR feature ID, else FALSE.
3811    
3812    =over 4
3813    
3814    =item fid
3815    
3816    Feature ID to check.
3817    
3818    =item RETURN
3819    
3820    Returns TRUE if the FID is for one of the NMPDR genomes, else FALSE.
3821    
3822    =back
3823    
3824    =cut
3825    
3826    sub _CheckFeature {
3827        # Get the parameters.
3828        my ($self, $fid) = @_;
3829        # Insure we have a genome hash.
3830        if (! defined $self->{genomeHash}) {
3831            my %genomeHash = map { $_ => 1 } $self->GetFlat(['Genome'], "", [], 'Genome(id)');
3832            $self->{genomeHash} = \%genomeHash;
3833        }
3834        # Get the feature's genome ID.
3835        my ($genomeID) = FIGRules::ParseFeatureID($fid);
3836        # Return an indicator of whether or not the genome ID is in the hash.
3837        return ($self->{genomeHash}->{$genomeID} ? 1 : 0);
3838    }
3839    
3840  =head3 FriendlyTimestamp  =head3 FriendlyTimestamp
3841    
3842  Convert a time number to a user-friendly time stamp for display.  Convert a time number to a user-friendly time stamp for display.
# Line 2601  Line 3859 
3859    
3860  sub FriendlyTimestamp {  sub FriendlyTimestamp {
3861      my ($timeValue) = @_;      my ($timeValue) = @_;
3862      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
3863      return $retVal;      return $retVal;
3864  }  }
3865    
3866    
3867  1;  1;

Legend:
Removed from v.1.3  
changed lines
  Added in v.1.101

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3