[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.11, Tue Mar 8 09:17:40 2005 UTC revision 1.104, Wed Jan 23 00:56:31 2008 UTC
# Line 2  Line 2 
2    
3          use Data::Dumper;          use Data::Dumper;
4          use strict;          use strict;
         use Carp;  
5          use DBKernel;          use DBKernel;
6          use XML::Simple;          use XML::Simple;
7          use DBQuery;          use DBQuery;
8          use DBObject;      use ERDBObject;
         use ERDB;  
9          use Tracer;          use Tracer;
10          use FIGRules;          use FIGRules;
11        use FidCheck;
12          use Stats;          use Stats;
13      use POSIX qw(strftime);      use POSIX qw(strftime);
14        use BasicLocation;
15        use CustomAttributes;
16        use RemoteCustomAttributes;
17        use base qw(ERDB);
18    
19  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
20    
# Line 25  Line 27 
27  on the constructor. For example, the following invocation specifies a PostgreSQL database named I<GenDB>  on the constructor. For example, the following invocation specifies a PostgreSQL database named I<GenDB>
28  whose definition and data files are in a co-directory named F<Data>.  whose definition and data files are in a co-directory named F<Data>.
29    
30  C<< my $sprout = Sprout->new('GenDB', { dbType => 'pg', dataDir => '../Data', xmlFileName => '../Data/SproutDBD.xml' }); >>      my $sprout = Sprout->new('GenDB', { dbType => 'pg', dataDir => '../Data', xmlFileName => '../Data/SproutDBD.xml' });
31    
32  Once you have a sprout object, you may use it to re-create the database, load the tables from  Once you have a sprout object, you may use it to re-create the database, load the tables from
33  tab-delimited flat files and perform queries. Several special methods are provided for common  tab-delimited flat files and perform queries. Several special methods are provided for common
34  query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and  query tasks. For example, L</Genomes> lists the IDs of all the genomes in the database and
35  L</dna_seq> returns the DNA sequence for a specified genome location.  L</DNASeq> returns the DNA sequence for a specified genome location.
36    
37    The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.
38    
39  =cut  =cut
40    
# Line 40  Line 44 
44    
45  =head3 new  =head3 new
46    
47  C<< my $sprout = Sprout->new($dbName, \%options); >>      my $sprout = Sprout->new($dbName, \%options);
48    
49  This is the constructor for a sprout object. It connects to the database and loads the  This is the constructor for a sprout object. It connects to the database and loads the
50  database definition into memory. The positional first parameter specifies the name of the  database definition into memory. The positional first parameter specifies the name of the
# Line 62  Line 66 
66    
67  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)
68    
69  * B<userData> user name and password, delimited by a slash (default C<root/>)  * B<userData> user name and password, delimited by a slash (default same as SEED)
70    
71  * B<port> connection port (default C<0>)  * B<port> connection port (default C<0>)
72    
73    * B<sock> connection socket (default same as SEED)
74    
75  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
76    
77  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
78    
79    * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
80    
81  =back  =back
82    
83  For example, the following constructor call specifies a database named I<Sprout> and a user name of  For example, the following constructor call specifies a database named I<Sprout> and a user name of
84  I<fig> with a password of I<admin>. The database load files are in the directory  I<fig> with a password of I<admin>. The database load files are in the directory
85  F</usr/fig/SproutData>.  F</usr/fig/SproutData>.
86    
87  C<< my $sprout = Sprout->new('Sprout', { userData =>; 'fig/admin', dataDir => '/usr/fig/SproutData' }); >>      my $sprout = Sprout->new('Sprout', { userData => 'fig/admin', dataDir => '/usr/fig/SproutData' });
88    
89  =cut  =cut
90    
91  sub new {  sub new {
92          # Get the parameters.          # Get the parameters.
93          my ($class, $dbName, $options) = @_;          my ($class, $dbName, $options) = @_;
94        # Compute the DBD directory.
95        my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
96                                                      $FIG_Config::fig );
97          # 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
98          # the incoming data.          # the incoming data.
99          my $optionTable = Tracer::GetOptions({          my $optionTable = Tracer::GetOptions({
100                                             dbType               => 'mysql',                     # database type                         dbType       => $FIG_Config::dbms,
101                                             dataDir              => 'Data',                      # data file directory                                                          # database type
102                                             xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
103                                             userData             => 'root/',                     # user name and password                                                          # data file directory
104                                             port                 => 0,                           # database connection port                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
105                                                            # database definition file name
106                           userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
107                                                            # user name and password
108                           port         => $FIG_Config::dbport,
109                                                            # database connection port
110                           sock         => $FIG_Config::dbsock,
111                           host         => $FIG_Config::dbhost,
112                                             maxSegmentLength => 4500,            # maximum feature segment length                                             maxSegmentLength => 4500,            # maximum feature segment length
113                                             maxSequenceLength => 8000,           # maximum contig sequence length                                             maxSequenceLength => 8000,           # maximum contig sequence length
114                           noDBOpen     => 0,               # 1 to suppress the database open
115                                            }, $options);                                            }, $options);
116          # Get the data directory.          # Get the data directory.
117          my $dataDir = $optionTable->{dataDir};          my $dataDir = $optionTable->{dataDir};
# Line 100  Line 119 
119          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
120          my ($userName, $password) = ($1, $2);          my ($userName, $password) = ($1, $2);
121          # Connect to the database.          # Connect to the database.
122          my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
123        if (! $optionTable->{noDBOpen}) {
124            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
125                                    $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
126        }
127          # Create the ERDB object.          # Create the ERDB object.
128          my $xmlFileName = "$optionTable->{xmlFileName}";          my $xmlFileName = "$optionTable->{xmlFileName}";
129          my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
130          # Create this object.      # Add the option table and XML file name.
131          my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
132          # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
133          bless $self;      # Set up space for the group file data.
134          return $self;      $retVal->{groupHash} = undef;
135        # Set up space for the genome hash. We use this to identify NMPDR genomes.
136        $retVal->{genomeHash} = undef;
137        # Connect to the attributes.
138        if ($FIG_Config::attrURL) {
139            Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);
140            $retVal->{_ca} = RemoteCustomAttributes->new($FIG_Config::attrURL);
141        } elsif ($FIG_Config::attrDbName) {
142            Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);
143            my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));
144            $retVal->{_ca} = CustomAttributes->new(user => $user);
145        }
146        # Return it.
147        return $retVal;
148  }  }
149    
150  =head3 MaxSegment  =head3 MaxSegment
151    
152  C<< my $length = $sprout->MaxSegment(); >>      my $length = $sprout->MaxSegment();
153    
154  This method returns the maximum permissible length of a feature segment. The length is important  This method returns the maximum permissible length of a feature segment. The length is important
155  because it enables us to make reasonable guesses at how to find features inside a particular  because it enables us to make reasonable guesses at how to find features inside a particular
# Line 130  Line 166 
166    
167  =head3 MaxSequence  =head3 MaxSequence
168    
169  C<< my $length = $sprout->MaxSequence(); >>      my $length = $sprout->MaxSequence();
170    
171  This method returns the maximum permissible length of a contig sequence. A contig is broken  This method returns the maximum permissible length of a contig sequence. A contig is broken
172  into sequences in order to save memory resources. In particular, when manipulating features,  into sequences in order to save memory resources. In particular, when manipulating features,
# Line 143  Line 179 
179          return $self->{_options}->{maxSequenceLength};          return $self->{_options}->{maxSequenceLength};
180  }  }
181    
182  =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]); >>  
183    
184  It is also permissible to specify I<only> an ORDER BY clause. For example, the following invocation gets      $sprout->Load($rebuild);;
 all genomes ordered by genus and species.  
185    
186  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.
187    
188  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
189  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
190  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
191    extension are used in preference to the files with an extension.
192    
193  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
194  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
195  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
196  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.  
197    
198  =over 4  =over 4
199    
200  =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  
201    
202  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
203    
204  =item RETURN  =item RETURN
205    
206  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,
207    the number of errors, and a list of the error messages.
208    
209  =back  =back
210    
211  =cut  =cut
212    #: Return Type %;
213  sub Get {  sub Load {
214          # Get the parameters.          # Get the parameters.
215          my ($self, $objectNames, $filterClause, $parameterList) = @_;      my ($self, $rebuild) = @_;
216          # We differ from the ERDB Get method in that the parameter list is passed in as a list reference      # Load the tables from the data directory.
217          # rather than a list of parameters. The next step is to convert the parameters from a reference      my $retVal = $self->LoadTables($self->{_options}->{dataDir}, $rebuild);
218          # to a real list. We can only do this if the parameters have been specified.      # Return the statistics.
219          my @parameters;      return $retVal;
         if ($parameterList) { @parameters = @{$parameterList}; }  
         return $self->{_erdb}->Get($objectNames, $filterClause, @parameters);  
220  }  }
221    
222  =head3 GetEntity  =head3 LoadUpdate
223    
224  C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>      my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList);
225    
226  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
227    or two tables without reloading the whole database. For each table, there must be a corresponding
228    file in the data directory, either with the same name as the table, or with a C<.dtx> suffix. So,
229    for example, to make updates to the B<FeatureTranslation> relation, there must be a
230    C<FeatureTranslation.dtx> file in the data directory. Unlike a full load, files without an extension
231    are not examined. This allows update files to co-exist with files from an original load.
232    
233  =over 4  =over 4
234    
235  =item entityType  =item truncateFlag
236    
237  Entity type name.  TRUE if the tables should be rebuilt before loading, else FALSE. A value of TRUE therefore causes
238    current data and schema of the tables to be replaced, while a value of FALSE means the new data
239    is added to the existing data in the various relations.
240    
241  =item ID  =item tableList
242    
243  ID of the desired entity.  List of the tables to be updated.
244    
245  =item RETURN  =item RETURN
246    
247  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,
248  instance is found with the specified key.  the number of errors encountered, and a list of error messages.
249    
250  =back  =back
251    
252  =cut  =cut
253    #: Return Type $%;
254  sub GetEntity {  sub LoadUpdate {
255          # Get the parameters.          # Get the parameters.
256          my ($self, $entityType, $ID) = @_;      my ($self, $truncateFlag, $tableList) = @_;
257          # Create a query.      # Declare the return value.
258          my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);      my $retVal = Stats->new();
259          # Get the first (and only) object.      # Get the data directory.
260          my $retVal = $query->Fetch();      my $optionTable = $self->{_options};
261          # Return the result.      my $dataDir = $optionTable->{dataDir};
262        # Loop through the incoming table names.
263        for my $tableName (@{$tableList}) {
264            # Find the table's file.
265            my $fileName = LoadFileName($dataDir, $tableName);
266            if (! $fileName) {
267                Trace("No load file found for $tableName in $dataDir.") if T(0);
268            } else {
269                # Attempt to load this table.
270                my $result = $self->LoadTable($fileName, $tableName, truncate => $truncateFlag);
271                # Accumulate the resulting statistics.
272                $retVal->Accumulate($result);
273            }
274        }
275        # Return the statistics.
276          return $retVal;          return $retVal;
277  }  }
278    
279  =head3 GetEntityValues  =head3 GenomeCounts
280    
281  C<< my @values = GetEntityValues($entityType, $ID, \@fields); >>      my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete);
282    
283  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
284    genomes will be included in the counts.
285    
286  =over 4  =over 4
287    
288  =item entityType  =item complete
289    
290  Entity type name.  TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
291    counted
 =item ID  
   
 ID of the desired entity.  
   
 =item fields  
   
 List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.  
292    
293  =item RETURN  =item RETURN
294    
295  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--
296    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
297    
298  =back  =back
299    
300  =cut  =cut
301  #: Return Type @;  
302  sub GetEntityValues {  sub GenomeCounts {
303          # Get the parameters.          # Get the parameters.
304          my ($self, $entityType, $ID, $fields) = @_;      my ($self, $complete) = @_;
305          # Get the specified entity.      # Set the filter based on the completeness flag.
306          my $entity = $self->GetEntity($entityType, $ID);      my $filter = ($complete ? "Genome(complete) = 1" : "");
307          # Declare the return list.      # Get all the genomes and the related taxonomy information.
308          my @retVal = ();      my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
309          # If we found the entity, push the values into the return list.      # Clear the counters.
310          if ($entity) {      my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
311                  push @retVal, $entity->Values($fields);      # Loop through, counting the domains.
312        for my $genome (@genomes) {
313            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
314            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
315            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
316            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
317            elsif ($genome->[1] =~ /^env/i)      { ++$env }
318            else  { ++$unk }
319          }          }
320          # Return the result.      # Return the counts.
321          return @retVal;      return ($arch, $bact, $euk, $vir, $env, $unk);
322  }  }
323    
324  =head3 ShowMetaData  =head3 ContigCount
325    
326  C<< $sprout->ShowMetaData($fileName); >>      my $count = $sprout->ContigCount($genomeID);
327    
328  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.
329    
330  =over 4  =over 4
331    
332  =item fileName  =item genomeID
333    
334  Fully-qualified name to give to the output file.  ID of the genome whose contig count is desired.
335    
336    =item RETURN
337    
338    Returns the number of contigs for the specified genome.
339    
340  =back  =back
341    
342  =cut  =cut
343    
344  sub ShowMetaData {  sub ContigCount {
345          # Get the parameters.          # Get the parameters.
346          my ($self, $fileName) = @_;      my ($self, $genomeID) = @_;
347          # Compute the file name.      # Get the contig count.
348          my $options = $self->{_options};      my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
349          # Call the show method on the underlying ERDB object.      # Return the result.
350          $self->{_erdb}->ShowMetaData($fileName);      return $retVal;
351  }  }
352    
353  =head3 Load  =head3 GeneMenu
   
 C<< $sprout->Load($rebuild); >>;  
354    
355  Load the database from files in the data directory, optionally re-creating the tables.      my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected);
   
 This method always deletes the data from the database before loading, even if the tables are not  
 re-created. The data is loaded into the relations from files in the data directory either having the  
 same name as the target relation with no extension or with an extension of C<.dtx>. Files without an  
 extension are used in preference to the files with an extension.  
356    
357  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,
358  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
359  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.  
360    
361  =over 4  =over 4
362    
363  =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  
364    
365  =cut  Reference to a hash mapping attributes to values for the SELECT tag generated.
 #: Return Type %;  
 sub Load {  
         # Get the parameters.  
         my ($self, $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;  
 }  
366    
367  =head3 LoadUpdate  =item filterString
368    
369  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  A filter string for use in selecting the genomes. The filter string must conform
370    to the rules for the C<< ERDB->Get >> method.
371    
372  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.  
373    
374  =over 4  Reference to a list of values to be substituted in for the parameter marks in
375    the filter string.
376    
377  =item truncateFlag  =item selected (optional)
378    
379  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.  
380    
381  =item tableList  =item fast (optional)
382    
383  List of the tables to be updated.  If specified and TRUE, the contig counts will be omitted to improve performance.
384    
385  =item RETURN  =item RETURN
386    
387  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.  
388    
389  =back  =back
390    
391  =cut  =cut
392  #: Return Type $%;  
393  sub LoadUpdate {  sub GeneMenu {
394          # Get the parameters.          # Get the parameters.
395          my ($self, $truncateFlag, $tableList) = @_;      my ($self, $attributes, $filterString, $params, $selected, $fast) = @_;
396          # Get the database object.      my $slowMode = ! $fast;
397          my $erdb = $self->{_erdb};      # Default to nothing selected. This prevents an execution warning if "$selected"
398          # Declare the return value.      # is undefined.
399          my $retVal = Stats->new();      $selected = "" unless defined $selected;
400          # Get the data directory.      Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3);
401          my $optionTable = $self->{_options};      # Start the menu.
402          my $dataDir = $optionTable->{dataDir};      my $retVal = "<select " .
403          # Loop through the incoming table names.          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
404          for my $tableName (@{$tableList}) {          ">\n";
405                  # Find the table's file.      # Get the genomes.
406                  my $fileName = "$dataDir/$tableName";      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
407                  if (! -e $fileName) {                                                                       'Genome(genus)',
408                          $fileName = "$fileName.dtx";                                                                       'Genome(species)',
409                  }                                                                       'Genome(unique-characterization)']);
410                  # Attempt to load this table.      # Sort them by name.
411                  my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
412                  # Accumulate the resulting statistics.      # Loop through the genomes, creating the option tags.
413                  $retVal->Accumulate($result);      for my $genomeData (@sorted) {
414            # Get the data for this genome.
415            my ($genomeID, $genus, $species, $strain) = @{$genomeData};
416            # Get the contig count.
417            my $contigInfo = "";
418            if ($slowMode) {
419                my $count = $self->ContigCount($genomeID);
420                my $counting = ($count == 1 ? "contig" : "contigs");
421                $contigInfo = "[$count $counting]";
422            }
423            # Find out if we're selected.
424            my $selectOption = ($selected eq $genomeID ? " selected" : "");
425            # Build the option tag.
426            $retVal .= "<option value=\"$genomeID\"$selectOption>$genus $species $strain ($genomeID)$contigInfo</option>\n";
427          }          }
428          # Return the statistics.      # Close the SELECT tag.
429        $retVal .= "</select>\n";
430        # Return the result.
431          return $retVal;          return $retVal;
432  }  }
433    
434  =head3 Build  =head3 Build
435    
436  C<< $sprout->Build(); >>      $sprout->Build();
437    
438  Build the database. The database will be cleared and the tables re-created from the metadata.  Build the database. The database will be cleared and the tables re-created from the metadata.
439  This method is useful when a database is brand new or when the database definition has  This method is useful when a database is brand new or when the database definition has
# Line 459  Line 445 
445          # Get the parameters.          # Get the parameters.
446          my ($self) = @_;          my ($self) = @_;
447          # Create the tables.          # Create the tables.
448          $self->{_erdb}->CreateTables;      $self->CreateTables();
449  }  }
450    
451  =head3 Genomes  =head3 Genomes
452    
453  C<< my @genomes = $sprout->Genomes(); >>      my @genomes = $sprout->Genomes();
454    
455  Return a list of all the genome IDs.  Return a list of all the genome IDs.
456    
# Line 481  Line 467 
467    
468  =head3 GenusSpecies  =head3 GenusSpecies
469    
470  C<< my $infoString = $sprout->GenusSpecies($genomeID); >>      my $infoString = $sprout->GenusSpecies($genomeID);
471    
472  Return the genus, species, and unique characterization for a genome.  Return the genus, species, and unique characterization for a genome.
473    
# Line 513  Line 499 
499    
500  =head3 FeaturesOf  =head3 FeaturesOf
501    
502  C<< my @features = $sprout->FeaturesOf($genomeID, $ftype); >>      my @features = $sprout->FeaturesOf($genomeID, $ftype);
503    
504  Return a list of the features relevant to a specified genome.  Return a list of the features relevant to a specified genome.
505    
# Line 558  Line 544 
544    
545  =head3 FeatureLocation  =head3 FeatureLocation
546    
547  C<< my @locations = $sprout->FeatureLocation($featureID); >>      my @locations = $sprout->FeatureLocation($featureID);
548    
549  Return the location of a feature in its genome's contig segments. In a list context, this method  Return the location of a feature in its genome's contig segments. In a list context, this method
550  will return a list of the locations. In a scalar context, it will return the locations as a space-  will return a list of the locations. In a scalar context, it will return the locations as a space-
# Line 582  Line 568 
568  =item RETURN  =item RETURN
569    
570  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
571  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context.
572    
573  =back  =back
574    
575  =cut  =cut
576  #: Return Type @;  
 #: Return Type $;  
577  sub FeatureLocation {  sub FeatureLocation {
578          # Get the parameters.          # Get the parameters.
579          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
580          # Create a query for the feature locations.      # Get the feature record.
581          my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",      my $object = $self->GetEntity('Feature', $featureID);
582                                                     [$featureID]);      Confess("Feature $featureID not found.") if ! defined($object);
583        # Get the location string.
584        my $locString = $object->PrimaryValue('Feature(location-string)');
585          # Create the return list.          # Create the return list.
586          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";  
         }  
587          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
588          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
589  }  }
590    
591  =head3 ParseLocation  =head3 ParseLocation
592    
593  C<< my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location); >>      my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location);
594    
595  Split a location specifier into the contig ID, the starting point, the direction, and the  Split a location specifier into the contig ID, the starting point, the direction, and the
596  length.  length.
# Line 649  Line 609 
609  =back  =back
610    
611  =cut  =cut
612  #: Return Type @;  
613  sub ParseLocation {  sub ParseLocation {
614          # Get the parameter. Note that if we're called as an instance method, we ignore          # Get the parameter. Note that if we're called as an instance method, we ignore
615      # the first parameter.      # the first parameter.
616      shift if UNIVERSAL::isa($_[0],__PACKAGE__);      shift if UNIVERSAL::isa($_[0],__PACKAGE__);
617          my ($location) = @_;          my ($location) = @_;
618          # Parse it into segments.          # Parse it into segments.
619          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
620          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
621          # If the direction is an underscore, convert it to a + or -.          # If the direction is an underscore, convert it to a + or -.
622          if ($dir eq "_") {          if ($dir eq "_") {
# Line 672  Line 632 
632          return ($contigID, $start, $dir, $len);          return ($contigID, $start, $dir, $len);
633  }  }
634    
635    
636    
637  =head3 PointLocation  =head3 PointLocation
638    
639  C<< my $found = Sprout::PointLocation($location, $point); >>      my $found = Sprout::PointLocation($location, $point);
640    
641  Return the offset into the specified location of the specified point on the contig. If  Return the offset into the specified location of the specified point on the contig. If
642  the specified point is before the location, a negative value will be returned. If it is  the specified point is before the location, a negative value will be returned. If it is
# Line 703  Line 665 
665  =back  =back
666    
667  =cut  =cut
668  #: Return Type $;  
669  sub PointLocation {  sub PointLocation {
670          # Get the parameter. Note that if we're called as an instance method, we ignore          # Get the parameter. Note that if we're called as an instance method, we ignore
671      # the first parameter.      # the first parameter.
# Line 726  Line 688 
688    
689  =head3 DNASeq  =head3 DNASeq
690    
691  C<< my $sequence = $sprout->DNASeq(\@locationList); >>      my $sequence = $sprout->DNASeq(\@locationList);
692    
693  This method returns the DNA sequence represented by a list of locations. The list of locations  This method returns the DNA sequence represented by a list of locations. The list of locations
694  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,
695  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>.
696    
697    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
698    between positions 1401 and 1532, inclusive.
699    
700        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
701    
702  =over 4  =over 4
703    
704  =item locationList  =item locationList
705    
706  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
707  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
708    
709  =item RETURN  =item RETURN
710    
# Line 764  Line 731 
731                  # 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
732                  # before putting it in the return value.                  # before putting it in the return value.
733                  my ($start, $stop);                  my ($start, $stop);
734            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
735                  if ($dir eq "+") {                  if ($dir eq "+") {
736                          $start = $beg;                          $start = $beg;
737                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
738                  } else {                  } else {
739                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
740                          $stop = $beg;                          $stop = $beg;
741                  }                  }
742            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
743                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
744                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
745                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 782  Line 751 
751                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
752                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
753                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
754                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
755                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
756                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
757                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
758                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
759                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
760                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
761                  }                  }
762                  # 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.
763                  if ($dir eq '+') {                  if ($dir eq '+') {
764                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
765                  } else {                  } else {
766                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
767                  }                  }
768          }          }
769          # Return the result.          # Return the result.
# Line 802  Line 772 
772    
773  =head3 AllContigs  =head3 AllContigs
774    
775  C<< my @idList = $sprout->AllContigs($genomeID); >>      my @idList = $sprout->AllContigs($genomeID);
776    
777  Return a list of all the contigs for a genome.  Return a list of all the contigs for a genome.
778    
# Line 830  Line 800 
800          return @retVal;          return @retVal;
801  }  }
802    
803    =head3 GenomeLength
804    
805        my $length = $sprout->GenomeLength($genomeID);
806    
807    Return the length of the specified genome in base pairs.
808    
809    =over 4
810    
811    =item genomeID
812    
813    ID of the genome whose base pair count is desired.
814    
815    =item RETURN
816    
817    Returns the number of base pairs in all the contigs of the specified
818    genome.
819    
820    =back
821    
822    =cut
823    
824    sub GenomeLength {
825        # Get the parameters.
826        my ($self, $genomeID) = @_;
827        # Declare the return variable.
828        my $retVal = 0;
829        # Get the genome's contig sequence lengths.
830        my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
831                           [$genomeID], 'IsMadeUpOf(len)');
832        # Sum the lengths.
833        map { $retVal += $_ } @lens;
834        # Return the result.
835        return $retVal;
836    }
837    
838    =head3 FeatureCount
839    
840        my $count = $sprout->FeatureCount($genomeID, $type);
841    
842    Return the number of features of the specified type in the specified genome.
843    
844    =over 4
845    
846    =item genomeID
847    
848    ID of the genome whose feature count is desired.
849    
850    =item type
851    
852    Type of feature to count (eg. C<peg>, C<rna>, etc.).
853    
854    =item RETURN
855    
856    Returns the number of features of the specified type for the specified genome.
857    
858    =back
859    
860    =cut
861    
862    sub FeatureCount {
863        # Get the parameters.
864        my ($self, $genomeID, $type) = @_;
865        # Compute the count.
866        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
867                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
868                                    [$genomeID, $type]);
869        # Return the result.
870        return $retVal;
871    }
872    
873    =head3 GenomeAssignments
874    
875        my $fidHash = $sprout->GenomeAssignments($genomeID);
876    
877    Return a list of a genome's assigned features. The return hash will contain each
878    assigned feature of the genome mapped to the text of its most recent functional
879    assignment.
880    
881    =over 4
882    
883    =item genomeID
884    
885    ID of the genome whose functional assignments are desired.
886    
887    =item RETURN
888    
889    Returns a reference to a hash which maps each feature to its most recent
890    functional assignment.
891    
892    =back
893    
894    =cut
895    
896    sub GenomeAssignments {
897        # Get the parameters.
898        my ($self, $genomeID) = @_;
899        # Declare the return variable.
900        my $retVal = {};
901        # Query the genome's features.
902        my $query = $self->Get(['HasFeature', 'Feature'], "HasFeature(from-link) = ?",
903                               [$genomeID]);
904        # Loop through the features.
905        while (my $data = $query->Fetch) {
906            # Get the feature ID and assignment.
907            my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']);
908            if ($assignment) {
909                $retVal->{$fid} = $assignment;
910            }
911        }
912        # Return the result.
913        return $retVal;
914    }
915    
916  =head3 ContigLength  =head3 ContigLength
917    
918  C<< my $length = $sprout->ContigLength($contigID); >>      my $length = $sprout->ContigLength($contigID);
919    
920  Compute the length of a contig.  Compute the length of a contig.
921    
# Line 863  Line 946 
946          # Set it from the sequence data, if any.          # Set it from the sequence data, if any.
947          if ($sequence) {          if ($sequence) {
948                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
949                  $retVal = $start + $len;          $retVal = $start + $len - 1;
950          }          }
951          # Return the result.          # Return the result.
952          return $retVal;          return $retVal;
953  }  }
954    
955  =head3 GenesInRegion  =head3 ClusterPEGs
956    
957  C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>      my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs);
958    
959  List the features which overlap a specified region in a contig.  Cluster the PEGs in a list according to the cluster coding scheme of the specified
960    subsystem. In order for this to work properly, the subsystem object must have
961    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> or
962    B<get_row> methods. This causes the cluster numbers to be pulled into the
963    subsystem's color hash. If a PEG is not found in the color hash, it will not
964    appear in the output sequence.
965    
966  =over 4  =over 4
967    
968  =item contigID  =item sub
969    
970  ID of the contig containing the region of interest.  Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
971    method.
972    
973  =item start  =item pegs
974    
975  Offset of the first residue in the region of interest.  Reference to the list of PEGs to be clustered.
976    
977  =item stop  =item RETURN
978    
979    Returns a list of the PEGs, grouped into smaller lists by cluster number.
980    
981    =back
982    
983    =cut
984    #: Return Type $@@;
985    sub ClusterPEGs {
986        # Get the parameters.
987        my ($self, $sub, $pegs) = @_;
988        # Declare the return variable.
989        my $retVal = [];
990        # Loop through the PEGs, creating arrays for each cluster.
991        for my $pegID (@{$pegs}) {
992            my $clusterNumber = $sub->get_cluster_number($pegID);
993            # Only proceed if the PEG is in a cluster.
994            if ($clusterNumber >= 0) {
995                # Push this PEG onto the sub-list for the specified cluster number.
996                push @{$retVal->[$clusterNumber]}, $pegID;
997            }
998        }
999        # Return the result.
1000        return $retVal;
1001    }
1002    
1003    =head3 GenesInRegion
1004    
1005        my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop);
1006    
1007    List the features which overlap a specified region in a contig.
1008    
1009    =over 4
1010    
1011    =item contigID
1012    
1013    ID of the contig containing the region of interest.
1014    
1015    =item start
1016    
1017    Offset of the first residue in the region of interest.
1018    
1019    =item stop
1020    
1021  Offset of the last residue in the region of interest.  Offset of the last residue in the region of interest.
1022    
# Line 900  Line 1031 
1031  =back  =back
1032    
1033  =cut  =cut
1034  #: Return Type @@;  
1035  sub GenesInRegion {  sub GenesInRegion {
1036          # Get the parameters.          # Get the parameters.
1037          my ($self, $contigID, $start, $stop) = @_;          my ($self, $contigID, $start, $stop) = @_;
1038          # Get the maximum segment length.          # Get the maximum segment length.
1039          my $maximumSegmentLength = $self->MaxSegment;          my $maximumSegmentLength = $self->MaxSegment;
         # Create a hash to receive the feature list. We use a hash so that we can eliminate  
         # duplicates easily. The hash key will be the feature ID. The value will be a two-element  
         # containing the minimum and maximum offsets. We will use the offsets to sort the results  
         # when we're building the result set.  
         my %featuresFound = ();  
1040          # Prime the values we'll use for the returned beginning and end.          # Prime the values we'll use for the returned beginning and end.
1041          my @initialMinMax = ($self->ContigLength($contigID), 0);          my @initialMinMax = ($self->ContigLength($contigID), 0);
1042          my ($min, $max) = @initialMinMax;          my ($min, $max) = @initialMinMax;
1043          # Create a table of parameters for each query. Each query looks for features travelling in      # Get the overlapping features.
1044        my @featureObjects = $self->GeneDataInRegion($contigID, $start, $stop);
1045        # We'l use this hash to help us track the feature IDs and sort them. The key is the
1046        # feature ID and the value is a [$left,$right] pair indicating the maximum extent
1047        # of the feature's locations.
1048        my %featureMap = ();
1049        # Loop through them to do the begin/end analysis.
1050        for my $featureObject (@featureObjects) {
1051            # Get the feature's location string. This may contain multiple actual locations.
1052            my ($locations, $fid) = $featureObject->Values([qw(Feature(location-string) Feature(id))]);
1053            my @locationSegments = split /\s*,\s*/, $locations;
1054            # Loop through the locations.
1055            for my $locationSegment (@locationSegments) {
1056                # Construct an object for the location.
1057                my $locationObject = BasicLocation->new($locationSegment);
1058                # Merge the current segment's begin and end into the min and max.
1059                my ($left, $right) = ($locationObject->Left, $locationObject->Right);
1060                my ($beg, $end);
1061                if (exists $featureMap{$fid}) {
1062                    ($beg, $end) = @{$featureMap{$fid}};
1063                    $beg = $left if $left < $beg;
1064                    $end = $right if $right > $end;
1065                } else {
1066                    ($beg, $end) = ($left, $right);
1067                }
1068                $min = $beg if $beg < $min;
1069                $max = $end if $end > $max;
1070                # Store the feature's new extent back into the hash table.
1071                $featureMap{$fid} = [$beg, $end];
1072            }
1073        }
1074        # Now we must compute the list of the IDs for the features found. We start with a list
1075        # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1076        # but the result of the sort will be the same.)
1077        my @list = map { [$featureMap{$_}->[0] + $featureMap{$_}->[1], $_] } keys %featureMap;
1078        # Now we sort by midpoint and yank out the feature IDs.
1079        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1080        # Return it along with the min and max.
1081        return (\@retVal, $min, $max);
1082    }
1083    
1084    =head3 GeneDataInRegion
1085    
1086        my @featureList = $sprout->GenesInRegion($contigID, $start, $stop);
1087    
1088    List the features which overlap a specified region in a contig.
1089    
1090    =over 4
1091    
1092    =item contigID
1093    
1094    ID of the contig containing the region of interest.
1095    
1096    =item start
1097    
1098    Offset of the first residue in the region of interest.
1099    
1100    =item stop
1101    
1102    Offset of the last residue in the region of interest.
1103    
1104    =item RETURN
1105    
1106    Returns a list of B<ERDBObjects> for the desired features. Each object will
1107    contain a B<Feature> record.
1108    
1109    =back
1110    
1111    =cut
1112    
1113    sub GeneDataInRegion {
1114        # Get the parameters.
1115        my ($self, $contigID, $start, $stop) = @_;
1116        # Get the maximum segment length.
1117        my $maximumSegmentLength = $self->MaxSegment;
1118        # Create a hash to receive the feature list. We use a hash so that we can eliminate
1119        # duplicates easily. The hash key will be the feature ID. The value will be the feature's
1120        # ERDBObject from the query.
1121        my %featuresFound = ();
1122        # Create a table of parameters for the queries. Each query looks for features travelling in
1123          # 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,
1124          # 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
1125          # 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 923  Line 1128 
1128          # Loop through the query parameters.          # Loop through the query parameters.
1129          for my $parms (values %queryParms) {          for my $parms (values %queryParms) {
1130                  # Create the query.                  # Create the query.
1131                  my $query = $self->Get(['IsLocatedIn'],          my $query = $self->Get([qw(Feature IsLocatedIn)],
1132                          "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",                          "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
1133                          $parms);                          $parms);
1134                  # Loop through the feature segments found.                  # Loop through the feature segments found.
1135                  while (my $segment = $query->Fetch) {                  while (my $segment = $query->Fetch) {
1136                          # Get the data about this segment.                          # Get the data about this segment.
1137                          my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',              my ($featureID, $contig, $dir, $beg, $len) = $segment->Values([qw(IsLocatedIn(from-link)
1138                                  'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);                  IsLocatedIn(to-link) IsLocatedIn(dir) IsLocatedIn(beg) IsLocatedIn(len))]);
1139                          # 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
1140                          # 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
1141                          # 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
1142                          # length.                          # length.
1143                          my ($found, $end) = (0, 0);              my $loc = BasicLocation->new($contig, $beg, $dir, $len);
1144                          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 '-') {  
                                 # Note we switch things around so that the beginning is to the left of the  
                                 # ending.  
                                 ($beg, $end) = ($beg - $len, $beg);  
                                 if ($beg <= $stop) {  
                                         # Denote we found a useful feature.  
                                         $found = 1;  
                                 }  
                         }  
1145                          if ($found) {                          if ($found) {
1146                                  # Here we need to record the feature and update the minima and maxima. First,                  # Save this feature in the result list.
1147                                  # get the current entry for the specified feature.                  $featuresFound{$featureID} = $segment;
                                 my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :  
                                                                          @initialMinMax);  
                                 # Merge the current segment's begin and end into the feature begin and end and the  
                                 # global min and max.  
                                 if ($beg < $loc1) {  
                                         $loc1 = $beg;  
                                         $min = $beg if $beg < $min;  
                                 }  
                                 if ($end > $loc2) {  
                                         $loc2 = $end;  
                                         $max = $end if $end > $max;  
                                 }  
                                 # Store the entry back into the hash table.  
                                 $featuresFound{$featureID} = [$loc1, $loc2];  
1148                          }                          }
1149                  }                  }
1150          }          }
1151          # Now we must compute the list of the IDs for the features found. We start with a list      # Return the ERDB objects for the features found.
1152          # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,      return values %featuresFound;
         # but the result of the sort will be the same.)  
         my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;  
         # Now we sort by midpoint and yank out the feature IDs.  
         my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;  
         # Return it along with the min and max.  
         return (\@retVal, $min, $max);  
1153  }  }
1154    
1155  =head3 FType  =head3 FType
1156    
1157  C<< my $ftype = $sprout->FType($featureID); >>      my $ftype = $sprout->FType($featureID);
1158    
1159  Return the type of a feature.  Return the type of a feature.
1160    
# Line 1013  Line 1184 
1184    
1185  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1186    
1187  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>      my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag);
1188    
1189  Return the annotations of a feature.  Return the annotations of a feature.
1190    
# Line 1023  Line 1194 
1194    
1195  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1196    
1197    =item rawFlag
1198    
1199    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1200    will be returned in human-readable form.
1201    
1202  =item RETURN  =item RETURN
1203    
1204  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.
1205    
1206  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1207    
1208  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1209    
1210  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1211    
# Line 1041  Line 1217 
1217  #: Return Type @%;  #: Return Type @%;
1218  sub FeatureAnnotations {  sub FeatureAnnotations {
1219          # Get the parameters.          # Get the parameters.
1220          my ($self, $featureID) = @_;      my ($self, $featureID, $rawFlag) = @_;
1221          # 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.
1222          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1223                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 1054  Line 1230 
1230                          $annotation->Values(['IsTargetOfAnnotation(from-link)',                          $annotation->Values(['IsTargetOfAnnotation(from-link)',
1231                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1232                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1233            # Convert the time, if necessary.
1234            if (! $rawFlag) {
1235                $timeStamp = FriendlyTimestamp($timeStamp);
1236            }
1237                  # Assemble them into a hash.                  # Assemble them into a hash.
1238          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1239                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1240                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1241                  # Add it to the return list.                  # Add it to the return list.
1242                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1067  Line 1247 
1247    
1248  =head3 AllFunctionsOf  =head3 AllFunctionsOf
1249    
1250  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>      my %functions = $sprout->AllFunctionsOf($featureID);
1251    
1252  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
1253  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,
# Line 1085  Line 1265 
1265    
1266  =item RETURN  =item RETURN
1267    
1268  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1269    
1270  =back  =back
1271    
# Line 1095  Line 1275 
1275          # Get the parameters.          # Get the parameters.
1276          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
1277          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1278      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1279                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1280                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1281                                               'MadeAnnotation(from-link)']);
1282          # Declare the return hash.          # Declare the return hash.
1283          my %retVal;          my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1284      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1285      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1286          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1287      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1288          # Get the annotation fields.          # Get the annotation fields.
1289          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1290                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1291                  my ($user, $function) = _ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1292          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1293              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1294              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1295              # return hash.              # return hash.
1296                          $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1297                  }                  }
1298          }          }
1299          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1125  Line 1302 
1302    
1303  =head3 FunctionOf  =head3 FunctionOf
1304    
1305  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>      my $functionText = $sprout->FunctionOf($featureID, $userID);
1306    
1307  Return the most recently-determined functional assignment of a particular feature.  Return the most recently-determined functional assignment of a particular feature.
1308    
1309  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
1310  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
1311  assignment is a type of annotation. The format of an assignment is described in  assignment is taken from the B<Feature> or C<Annotation> table, depending.
 L</ParseLocation>. 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.  
1312    
1313  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
1314  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 1153  Line 1327 
1327    
1328  =item userID (optional)  =item userID (optional)
1329    
1330  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
1331  C<FIG> assignment will be returned.  functional assignment in the B<Feature> table will be returned.
1332    
1333  =item RETURN  =item RETURN
1334    
# Line 1171  Line 1345 
1345      my $retVal;      my $retVal;
1346      # Determine the ID type.      # Determine the ID type.
1347      if ($featureID =~ m/^fig\|/) {      if ($featureID =~ m/^fig\|/) {
1348          # Here we have a FIG feature ID. We must build the list of trusted          # Here we have a FIG feature ID.
1349          # users.          if (!$userID) {
1350                # Use the primary assignment.
1351                ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']);
1352            } else {
1353                # We must build the list of trusted users.
1354          my %trusteeTable = ();          my %trusteeTable = ();
1355          # Check the user ID.          # Check the user ID.
1356          if (!$userID) {          if (!$userID) {
# Line 1194  Line 1372 
1372              }              }
1373          }          }
1374          # 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.
1375          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],              my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1376                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1377                                 [$featureID]);                                 [$featureID]);
1378          my $timeSelected = 0;          my $timeSelected = 0;
1379          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1380          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1381              # Get the annotation text.              # Get the annotation text.
1382              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);                  my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1383                                                             'Annotation(time)', 'MadeAnnotation(from-link)']);
1384              # 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.
1385              my ($user, $function) = _ParseAssignment($text);                  my ($actualUser, $function) = _ParseAssignment($user, $text);
1386              if ($user) {                  Trace("Assignment user is $actualUser, text is $function.") if T(4);
1387                    if ($actualUser) {
1388                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1389                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1390                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                      if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1391                      $retVal = $function;                      $retVal = $function;
1392                      $timeSelected = $time;                      $timeSelected = $time;
1393                  }                  }
1394              }              }
1395          }          }
1396            }
1397      } else {      } else {
1398          # 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
1399          # matter. We simply get the information from the External Alias Function          # matter. We simply get the information from the External Alias Function
# Line 1223  Line 1404 
1404          return $retVal;          return $retVal;
1405  }  }
1406    
1407    =head3 FunctionsOf
1408    
1409        my @functionList = $sprout->FunctionOf($featureID, $userID);
1410    
1411    Return the functional assignments of a particular feature.
1412    
1413    The functional assignment is handled differently depending on the type of feature. If
1414    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1415    assignment is a type of annotation. The format of an assignment is described in
1416    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1417    annotation itself because it's a text field; however, this is not a big problem because
1418    most features only have a small number of annotations.
1419    
1420    If the feature is B<not> identified by a FIG ID, then the functional assignment
1421    information is taken from the B<ExternalAliasFunc> table. If the table does
1422    not contain an entry for the feature, an empty list is returned.
1423    
1424    =over 4
1425    
1426    =item featureID
1427    
1428    ID of the feature whose functional assignments are desired.
1429    
1430    =item RETURN
1431    
1432    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1433    that user.
1434    
1435    =back
1436    
1437    =cut
1438    #: Return Type @@;
1439    sub FunctionsOf {
1440        # Get the parameters.
1441        my ($self, $featureID) = @_;
1442        # Declare the return value.
1443        my @retVal = ();
1444        # Determine the ID type.
1445        if ($featureID =~ m/^fig\|/) {
1446            # Here we have a FIG feature ID. We must build the list of trusted
1447            # users.
1448            my %trusteeTable = ();
1449            # Build a query for all of the feature's annotations, sorted by date.
1450            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1451                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1452                                   [$featureID]);
1453            my $timeSelected = 0;
1454            # Loop until we run out of annotations.
1455            while (my $annotation = $query->Fetch()) {
1456                # Get the annotation text.
1457                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1458                                                                'Annotation(time)',
1459                                                                'MadeAnnotation(user)']);
1460                # Check to see if this is a functional assignment for a trusted user.
1461                my ($actualUser, $function) = _ParseAssignment($user, $text);
1462                if ($actualUser) {
1463                    # Here it is a functional assignment.
1464                    push @retVal, [$actualUser, $function];
1465                }
1466            }
1467        } else {
1468            # Here we have a non-FIG feature ID. In this case the user ID does not
1469            # matter. We simply get the information from the External Alias Function
1470            # table.
1471            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1472                                                     ['ExternalAliasFunc(func)']);
1473            push @retVal, map { ['master', $_] } @assignments;
1474        }
1475        # Return the assignments found.
1476        return @retVal;
1477    }
1478    
1479  =head3 BBHList  =head3 BBHList
1480    
1481  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>      my $bbhHash = $sprout->BBHList($genomeID, \@featureList);
1482    
1483  Return a hash mapping the features in a specified list to their bidirectional best hits  Return a hash mapping the features in a specified list to their bidirectional best hits
1484  on a specified target genome.  on a specified target genome.
# Line 1242  Line 1495 
1495    
1496  =item RETURN  =item RETURN
1497    
1498  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
1499  their best hits.  on the target genome.
1500    
1501  =back  =back
1502    
# Line 1256  Line 1509 
1509          my %retVal = ();          my %retVal = ();
1510          # Loop through the incoming features.          # Loop through the incoming features.
1511          for my $featureID (@{$featureList}) {          for my $featureID (@{$featureList}) {
1512                  # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1513                  my $query = $self->Get(['IsBidirectionalBestHitOf'],          my @bbhData = FIGRules::BBHData($featureID);
1514                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",          # Peel off the BBHs found.
1515                                                             [$featureID, $genomeID]);          my @found = ();
1516                  # Look for the best hit.          for my $bbh (@bbhData) {
1517                  my $bbh = $query->Fetch;              my $fid = $bbh->[0];
1518                  if ($bbh) {              my $bbGenome = $self->GenomeOf($fid);
1519                          my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              if ($bbGenome eq $genomeID) {
1520                          $retVal{$featureID} = $targetFeature;                  push @found, $fid;
1521                  }                  }
1522          }          }
1523            $retVal{$featureID} = \@found;
1524        }
1525          # Return the mapping.          # Return the mapping.
1526          return \%retVal;          return \%retVal;
1527  }  }
1528    
1529    =head3 SimList
1530    
1531        my %similarities = $sprout->SimList($featureID, $count);
1532    
1533    Return a list of the similarities to the specified feature.
1534    
1535    This method just returns the bidirectional best hits for performance reasons.
1536    
1537    =over 4
1538    
1539    =item featureID
1540    
1541    ID of the feature whose similarities are desired.
1542    
1543    =item count
1544    
1545    Maximum number of similar features to be returned, or C<0> to return them all.
1546    
1547    =back
1548    
1549    =cut
1550    #: Return Type %;
1551    sub SimList {
1552        # Get the parameters.
1553        my ($self, $featureID, $count) = @_;
1554        # Ask for the best hits.
1555        my @lists = FIGRules::BBHData($featureID);
1556        # Create the return value.
1557        my %retVal = ();
1558        for my $tuple (@lists) {
1559            $retVal{$tuple->[0]} = $tuple->[1];
1560        }
1561        # Return the result.
1562        return %retVal;
1563    }
1564    
1565    =head3 IsComplete
1566    
1567        my $flag = $sprout->IsComplete($genomeID);
1568    
1569    Return TRUE if the specified genome is complete, else FALSE.
1570    
1571    =over 4
1572    
1573    =item genomeID
1574    
1575    ID of the genome whose completeness status is desired.
1576    
1577    =item RETURN
1578    
1579    Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1580    not found.
1581    
1582    =back
1583    
1584    =cut
1585    #: Return Type $;
1586    sub IsComplete {
1587        # Get the parameters.
1588        my ($self, $genomeID) = @_;
1589        # Declare the return variable.
1590        my $retVal;
1591        # Get the genome's data.
1592        my $genomeData = $self->GetEntity('Genome', $genomeID);
1593        if ($genomeData) {
1594            # The genome exists, so get the completeness flag.
1595            $retVal = $genomeData->PrimaryValue('Genome(complete)');
1596        }
1597        # Return the result.
1598        return $retVal;
1599    }
1600    
1601  =head3 FeatureAliases  =head3 FeatureAliases
1602    
1603  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>      my @aliasList = $sprout->FeatureAliases($featureID);
1604    
1605  Return a list of the aliases for a specified feature.  Return a list of the aliases for a specified feature.
1606    
# Line 1296  Line 1623 
1623          # Get the parameters.          # Get the parameters.
1624          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
1625          # Get the desired feature's aliases          # Get the desired feature's aliases
1626          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);      my @retVal = $self->GetFlat(['IsAliasOf'], "IsAliasOf(to-link) = ?", [$featureID], 'IsAliasOf(from-link)');
1627          # Return the result.          # Return the result.
1628          return @retVal;          return @retVal;
1629  }  }
1630    
1631  =head3 GenomeOf  =head3 GenomeOf
1632    
1633  C<< my $genomeID = $sprout->GenomeOf($featureID); >>      my $genomeID = $sprout->GenomeOf($featureID);
1634    
1635  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1636    
1637  =over 4  =over 4
1638    
1639  =item featureID  =item featureID
1640    
1641  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1642    
1643  =item RETURN  =item RETURN
1644    
1645  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
1646  an undefined value.  found, returns an undefined value.
1647    
1648  =back  =back
1649    
# Line 1325  Line 1652 
1652  sub GenomeOf {  sub GenomeOf {
1653          # Get the parameters.          # Get the parameters.
1654          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
         # Create a query to find the genome associated with the feature.  
         my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);  
1655          # Declare the return value.          # Declare the return value.
1656          my $retVal;          my $retVal;
1657          # Get the genome ID.      # Parse the genome ID from the feature ID.
1658          if (my $relationship = $query->Fetch()) {      if ($featureID =~ /^fig\|(\d+\.\d+)/) {
1659                  ($retVal) = $relationship->Value('HasContig(from-link)');          $retVal = $1;
1660        } else {
1661            Confess("Invalid feature ID $featureID.");
1662          }          }
1663          # Return the value found.          # Return the value found.
1664          return $retVal;          return $retVal;
# Line 1339  Line 1666 
1666    
1667  =head3 CoupledFeatures  =head3 CoupledFeatures
1668    
1669  C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >>      my %coupleHash = $sprout->CoupledFeatures($featureID);
1670    
1671  Return the features functionally coupled with a specified feature. Features are considered  Return the features functionally coupled with a specified feature. Features are considered
1672  functionally coupled if they tend to be clustered on the same chromosome.  functionally coupled if they tend to be clustered on the same chromosome.
# Line 1361  Line 1688 
1688  sub CoupledFeatures {  sub CoupledFeatures {
1689          # Get the parameters.          # Get the parameters.
1690          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
1691          # Create a query to retrieve the functionally-coupled features. Note that we depend on the      # Ask the coupling server for the data.
1692          # fact that the functional coupling is physically paired. If (A,B) is in the database, then      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1693          # (B,A) will also be found.      my @rawPairs = FIGRules::NetCouplingData('coupled_to', id1 => $featureID);
1694          my $query = $self->Get(['IsClusteredOnChromosomeWith'],      Trace(scalar(@rawPairs) . " couplings returned.") if T(coupling => 3);
1695                                                     "IsClusteredOnChromosomeWith(from-link) = ?", [$featureID]);      # Form them into a hash.
         # This value will be set to TRUE if we find at least one coupled feature.  
         my $found = 0;  
         # Create the return hash.  
1696          my %retVal = ();          my %retVal = ();
1697          # Retrieve the relationship records and store them in the hash.      for my $pair (@rawPairs) {
1698          while (my $clustering = $query->Fetch()) {          # Get the feature ID and score.
1699                  my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',          my ($featureID2, $score) = @{$pair};
1700                                                                      'IsClusteredOnChromosomeWith(score)']);          # Only proceed if the feature is in NMPDR.
1701                  $retVal{$otherFeatureID} = $score;          if ($self->_CheckFeature($featureID2)) {
1702                  $found = 1;              $retVal{$featureID2} = $score;
1703            }
1704          }          }
1705          # 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
1706          # the incoming feature as well.          # the incoming feature as well.
1707          if ($found) {      if (keys %retVal) {
1708                  $retVal{$featureID} = 9999;                  $retVal{$featureID} = 9999;
1709      }      }
1710          # Return the hash.          # Return the hash.
1711          return %retVal;          return %retVal;
1712  }  }
1713    
1714  =head3 GetEntityTypes  =head3 CouplingEvidence
1715    
1716        my @evidence = $sprout->CouplingEvidence($peg1, $peg2);
1717    
1718    Return the evidence for a functional coupling.
1719    
1720    A pair of features is considered evidence of a coupling between two other
1721    features if they occur close together on a contig and both are similar to
1722    the coupled features. So, if B<A1> and B<A2> are close together on a contig,
1723    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
1724    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
1725    similar to B<A2>.
1726    
1727    The score of a coupling is determined by the number of pieces of evidence
1728    that are considered I<representative>. If several evidence items belong to
1729    a group of genomes that are close to each other, only one of those items
1730    is considered representative. The other evidence items are presumed to be
1731    there because of the relationship between the genomes rather than because
1732    the two proteins generated by the features have a related functionality.
1733    
1734    Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
1735    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
1736    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
1737    and FALSE otherwise.
1738    
1739    =over 4
1740    
1741    =item peg1
1742    
1743    ID of the feature of interest.
1744    
1745  C<< my @entityList = $sprout->GetEntityTypes(); >>  =item peg2
1746    
1747  Return the list of supported entity types.  ID of a feature functionally coupled to the feature of interest.
1748    
1749    =item RETURN
1750    
1751    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
1752    of interest, a feature similar to the functionally coupled feature, and a flag
1753    that is TRUE for a representative piece of evidence and FALSE otherwise.
1754    
1755    =back
1756    
1757  =cut  =cut
1758  #: Return Type @;  #: Return Type @@;
1759  sub GetEntityTypes {  sub CouplingEvidence {
1760          # Get the parameters.          # Get the parameters.
1761          my ($self) = @_;      my ($self, $peg1, $peg2) = @_;
1762          # Get the underlying database object.      # Declare the return variable.
1763          my $erdb = $self->{_erdb};      my @retVal = ();
1764          # Get its entity type list.      # Get the coupling and evidence data.
1765          my @retVal = $erdb->GetEntityTypes();      my @rawData = FIGRules::NetCouplingData('coupling_evidence', id1 => $peg1, id2 => $peg2);
1766        # Loop through the raw data, saving the ones that are in NMPDR genomes.
1767        for my $rawTuple (@rawData) {
1768            if ($self->_CheckFeature($rawTuple->[0]) && $self->_CheckFeature($rawTuple->[1])) {
1769                push @retVal, $rawTuple;
1770            }
1771        }
1772        # Return the result.
1773        return @retVal;
1774  }  }
1775    
1776  =head3 ReadFasta  =head3 GetSynonymGroup
1777    
1778  C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>      my $id = $sprout->GetSynonymGroup($fid);
1779    
1780  Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by  Return the synonym group name for the specified feature.
 one or more lines of data. The first line begins with a > character and contains an ID.  
 The remaining lines contain the sequence data in order.  
1781    
1782  =over 4  =over 4
1783    
1784  =item fileName  =item fid
   
 Name of the FASTA file.  
   
 =item prefix (optional)  
1785    
1786  Prefix to be put in front of each ID found.  ID of the feature whose synonym group is desired.
1787    
1788  =item RETURN  =item RETURN
1789    
1790  Returns a hash that maps each ID to its sequence.  The name of the synonym group to which the feature belongs. If the feature does
1791    not belong to a synonym group, the feature ID itself is returned.
1792    
1793  =back  =back
1794    
1795  =cut  =cut
1796  #: Return Type %;  
1797  sub ReadFasta {  sub GetSynonymGroup {
1798          # Get the parameters.          # Get the parameters.
1799          my ($fileName, $prefix) = @_;      my ($self, $fid) = @_;
1800          # Create the return hash.      # Declare the return variable.
1801          my %retVal = ();      my $retVal;
1802        # Find the synonym group.
1803        my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1804                                       [$fid], 'IsSynonymGroupFor(from-link)');
1805        # Check to see if we found anything.
1806        if (@groups) {
1807            $retVal = $groups[0];
1808        } else {
1809            $retVal = $fid;
1810        }
1811        # Return the result.
1812        return $retVal;
1813    }
1814    
1815    =head3 GetBoundaries
1816    
1817        my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList);
1818    
1819    Determine the begin and end boundaries for the locations in a list. All of the
1820    locations must belong to the same contig and have mostly the same direction in
1821    order for this method to produce a meaningful result. The resulting
1822    begin/end pair will contain all of the bases in any of the locations.
1823    
1824    =over 4
1825    
1826    =item locList
1827    
1828    List of locations to process.
1829    
1830    =item RETURN
1831    
1832    Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1833    and the ending boundary. The beginning boundary will be left of the
1834    end for mostly-forward locations and right of the end for mostly-backward
1835    locations.
1836    
1837    =back
1838    
1839    =cut
1840    
1841    sub GetBoundaries {
1842        # Get the parameters.
1843        my ($self, @locList) = @_;
1844        # Set up the counters used to determine the most popular direction.
1845        my %counts = ( '+' => 0, '-' => 0 );
1846        # Get the last location and parse it.
1847        my $locObject = BasicLocation->new(pop @locList);
1848        # Prime the loop with its data.
1849        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
1850        # Count its direction.
1851        $counts{$locObject->Dir}++;
1852        # Loop through the remaining locations. Note that in most situations, this loop
1853        # will not iterate at all, because most of the time we will be dealing with a
1854        # singleton list.
1855        for my $loc (@locList) {
1856            # Create a location object.
1857            my $locObject = BasicLocation->new($loc);
1858            # Count the direction.
1859            $counts{$locObject->Dir}++;
1860            # Get the left end and the right end.
1861            my $left = $locObject->Left;
1862            my $right = $locObject->Right;
1863            # Merge them into the return variables.
1864            if ($left < $beg) {
1865                $beg = $left;
1866            }
1867            if ($right > $end) {
1868                $end = $right;
1869            }
1870        }
1871        # If the most common direction is reverse, flip the begin and end markers.
1872        if ($counts{'-'} > $counts{'+'}) {
1873            ($beg, $end) = ($end, $beg);
1874        }
1875        # Return the result.
1876        return ($contig, $beg, $end);
1877    }
1878    
1879    =head3 ReadFasta
1880    
1881        my %sequenceData = Sprout::ReadFasta($fileName, $prefix);
1882    
1883    Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by
1884    one or more lines of data. The first line begins with a > character and contains an ID.
1885    The remaining lines contain the sequence data in order.
1886    
1887    =over 4
1888    
1889    =item fileName
1890    
1891    Name of the FASTA file.
1892    
1893    =item prefix (optional)
1894    
1895    Prefix to be put in front of each ID found.
1896    
1897    =item RETURN
1898    
1899    Returns a hash that maps each ID to its sequence.
1900    
1901    =back
1902    
1903    =cut
1904    #: Return Type %;
1905    sub ReadFasta {
1906        # Get the parameters.
1907        my ($fileName, $prefix) = @_;
1908        # Create the return hash.
1909        my %retVal = ();
1910          # Open the file for input.          # Open the file for input.
1911          open FASTAFILE, '<', $fileName;          open FASTAFILE, '<', $fileName;
1912          # Declare the ID variable and clear the sequence accumulator.          # Declare the ID variable and clear the sequence accumulator.
# Line 1447  Line 1920 
1920                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
1921                          # 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.
1922                          if ($id) {                          if ($id) {
1923                                  $retVal{$id} = $sequence;                  $retVal{$id} = lc $sequence;
1924                          }                          }
1925                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
1926                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
1927                  } else {                  } else {
1928                          # 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.
1929                          # First, we get the actual data out.              # First, we get the actual data out. Note that we normalize to lower
1930                # case.
1931                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
1932                          $sequence .= $1;                          $sequence .= $1;
1933                  }                  }
1934          }          }
1935          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
1936          if ($sequence) {          if ($sequence) {
1937                  $retVal {$id} = $sequence;          $retVal{$id} = lc $sequence;
1938          }          }
1939        # Close the file.
1940        close FASTAFILE;
1941          # Return the hash constructed from the file.          # Return the hash constructed from the file.
1942          return %retVal;          return %retVal;
1943  }  }
1944    
1945  =head3 FormatLocations  =head3 FormatLocations
1946    
1947  C<< my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat); >>      my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat);
1948    
1949  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
1950  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
# Line 1533  Line 2009 
2009    
2010  =head3 DumpData  =head3 DumpData
2011    
2012  C<< $sprout->DumpData(); >>      $sprout->DumpData();
2013    
2014  Dump all the tables to tab-delimited DTX files. The files will be stored in the data directory.  Dump all the tables to tab-delimited DTX files. The files will be stored in the data directory.
2015    
# Line 1545  Line 2021 
2021          # Get the data directory name.          # Get the data directory name.
2022          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
2023          # Dump the relations.          # Dump the relations.
2024          $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2025  }  }
2026    
2027  =head3 XMLFileName  =head3 XMLFileName
2028    
2029  C<< my $fileName = $sprout->XMLFileName(); >>      my $fileName = $sprout->XMLFileName();
2030    
2031  Return the name of this database's XML definition file.  Return the name of this database's XML definition file.
2032    
# Line 1561  Line 2037 
2037          return $self->{_xmlName};          return $self->{_xmlName};
2038  }  }
2039    
2040    =head3 GetGenomeNameData
2041    
2042        my ($genus, $species, $strain) = $sprout->GenomeNameData($genomeID);
2043    
2044    Return the genus, species, and unique characterization for a genome. This
2045    is similar to L</GenusSpecies>, with the exception that it returns the
2046    values in three seperate fields.
2047    
2048    =over 4
2049    
2050    =item genomeID
2051    
2052    ID of the genome whose name data is desired.
2053    
2054    =item RETURN
2055    
2056    Returns a three-element list, consisting of the genus, species, and strain
2057    of the specified genome. If the genome is not found, an error occurs.
2058    
2059    =back
2060    
2061    =cut
2062    
2063    sub GetGenomeNameData {
2064        # Get the parameters.
2065        my ($self, $genomeID) = @_;
2066        # Get the desired values.
2067        my ($genus, $species, $strain) = $self->GetEntityValues('Genome', $genomeID =>
2068                                                                [qw(Genome(genus) Genome(species) Genome(unique-characterization))]);
2069        # Throw an error if they were not found.
2070        if (! defined $genus) {
2071            Confess("Genome $genomeID not found in database.");
2072        }
2073        # Return the results.
2074        return ($genus, $species, $strain);
2075    }
2076    
2077    =head3 GetGenomeByNameData
2078    
2079        my @genomes = $sprout->GetGenomeByNameData($genus, $species, $strain);
2080    
2081    Return a list of the IDs of the genomes with the specified genus,
2082    species, and strain. In almost every case, there will be either zero or
2083    one IDs returned; however, two or more IDs could be returned if there are
2084    multiple versions of the genome in the database.
2085    
2086    =over 4
2087    
2088    =item genus
2089    
2090    Genus of the desired genome.
2091    
2092    =item species
2093    
2094    Species of the desired genome.
2095    
2096    =item strain
2097    
2098    Strain (unique characterization) of the desired genome. This may be an empty
2099    string, in which case it is presumed that the desired genome has no strain
2100    specified.
2101    
2102    =item RETURN
2103    
2104    Returns a list of the IDs of the genomes having the specified genus, species, and
2105    strain.
2106    
2107    =back
2108    
2109    =cut
2110    
2111    sub GetGenomeByNameData {
2112        # Get the parameters.
2113        my ($self, $genus, $species, $strain) = @_;
2114        # Try to find the genomes.
2115        my @retVal = $self->GetFlat(['Genome'], "Genome(genus) = ? AND Genome(species) = ? AND Genome(unique-characterization) = ?",
2116                                    [$genus, $species, $strain], 'Genome(id)');
2117        # Return the result.
2118        return @retVal;
2119    }
2120    
2121  =head3 Insert  =head3 Insert
2122    
2123  C<< $sprout->Insert($objectType, \%fieldHash); >>      $sprout->Insert($objectType, \%fieldHash);
2124    
2125  Insert an entity or relationship instance into the database. The entity or relationship of interest  Insert an entity or relationship instance into the database. The entity or relationship of interest
2126  is defined by a type name and then a hash of field names to values. Field values in the primary  is defined by a type name and then a hash of field names to values. Field values in the primary
# Line 1572  Line 2129 
2129  list references. For example, the following line inserts an inactive PEG feature named  list references. For example, the following line inserts an inactive PEG feature named
2130  C<fig|188.1.peg.1> with aliases C<ZP_00210270.1> and C<gi|46206278>.  C<fig|188.1.peg.1> with aliases C<ZP_00210270.1> and C<gi|46206278>.
2131    
2132  C<< $sprout->Insert('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >>      $sprout->Insert('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']});
2133    
2134  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
2135  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>.
2136    
2137  C<< $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence = 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>      $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'});
2138    
2139  =over 4  =over 4
2140    
# Line 1597  Line 2154 
2154          # Get the parameters.          # Get the parameters.
2155          my ($self, $objectType, $fieldHash) = @_;          my ($self, $objectType, $fieldHash) = @_;
2156          # Call the underlying method.          # Call the underlying method.
2157          $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2158  }  }
2159    
2160  =head3 Annotate  =head3 Annotate
2161    
2162  C<< my $ok = $sprout->Annotate($fid, $timestamp, $user, $text); >>      my $ok = $sprout->Annotate($fid, $timestamp, $user, $text);
2163    
2164  Annotate a feature. This inserts an Annotation record into the database and links it to the  Annotate a feature. This inserts an Annotation record into the database and links it to the
2165  specified feature and user.  specified feature and user.
# Line 1656  Line 2213 
2213    
2214  =head3 AssignFunction  =head3 AssignFunction
2215    
2216  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>      my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser);
2217    
2218  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
2219  format is described in L</ParseAssignment>.  format is described in L</ParseAssignment>.
# Line 1716  Line 2273 
2273    
2274  =head3 FeaturesByAlias  =head3 FeaturesByAlias
2275    
2276  C<< my @features = $sprout->FeaturesByAlias($alias); >>      my @features = $sprout->FeaturesByAlias($alias);
2277    
2278  Returns a list of features with the specified alias. The alias is parsed to determine  Returns a list of features with the specified alias. The alias is parsed to determine
2279  the type of the alias. A string of digits is a GenBack ID and a string of exactly 6  the type of the alias. A string of digits is a GenBack ID and a string of exactly 6
# Line 1750  Line 2307 
2307                  push @retVal, $mappedAlias;                  push @retVal, $mappedAlias;
2308          } else {          } else {
2309                  # 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.
2310                  @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');          @retVal = $self->GetFlat(['IsAliasOf'], 'IsAliasOf(from-link) = ?', [$mappedAlias], 'IsAliasOf(to-link)');
2311          }          }
2312          # Return the result.          # Return the result.
2313          return @retVal;          return @retVal;
2314  }  }
2315    
 =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, $entityName, $entityID) = @_;  
         # Check for the entity instance.  
         my $testInstance = $self->GetEntity($entityName, $entityID);  
         # Return an existence indicator.  
         my $retVal = ($testInstance ? 1 : 0);  
         return $retVal;  
 }  
   
2316  =head3 FeatureTranslation  =head3 FeatureTranslation
2317    
2318  C<< my $translation = $sprout->FeatureTranslation($featureID); >>      my $translation = $sprout->FeatureTranslation($featureID);
2319    
2320  Return the translation of a feature.  Return the translation of a feature.
2321    
# Line 1820  Line 2343 
2343    
2344  =head3 Taxonomy  =head3 Taxonomy
2345    
2346  C<< my @taxonomyList = $sprout->Taxonomy($genome); >>      my @taxonomyList = $sprout->Taxonomy($genome);
2347    
2348  Return the taxonomy of the specified genome. This will be in the form of a list  Return the taxonomy of the specified genome. This will be in the form of a list
2349  containing the various classifications in order from domain (eg. C<Bacteria>, C<Archaea>,  containing the various classifications in order from domain (eg. C<Bacteria>, C<Archaea>,
2350  or C<Eukaryote>) to sub-species. For example,  or C<Eukaryote>) to sub-species. For example,
2351    
2352  C<< (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12) >>      (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12)
2353    
2354  =over 4  =over 4
2355    
# Line 1861  Line 2384 
2384    
2385  =head3 CrudeDistance  =head3 CrudeDistance
2386    
2387  C<< my $distance = $sprout->CrudeDistance($genome1, $genome2); >>      my $distance = $sprout->CrudeDistance($genome1, $genome2);
2388    
2389  Returns a crude estimate of the distance between two genomes. The distance is construed so  Returns a crude estimate of the distance between two genomes. The distance is construed so
2390  that it will be 0 for genomes with identical taxonomies and 1 for genomes from different domains.  that it will be 0 for genomes with identical taxonomies and 1 for genomes from different domains.
# Line 1913  Line 2436 
2436    
2437  =head3 RoleName  =head3 RoleName
2438    
2439  C<< my $roleName = $sprout->RoleName($roleID); >>      my $roleName = $sprout->RoleName($roleID);
2440    
2441  Return the descriptive name of the role with the specified ID. In general, a role  Return the descriptive name of the role with the specified ID. In general, a role
2442  will only have a descriptive name if it is coded as an EC number.  will only have a descriptive name if it is coded as an EC number.
# Line 1947  Line 2470 
2470    
2471  =head3 RoleDiagrams  =head3 RoleDiagrams
2472    
2473  C<< my @diagrams = $sprout->RoleDiagrams($roleID); >>      my @diagrams = $sprout->RoleDiagrams($roleID);
2474    
2475  Return a list of the diagrams containing a specified functional role.  Return a list of the diagrams containing a specified functional role.
2476    
# Line 1975  Line 2498 
2498          return @retVal;          return @retVal;
2499  }  }
2500    
2501    =head3 GetProperties
2502    
2503        my @list = $sprout->GetProperties($fid, $key, $value, $url);
2504    
2505    Return a list of the properties with the specified characteristics.
2506    
2507    Properties are the Sprout analog of the FIG attributes. The call is
2508    passed directly to the CustomAttributes or RemoteCustomAttributes object
2509    contained in this object.
2510    
2511    This method returns a series of tuples that match the specified criteria. Each tuple
2512    will contain an object ID, a key, and one or more values. The parameters to this
2513    method therefore correspond structurally to the values expected in each tuple. In
2514    addition, you can ask for a generic search by suffixing a percent sign (C<%>) to any
2515    of the parameters. So, for example,
2516    
2517        my @attributeList = $sprout->GetProperties('fig|100226.1.peg.1004', 'structure%', 1, 2);
2518    
2519    would return something like
2520    
2521        ['fig}100226.1.peg.1004', 'structure', 1, 2]
2522        ['fig}100226.1.peg.1004', 'structure1', 1, 2]
2523        ['fig}100226.1.peg.1004', 'structure2', 1, 2]
2524        ['fig}100226.1.peg.1004', 'structureA', 1, 2]
2525    
2526    Use of C<undef> in any position acts as a wild card (all values). You can also specify
2527    a list reference in the ID column. Thus,
2528    
2529        my @attributeList = $sprout->GetProperties(['100226.1', 'fig|100226.1.%'], 'PUBMED');
2530    
2531    would get the PUBMED attribute data for Streptomyces coelicolor A3(2) and all its
2532    features.
2533    
2534    In addition to values in multiple sections, a single attribute key can have multiple
2535    values, so even
2536    
2537        my @attributeList = $sprout->GetProperties($peg, 'virulent');
2538    
2539    which has no wildcard in the key or the object ID, may return multiple tuples.
2540    
2541    =over 4
2542    
2543    =item objectID
2544    
2545    ID of object whose attributes are desired. If the attributes are desired for multiple
2546    objects, this parameter can be specified as a list reference. If the attributes are
2547    desired for all objects, specify C<undef> or an empty string. Finally, you can specify
2548    attributes for a range of object IDs by putting a percent sign (C<%>) at the end.
2549    
2550    =item key
2551    
2552    Attribute key name. A value of C<undef> or an empty string will match all
2553    attribute keys. If the values are desired for multiple keys, this parameter can be
2554    specified as a list reference. Finally, you can specify attributes for a range of
2555    keys by putting a percent sign (C<%>) at the end.
2556    
2557    =item values
2558    
2559    List of the desired attribute values, section by section. If C<undef>
2560    or an empty string is specified, all values in that section will match. A
2561    generic match can be requested by placing a percent sign (C<%>) at the end.
2562    In that case, all values that match up to and not including the percent sign
2563    will match. You may also specify a regular expression enclosed
2564    in slashes. All values that match the regular expression will be returned. For
2565    performance reasons, only values have this extra capability.
2566    
2567    =item RETURN
2568    
2569    Returns a list of tuples. The first element in the tuple is an object ID, the
2570    second is an attribute key, and the remaining elements are the sections of
2571    the attribute value. All of the tuples will match the criteria set forth in
2572    the parameter list.
2573    
2574    =back
2575    
2576    =cut
2577    
2578    sub GetProperties {
2579        # Get the parameters.
2580        my ($self, @parms) = @_;
2581        # Declare the return variable.
2582        my @retVal = $self->{_ca}->GetAttributes(@parms);
2583        # Return the result.
2584        return @retVal;
2585    }
2586    
2587  =head3 FeatureProperties  =head3 FeatureProperties
2588    
2589  C<< my @properties = $sprout->FeatureProperties($featureID); >>      my @properties = $sprout->FeatureProperties($featureID);
2590    
2591  Return a list of the properties for the specified feature. Properties are key-value pairs  Return a list of the properties for the specified feature. Properties are key-value pairs
2592  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
2593  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
2594  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
2595  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.  
2596    
2597  =over 4  =over 4
2598    
# Line 1995  Line 2602 
2602    
2603  =item RETURN  =item RETURN
2604    
2605  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.  
2606    
2607  =back  =back
2608    
# Line 2006  Line 2612 
2612          # Get the parameters.          # Get the parameters.
2613          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
2614          # Get the properties.          # Get the properties.
2615          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],      my @attributes = $self->{_ca}->GetAttributes($featureID);
2616                                                          ['Property(property-name)', 'Property(property-value)',      # Strip the feature ID off each tuple.
2617                                                           'HasProperty(evidence)']);      my @retVal = ();
2618        for my $attributeRow (@attributes) {
2619            shift @{$attributeRow};
2620            push @retVal, $attributeRow;
2621        }
2622          # Return the resulting list.          # Return the resulting list.
2623          return @retVal;          return @retVal;
2624  }  }
2625    
2626  =head3 DiagramName  =head3 DiagramName
2627    
2628  C<< my $diagramName = $sprout->DiagramName($diagramID); >>      my $diagramName = $sprout->DiagramName($diagramID);
2629    
2630  Return the descriptive name of a diagram.  Return the descriptive name of a diagram.
2631    
# Line 2041  Line 2651 
2651          return $retVal;          return $retVal;
2652  }  }
2653    
2654    =head3 PropertyID
2655    
2656        my $id = $sprout->PropertyID($propName, $propValue);
2657    
2658    Return the ID of the specified property name and value pair, if the
2659    pair exists. Only a small subset of the FIG attributes are stored as
2660    Sprout properties, mostly for use in search optimization.
2661    
2662    =over 4
2663    
2664    =item propName
2665    
2666    Name of the desired property.
2667    
2668    =item propValue
2669    
2670    Value expected for the desired property.
2671    
2672    =item RETURN
2673    
2674    Returns the ID of the name/value pair, or C<undef> if the pair does not exist.
2675    
2676    =back
2677    
2678    =cut
2679    
2680    sub PropertyID {
2681        # Get the parameters.
2682        my ($self, $propName, $propValue) = @_;
2683        # Try to find the ID.
2684        my ($retVal) = $self->GetFlat(['Property'],
2685                                      "Property(property-name) = ? AND Property(property-value) = ?",
2686                                      [$propName, $propValue], 'Property(id)');
2687        # Return the result.
2688        return $retVal;
2689    }
2690    
2691  =head3 MergedAnnotations  =head3 MergedAnnotations
2692    
2693  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>      my @annotationList = $sprout->MergedAnnotations(\@list);
2694    
2695  Returns a merged list of the annotations for the features in a list. Each annotation is  Returns a merged list of the annotations for the features in a list. Each annotation is
2696  represented by a 4-tuple of the form C<($fid, $timestamp, $userID, $annotation)>, where  represented by a 4-tuple of the form C<($fid, $timestamp, $userID, $annotation)>, where
# Line 2092  Line 2739 
2739    
2740  =head3 RoleNeighbors  =head3 RoleNeighbors
2741    
2742  C<< my @roleList = $sprout->RoleNeighbors($roleID); >>      my @roleList = $sprout->RoleNeighbors($roleID);
2743    
2744  Returns a list of the roles that occur in the same diagram as the specified role. Because  Returns a list of the roles that occur in the same diagram as the specified role. Because
2745  diagrams and roles are in a many-to-many relationship with each other, the list is  diagrams and roles are in a many-to-many relationship with each other, the list is
# Line 2135  Line 2782 
2782    
2783  =head3 FeatureLinks  =head3 FeatureLinks
2784    
2785  C<< my @links = $sprout->FeatureLinks($featureID); >>      my @links = $sprout->FeatureLinks($featureID);
2786    
2787  Return a list of the web hyperlinks associated with a feature. The web hyperlinks are  Return a list of the web hyperlinks associated with a feature. The web hyperlinks are
2788  to external websites describing either the feature itself or the organism containing it  to external websites describing either the feature itself or the organism containing it
# Line 2166  Line 2813 
2813    
2814  =head3 SubsystemsOf  =head3 SubsystemsOf
2815    
2816  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>      my %subsystems = $sprout->SubsystemsOf($featureID);
2817    
2818  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
2819  to the role the feature performs.  to the roles the feature performs.
2820    
2821  =over 4  =over 4
2822    
# Line 2179  Line 2826 
2826    
2827  =item RETURN  =item RETURN
2828    
2829  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.
2830    
2831  =back  =back
2832    
2833  =cut  =cut
2834  #: Return Type %;  #: Return Type %@;
2835  sub SubsystemsOf {  sub SubsystemsOf {
2836          # Get the parameters.          # Get the parameters.
2837          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
2838          # Use the SSCell to connect features to subsystems.      # Get the subsystem list.
2839          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
2840                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
2841                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2842          # Create the return value.          # Create the return value.
2843          my %retVal = ();          my %retVal = ();
2844        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2845        # in two spreadsheet cells.
2846        my %dupHash = ();
2847          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
2848          for my $record (@subsystems) {          for my $record (@subsystems) {
2849                  $retVal{$record->[0]} = $record->[1];          # Get this subsystem and role.
2850            my ($subsys, $role) = @{$record};
2851            # Insure it's the first time for both.
2852            my $dupKey = "$subsys\n$role";
2853            if (! exists $dupHash{"$subsys\n$role"}) {
2854                $dupHash{$dupKey} = 1;
2855                push @{$retVal{$subsys}}, $role;
2856            }
2857          }          }
2858          # Return the hash.          # Return the hash.
2859          return %retVal;          return %retVal;
2860  }  }
2861    
2862    =head3 SubsystemList
2863    
2864        my @subsystems = $sprout->SubsystemList($featureID);
2865    
2866    Return a list containing the names of the subsystems in which the specified
2867    feature participates. Unlike L</SubsystemsOf>, this method only returns the
2868    subsystem names, not the roles.
2869    
2870    =over 4
2871    
2872    =item featureID
2873    
2874    ID of the feature whose subsystem names are desired.
2875    
2876    =item RETURN
2877    
2878    Returns a list of the names of the subsystems in which the feature participates.
2879    
2880    =back
2881    
2882    =cut
2883    #: Return Type @;
2884    sub SubsystemList {
2885        # Get the parameters.
2886        my ($self, $featureID) = @_;
2887        # Get the list of names.
2888        my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?",
2889                                    [$featureID], 'HasRoleInSubsystem(to-link)');
2890        # Return the result, sorted.
2891        return sort @retVal;
2892    }
2893    
2894    =head3 GenomeSubsystemData
2895    
2896        my %featureData = $sprout->GenomeSubsystemData($genomeID);
2897    
2898    Return a hash mapping genome features to their subsystem roles.
2899    
2900    =over 4
2901    
2902    =item genomeID
2903    
2904    ID of the genome whose subsystem feature map is desired.
2905    
2906    =item RETURN
2907    
2908    Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb
2909    2-tuple contains a subsystem name followed by a role ID.
2910    
2911    =back
2912    
2913    =cut
2914    
2915    sub GenomeSubsystemData {
2916        # Get the parameters.
2917        my ($self, $genomeID) = @_;
2918        # Declare the return variable.
2919        my %retVal = ();
2920        # Get a list of the genome features that participate in subsystems. For each
2921        # feature we get its spreadsheet cells and the corresponding roles.
2922        my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],
2923                                 "HasFeature(from-link) = ?", [$genomeID],
2924                                 ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);
2925        # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems
2926        # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the
2927        # list. We use it at the beginning to get all the spreadsheet cells for the genome and
2928        # again at the end to filter out participation in subsystems with a negative variant code.
2929        my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],
2930                                     "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?",
2931                                     [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']);
2932        # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features.
2933        # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We
2934        # link these two lists together to create the result. First, we want a hash mapping
2935        # spreadsheet cells to subsystem names.
2936        my %subHash = map { $_->[0] => $_->[1] } @cellData;
2937        # We loop through @cellData to build the hash.
2938        for my $roleEntry (@roleData) {
2939            # Get the data for this feature and cell.
2940            my ($fid, $cellID, $role) = @{$roleEntry};
2941            # Check for a subsystem name.
2942            my $subsys = $subHash{$cellID};
2943            if ($subsys) {
2944                # Insure this feature has an entry in the return hash.
2945                if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
2946                # Merge in this new data.
2947                push @{$retVal{$fid}}, [$subsys, $role];
2948            }
2949        }
2950        # Return the result.
2951        return %retVal;
2952    }
2953    
2954  =head3 RelatedFeatures  =head3 RelatedFeatures
2955    
2956  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>      my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID);
2957    
2958  Return a list of the features which are bi-directional best hits of the specified feature and  Return a list of the features which are bi-directional best hits of the specified feature and
2959  have been assigned the specified function by the specified user. If no such features exists,  have been assigned the specified function by the specified user. If no such features exists,
# Line 2237  Line 2986 
2986          # Get the parameters.          # Get the parameters.
2987          my ($self, $featureID, $function, $userID) = @_;          my ($self, $featureID, $function, $userID) = @_;
2988          # 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.
2989          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
                                                                          "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],  
                                                                          'IsBidirectionalBestHitOf(to-link)');  
2990          # 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
2991          # functional assignment.          # functional assignment.
2992          my @retVal = ();          my @retVal = ();
# Line 2257  Line 3004 
3004    
3005  =head3 TaxonomySort  =head3 TaxonomySort
3006    
3007  C<< my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs); >>      my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs);
3008    
3009  Return a list formed by sorting the specified features by the taxonomy of the containing  Return a list formed by sorting the specified features by the taxonomy of the containing
3010  genome. This will cause genomes from similar organisms to float close to each other.  genome. This will cause genomes from similar organisms to float close to each other.
# Line 2303  Line 3050 
3050          return @retVal;          return @retVal;
3051  }  }
3052    
3053  =head3 GetAll  =head3 Protein
   
 C<< my @list = $sprout->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>  
   
 Return a list of values taken from the objects returned by a query. The first three  
 parameters correspond to the parameters of the L</Get> method. The final parameter is  
 a list of the fields desired from each record found by the query. The field name  
 syntax is the standard syntax used for fields in the B<ERDB> system--  
 B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity  
 or relationship and I<fieldName> is the name of the field.  
3054    
3055  The list returned will be a list of lists. Each element of the list will contain      my $protein = Sprout::Protein($sequence, $table);
 the values returned for the fields specified in the fourth parameter. If one of the  
 fields specified returns multiple values, they are flattened in with the rest. For  
 example, the following call will return a list of the features in a particular  
 spreadsheet cell, and each feature will be represented by a list containing the  
 feature ID followed by all of its aliases.  
3056    
3057  C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>  Translate a DNA sequence into a protein sequence.
3058    
3059  =over 4  =over 4
3060    
3061  =item objectNames  =item sequence
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item fields  
3062    
3063  List of the fields to be returned in each element of the list returned.  DNA sequence to translate.
3064    
3065  =item count  =item table (optional)
3066    
3067  Maximum number of records to return. If omitted or 0, all available records will be returned.  Reference to a Hash that translates DNA triples to proteins. A triple that does not
3068    appear in the hash will be translated automatically to C<X>.
3069    
3070  =item RETURN  =item RETURN
3071    
3072  Returns a list of list references. Each element of the return list contains the values for the  Returns the protein sequence that would be created by the DNA sequence.
 fields specified in the B<fields> parameter.  
   
 =back  
   
 =cut  
 #: Return Type @@;  
 sub GetAll {  
         # Get the parameters.  
         my ($self, $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, $objectNames, $filterClause, $parameterList, $field) = @_;  
         # Construct the query.  
         my $query = $self->Get($objectNames, $filterClause, $parameterList);  
         # Create the result list.  
         my @retVal = ();  
         # Loop through the records, adding the field values found to the result list.  
         while (my $row = $query->Fetch()) {  
                 push @retVal, $row->Value($field);  
         }  
         # Return the list created.  
         return @retVal;  
 }  
   
 =head3 Protein  
   
 C<< my $protein = Sprout::Protein($sequence, $table); >>  
   
 Translate a DNA sequence into a protein sequence.  
   
 =over 4  
   
 =item sequence  
   
 DNA sequence to translate.  
   
 =item table (optional)  
   
 Reference to a Hash that translates DNA triples to proteins. A triple that does not  
 appear in the hash will be translated automatically to C<X>.  
   
 =item RETURN  
   
 Returns the protein sequence that would be created by the DNA sequence.  
3073    
3074  =back  =back
3075    
# Line 2507  Line 3122 
3122          # Loop through the input triples.          # Loop through the input triples.
3123          my $n = length $sequence;          my $n = length $sequence;
3124          for (my $i = 0; $i < $n; $i += 3) {          for (my $i = 0; $i < $n; $i += 3) {
3125                  # Get the current triple from the sequence.          # Get the current triple from the sequence. Note we convert to
3126                  my $triple = substr($sequence, $i, 3);          # upper case to insure a match.
3127            my $triple = uc substr($sequence, $i, 3);
3128                  # Translate it using the table.                  # Translate it using the table.
3129                  my $protein = "X";                  my $protein = "X";
3130                  if (exists $table->{$triple}) { $protein = $table->{$triple}; }                  if (exists $table->{$triple}) { $protein = $table->{$triple}; }
# Line 2522  Line 3138 
3138    
3139  =head3 LoadInfo  =head3 LoadInfo
3140    
3141  C<< my ($dirName, @relNames) = $sprout->LoadInfo(); >>      my ($dirName, @relNames) = $sprout->LoadInfo();
3142    
3143  Return the name of the directory from which data is to be loaded and a list of the relation  Return the name of the directory from which data is to be loaded and a list of the relation
3144  names. This information is useful when trying to analyze what needs to be put where in order  names. This information is useful when trying to analyze what needs to be put where in order
# Line 2536  Line 3152 
3152          # 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.
3153          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
3154          # Concatenate the table names.          # Concatenate the table names.
3155          push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
3156          # Return the result.          # Return the result.
3157          return @retVal;          return @retVal;
3158  }  }
3159    
3160    =head3 BBHMatrix
3161    
3162        my %bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets);
3163    
3164    Find all the bidirectional best hits for the features of a genome in a
3165    specified list of target genomes. The return value will be a hash mapping
3166    features in the original genome to their bidirectional best hits in the
3167    target genomes.
3168    
3169    =over 4
3170    
3171    =item genomeID
3172    
3173    ID of the genome whose features are to be examined for bidirectional best hits.
3174    
3175    =item cutoff
3176    
3177    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3178    
3179    =item targets
3180    
3181    List of target genomes. Only pairs originating in the original
3182    genome and landing in one of the target genomes will be returned.
3183    
3184    =item RETURN
3185    
3186    Returns a hash mapping each feature in the original genome to a hash mapping its
3187    BBH pegs in the target genomes to their scores.
3188    
3189    =back
3190    
3191    =cut
3192    
3193    sub BBHMatrix {
3194        # Get the parameters.
3195        my ($self, $genomeID, $cutoff, @targets) = @_;
3196        # Declare the return variable.
3197        my %retVal = ();
3198        # Ask for the BBHs.
3199        my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets);
3200        # We now have a set of 4-tuples that we need to convert into a hash of hashes.
3201        for my $bbhData (@bbhList) {
3202            my ($peg1, $peg2, $score) = @{$bbhData};
3203            if (! exists $retVal{$peg1}) {
3204                $retVal{$peg1} = { $peg2 => $score };
3205            } else {
3206                $retVal{$peg1}->{$peg2} = $score;
3207            }
3208        }
3209        # Return the result.
3210        return %retVal;
3211    }
3212    
3213    
3214    =head3 SimMatrix
3215    
3216        my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets);
3217    
3218    Find all the similarities for the features of a genome in a
3219    specified list of target genomes. The return value will be a hash mapping
3220    features in the original genome to their similarites in the
3221    target genomes.
3222    
3223    =over 4
3224    
3225    =item genomeID
3226    
3227    ID of the genome whose features are to be examined for similarities.
3228    
3229    =item cutoff
3230    
3231    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3232    
3233    =item targets
3234    
3235    List of target genomes. Only pairs originating in the original
3236    genome and landing in one of the target genomes will be returned.
3237    
3238    =item RETURN
3239    
3240    Returns a hash mapping each feature in the original genome to a hash mapping its
3241    similar pegs in the target genomes to their scores.
3242    
3243    =back
3244    
3245    =cut
3246    
3247    sub SimMatrix {
3248        # Get the parameters.
3249        my ($self, $genomeID, $cutoff, @targets) = @_;
3250        # Declare the return variable.
3251        my %retVal = ();
3252        # Get the list of features in the source organism.
3253        my @fids = $self->FeaturesOf($genomeID);
3254        # Ask for the sims. We only want similarities to fig features.
3255        my $simList = FIGRules::GetNetworkSims($self, \@fids, {}, 1000, $cutoff, "fig");
3256        if (! defined $simList) {
3257            Confess("Unable to retrieve similarities from server.");
3258        } else {
3259            Trace("Processing sims.") if T(3);
3260            # We now have a set of sims that we need to convert into a hash of hashes. First, we
3261            # Create a hash for the target genomes.
3262            my %targetHash = map { $_ => 1 } @targets;
3263            for my $simData (@{$simList}) {
3264                # Get the PEGs and the score.
3265                my ($peg1, $peg2, $score) = ($simData->id1, $simData->id2, $simData->psc);
3266                # Insure the second ID is in the target list.
3267                my ($genome2) = FIGRules::ParseFeatureID($peg2);
3268                if (exists $targetHash{$genome2}) {
3269                    # Here it is. Now we need to add it to the return hash. How we do that depends
3270                    # on whether or not $peg1 is new to us.
3271                    if (! exists $retVal{$peg1}) {
3272                        $retVal{$peg1} = { $peg2 => $score };
3273                    } else {
3274                        $retVal{$peg1}->{$peg2} = $score;
3275                    }
3276                }
3277            }
3278        }
3279        # Return the result.
3280        return %retVal;
3281    }
3282    
3283    
3284  =head3 LowBBHs  =head3 LowBBHs
3285    
3286  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>      my %bbhMap = $sprout->LowBBHs($featureID, $cutoff);
3287    
3288  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
3289  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 2572  Line 3312 
3312          my ($self, $featureID, $cutoff) = @_;          my ($self, $featureID, $cutoff) = @_;
3313          # Create the return hash.          # Create the return hash.
3314          my %retVal = ();          my %retVal = ();
3315          # Create a query to get the desired BBHs.      # Query for the desired BBHs.
3316          my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BBHData($featureID, $cutoff);
                                                                 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',  
                                                                 [$cutoff, $featureID],  
                                                                 ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);  
3317          # Form the results into the return hash.          # Form the results into the return hash.
3318          for my $pair (@bbhList) {          for my $pair (@bbhList) {
3319                  $retVal{$pair->[0]} = $pair->[1];          my $fid = $pair->[0];
3320            if ($self->Exists('Feature', $fid)) {
3321                $retVal{$fid} = $pair->[1];
3322            }
3323          }          }
3324          # Return the result.          # Return the result.
3325          return %retVal;          return %retVal;
3326  }  }
3327    
3328    =head3 Sims
3329    
3330        my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters);
3331    
3332    Get a list of similarities for a specified feature. Similarity information is not kept in the
3333    Sprout database; rather, they are retrieved from a network server. The similarities are
3334    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3335    so that its elements can be accessed by name.
3336    
3337    Similarities can be either raw or expanded. The raw similarities are basic
3338    hits between features with similar DNA. Expanding a raw similarity drags in any
3339    features considered substantially identical. So, for example, if features B<A1>,
3340    B<A2>, and B<A3> are all substantially identical to B<A>, then a raw similarity
3341    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3342    
3343    =over 4
3344    
3345    =item fid
3346    
3347    ID of the feature whose similarities are desired, or reference to a list of IDs
3348    of features whose similarities are desired.
3349    
3350    =item maxN
3351    
3352    Maximum number of similarities to return.
3353    
3354    =item maxP
3355    
3356    Minumum allowable similarity score.
3357    
3358    =item select
3359    
3360    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3361    means only similarities to FIG features are returned; C<all> means all expanded
3362    similarities are returned; and C<figx> means similarities are expanded until the
3363    number of FIG features equals the maximum.
3364    
3365    =item max_expand
3366    
3367    The maximum number of features to expand.
3368    
3369    =item filters
3370    
3371    Reference to a hash containing filter information, or a subroutine that can be
3372    used to filter the sims.
3373    
3374    =item RETURN
3375    
3376    Returns a reference to a list of similarity objects, or C<undef> if an error
3377    occurred.
3378    
3379    =back
3380    
3381    =cut
3382    
3383    sub Sims {
3384        # Get the parameters.
3385        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3386        # Create the shim object to test for deleted FIDs.
3387        my $shim = FidCheck->new($self);
3388        # Ask the network for sims.
3389        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3390        # Return the result.
3391        return $retVal;
3392    }
3393    
3394    =head3 IsAllGenomes
3395    
3396        my $flag = $sprout->IsAllGenomes(\@list, \@checkList);
3397    
3398    Return TRUE if all genomes in the second list are represented in the first list at
3399    least one. Otherwise, return FALSE. If the second list is omitted, the first list is
3400    compared to a list of all the genomes.
3401    
3402    =over 4
3403    
3404    =item list
3405    
3406    Reference to the list to be compared to the second list.
3407    
3408    =item checkList (optional)
3409    
3410    Reference to the comparison target list. Every genome ID in this list must occur at
3411    least once in the first list. If this parameter is omitted, a list of all the genomes
3412    is used.
3413    
3414    =item RETURN
3415    
3416    Returns TRUE if every item in the second list appears at least once in the
3417    first list, else FALSE.
3418    
3419    =back
3420    
3421    =cut
3422    
3423    sub IsAllGenomes {
3424        # Get the parameters.
3425        my ($self, $list, $checkList) = @_;
3426        # Supply the checklist if it was omitted.
3427        $checkList = [$self->Genomes()] if ! defined($checkList);
3428        # Create a hash of the original list.
3429        my %testList = map { $_ => 1 } @{$list};
3430        # Declare the return variable. We assume that the representation
3431        # is complete and stop at the first failure.
3432        my $retVal = 1;
3433        my $n = scalar @{$checkList};
3434        for (my $i = 0; $retVal && $i < $n; $i++) {
3435            if (! $testList{$checkList->[$i]}) {
3436                $retVal = 0;
3437            }
3438        }
3439        # Return the result.
3440        return $retVal;
3441    }
3442    
3443  =head3 GetGroups  =head3 GetGroups
3444    
3445  C<< my %groups = $sprout->GetGroups(\@groupList); >>      my %groups = $sprout->GetGroups(\@groupList);
3446    
3447  Return a hash mapping each group to the IDs of the genomes in the group.  Return a hash mapping each group to the IDs of the genomes in the group.
3448  A list of groups may be specified, in which case only those groups will be  A list of groups may be specified, in which case only those groups will be
# Line 2606  Line 3461 
3461          # Here we have a group list. Loop through them individually,          # Here we have a group list. Loop through them individually,
3462          # getting a list of the relevant genomes.          # getting a list of the relevant genomes.
3463          for my $group (@{$groupList}) {          for my $group (@{$groupList}) {
3464              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3465                  [$group], "Genome(id)");                  [$group], "Genome(id)");
3466              $retVal{$group} = \@genomeIDs;              $retVal{$group} = \@genomeIDs;
3467          }          }
# Line 2614  Line 3469 
3469          # Here we need all of the groups. In this case, we run through all          # Here we need all of the groups. In this case, we run through all
3470          # of the genome records, putting each one found into the appropriate          # of the genome records, putting each one found into the appropriate
3471          # group. Note that we use a filter clause to insure that only genomes          # group. Note that we use a filter clause to insure that only genomes
3472          # in groups are included in the return set.          # in real NMPDR groups are included in the return set.
3473          my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],          my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3474                                      ['Genome(id)', 'Genome(group-name)']);                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3475          # Loop through the genomes found.          # Loop through the genomes found.
3476          for my $genome (@genomes) {          for my $genome (@genomes) {
3477              # Pop this genome's ID off the current list.              # Get the genome ID and group, and add this genome to the group's list.
3478              my @groups = @{$genome};              my ($genomeID, $group) = @{$genome};
3479              my $genomeID = shift @groups;              push @{$retVal{$group}}, $genomeID;
             # Loop through the groups, adding the genome ID to each group's  
             # list.  
             for my $group (@groups) {  
                 Tracer::AddToListMap(\%retVal, $group, $genomeID);  
             }  
3480          }          }
3481      }      }
3482      # Return the hash we just built.      # Return the hash we just built.
3483      return %retVal;      return %retVal;
3484  }  }
3485    
3486    =head3 MyGenomes
3487    
3488        my @genomes = Sprout::MyGenomes($dataDir);
3489    
3490    Return a list of the genomes to be included in the Sprout.
3491    
3492    This method is provided for use during the Sprout load. It presumes the Genome load file has
3493    already been created. (It will be in the Sprout data directory and called either C<Genome>
3494    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3495    IDs.
3496    
3497    =over 4
3498    
3499    =item dataDir
3500    
3501    Directory containing the Sprout load files.
3502    
3503    =back
3504    
3505    =cut
3506    #: Return Type @;
3507    sub MyGenomes {
3508        # Get the parameters.
3509        my ($dataDir) = @_;
3510        # Compute the genome file name.
3511        my $genomeFileName = LoadFileName($dataDir, "Genome");
3512        # Extract the genome IDs from the files.
3513        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3514        # Return the result.
3515        return @retVal;
3516    }
3517    
3518    =head3 LoadFileName
3519    
3520        my $fileName = Sprout::LoadFileName($dataDir, $tableName);
3521    
3522    Return the name of the load file for the specified table in the specified data
3523    directory.
3524    
3525    =over 4
3526    
3527    =item dataDir
3528    
3529    Directory containing the Sprout load files.
3530    
3531    =item tableName
3532    
3533    Name of the table whose load file is desired.
3534    
3535    =item RETURN
3536    
3537    Returns the name of the file containing the load data for the specified table, or
3538    C<undef> if no load file is present.
3539    
3540    =back
3541    
3542    =cut
3543    #: Return Type $;
3544    sub LoadFileName {
3545        # Get the parameters.
3546        my ($dataDir, $tableName) = @_;
3547        # Declare the return variable.
3548        my $retVal;
3549        # Check for the various file names.
3550        if (-e "$dataDir/$tableName") {
3551            $retVal = "$dataDir/$tableName";
3552        } elsif (-e "$dataDir/$tableName.dtx") {
3553            $retVal = "$dataDir/$tableName.dtx";
3554        }
3555        # Return the result.
3556        return $retVal;
3557    }
3558    
3559    =head3 DeleteGenome
3560    
3561        my $stats = $sprout->DeleteGenome($genomeID, $testFlag);
3562    
3563    Delete a genome from the database.
3564    
3565    =over 4
3566    
3567    =item genomeID
3568    
3569    ID of the genome to delete
3570    
3571    =item testFlag
3572    
3573    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3574    
3575    =item RETURN
3576    
3577    Returns a statistics object describing the rows deleted.
3578    
3579    =back
3580    
3581    =cut
3582    #: Return Type $%;
3583    sub DeleteGenome {
3584        # Get the parameters.
3585        my ($self, $genomeID, $testFlag) = @_;
3586        # Perform the delete for the genome's features.
3587        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", testMode => $testFlag);
3588        # Perform the delete for the primary genome data.
3589        my $stats = $self->Delete('Genome', $genomeID, testMode => $testFlag);
3590        $retVal->Accumulate($stats);
3591        # Return the result.
3592        return $retVal;
3593    }
3594    
3595    =head3 Fix
3596    
3597        my %fixedHash = $sprout->Fix(%groupHash);
3598    
3599    Prepare a genome group hash (like that returned by L</GetGroups>) for processing.
3600    The groups will be combined into the appropriate super-groups.
3601    
3602    =over 4
3603    
3604    =item groupHash
3605    
3606    Hash to be fixed up.
3607    
3608    =item RETURN
3609    
3610    Returns a fixed-up version of the hash.
3611    
3612    =back
3613    
3614    =cut
3615    
3616    sub Fix {
3617        # Get the parameters.
3618        my ($self, %groupHash) = @_;
3619        # Create the result hash.
3620        my %retVal = ();
3621        # Get the super-group table.
3622        my %superTable = $self->CheckGroupFile();
3623        # Copy over the genomes.
3624        for my $groupID (keys %groupHash) {
3625            # Get the super-group name.
3626            my $realGroupID;
3627            if ($groupID =~ /([A-Z]\w+)/) {
3628                if (! defined($superTable{$1})) {
3629                    Confess("Super-group name not found for group $groupID.");
3630                } else {
3631                    $realGroupID = $1;
3632                }
3633            } else {
3634                Confess("Invalid group name $groupID.");
3635            }
3636            # Append this group's genomes into the result hash.
3637            push @{$retVal{$realGroupID}}, @{$groupHash{$groupID}};
3638        }
3639        # Return the result hash.
3640        return %retVal;
3641    }
3642    
3643    =head3 GroupPageName
3644    
3645        my $name = $sprout->GroupPageName($group);
3646    
3647    Return the name of the page for the specified NMPDR group.
3648    
3649    =over 4
3650    
3651    =item group
3652    
3653    Name of the relevant group.
3654    
3655    =item RETURN
3656    
3657    Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3658    memory it will be read in.
3659    
3660    =back
3661    
3662    =cut
3663    
3664    sub GroupPageName {
3665        # Get the parameters.
3666        my ($self, $group) = @_;
3667        # Declare the return variable.
3668        my $retVal;
3669        # Check for the group file data.
3670        my %superTable = $self->CheckGroupFile();
3671        # Compute the real group name.
3672        if ($group =~ /([A-Z]\w+)/) {
3673            my $realGroup = $1;
3674            if (! defined($superTable{$1})) {
3675                Confess("No super-group found for \"$group\".");
3676            } else {
3677                $retVal = "../content/$superTable{$1}->{page}";
3678            }
3679        } else {
3680            Confess("\"group\" is not a valid group name.");
3681        }
3682        # Return the result.
3683        return $retVal;
3684    }
3685    
3686    
3687    =head3 AddProperty
3688    
3689        $sprout->AddProperty($featureID, $key, @values);
3690    
3691    Add a new attribute value (Property) to a feature.
3692    
3693    =over 4
3694    
3695    =item peg
3696    
3697    ID of the feature to which the attribute is to be added.
3698    
3699    =item key
3700    
3701    Name of the attribute (key).
3702    
3703    =item values
3704    
3705    Values of the attribute.
3706    
3707    =back
3708    
3709    =cut
3710    #: Return Type ;
3711    sub AddProperty {
3712        # Get the parameters.
3713        my ($self, $featureID, $key, @values) = @_;
3714        # Add the property using the attached attributes object.
3715        $self->{_ca}->AddAttribute($featureID, $key, @values);
3716    }
3717    
3718    =head3 CheckGroupFile
3719    
3720        my %groupData = $sprout->CheckGroupFile();
3721    
3722    Get the group file hash. The group file hash describes the relationship
3723    between a group and the super-group to which it belongs for purposes of
3724    display. The super-group name is computed from the first capitalized word
3725    in the actual group name. For each super-group, the group file contains
3726    the page name and a list of the species expected to be in the group.
3727    Each species is specified by a genus and a species name. A species name
3728    of C<0> implies an entire genus.
3729    
3730    This method returns a hash from super-group names to a hash reference. Each
3731    resulting hash reference contains the following fields.
3732    
3733    =over 4
3734    
3735    =item page
3736    
3737    The super-group's web page in the NMPDR.
3738    
3739    =item contents
3740    
3741    A list of 2-tuples, each containing a genus name followed by a species name
3742    (or 0, indicating all species). This list indicates which organisms belong
3743    in the super-group.
3744    
3745    =back
3746    
3747    =cut
3748    
3749    sub CheckGroupFile{
3750        # Get the parameters.
3751        my ($self) = @_;
3752        # Check to see if we already have this hash.
3753        if (! defined $self->{groupHash}) {
3754            # We don't, so we need to read it in.
3755            my %groupHash;
3756            # Read the group file.
3757            my @groupLines = Tracer::GetFile("$FIG_Config::sproutData/groups.tbl");
3758            # Loop through the list of sort-of groups.
3759            for my $groupLine (@groupLines) {
3760                my ($name, $page, @contents) = split /\t/, $groupLine;
3761                $groupHash{$name} = { page => $page,
3762                                      contents => [ map { [ split /\s*,\s*/, $_ ] } @contents ]
3763                                    };
3764            }
3765            # Save the hash.
3766            $self->{groupHash} = \%groupHash;
3767        }
3768        # Return the result.
3769        return %{$self->{groupHash}};
3770    }
3771    
3772    =head2 Virtual Methods
3773    
3774    =head3 CleanKeywords
3775    
3776        my $cleanedString = $sprout->CleanKeywords($searchExpression);
3777    
3778    Clean up a search expression or keyword list. This involves converting the periods
3779    in EC numbers to underscores, converting non-leading minus signs to underscores,
3780    a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
3781    characters. In addition, any extra spaces are removed.
3782    
3783    =over 4
3784    
3785    =item searchExpression
3786    
3787    Search expression or keyword list to clean. Note that a search expression may
3788    contain boolean operators which need to be preserved. This includes leading
3789    minus signs.
3790    
3791    =item RETURN
3792    
3793    Cleaned expression or keyword list.
3794    
3795    =back
3796    
3797    =cut
3798    
3799    sub CleanKeywords {
3800        # Get the parameters.
3801        my ($self, $searchExpression) = @_;
3802        # Perform the standard cleanup.
3803        my $retVal = $self->ERDB::CleanKeywords($searchExpression);
3804        # Fix the periods in EC and TC numbers.
3805        $retVal =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g;
3806        # Fix non-trailing periods.
3807        $retVal =~ s/\.(\w)/_$1/g;
3808        # Fix non-leading minus signs.
3809        $retVal =~ s/(\w)[\-]/$1_/g;
3810        # Fix the vertical bars and colons
3811        $retVal =~ s/(\w)[|:](\w)/$1'$2/g;
3812        # Return the result.
3813        return $retVal;
3814    }
3815    
3816  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3817    
3818  =head3 ParseAssignment  =head3 ParseAssignment
# Line 2643  Line 3823 
3823    
3824  A functional assignment is always of the form  A functional assignment is always of the form
3825    
3826      I<XXXX>C<\nset >I<YYYY>C< function to\n>I<ZZZZZ>      set YYYY function to
3827        ZZZZ
3828    
3829    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3830    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3831    not always the case.
3832    
3833  where I<XXXX> is the B<assigning user>, I<YYYY> is the B<user>, and I<ZZZZ> is the  In addition, the functional role may contain extra data that is stripped, such as
3834  actual functional role. In most cases, the user and the assigning user will be the  terminating spaces or a comment separated from the rest of the text by a tab.
 same, but that is not always the case.  
3835    
3836  This is a static method.  This is a static method.
3837    
3838  =over 4  =over 4
3839    
3840    =item user
3841    
3842    Name of the assigning user.
3843    
3844  =item text  =item text
3845    
3846  Text of the annotation.  Text of the annotation.
# Line 2668  Line 3856 
3856    
3857  sub _ParseAssignment {  sub _ParseAssignment {
3858          # Get the parameters.          # Get the parameters.
3859          my ($text) = @_;      my ($user, $text) = @_;
3860          # Declare the return value.          # Declare the return value.
3861          my @retVal = ();          my @retVal = ();
3862          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
3863          my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3864          if ($type =~ m/^set ([^ ]+) function to$/i) {      if ($type =~ m/^set function to$/i) {
3865                  # Here it is, so we return the user name (which is in $1), the functional role text,          # Here we have an assignment without a user, so we use the incoming user ID.
3866          # and the assigning user.          @retVal = ($user, $function);
3867                  @retVal = ($1, $function, $user);      } elsif ($type =~ m/^set (\S+) function to$/i) {
3868            # Here we have an assignment with a user that is passed back to the caller.
3869            @retVal = ($1, $function);
3870        }
3871        # If we have an assignment, we need to clean the function text. There may be
3872        # extra junk at the end added as a note from the user.
3873        if (defined( $retVal[1] )) {
3874            $retVal[1] =~ s/(\t\S)?\s*$//;
3875          }          }
3876          # Return the result list.          # Return the result list.
3877          return @retVal;          return @retVal;
3878  }  }
3879    
3880    =head3 _CheckFeature
3881    
3882        my $flag = $sprout->_CheckFeature($fid);
3883    
3884    Return TRUE if the specified FID is probably an NMPDR feature ID, else FALSE.
3885    
3886    =over 4
3887    
3888    =item fid
3889    
3890    Feature ID to check.
3891    
3892    =item RETURN
3893    
3894    Returns TRUE if the FID is for one of the NMPDR genomes, else FALSE.
3895    
3896    =back
3897    
3898    =cut
3899    
3900    sub _CheckFeature {
3901        # Get the parameters.
3902        my ($self, $fid) = @_;
3903        # Insure we have a genome hash.
3904        if (! defined $self->{genomeHash}) {
3905            my %genomeHash = map { $_ => 1 } $self->GetFlat(['Genome'], "", [], 'Genome(id)');
3906            $self->{genomeHash} = \%genomeHash;
3907        }
3908        # Get the feature's genome ID.
3909        my ($genomeID) = FIGRules::ParseFeatureID($fid);
3910        # Return an indicator of whether or not the genome ID is in the hash.
3911        return ($self->{genomeHash}->{$genomeID} ? 1 : 0);
3912    }
3913    
3914  =head3 FriendlyTimestamp  =head3 FriendlyTimestamp
3915    
3916  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 2704  Line 3933 
3933    
3934  sub FriendlyTimestamp {  sub FriendlyTimestamp {
3935      my ($timeValue) = @_;      my ($timeValue) = @_;
3936      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
3937      return $retVal;      return $retVal;
3938  }  }
3939    
3940    
3941  1;  1;

Legend:
Removed from v.1.11  
changed lines
  Added in v.1.104

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3