[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.10, Fri Feb 25 18:41:45 2005 UTC revision 1.119, Tue Sep 30 15:23:55 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 CGI;
18        use WikiTools;
19        use BioWords;
20        use base qw(ERDB);
21    
22  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
23    
# Line 25  Line 30 
30  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>
31  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>.
32    
33  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' });
34    
35  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
36  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
37  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
38  L</dna_seq> returns the DNA sequence for a specified genome location.  L</DNASeq> returns the DNA sequence for a specified genome location.
39    
40    The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.
41    
42  =cut  =cut
43    
# Line 40  Line 47 
47    
48  =head3 new  =head3 new
49    
50  C<< my $sprout = Sprout->new($dbName, \%options); >>      my $sprout = Sprout->new($dbName, \%options);
51    
52  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
53  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 50  Line 57 
57    
58  =item dbName  =item dbName
59    
60  Name of the database.  Name of the database. If omitted, the default Sprout database name is used.
61    
62  =item options  =item options
63    
# Line 62  Line 69 
69    
70  * 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>)
71    
72  * 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)
73    
74  * B<port> connection port (default C<0>)  * B<port> connection port (default C<0>)
75    
76    * B<sock> connection socket (default same as SEED)
77    
78  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
79    
80  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
81    
82    * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
83    
84    * B<host> name of the database host
85    
86  =back  =back
87    
88  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
89  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
90  F</usr/fig/SproutData>.  F</usr/fig/SproutData>.
91    
92  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' });
93    
94  =cut  =cut
95    
96  sub new {  sub new {
97          # Get the parameters.          # Get the parameters.
98          my ($class, $dbName, $options) = @_;          my ($class, $dbName, $options) = @_;
99        # Default the database name if it is missing.
100        if (! defined $dbName) {
101            $dbName = $FIG_Config::sproutDB;
102        } elsif (ref $dbName eq 'HASH') {
103            $options = $dbName;
104            $dbName = $FIG_Config::sproutDB;
105        }
106        # Compute the DBD directory.
107        my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
108                                                      $FIG_Config::fig );
109          # 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
110          # the incoming data.          # the incoming data.
111          my $optionTable = Tracer::GetOptions({          my $optionTable = Tracer::GetOptions({
112                                             dbType               => 'mysql',                     # database type                         dbType       => $FIG_Config::dbms,
113                                             dataDir              => 'Data',                      # data file directory                                                          # database type
114                                             xmlFileName  => 'SproutDBD.xml', # database definition file name                         dataDir      => $FIG_Config::sproutData,
115                                             userData             => 'root/',                     # user name and password                                                          # data file directory
116                                             port                 => 0,                           # database connection port                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
117                                                            # database definition file name
118                           userData     => "$FIG_Config::sproutUser/$FIG_Config::sproutPass",
119                                                            # user name and password
120                           port         => $FIG_Config::sproutPort,
121                                                            # database connection port
122                           sock         => $FIG_Config::sproutSock,
123                           host         => $FIG_Config::sprout_host,
124                                             maxSegmentLength => 4500,            # maximum feature segment length                                             maxSegmentLength => 4500,            # maximum feature segment length
125                                             maxSequenceLength => 8000,           # maximum contig sequence length                                             maxSequenceLength => 8000,           # maximum contig sequence length
126                           noDBOpen     => 0,               # 1 to suppress the database open
127                                            }, $options);                                            }, $options);
128          # Get the data directory.          # Get the data directory.
129          my $dataDir = $optionTable->{dataDir};          my $dataDir = $optionTable->{dataDir};
# Line 100  Line 131 
131          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;          $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
132          my ($userName, $password) = ($1, $2);          my ($userName, $password) = ($1, $2);
133          # Connect to the database.          # Connect to the database.
134          my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});      my $dbh;
135        if (! $optionTable->{noDBOpen}) {
136            Trace("Connect data: host = $optionTable->{host}, port = $optionTable->{port}.") if T(3);
137            $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
138                                    $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
139        }
140          # Create the ERDB object.          # Create the ERDB object.
141          my $xmlFileName = "$optionTable->{xmlFileName}";          my $xmlFileName = "$optionTable->{xmlFileName}";
142          my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
143          # Create this object.      # Add the option table and XML file name.
144          my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
145          # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
146          bless $self;      # Set up space for the group file data.
147          return $self;      $retVal->{groupHash} = undef;
148        # Set up space for the genome hash. We use this to identify NMPDR genomes.
149        $retVal->{genomeHash} = undef;
150        # Remember the data directory name.
151        $retVal->{dataDir} = $dataDir;
152        # Connect to the attributes.
153        if ($FIG_Config::attrURL) {
154            Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);
155            $retVal->{_ca} = RemoteCustomAttributes->new($FIG_Config::attrURL);
156        } elsif ($FIG_Config::attrDbName) {
157            Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);
158            my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));
159            $retVal->{_ca} = CustomAttributes->new(user => $user);
160        }
161        # Return it.
162        return $retVal;
163    }
164    
165    =head3 CoreGenomes
166    
167        my @genomes = $sprout->CoreGenomes($scope);
168    
169    Return the IDs of NMPDR genomes in the specified scope.
170    
171    =over 4
172    
173    =item scope
174    
175    Scope of the desired genomes. C<core> covers the original core genomes,
176    C<nmpdr> covers all genomes in NMPDR groups, and C<all> covers all
177    genomes in the system.
178    
179    =item RETURN
180    
181    Returns a list of the IDs for the genomes in the specified scope.
182    
183    =back
184    
185    =cut
186    
187    sub CoreGenomes {
188        # Get the parameters.
189        my ($self, $scope) = @_;
190        # Declare the return variable.
191        my @retVal = ();
192        # If we want all genomes, then this is easy.
193        if ($scope eq 'all') {
194            @retVal = $self->Genomes();
195        } else {
196            # Here we're dealing with groups. Get the hash of all the
197            # genome groups.
198            my %groups = $self->GetGroups();
199            # Loop through the groups, keeping the ones that we want.
200            for my $group (keys %groups) {
201                # Decide if we want to keep this group.
202                my $keepGroup = 0;
203                if ($scope eq 'nmpdr') {
204                    # NMPDR mode: keep all groups.
205                    $keepGroup = 1;
206                } elsif ($scope eq 'core') {
207                    # CORE mode. Only keep real core groups.
208                    if (grep { $group =~ /$_/ } @{$FIG_Config::realCoreGroups}) {
209                        $keepGroup = 1;
210                    }
211                }
212                # Add this group if we're keeping it.
213                if ($keepGroup) {
214                    push @retVal, @{$groups{$group}};
215                }
216            }
217        }
218        # Return the result.
219        return @retVal;
220    }
221    
222    =head3 SuperGroup
223    
224        my $superGroup = $sprout->SuperGroup($groupName);
225    
226    Return the name of the super-group containing the specified NMPDR genome
227    group. If no appropriate super-group can be found, an error will be
228    thrown.
229    
230    =over 4
231    
232    =item groupName
233    
234    Name of the group whose super-group is desired.
235    
236    =item RETURN
237    
238    Returns the name of the super-group containing the incoming group.
239    
240    =back
241    
242    =cut
243    
244    sub SuperGroup {
245        # Get the parameters.
246        my ($self, $groupName) = @_;
247        # Declare the return variable.
248        my $retVal;
249        # Get the group hash.
250        my %groupHash = $self->CheckGroupFile();
251        # Find the super-group genus.
252        $groupName =~ /([A-Z]\w+)/;
253        my $nameThing = $1;
254        # See if it's directly in the group hash.
255        if (exists $groupHash{$nameThing}) {
256            # Yes, then it's our result.
257            $retVal = $nameThing;
258        } else {
259            # No, so we have to search.
260            for my $superGroup (keys %groupHash) {
261                # Get this super-group's item list.
262                my $list = $groupHash{$superGroup}->{contents};
263                # Search it.
264                if (grep { $_->[0] eq $nameThing } @{$list}) {
265                    $retVal = $superGroup;
266                }
267            }
268            # Make sure we found something.
269            if (! $retVal) {
270                Confess("No super-group found for \"$groupName\".");
271            }
272        }
273        # Return the result.
274        return $retVal;
275  }  }
276    
277  =head3 MaxSegment  =head3 MaxSegment
278    
279  C<< my $length = $sprout->MaxSegment(); >>      my $length = $sprout->MaxSegment();
280    
281  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
282  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 293 
293    
294  =head3 MaxSequence  =head3 MaxSequence
295    
296  C<< my $length = $sprout->MaxSequence(); >>      my $length = $sprout->MaxSequence();
297    
298  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
299  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 306 
306          return $self->{_options}->{maxSequenceLength};          return $self->{_options}->{maxSequenceLength};
307  }  }
308    
309  =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.  
310    
311  C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>      $sprout->Load($rebuild);;
312    
313  The WHERE clause contains a single question mark, so there is a single additional  Load the database from files in the data directory, optionally re-creating the tables.
 parameter representing the parameter value. It would also be possible to code  
314    
315  C<< $query = $sprout->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>  This method always deletes the data from the database before loading, even if the tables are not
316    re-created. The data is loaded into the relations from files in the data directory either having the
317    same name as the target relation with no extension or with an extension of C<.dtx>. Files without an
318    extension are used in preference to the files with an extension.
319    
320  however, this version of the call would generate a syntax error if there were any quote  The files are loaded based on the presumption that each line of the file is a record in the
321  characters inside the variable C<$genus>.  relation, and the individual fields are delimited by tabs. Tab and new-line characters inside
322    fields must be represented by the escape sequences C<\t> and C<\n>, respectively. The fields must
323    be presented in the order given in the relation tables produced by the L</ShowMetaData> method.
324    
325  The use of the strange parenthesized notation for field names enables us to distinguish  =over 4
 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.  
326    
327  It is possible to specify multiple entity and relationship names in order to retrieve more than  =item rebuild
 one object's data at the same time, which allows highly complex joined queries. For example,  
328    
329  C<< $query = $sprout->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>  TRUE if the data tables need to be created or re-created, else FALSE
330    
331  This query returns all the genomes for a particular genus and allows access to the  =item RETURN
 sources from which they came. The join clauses to go from Genome to Source are generated  
 automatically.  
332    
333  Finally, the filter clause can contain sort information. To do this, simply put an C<ORDER BY>  Returns a statistical object containing the number of records read, the number of duplicates found,
334  clause at the end of the filter. Field references in the ORDER BY section follow the same rules  the number of errors, and a list of the error messages.
 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.  
335    
336  C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ? ORDER BY Genome(species)", [$genus]); >>  =back
337    
338  It is also permissible to specify I<only> an ORDER BY clause. For example, the following invocation gets  =cut
339  all genomes ordered by genus and species.  #: Return Type %;
340    sub Load {
341        # Get the parameters.
342        my ($self, $rebuild) = @_;
343        # Load the tables from the data directory.
344        my $retVal = $self->LoadTables($self->{_options}->{dataDir}, $rebuild);
345        # Return the statistics.
346        return $retVal;
347    }
348    
349  C<< $query = $sprout->Get(['Genome'], "ORDER BY Genome(genus), Genome(species)"); >>  =head3 LoadUpdate
350    
351  Odd things may happen if one of the ORDER BY fields is in a secondary relation. So, for example, an      my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList);
 attempt to order B<Feature>s by alias may (depending on the underlying database engine used) cause  
 a single feature to appear more than once.  
352    
353  If multiple names are specified, then the query processor will automatically determine a  Load updates to one or more database tables. This method enables the client to make changes to one
354  join path between the entities and relationships. The algorithm used is very simplistic.  or two tables without reloading the whole database. For each table, there must be a corresponding
355  In particular, you can't specify any entity or relationship more than once, and if a  file in the data directory, either with the same name as the table, or with a C<.dtx> suffix. So,
356  relationship is recursive, the path is determined by the order in which the entity  for example, to make updates to the B<FeatureTranslation> relation, there must be a
357  and the relationship appear. For example, consider a recursive relationship B<IsParentOf>  C<FeatureTranslation.dtx> file in the data directory. Unlike a full load, files without an extension
358  which relates B<People> objects to other B<People> objects. If the join path is  are not examined. This allows update files to co-exist with files from an original load.
 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.  
359    
360  =over 4  =over 4
361    
362  =item objectNames  =item truncateFlag
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
363    
364  WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  TRUE if the tables should be rebuilt before loading, else FALSE. A value of TRUE therefore causes
365  be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  current data and schema of the tables to be replaced, while a value of FALSE means the new data
366  B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  is added to the existing data in the various relations.
 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.  
367    
368  =item parameterList  =item tableList
369    
370  List of the parameters to be substituted in for the parameters marks in the filter clause.  List of the tables to be updated.
371    
372  =item RETURN  =item RETURN
373    
374  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,
375    the number of errors encountered, and a list of error messages.
376    
377  =back  =back
378    
379  =cut  =cut
380    #: Return Type $%;
381  sub Get {  sub LoadUpdate {
382          # Get the parameters.          # Get the parameters.
383          my ($self, $objectNames, $filterClause, $parameterList) = @_;      my ($self, $truncateFlag, $tableList) = @_;
384          # We differ from the ERDB Get method in that the parameter list is passed in as a list reference      # Declare the return value.
385          # rather than a list of parameters. The next step is to convert the parameters from a reference      my $retVal = Stats->new();
386          # to a real list. We can only do this if the parameters have been specified.      # Get the data directory.
387          my @parameters;      my $optionTable = $self->{_options};
388          if ($parameterList) { @parameters = @{$parameterList}; }      my $dataDir = $optionTable->{dataDir};
389          return $self->{_erdb}->Get($objectNames, $filterClause, @parameters);      # Loop through the incoming table names.
390        for my $tableName (@{$tableList}) {
391            # Find the table's file.
392            my $fileName = LoadFileName($dataDir, $tableName);
393            if (! $fileName) {
394                Trace("No load file found for $tableName in $dataDir.") if T(0);
395            } else {
396                # Attempt to load this table.
397                my $result = $self->LoadTable($fileName, $tableName, truncate => $truncateFlag);
398                # Accumulate the resulting statistics.
399                $retVal->Accumulate($result);
400            }
401        }
402        # Return the statistics.
403        return $retVal;
404  }  }
405    
406  =head3 GetEntity  =head3 GenomeCounts
407    
408  C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>      my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete);
409    
410  Return an object describing the entity instance with a specified ID.  Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
411    genomes will be included in the counts.
412    
413  =over 4  =over 4
414    
415  =item entityType  =item complete
   
 Entity type name.  
   
 =item ID  
416    
417  ID of the desired entity.  TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
418    counted
419    
420  =item RETURN  =item RETURN
421    
422  Returns a B<DBObject> representing the desired entity instance, or an undefined value if no  A six-element list containing the number of genomes in each of six categories--
423  instance is found with the specified key.  Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
424    
425  =back  =back
426    
427  =cut  =cut
428    
429  sub GetEntity {  sub GenomeCounts {
430          # Get the parameters.          # Get the parameters.
431          my ($self, $entityType, $ID) = @_;      my ($self, $complete) = @_;
432          # Create a query.      # Set the filter based on the completeness flag.
433          my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);      my $filter = ($complete ? "Genome(complete) = 1" : "");
434          # Get the first (and only) object.      # Get all the genomes and the related taxonomy information.
435          my $retVal = $query->Fetch();      my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
436          # Return the result.      # Clear the counters.
437          return $retVal;      my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
438        # Loop through, counting the domains.
439        for my $genome (@genomes) {
440            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
441            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
442            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
443            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
444            elsif ($genome->[1] =~ /^env/i)      { ++$env }
445            else  { ++$unk }
446        }
447        # Return the counts.
448        return ($arch, $bact, $euk, $vir, $env, $unk);
449  }  }
450    
451  =head3 GetEntityValues  =head3 ContigCount
452    
453  C<< my @values = GetEntityValues($entityType, $ID, \@fields); >>      my $count = $sprout->ContigCount($genomeID);
454    
455  Return a list of values from a specified entity instance.  Return the number of contigs for the specified genome ID.
456    
457  =over 4  =over 4
458    
459  =item entityType  =item genomeID
   
 Entity type name.  
   
 =item ID  
   
 ID of the desired entity.  
   
 =item fields  
460    
461  List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.  ID of the genome whose contig count is desired.
462    
463  =item RETURN  =item RETURN
464    
465  Returns a flattened list of the values of the specified fields for the specified entity.  Returns the number of contigs for the specified genome.
466    
467  =back  =back
468    
469  =cut  =cut
470  #: Return Type @;  
471  sub GetEntityValues {  sub ContigCount {
472          # Get the parameters.          # Get the parameters.
473          my ($self, $entityType, $ID, $fields) = @_;      my ($self, $genomeID) = @_;
474          # Get the specified entity.      # Get the contig count.
475          my $entity = $self->GetEntity($entityType, $ID);      my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
         # Declare the return list.  
         my @retVal = ();  
         # If we found the entity, push the values into the return list.  
         if ($entity) {  
                 push @retVal, $entity->Values($fields);  
         }  
476          # Return the result.          # Return the result.
477          return @retVal;      return $retVal;
478  }  }
479    
480  =head3 ShowMetaData  =head3 GenomeMenu
481    
482  C<< $sprout->ShowMetaData($fileName); >>      my $html = $sprout->GenomeMenu(%options);
483    
484  This method outputs a description of the database to an HTML file in the data directory.  Generate a genome selection control with the specified name and options.
485    This control is almost but not quite the same as the genome control in the
486    B<SearchHelper> class. Eventually, the two will be combined.
487    
488  =over 4  =over 4
489    
490  =item fileName  =item options
491    
492    Optional parameters for the control (see below).
493    
494    =item RETURN
495    
496  Fully-qualified name to give to the output file.  Returns the HTML for a genome selection control on a form (sometimes called a popup menu).
497    
498  =back  =back
499    
500  =cut  The valid options are as follows.
501    
502  sub ShowMetaData {  =over 4
         # Get the parameters.  
         my ($self, $fileName) = @_;  
         # Compute the file name.  
         my $options = $self->{_options};  
         # Call the show method on the underlying ERDB object.  
         $self->{_erdb}->ShowMetaData($fileName);  
 }  
503    
504  =head3 Load  =item name
505    
506  C<< $sprout->Load($rebuild); >>;  Name to give this control for use in passing it to the form. The default is C<myGenomeControl>.
507    Terrible things will happen if you have two controls with the same name on the same page.
508    
509  Load the database from files in the data directory, optionally re-creating the tables.  =item filter
510    
511  This method always deletes the data from the database before loading, even if the tables are not  If specified, a filter for the list of genomes to display. The filter should be in the form of a
512  re-created. The data is loaded into the relations from files in the data directory either having the  list reference. The first element of the list should be the filter string, and the remaining elements
513  same name as the target relation with no extension or with an extension of C<.dtx>. Files without an  the filter parameters.
 extension are used in preference to the files with an extension.  
514    
515  The files are loaded based on the presumption that each line of the file is a record in the  =item multiSelect
 relation, and the individual fields are delimited by tabs. Tab and new-line characters inside  
 fields must be represented by the escape sequences C<\t> and C<\n>, respectively. The fields must  
 be presented in the order given in the relation tables produced by the L</ShowMetaData> method.  
516    
517  =over 4  If TRUE, then the user can select multiple genomes. If FALSE, the user can only select one genome.
518    
519  =item rebuild  =item size
520    
521  TRUE if the data tables need to be created or re-created, else FALSE  Number of rows to display in the control. The default is C<10>
522    
523  =item RETURN  =item id
524    
525  Returns a statistical object containing the number of records read, the number of duplicates found,  ID to give this control. The default is the value of the C<name> option. Nothing will work correctly
526  the number of errors, and a list of the error messages.  unless this ID is unique.
527    
528    =item selected
529    
530    A comma-delimited list of selected genomes, or a reference to a list of selected genomes. The
531    default is none.
532    
533    =item class
534    
535    If specified, a style class to assign to the genome control.
536    
537  =back  =back
538    
539  =cut  =cut
540  #: Return Type %;  
541  sub Load {  sub GenomeMenu {
542          # Get the parameters.          # Get the parameters.
543          my ($self, $rebuild) = @_;      my ($self, %options) = @_;
544          # Get the database object.      # Get the control's name and ID.
545          my $erdb = $self->{_erdb};      my $menuName = $options{name} || $options{id} || 'myGenomeControl';
546          # Load the tables from the data directory.      my $menuID = $options{id} || $menuName;
547          my $retVal = $erdb->LoadTables($self->{_options}->{dataDir}, $rebuild);      Trace("Genome menu name = $menuName with ID $menuID.") if T(3);
548          # Return the statistics.      # Compute the IDs for the status display.
549        my $divID = "${menuID}_status";
550        my $urlID = "${menuID}_url";
551        # Compute the code to show selected genomes in the status area.
552        my $showSelect = "showSelected('$menuID', '$divID', '$urlID', 1000)";
553        # Check for single-select or multi-select.
554        my $multiSelect = $options{multiSelect} || 0;
555        # Get the style data.
556        my $class = $options{class} || '';
557        # Get the list of pre-selected items.
558        my $selections = $options{selected} || [];
559        if (ref $selections ne 'ARRAY') {
560            $selections = [ split /\s*,\s*/, $selections ];
561        }
562        my %selected = map { $_ => 1 } @{$selections};
563        # Extract the filter information. The default is no filtering. It can be passed as a tab-delimited
564        # string or a list reference.
565        my $filterParms = $options{filter} || "";
566        if (! ref $filterParms) {
567            $filterParms = [split /\t|\\t/, $filterParms];
568        }
569        my $filterString = shift @{$filterParms};
570        # Get a list of all the genomes in group order. In fact, we only need them ordered
571        # by name (genus,species,strain), but putting primary-group in front enables us to
572        # take advantage of an existing index.
573        my @genomeList = $self->GetAll(['Genome'], "$filterString ORDER BY Genome(primary-group), Genome(genus), Genome(species), Genome(unique-characterization)",
574                                       $filterParms,
575                                       [qw(Genome(primary-group) Genome(id) Genome(genus) Genome(species) Genome(unique-characterization) Genome(taxonomy) Genome(contigs))]);
576        # Create a hash to organize the genomes by group. Each group will contain a list of
577        # 2-tuples, the first element being the genome ID and the second being the genome
578        # name.
579        my %gHash = ();
580        for my $genome (@genomeList) {
581            # Get the genome data.
582            my ($group, $genomeID, $genus, $species, $strain, $taxonomy, $contigs) = @{$genome};
583            # Compute its name. This is the genus, species, strain (if any), and the contig count.
584            my $name = "$genus $species ";
585            $name .= "$strain " if $strain;
586            my $contigCount = ($contigs == 1 ? "" : ", $contigs contigs");
587            # Now we get the domain. The domain tells us the display style of the organism.
588            my ($domain) = split /\s*;\s*/, $taxonomy, 2;
589            # Now compute the display group. This is normally the primary group, but if the
590            # organism is supporting, we blank it out.
591            my $displayGroup = ($group eq $FIG_Config::otherGroup ? "" : $group);
592            # Push the genome into the group's list. Note that we use the real group
593            # name for the hash key here, not the display group name.
594            push @{$gHash{$group}}, [$genomeID, $name, $contigCount, $domain];
595        }
596        # We are almost ready to unroll the menu out of the group hash. The final step is to separate
597        # the supporting genomes by domain. First, we extract the NMPDR groups and sort them. They
598        # are sorted by the first capitalized word. Groups with "other" are sorted after groups
599        # that aren't "other". At some point, we will want to make this less complicated.
600        my %sortGroups = map { $_ =~ /(other)?(.*)([A-Z].+)/; "$3$1$2" => $_ }
601                             grep { $_ ne $FIG_Config::otherGroup } keys %gHash;
602        my @groups = map { $sortGroups{$_} } sort keys %sortGroups;
603        # Remember the number of NMPDR groups.
604        my $nmpdrGroupCount = scalar @groups;
605        # Loop through the supporting genomes, classifying them by domain. We'll also keep a list
606        # of the domains found.
607        my @otherGenomes = @{$gHash{$FIG_Config::otherGroup}};
608        my @domains = ();
609        for my $genomeData (@otherGenomes) {
610            my ($genomeID, $name, $contigCount, $domain) = @{$genomeData};
611            if (exists $gHash{$domain}) {
612                push @{$gHash{$domain}}, $genomeData;
613            } else {
614                $gHash{$domain} = [$genomeData];
615                push @domains, $domain;
616            }
617        }
618        # Add the domain groups at the end of the main group list. The main group list will now
619        # contain all the categories we need to display the genomes.
620        push @groups, sort @domains;
621        # Delete the supporting group.
622        delete $gHash{$FIG_Config::otherGroup};
623        # Now it gets complicated. We need a way to mark all the NMPDR genomes. We take advantage
624        # of the fact they come first in the list. We'll accumulate a count of the NMPDR genomes
625        # and use that to make the selections.
626        my $nmpdrCount = 0;
627        # Create the type counters.
628        my $groupCount = 1;
629        # Get the number of rows to display.
630        my $rows = $options{size} || 10;
631        # If we're multi-row, create an onChange event.
632        my $onChangeTag = ( $rows > 1 ? " onChange=\"$showSelect;\" onFocus=\"$showSelect;\"" : "" );
633        # Set up the multiple-select flag.
634        my $multipleTag = ($multiSelect ? " multiple" : "" );
635        # Set up the style class.
636        my $classTag = ($class ? " class=\"$class\"" : "" );
637        # Create the SELECT tag and stuff it into the output array.
638        my @lines = ("<SELECT name=\"$menuName\" id=\"$menuID\" $onChangeTag$multipleTag$classTag size=\"$rows\">");
639        # Loop through the groups.
640        for my $group (@groups) {
641            # Get the genomes in the group.
642            for my $genome (@{$gHash{$group}}) {
643                # If this is an NMPDR organism, we add an extra style and count it.
644                my $nmpdrStyle = "";
645                if ($nmpdrGroupCount > 0) {
646                    $nmpdrCount++;
647                    $nmpdrStyle = " Core";
648                }
649                # Get the organism ID, name, contig count, and domain.
650                my ($genomeID, $name, $contigCount, $domain) = @{$genome};
651                # See if we're pre-selected.
652                my $selectTag = ($selected{$genomeID} ? " SELECTED" : "");
653                # Compute the display name.
654                my $nameString = "$name ($genomeID$contigCount)";
655                # Generate the option tag.
656                my $optionTag = "<OPTION class=\"$domain$nmpdrStyle\" title=\"$group\" value=\"$genomeID\"$selectTag>$nameString</OPTION>";
657                push @lines, "    $optionTag";
658            }
659            # Record this group in the nmpdrGroup count. When that gets to 0, we've finished the NMPDR
660            # groups.
661            $nmpdrGroupCount--;
662        }
663        # Close the SELECT tag.
664        push @lines, "</SELECT>";
665        if ($rows > 1) {
666            # We're in a non-compact mode, so we need to add some selection helpers. First is
667            # the search box. This allows the user to type text and change which genomes are
668            # displayed. For multiple-select mode, we include a button that selects the displayed
669            # genes. For single-select mode, we use a plain label instead.
670            my $searchThingName = "${menuID}_SearchThing";
671            my $searchThingLabel = ($multiSelect ? "<INPUT type=\"button\" name=\"MacroSearch\" class=\"button\" value=\"Select genomes containing\" onClick=\"selectShowing('$menuID', '$searchThingName'); $showSelect;\" />"
672                                                 : "Show genomes containing");
673            push @lines, "<br />$searchThingLabel&nbsp;" .
674                         "<INPUT type=\"text\" id=\"$searchThingName\" name=\"$searchThingName\" size=\"30\" onKeyup=\"showTyped('$menuID', '$searchThingName');\" />" .
675                         Hint("GenomeControl", "Type here to filter the genomes displayed.") . "<br />";
676            # For multi-select mode, we also have buttons to set and clear selections.
677            if ($multiSelect) {
678                push @lines, "<INPUT type=\"button\" name=\"ClearAll\" class=\"bigButton\"  value=\"Clear All\" onClick=\"clearAll('$menuID'); $showSelect\" />";
679                push @lines, "<INPUT type=\"button\" name=\"SelectAll\" class=\"bigButton\" value=\"Select All\" onClick=\"selectAll('$menuID'); $showSelect\" />";
680                push @lines, "<INPUT type=\"button\" name=\"NMPDROnly\" class=\"bigButton\"  value=\"Select NMPDR\" onClick=\"selectSome('$menuID', $nmpdrCount, true); $showSelect;\" />";
681            }
682            # Add a hidden field we can use to generate organism page hyperlinks.
683            push @lines, "<INPUT type=\"hidden\" id=\"$urlID\" value=\"$FIG_Config::cgi_url/wiki/rest.cgi/NmpdrPlugin/SeedViewer?page=Organism;organism=\" />";
684            # Add the status display. This tells the user what's selected no matter where the list is scrolled.
685            push @lines, "<DIV id=\"$divID\" class=\"Panel\"></DIV>";
686        }
687        # Assemble all the lines into a string.
688        my $retVal = join("\n", @lines, "");
689        # Return the result.
690          return $retVal;          return $retVal;
691  }  }
692    
 =head3 LoadUpdate  
   
 C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  
693    
694  Load updates to one or more database tables. This method enables the client to make changes to one  =head3 Stem
 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.  
695    
696  =over 4      my $stem = $sprout->Stem($word);
697    
698  =item truncateFlag  Return the stem of the specified word, or C<undef> if the word is not
699    stemmable. Note that even if the word is stemmable, the stem may be
700    the same as the original word.
701    
702  TRUE if the tables should be rebuilt before loading, else FALSE. A value of TRUE therefore causes  =over 4
 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.  
703    
704  =item tableList  =item word
705    
706  List of the tables to be updated.  Word to convert into a stem.
707    
708  =item RETURN  =item RETURN
709    
710  Returns a statistical object containing the number of records read, the number of duplicates found,  Returns a stem of the word (which may be the word itself), or C<undef> if
711  the number of errors encountered, and a list of error messages.  the word is not stemmable.
712    
713  =back  =back
714    
715  =cut  =cut
716  #: Return Type $%;  
717  sub LoadUpdate {  sub Stem {
718          # Get the parameters.          # Get the parameters.
719          my ($self, $truncateFlag, $tableList) = @_;      my ($self, $word) = @_;
720          # Get the database object.      # Get the stemmer object.
721          my $erdb = $self->{_erdb};      my $stemmer = $self->{stemmer};
722          # Declare the return value.      if (! defined $stemmer) {
723          my $retVal = Stats->new();          # We don't have one pre-built, so we build and save it now.
724          # Get the data directory.          $stemmer = BioWords->new(exceptions => "$FIG_Config::sproutData/Exceptions.txt",
725          my $optionTable = $self->{_options};                                   stops => "$FIG_Config::sproutData/StopWords.txt",
726          my $dataDir = $optionTable->{dataDir};                                   cache => 0);
727          # Loop through the incoming table names.          $self->{stemmer} = $stemmer;
         for my $tableName (@{$tableList}) {  
                 # Find the table's file.  
                 my $fileName = "$dataDir/$tableName";  
                 if (! -e $fileName) {  
                         $fileName = "$fileName.dtx";  
                 }  
                 # Attempt to load this table.  
                 my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);  
                 # Accumulate the resulting statistics.  
                 $retVal->Accumulate($result);  
728          }          }
729          # Return the statistics.      # Try to stem the word.
730        my $retVal = $stemmer->Process($word);
731        # Return the result.
732          return $retVal;          return $retVal;
733  }  }
734    
735    
736  =head3 Build  =head3 Build
737    
738  C<< $sprout->Build(); >>      $sprout->Build();
739    
740  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.
741  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 747 
747          # Get the parameters.          # Get the parameters.
748          my ($self) = @_;          my ($self) = @_;
749          # Create the tables.          # Create the tables.
750          $self->{_erdb}->CreateTables;      $self->CreateTables();
751  }  }
752    
753  =head3 Genomes  =head3 Genomes
754    
755  C<< my @genomes = $sprout->Genomes(); >>      my @genomes = $sprout->Genomes();
756    
757  Return a list of all the genome IDs.  Return a list of all the genome IDs.
758    
# Line 481  Line 769 
769    
770  =head3 GenusSpecies  =head3 GenusSpecies
771    
772  C<< my $infoString = $sprout->GenusSpecies($genomeID); >>      my $infoString = $sprout->GenusSpecies($genomeID);
773    
774  Return the genus, species, and unique characterization for a genome.  Return the genus, species, and unique characterization for a genome.
775    
# Line 513  Line 801 
801    
802  =head3 FeaturesOf  =head3 FeaturesOf
803    
804  C<< my @features = $sprout->FeaturesOf($genomeID, $ftype); >>      my @features = $sprout->FeaturesOf($genomeID, $ftype);
805    
806  Return a list of the features relevant to a specified genome.  Return a list of the features relevant to a specified genome.
807    
# Line 558  Line 846 
846    
847  =head3 FeatureLocation  =head3 FeatureLocation
848    
849  C<< my @locations = $sprout->FeatureLocation($featureID); >>      my @locations = $sprout->FeatureLocation($featureID);
850    
851  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
852  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 870 
870  =item RETURN  =item RETURN
871    
872  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
873  context and as a space-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context. An empty list means the feature
874    wasn't found.
875    
876  =back  =back
877    
878  =cut  =cut
879  #: Return Type @;  
 #: Return Type $;  
880  sub FeatureLocation {  sub FeatureLocation {
881          # Get the parameters.          # Get the parameters.
882          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
883          # Create a query for the feature locations.      # Declare the return variable.
         my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",  
                                                    [$featureID]);  
         # Create the return list.  
884          my @retVal = ();          my @retVal = ();
885          # Set up the variables used to determine if we have adjacent segments. This initial setup will      # Get the feature record.
886          # not match anything.      my $object = $self->GetEntity('Feature', $featureID);
887          my ($prevContig, $prevBeg, $prevDir, $prevLen) = ("", 0, "0", 0);      # Only proceed if we found it.
888          # Loop through the query results, creating location specifiers.      if (defined $object) {
889          while (my $location = $query->Fetch()) {          # Get the location string.
890                  # Get the location parameters.          my $locString = $object->PrimaryValue('Feature(location-string)');
891                  my ($contigID, $beg, $dir, $len) = $location->Values(['IsLocatedIn(to-link)',          # Create the return list.
892                          'IsLocatedIn(beg)', 'IsLocatedIn(dir)', 'IsLocatedIn(len)']);          @retVal = split /\s*,\s*/, $locString;
                 # 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";  
893          }          }
894          # Return the list in the format indicated by the context.          # Return the list in the format indicated by the context.
895          return (wantarray ? @retVal : join(' ', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
896  }  }
897    
898  =head3 ParseLocation  =head3 ParseLocation
899    
900  C<< my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location); >>      my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location);
901    
902  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
903  length.  length.
# Line 649  Line 916 
916  =back  =back
917    
918  =cut  =cut
919  #: Return Type @;  
920  sub ParseLocation {  sub ParseLocation {
921          # 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
922      # the first parameter.      # the first parameter.
923      shift if UNIVERSAL::isa($_[0],__PACKAGE__);      shift if UNIVERSAL::isa($_[0],__PACKAGE__);
924          my ($location) = @_;          my ($location) = @_;
925          # Parse it into segments.          # Parse it into segments.
926          $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
927          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);          my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
928          # If the direction is an underscore, convert it to a + or -.          # If the direction is an underscore, convert it to a + or -.
929          if ($dir eq "_") {          if ($dir eq "_") {
# Line 672  Line 939 
939          return ($contigID, $start, $dir, $len);          return ($contigID, $start, $dir, $len);
940  }  }
941    
942    
943    
944  =head3 PointLocation  =head3 PointLocation
945    
946  C<< my $found = Sprout::PointLocation($location, $point); >>      my $found = Sprout::PointLocation($location, $point);
947    
948  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
949  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 972 
972  =back  =back
973    
974  =cut  =cut
975  #: Return Type $;  
976  sub PointLocation {  sub PointLocation {
977          # 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
978      # the first parameter.      # the first parameter.
# Line 726  Line 995 
995    
996  =head3 DNASeq  =head3 DNASeq
997    
998  C<< my $sequence = $sprout->DNASeq(\@locationList); >>      my $sequence = $sprout->DNASeq(\@locationList);
999    
1000  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
1001  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,
1002  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>.
1003    
1004    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
1005    between positions 1401 and 1532, inclusive.
1006    
1007        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
1008    
1009  =over 4  =over 4
1010    
1011  =item locationList  =item locationList
1012    
1013  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
1014  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
1015    
1016  =item RETURN  =item RETURN
1017    
# Line 764  Line 1038 
1038                  # 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
1039                  # before putting it in the return value.                  # before putting it in the return value.
1040                  my ($start, $stop);                  my ($start, $stop);
1041            Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
1042                  if ($dir eq "+") {                  if ($dir eq "+") {
1043                          $start = $beg;                          $start = $beg;
1044                          $stop = $beg + $len - 1;                          $stop = $beg + $len - 1;
1045                  } else {                  } else {
1046                          $start = $beg + $len + 1;              $start = $beg - $len + 1;
1047                          $stop = $beg;                          $stop = $beg;
1048                  }                  }
1049            Trace("Looking for sequences containing $start through $stop.") if T(SDNA => 4);
1050                  my $query = $self->Get(['IsMadeUpOf','Sequence'],                  my $query = $self->Get(['IsMadeUpOf','Sequence'],
1051                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .                          "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
1052                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",                          " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
# Line 782  Line 1058 
1058                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',                                  $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
1059                                                                     'IsMadeUpOf(len)']);                                                                     'IsMadeUpOf(len)']);
1060                          my $stopPosition = $startPosition + $sequenceLength;                          my $stopPosition = $startPosition + $sequenceLength;
1061                Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
1062                          # Figure out the start point and length of the relevant section.                          # Figure out the start point and length of the relevant section.
1063                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);                          my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
1064                          my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
1065                Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
1066                          # Add the relevant data to the location data.                          # Add the relevant data to the location data.
1067                          $locationDNA .= substr($sequenceData, $pos1, $len);              $locationDNA .= substr($sequenceData, $pos1, $len1);
1068                  }                  }
1069                  # 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.
1070                  if ($dir eq '+') {                  if ($dir eq '+') {
1071                          $retVal .= $locationDNA;                          $retVal .= $locationDNA;
1072                  } else {                  } else {
1073                          $locationDNA = join('', reverse split //, $locationDNA);              $retVal .= FIG::reverse_comp($locationDNA);
                         $retVal .= $locationDNA;  
1074                  }                  }
1075          }          }
1076          # Return the result.          # Return the result.
# Line 802  Line 1079 
1079    
1080  =head3 AllContigs  =head3 AllContigs
1081    
1082  C<< my @idList = $sprout->AllContigs($genomeID); >>      my @idList = $sprout->AllContigs($genomeID);
1083    
1084  Return a list of all the contigs for a genome.  Return a list of all the contigs for a genome.
1085    
# Line 830  Line 1107 
1107          return @retVal;          return @retVal;
1108  }  }
1109    
1110  =head3 ContigLength  =head3 GenomeLength
1111    
1112  C<< my $length = $sprout->ContigLength($contigID); >>      my $length = $sprout->GenomeLength($genomeID);
1113    
1114  Compute the length of a contig.  Return the length of the specified genome in base pairs.
1115    
1116  =over 4  =over 4
1117    
1118  =item contigID  =item genomeID
1119    
1120  ID of the contig whose length is desired.  ID of the genome whose base pair count is desired.
1121    
1122  =item RETURN  =item RETURN
1123    
1124  Returns the number of positions in the contig.  Returns the number of base pairs in all the contigs of the specified
1125    genome.
1126    
1127  =back  =back
1128    
1129  =cut  =cut
1130  #: Return Type $;  
1131  sub ContigLength {  sub GenomeLength {
1132          # Get the parameters.          # Get the parameters.
1133          my ($self, $contigID) = @_;      my ($self, $genomeID) = @_;
1134          # Get the contig's last sequence.      # Declare the return variable.
1135          my $query = $self->Get(['IsMadeUpOf'],      my $retVal = 0;
1136                  "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",      # Get the genome's contig sequence lengths.
1137                  [$contigID]);      my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
1138          my $sequence = $query->Fetch();                         [$genomeID], 'IsMadeUpOf(len)');
1139          # Declare the return value.      # Sum the lengths.
1140        map { $retVal += $_ } @lens;
1141        # Return the result.
1142        return $retVal;
1143    }
1144    
1145    =head3 FeatureCount
1146    
1147        my $count = $sprout->FeatureCount($genomeID, $type);
1148    
1149    Return the number of features of the specified type in the specified genome.
1150    
1151    =over 4
1152    
1153    =item genomeID
1154    
1155    ID of the genome whose feature count is desired.
1156    
1157    =item type
1158    
1159    Type of feature to count (eg. C<peg>, C<rna>, etc.).
1160    
1161    =item RETURN
1162    
1163    Returns the number of features of the specified type for the specified genome.
1164    
1165    =back
1166    
1167    =cut
1168    
1169    sub FeatureCount {
1170        # Get the parameters.
1171        my ($self, $genomeID, $type) = @_;
1172        # Compute the count.
1173        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
1174                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
1175                                    [$genomeID, $type]);
1176        # Return the result.
1177        return $retVal;
1178    }
1179    
1180    =head3 GenomeAssignments
1181    
1182        my $fidHash = $sprout->GenomeAssignments($genomeID);
1183    
1184    Return a list of a genome's assigned features. The return hash will contain each
1185    assigned feature of the genome mapped to the text of its most recent functional
1186    assignment.
1187    
1188    =over 4
1189    
1190    =item genomeID
1191    
1192    ID of the genome whose functional assignments are desired.
1193    
1194    =item RETURN
1195    
1196    Returns a reference to a hash which maps each feature to its most recent
1197    functional assignment.
1198    
1199    =back
1200    
1201    =cut
1202    
1203    sub GenomeAssignments {
1204        # Get the parameters.
1205        my ($self, $genomeID) = @_;
1206        # Declare the return variable.
1207        my $retVal = {};
1208        # Query the genome's features.
1209        my $query = $self->Get(['HasFeature', 'Feature'], "HasFeature(from-link) = ?",
1210                               [$genomeID]);
1211        # Loop through the features.
1212        while (my $data = $query->Fetch) {
1213            # Get the feature ID and assignment.
1214            my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']);
1215            if ($assignment) {
1216                $retVal->{$fid} = $assignment;
1217            }
1218        }
1219        # Return the result.
1220        return $retVal;
1221    }
1222    
1223    =head3 ContigLength
1224    
1225        my $length = $sprout->ContigLength($contigID);
1226    
1227    Compute the length of a contig.
1228    
1229    =over 4
1230    
1231    =item contigID
1232    
1233    ID of the contig whose length is desired.
1234    
1235    =item RETURN
1236    
1237    Returns the number of positions in the contig.
1238    
1239    =back
1240    
1241    =cut
1242    #: Return Type $;
1243    sub ContigLength {
1244        # Get the parameters.
1245        my ($self, $contigID) = @_;
1246        # Get the contig's last sequence.
1247        my $query = $self->Get(['IsMadeUpOf'],
1248            "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
1249            [$contigID]);
1250        my $sequence = $query->Fetch();
1251        # Declare the return value.
1252          my $retVal = 0;          my $retVal = 0;
1253          # Set it from the sequence data, if any.          # Set it from the sequence data, if any.
1254          if ($sequence) {          if ($sequence) {
1255                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);                  my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
1256                  $retVal = $start + $len;          $retVal = $start + $len - 1;
1257        }
1258        # Return the result.
1259        return $retVal;
1260    }
1261    
1262    =head3 ClusterPEGs
1263    
1264        my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs);
1265    
1266    Cluster the PEGs in a list according to the cluster coding scheme of the specified
1267    subsystem. In order for this to work properly, the subsystem object must have
1268    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> or
1269    B<get_row> methods. This causes the cluster numbers to be pulled into the
1270    subsystem's color hash. If a PEG is not found in the color hash, it will not
1271    appear in the output sequence.
1272    
1273    =over 4
1274    
1275    =item sub
1276    
1277    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
1278    method.
1279    
1280    =item pegs
1281    
1282    Reference to the list of PEGs to be clustered.
1283    
1284    =item RETURN
1285    
1286    Returns a list of the PEGs, grouped into smaller lists by cluster number.
1287    
1288    =back
1289    
1290    =cut
1291    #: Return Type $@@;
1292    sub ClusterPEGs {
1293        # Get the parameters.
1294        my ($self, $sub, $pegs) = @_;
1295        # Declare the return variable.
1296        my $retVal = [];
1297        # Loop through the PEGs, creating arrays for each cluster.
1298        for my $pegID (@{$pegs}) {
1299            my $clusterNumber = $sub->get_cluster_number($pegID);
1300            # Only proceed if the PEG is in a cluster.
1301            if ($clusterNumber >= 0) {
1302                # Push this PEG onto the sub-list for the specified cluster number.
1303                push @{$retVal->[$clusterNumber]}, $pegID;
1304            }
1305          }          }
1306          # Return the result.          # Return the result.
1307          return $retVal;          return $retVal;
# Line 871  Line 1309 
1309    
1310  =head3 GenesInRegion  =head3 GenesInRegion
1311    
1312  C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>      my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop);
1313    
1314  List the features which overlap a specified region in a contig.  List the features which overlap a specified region in a contig.
1315    
# Line 900  Line 1338 
1338  =back  =back
1339    
1340  =cut  =cut
1341  #: Return Type @@;  
1342  sub GenesInRegion {  sub GenesInRegion {
1343          # Get the parameters.          # Get the parameters.
1344          my ($self, $contigID, $start, $stop) = @_;          my ($self, $contigID, $start, $stop) = @_;
1345          # Get the maximum segment length.          # Get the maximum segment length.
1346          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 = ();  
1347          # Prime the values we'll use for the returned beginning and end.          # Prime the values we'll use for the returned beginning and end.
1348          my @initialMinMax = ($self->ContigLength($contigID), 0);          my @initialMinMax = ($self->ContigLength($contigID), 0);
1349          my ($min, $max) = @initialMinMax;          my ($min, $max) = @initialMinMax;
1350          # Create a table of parameters for each query. Each query looks for features travelling in      # Get the overlapping features.
1351        my @featureObjects = $self->GeneDataInRegion($contigID, $start, $stop);
1352        # We'l use this hash to help us track the feature IDs and sort them. The key is the
1353        # feature ID and the value is a [$left,$right] pair indicating the maximum extent
1354        # of the feature's locations.
1355        my %featureMap = ();
1356        # Loop through them to do the begin/end analysis.
1357        for my $featureObject (@featureObjects) {
1358            # Get the feature's location string. This may contain multiple actual locations.
1359            my ($locations, $fid) = $featureObject->Values([qw(Feature(location-string) Feature(id))]);
1360            my @locationSegments = split /\s*,\s*/, $locations;
1361            # Loop through the locations.
1362            for my $locationSegment (@locationSegments) {
1363                # Construct an object for the location.
1364                my $locationObject = BasicLocation->new($locationSegment);
1365                # Merge the current segment's begin and end into the min and max.
1366                my ($left, $right) = ($locationObject->Left, $locationObject->Right);
1367                my ($beg, $end);
1368                if (exists $featureMap{$fid}) {
1369                    ($beg, $end) = @{$featureMap{$fid}};
1370                    $beg = $left if $left < $beg;
1371                    $end = $right if $right > $end;
1372                } else {
1373                    ($beg, $end) = ($left, $right);
1374                }
1375                $min = $beg if $beg < $min;
1376                $max = $end if $end > $max;
1377                # Store the feature's new extent back into the hash table.
1378                $featureMap{$fid} = [$beg, $end];
1379            }
1380        }
1381        # Now we must compute the list of the IDs for the features found. We start with a list
1382        # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1383        # but the result of the sort will be the same.)
1384        my @list = map { [$featureMap{$_}->[0] + $featureMap{$_}->[1], $_] } keys %featureMap;
1385        # Now we sort by midpoint and yank out the feature IDs.
1386        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1387        # Return it along with the min and max.
1388        return (\@retVal, $min, $max);
1389    }
1390    
1391    =head3 GeneDataInRegion
1392    
1393        my @featureList = $sprout->GenesInRegion($contigID, $start, $stop);
1394    
1395    List the features which overlap a specified region in a contig.
1396    
1397    =over 4
1398    
1399    =item contigID
1400    
1401    ID of the contig containing the region of interest.
1402    
1403    =item start
1404    
1405    Offset of the first residue in the region of interest.
1406    
1407    =item stop
1408    
1409    Offset of the last residue in the region of interest.
1410    
1411    =item RETURN
1412    
1413    Returns a list of B<ERDBObjects> for the desired features. Each object will
1414    contain a B<Feature> record.
1415    
1416    =back
1417    
1418    =cut
1419    
1420    sub GeneDataInRegion {
1421        # Get the parameters.
1422        my ($self, $contigID, $start, $stop) = @_;
1423        # Get the maximum segment length.
1424        my $maximumSegmentLength = $self->MaxSegment;
1425        # Create a hash to receive the feature list. We use a hash so that we can eliminate
1426        # duplicates easily. The hash key will be the feature ID. The value will be the feature's
1427        # ERDBObject from the query.
1428        my %featuresFound = ();
1429        # Create a table of parameters for the queries. Each query looks for features travelling in
1430          # 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,
1431          # 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
1432          # 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 1435 
1435          # Loop through the query parameters.          # Loop through the query parameters.
1436          for my $parms (values %queryParms) {          for my $parms (values %queryParms) {
1437                  # Create the query.                  # Create the query.
1438                  my $query = $self->Get(['IsLocatedIn'],          my $query = $self->Get([qw(Feature IsLocatedIn)],
1439                          "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",                          "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
1440                          $parms);                          $parms);
1441                  # Loop through the feature segments found.                  # Loop through the feature segments found.
1442                  while (my $segment = $query->Fetch) {                  while (my $segment = $query->Fetch) {
1443                          # Get the data about this segment.                          # Get the data about this segment.
1444                          my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',              my ($featureID, $contig, $dir, $beg, $len) = $segment->Values([qw(IsLocatedIn(from-link)
1445                                  'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);                  IsLocatedIn(to-link) IsLocatedIn(dir) IsLocatedIn(beg) IsLocatedIn(len))]);
1446                          # 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
1447                          # 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
1448                          # 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
1449                          # length.                          # length.
1450                          my ($found, $end) = (0, 0);              my $loc = BasicLocation->new($contig, $beg, $dir, $len);
1451                          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;  
                                 }  
                         }  
1452                          if ($found) {                          if ($found) {
1453                                  # Here we need to record the feature and update the minima and maxima. First,                  # Save this feature in the result list.
1454                                  # 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;  
1455                                  }                                  }
                                 if ($end > $loc2) {  
                                         $loc2 = $end;  
                                         $max = $end if $end > $max;  
                                 }  
                                 # Store the entry back into the hash table.  
                                 $featuresFound{$featureID} = [$loc1, $loc2];  
1456                          }                          }
1457                  }                  }
1458          }      # Return the ERDB objects for the features found.
1459          # Now we must compute the list of the IDs for the features found. We start with a list      return values %featuresFound;
         # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,  
         # 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);  
1460  }  }
1461    
1462  =head3 FType  =head3 FType
1463    
1464  C<< my $ftype = $sprout->FType($featureID); >>      my $ftype = $sprout->FType($featureID);
1465    
1466  Return the type of a feature.  Return the type of a feature.
1467    
# Line 1013  Line 1491 
1491    
1492  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1493    
1494  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>      my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag);
1495    
1496  Return the annotations of a feature.  Return the annotations of a feature.
1497    
# Line 1023  Line 1501 
1501    
1502  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1503    
1504    =item rawFlag
1505    
1506    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1507    will be returned in human-readable form.
1508    
1509  =item RETURN  =item RETURN
1510    
1511  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.
1512    
1513  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1514    
1515  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1516    
1517  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1518    
# Line 1041  Line 1524 
1524  #: Return Type @%;  #: Return Type @%;
1525  sub FeatureAnnotations {  sub FeatureAnnotations {
1526          # Get the parameters.          # Get the parameters.
1527          my ($self, $featureID) = @_;      my ($self, $featureID, $rawFlag) = @_;
1528          # 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.
1529          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1530                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                                                     "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 1054  Line 1537 
1537                          $annotation->Values(['IsTargetOfAnnotation(from-link)',                          $annotation->Values(['IsTargetOfAnnotation(from-link)',
1538                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1539                                                                   'Annotation(annotation)']);                                                                   'Annotation(annotation)']);
1540            # Convert the time, if necessary.
1541            if (! $rawFlag) {
1542                $timeStamp = FriendlyTimestamp($timeStamp);
1543            }
1544                  # Assemble them into a hash.                  # Assemble them into a hash.
1545          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1546                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1547                                                             user => $user, text => $text };                                                             user => $user, text => $text };
1548                  # Add it to the return list.                  # Add it to the return list.
1549                  push @retVal, $annotationHash;                  push @retVal, $annotationHash;
# Line 1067  Line 1554 
1554    
1555  =head3 AllFunctionsOf  =head3 AllFunctionsOf
1556    
1557  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>      my %functions = $sprout->AllFunctionsOf($featureID);
1558    
1559  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
1560  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,
1561  It has the format "XXXX\nset XXXX function to\nYYYYY". In this instance, XXXX is the user ID  Functional assignments are described in the L</ParseAssignment> function. Its worth noting that
1562  and YYYYY is the functional assignment text. Its worth noting that we cannot filter on the content  we cannot filter on the content of the annotation itself because it's a text field; however,
1563  of the annotation itself because it's a text field; however, this is not a big problem because most  this is not a big problem because most features only have a small number of annotations.
1564  features only have a small number of annotations. Finally, if a single user has multiple  Finally, if a single user has multiple functional assignments, we will only keep the most
1565  functional assignments, we will only keep the most recent one.  recent one.
1566    
1567  =over 4  =over 4
1568    
# Line 1085  Line 1572 
1572    
1573  =item RETURN  =item RETURN
1574    
1575  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1576    
1577  =back  =back
1578    
# Line 1095  Line 1582 
1582          # Get the parameters.          # Get the parameters.
1583          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
1584          # Get all of the feature's annotations.          # Get all of the feature's annotations.
1585      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1586                                                      "IsTargetOfAnnotation(from-link) = ?",                                                      "IsTargetOfAnnotation(from-link) = ?",
1587                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1588                                               'MadeAnnotation(from-link)']);
1589          # Declare the return hash.          # Declare the return hash.
1590          my %retVal;          my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1591      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1592      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1593          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1594      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1595          # Get the annotation fields.          # Get the annotation fields.
1596          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1597                  # Check to see if this is a functional assignment.                  # Check to see if this is a functional assignment.
1598                  my ($user, $function) = ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1599          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1600              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1601              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1602              # return hash.              # return hash.
1603                          $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1604                  }                  }
1605          }          }
1606          # Return the hash of assignments found.          # Return the hash of assignments found.
# Line 1125  Line 1609 
1609    
1610  =head3 FunctionOf  =head3 FunctionOf
1611    
1612  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>      my $functionText = $sprout->FunctionOf($featureID, $userID);
1613    
1614  Return the most recently-determined functional assignment of a particular feature.  Return the most recently-determined functional assignment of a particular feature.
1615    
1616  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
1617  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
1618  assignment is a type of annotation. It has the format "XXXX\nset XXXX function to\nYYYYY". In this  assignment is taken from the B<Feature> or C<Annotation> table, depending.
 instance, XXXX is the user ID and YYYYY is the functional assignment text. Its worth noting that  
 we cannot filter on the content of the annotation itself because it's a text field; however, this  
 is not a big problem because most features only have a small number of annotations.  
1619    
1620  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
1621  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
1622  the specified user and FIG are considered trusted. If the user ID is omitted, only FIG  the specified user and FIG are considered trusted. If the user ID is omitted, only FIG
1623  is trusted.  is trusted.
1624    
1625  If the feature is B<not> identified by a FIG ID, then the functional assignment  If the feature is B<not> identified by a FIG ID, then we search the aliases for it.
1626  information is taken from the B<ExternalAliasFunc> table. If the table does  If no matching alias is found, we return an undefined value.
 not contain an entry for the feature, an undefined value is returned.  
1627    
1628  =over 4  =over 4
1629    
# Line 1153  Line 1633 
1633    
1634  =item userID (optional)  =item userID (optional)
1635    
1636  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
1637  C<FIG> assignment will be returned.  functional assignment in the B<Feature> table will be returned.
1638    
1639  =item RETURN  =item RETURN
1640    
# Line 1169  Line 1649 
1649          my ($self, $featureID, $userID) = @_;          my ($self, $featureID, $userID) = @_;
1650      # Declare the return value.      # Declare the return value.
1651      my $retVal;      my $retVal;
1652      # Determine the ID type.      # Find a FIG ID for this feature.
1653      if ($featureID =~ m/^fig\|/) {      my ($fid) = $self->FeaturesByAlias($featureID);
1654          # Here we have a FIG feature ID. We must build the list of trusted      # Only proceed if we have an ID.
1655          # users.      if ($fid) {
1656            # Here we have a FIG feature ID.
1657            if (!$userID) {
1658                # Use the primary assignment.
1659                ($retVal) = $self->GetEntityValues('Feature', $fid, ['Feature(assignment)']);
1660            } else {
1661                # We must build the list of trusted users.
1662          my %trusteeTable = ();          my %trusteeTable = ();
1663          # Check the user ID.          # Check the user ID.
1664          if (!$userID) {          if (!$userID) {
# Line 1194  Line 1680 
1680              }              }
1681          }          }
1682          # 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.
1683          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],              my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1684                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1685                                 [$featureID]);                                     [$fid]);
1686          my $timeSelected = 0;          my $timeSelected = 0;
1687          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1688          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1689              # Get the annotation text.              # Get the annotation text.
1690              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);                  my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1691                                                             'Annotation(time)', 'MadeAnnotation(from-link)']);
1692              # 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.
1693              my ($user, $type, $function) = split(/\n/, $text);                  my ($actualUser, $function) = _ParseAssignment($user, $text);
1694              if ($type =~ m/^set $user function to$/i) {                  Trace("Assignment user is $actualUser, text is $function.") if T(4);
1695                    if ($actualUser) {
1696                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1697                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1698                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                      if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1699                      $retVal = $function;                      $retVal = $function;
1700                      $timeSelected = $time;                      $timeSelected = $time;
1701                  }                  }
1702              }              }
1703          }          }
1704      } else {          }
         # Here we have a non-FIG feature ID. In this case the user ID does not  
         # matter. We simply get the information from the External Alias Function  
         # table.  
         ($retVal) = $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']);  
1705      }      }
1706          # Return the assignment found.          # Return the assignment found.
1707          return $retVal;          return $retVal;
1708  }  }
1709    
1710    =head3 FunctionsOf
1711    
1712        my @functionList = $sprout->FunctionOf($featureID, $userID);
1713    
1714    Return the functional assignments of a particular feature.
1715    
1716    The functional assignment is handled differently depending on the type of feature. If
1717    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1718    assignment is a type of annotation. The format of an assignment is described in
1719    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1720    annotation itself because it's a text field; however, this is not a big problem because
1721    most features only have a small number of annotations.
1722    
1723    =over 4
1724    
1725    =item featureID
1726    
1727    ID of the feature whose functional assignments are desired.
1728    
1729    =item RETURN
1730    
1731    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1732    that user.
1733    
1734    =back
1735    
1736    =cut
1737    #: Return Type @@;
1738    sub FunctionsOf {
1739        # Get the parameters.
1740        my ($self, $featureID) = @_;
1741        # Declare the return value.
1742        my @retVal = ();
1743        # Convert to a FIG ID.
1744        my ($fid) = $self->FeaturesByAlias($featureID);
1745        # Only proceed if we found one.
1746        if ($fid) {
1747            # Here we have a FIG feature ID. We must build the list of trusted
1748            # users.
1749            my %trusteeTable = ();
1750            # Build a query for all of the feature's annotations, sorted by date.
1751            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1752                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1753                                   [$fid]);
1754            my $timeSelected = 0;
1755            # Loop until we run out of annotations.
1756            while (my $annotation = $query->Fetch()) {
1757                # Get the annotation text.
1758                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1759                                                                'Annotation(time)',
1760                                                                'MadeAnnotation(user)']);
1761                # Check to see if this is a functional assignment for a trusted user.
1762                my ($actualUser, $function) = _ParseAssignment($user, $text);
1763                if ($actualUser) {
1764                    # Here it is a functional assignment.
1765                    push @retVal, [$actualUser, $function];
1766                }
1767            }
1768        }
1769        # Return the assignments found.
1770        return @retVal;
1771    }
1772    
1773  =head3 BBHList  =head3 BBHList
1774    
1775  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>      my $bbhHash = $sprout->BBHList($genomeID, \@featureList);
1776    
1777  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
1778  on a specified target genome.  on a specified target genome.
# Line 1242  Line 1789 
1789    
1790  =item RETURN  =item RETURN
1791    
1792  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
1793  their best hits.  on the target genome.
1794    
1795  =back  =back
1796    
# Line 1256  Line 1803 
1803          my %retVal = ();          my %retVal = ();
1804          # Loop through the incoming features.          # Loop through the incoming features.
1805          for my $featureID (@{$featureList}) {          for my $featureID (@{$featureList}) {
1806                  # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1807                  my $query = $self->Get(['IsBidirectionalBestHitOf'],          my @bbhData = FIGRules::BBHData($featureID);
1808                                                             "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",          # Peel off the BBHs found.
1809                                                             [$featureID, $genomeID]);          my @found = ();
1810                  # Look for the best hit.          for my $bbh (@bbhData) {
1811                  my $bbh = $query->Fetch;              my $fid = $bbh->[0];
1812                  if ($bbh) {              my $bbGenome = $self->GenomeOf($fid);
1813                          my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              if ($bbGenome eq $genomeID) {
1814                          $retVal{$featureID} = $targetFeature;                  push @found, $fid;
1815                  }                  }
1816          }          }
1817            $retVal{$featureID} = \@found;
1818        }
1819          # Return the mapping.          # Return the mapping.
1820          return \%retVal;          return \%retVal;
1821  }  }
1822    
1823  =head3 FeatureAliases  =head3 SimList
1824    
1825  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>      my %similarities = $sprout->SimList($featureID, $count);
1826    
1827  Return a list of the aliases for a specified feature.  Return a list of the similarities to the specified feature.
1828    
1829    This method just returns the bidirectional best hits for performance reasons.
1830    
1831  =over 4  =over 4
1832    
1833  =item featureID  =item featureID
1834    
1835  ID of the feature whose aliases are desired.  ID of the feature whose similarities are desired.
1836    
1837  =item RETURN  =item count
1838    
1839  Returns a list of the feature's aliases. If the feature is not found or has no aliases, it will  Maximum number of similar features to be returned, or C<0> to return them all.
 return an empty list.  
1840    
1841  =back  =back
1842    
1843  =cut  =cut
1844  #: Return Type @;  #: Return Type %;
1845  sub FeatureAliases {  sub SimList {
1846          # Get the parameters.          # Get the parameters.
1847          my ($self, $featureID) = @_;      my ($self, $featureID, $count) = @_;
1848          # Get the desired feature's aliases      # Ask for the best hits.
1849          my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);      my @lists = FIGRules::BBHData($featureID);
1850        # Create the return value.
1851        my %retVal = ();
1852        for my $tuple (@lists) {
1853            $retVal{$tuple->[0]} = $tuple->[1];
1854        }
1855          # Return the result.          # Return the result.
1856          return @retVal;      return %retVal;
1857  }  }
1858    
1859  =head3 GenomeOf  =head3 IsComplete
1860    
1861  C<< my $genomeID = $sprout->GenomeOf($featureID); >>      my $flag = $sprout->IsComplete($genomeID);
1862    
1863  Return the genome that contains a specified feature.  Return TRUE if the specified genome is complete, else FALSE.
1864    
1865  =over 4  =over 4
1866    
1867  =item featureID  =item genomeID
1868    
1869  ID of the feature whose genome is desired.  ID of the genome whose completeness status is desired.
1870    
1871  =item RETURN  =item RETURN
1872    
1873  Returns the ID of the genome for the specified feature. If the feature is not found, returns  Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
1874  an undefined value.  not found.
1875    
1876  =back  =back
1877    
1878  =cut  =cut
1879  #: Return Type $;  #: Return Type $;
1880  sub GenomeOf {  sub IsComplete {
1881          # Get the parameters.          # Get the parameters.
1882          my ($self, $featureID) = @_;      my ($self, $genomeID) = @_;
1883          # Create a query to find the genome associated with the feature.      # Declare the return variable.
         my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);  
         # Declare the return value.  
1884          my $retVal;          my $retVal;
1885          # Get the genome ID.      # Get the genome's data.
1886          if (my $relationship = $query->Fetch()) {      my $genomeData = $self->GetEntity('Genome', $genomeID);
1887                  ($retVal) = $relationship->Value('HasContig(from-link)');      if ($genomeData) {
1888            # The genome exists, so get the completeness flag.
1889            $retVal = $genomeData->PrimaryValue('Genome(complete)');
1890          }          }
1891          # Return the value found.      # Return the result.
1892          return $retVal;          return $retVal;
1893  }  }
1894    
1895  =head3 CoupledFeatures  =head3 FeatureAliases
1896    
1897  C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >>      my @aliasList = $sprout->FeatureAliases($featureID);
1898    
1899  Return the features functionally coupled with a specified feature. Features are considered  Return a list of the aliases for a specified feature.
1900  functionally coupled if they tend to be clustered on the same chromosome.  
1901    =over 4
1902    
1903    =item featureID
1904    
1905    ID of the feature whose aliases are desired.
1906    
1907    =item RETURN
1908    
1909    Returns a list of the feature's aliases. If the feature is not found or has no aliases, it will
1910    return an empty list.
1911    
1912    =back
1913    
1914    =cut
1915    #: Return Type @;
1916    sub FeatureAliases {
1917        # Get the parameters.
1918        my ($self, $featureID) = @_;
1919        # Get the desired feature's aliases
1920        my @retVal = $self->GetFlat(['IsAliasOf'], "IsAliasOf(to-link) = ?", [$featureID], 'IsAliasOf(from-link)');
1921        # Return the result.
1922        return @retVal;
1923    }
1924    
1925    =head3 GenomeOf
1926    
1927        my $genomeID = $sprout->GenomeOf($featureID);
1928    
1929    Return the genome that contains a specified feature or contig.
1930    
1931    =over 4
1932    
1933    =item featureID
1934    
1935    ID of the feature or contig whose genome is desired.
1936    
1937    =item RETURN
1938    
1939    Returns the ID of the genome for the specified feature or contig. If the feature or contig is not
1940    found, returns an undefined value.
1941    
1942    =back
1943    
1944    =cut
1945    #: Return Type $;
1946    sub GenomeOf {
1947        # Get the parameters.
1948        my ($self, $featureID) = @_;
1949        # Declare the return value.
1950        my $retVal;
1951        # Parse the genome ID from the feature ID.
1952        if ($featureID =~ /^fig\|(\d+\.\d+)/) {
1953            $retVal = $1;
1954        } else {
1955            # Find the feature by alias.
1956            my ($realFeatureID) = $self->FeaturesByAlias($featureID);
1957            if ($realFeatureID && $realFeatureID =~ /^fig\|(\d+\.\d+)/) {
1958                $retVal = $1;
1959            }
1960        }
1961        # Return the value found.
1962        return $retVal;
1963    }
1964    
1965    =head3 CoupledFeatures
1966    
1967        my %coupleHash = $sprout->CoupledFeatures($featureID);
1968    
1969    Return the features functionally coupled with a specified feature. Features are considered
1970    functionally coupled if they tend to be clustered on the same chromosome.
1971    
1972  =over 4  =over 4
1973    
# Line 1361  Line 1986 
1986  sub CoupledFeatures {  sub CoupledFeatures {
1987          # Get the parameters.          # Get the parameters.
1988          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
1989          # Create a query to retrieve the functionally-coupled features. Note that we depend on the      # Ask the coupling server for the data.
1990          # 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);
1991          # (B,A) will also be found.      my @rawPairs = FIGRules::NetCouplingData('coupled_to', id1 => $featureID);
1992          my $query = $self->Get(['IsClusteredOnChromosomeWith'],      Trace(scalar(@rawPairs) . " couplings returned.") if T(coupling => 3);
1993                                                     "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.  
1994          my %retVal = ();          my %retVal = ();
1995          # Retrieve the relationship records and store them in the hash.      for my $pair (@rawPairs) {
1996          while (my $clustering = $query->Fetch()) {          # Get the feature ID and score.
1997                  my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)',          my ($featureID2, $score) = @{$pair};
1998                                                                      'IsClusteredOnChromosomeWith(score)']);          # Only proceed if the feature is in NMPDR.
1999                  $retVal{$otherFeatureID} = $score;          if ($self->_CheckFeature($featureID2)) {
2000                  $found = 1;              $retVal{$featureID2} = $score;
2001            }
2002          }          }
2003          # 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
2004          # the incoming feature as well.          # the incoming feature as well.
2005          if ($found) {      if (keys %retVal) {
2006                  $retVal{$featureID} = 9999;                  $retVal{$featureID} = 9999;
2007      }      }
2008          # Return the hash.          # Return the hash.
2009          return %retVal;          return %retVal;
2010  }  }
2011    
2012  =head3 GetEntityTypes  =head3 CouplingEvidence
2013    
2014        my @evidence = $sprout->CouplingEvidence($peg1, $peg2);
2015    
2016    Return the evidence for a functional coupling.
2017    
2018    A pair of features is considered evidence of a coupling between two other
2019    features if they occur close together on a contig and both are similar to
2020    the coupled features. So, if B<A1> and B<A2> are close together on a contig,
2021    B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
2022    B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
2023    similar to B<A2>.
2024    
2025    The score of a coupling is determined by the number of pieces of evidence
2026    that are considered I<representative>. If several evidence items belong to
2027    a group of genomes that are close to each other, only one of those items
2028    is considered representative. The other evidence items are presumed to be
2029    there because of the relationship between the genomes rather than because
2030    the two proteins generated by the features have a related functionality.
2031    
2032    Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
2033    I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
2034    is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
2035    and FALSE otherwise.
2036    
2037    =over 4
2038    
2039    =item peg1
2040    
2041    ID of the feature of interest.
2042    
2043    =item peg2
2044    
2045    ID of a feature functionally coupled to the feature of interest.
2046    
2047    =item RETURN
2048    
2049    Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
2050    of interest, a feature similar to the functionally coupled feature, and a flag
2051    that is TRUE for a representative piece of evidence and FALSE otherwise.
2052    
2053    =back
2054    
2055    =cut
2056    #: Return Type @@;
2057    sub CouplingEvidence {
2058        # Get the parameters.
2059        my ($self, $peg1, $peg2) = @_;
2060        # Declare the return variable.
2061        my @retVal = ();
2062        # Get the coupling and evidence data.
2063        my @rawData = FIGRules::NetCouplingData('coupling_evidence', id1 => $peg1, id2 => $peg2);
2064        # Loop through the raw data, saving the ones that are in NMPDR genomes.
2065        for my $rawTuple (@rawData) {
2066            if ($self->_CheckFeature($rawTuple->[0]) && $self->_CheckFeature($rawTuple->[1])) {
2067                push @retVal, $rawTuple;
2068            }
2069        }
2070        # Return the result.
2071        return @retVal;
2072    }
2073    
2074    =head3 GetSynonymGroup
2075    
2076        my $id = $sprout->GetSynonymGroup($fid);
2077    
2078    Return the synonym group name for the specified feature.
2079    
2080    =over 4
2081    
2082    =item fid
2083    
2084    ID of the feature whose synonym group is desired.
2085    
2086    =item RETURN
2087    
2088    The name of the synonym group to which the feature belongs. If the feature does
2089    not belong to a synonym group, the feature ID itself is returned.
2090    
2091    =back
2092    
2093    =cut
2094    
2095    sub GetSynonymGroup {
2096        # Get the parameters.
2097        my ($self, $fid) = @_;
2098        # Declare the return variable.
2099        my $retVal;
2100        # Find the synonym group.
2101        my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
2102                                       [$fid], 'IsSynonymGroupFor(from-link)');
2103        # Check to see if we found anything.
2104        if (@groups) {
2105            $retVal = $groups[0];
2106        } else {
2107            $retVal = $fid;
2108        }
2109        # Return the result.
2110        return $retVal;
2111    }
2112    
2113    =head3 GetBoundaries
2114    
2115  C<< my @entityList = $sprout->GetEntityTypes(); >>      my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList);
2116    
2117  Return the list of supported entity types.  Determine the begin and end boundaries for the locations in a list. All of the
2118    locations must belong to the same contig and have mostly the same direction in
2119    order for this method to produce a meaningful result. The resulting
2120    begin/end pair will contain all of the bases in any of the locations.
2121    
2122    =over 4
2123    
2124    =item locList
2125    
2126    List of locations to process.
2127    
2128    =item RETURN
2129    
2130    Returns a 3-tuple consisting of the contig ID, the beginning boundary,
2131    and the ending boundary. The beginning boundary will be left of the
2132    end for mostly-forward locations and right of the end for mostly-backward
2133    locations.
2134    
2135    =back
2136    
2137  =cut  =cut
2138  #: Return Type @;  
2139  sub GetEntityTypes {  sub GetBoundaries {
2140          # Get the parameters.          # Get the parameters.
2141          my ($self) = @_;      my ($self, @locList) = @_;
2142          # Get the underlying database object.      # Set up the counters used to determine the most popular direction.
2143          my $erdb = $self->{_erdb};      my %counts = ( '+' => 0, '-' => 0 );
2144          # Get its entity type list.      # Get the last location and parse it.
2145          my @retVal = $erdb->GetEntityTypes();      my $locObject = BasicLocation->new(pop @locList);
2146        # Prime the loop with its data.
2147        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
2148        # Count its direction.
2149        $counts{$locObject->Dir}++;
2150        # Loop through the remaining locations. Note that in most situations, this loop
2151        # will not iterate at all, because most of the time we will be dealing with a
2152        # singleton list.
2153        for my $loc (@locList) {
2154            # Create a location object.
2155            my $locObject = BasicLocation->new($loc);
2156            # Count the direction.
2157            $counts{$locObject->Dir}++;
2158            # Get the left end and the right end.
2159            my $left = $locObject->Left;
2160            my $right = $locObject->Right;
2161            # Merge them into the return variables.
2162            if ($left < $beg) {
2163                $beg = $left;
2164            }
2165            if ($right > $end) {
2166                $end = $right;
2167            }
2168        }
2169        # If the most common direction is reverse, flip the begin and end markers.
2170        if ($counts{'-'} > $counts{'+'}) {
2171            ($beg, $end) = ($end, $beg);
2172        }
2173        # Return the result.
2174        return ($contig, $beg, $end);
2175  }  }
2176    
2177  =head3 ReadFasta  =head3 ReadFasta
2178    
2179  C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>      my %sequenceData = Sprout::ReadFasta($fileName, $prefix);
2180    
2181  Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by  Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by
2182  one or more lines of data. The first line begins with a > character and contains an ID.  one or more lines of data. The first line begins with a > character and contains an ID.
# Line 1447  Line 2218 
2218                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {                  if ($line =~ m/^>\s*(.+?)(\s|\n)/) {
2219                          # 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.
2220                          if ($id) {                          if ($id) {
2221                                  $retVal{$id} = $sequence;                  $retVal{$id} = lc $sequence;
2222                          }                          }
2223                          # Clear the sequence accumulator and save the new ID.                          # Clear the sequence accumulator and save the new ID.
2224                          ($id, $sequence) = ("$prefix$1", "");                          ($id, $sequence) = ("$prefix$1", "");
2225                  } else {                  } else {
2226                          # 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.
2227                          # First, we get the actual data out.              # First, we get the actual data out. Note that we normalize to lower
2228                # case.
2229                          $line =~ /^\s*(.*?)(\s|\n)/;                          $line =~ /^\s*(.*?)(\s|\n)/;
2230                          $sequence .= $1;                          $sequence .= $1;
2231                  }                  }
2232          }          }
2233          # Flush out the last sequence (if any).          # Flush out the last sequence (if any).
2234          if ($sequence) {          if ($sequence) {
2235                  $retVal {$id} = $sequence;          $retVal{$id} = lc $sequence;
2236          }          }
2237        # Close the file.
2238        close FASTAFILE;
2239          # Return the hash constructed from the file.          # Return the hash constructed from the file.
2240          return %retVal;          return %retVal;
2241  }  }
2242    
2243  =head3 FormatLocations  =head3 FormatLocations
2244    
2245  C<< my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat); >>      my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat);
2246    
2247  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
2248  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 2307 
2307    
2308  =head3 DumpData  =head3 DumpData
2309    
2310  C<< $sprout->DumpData(); >>      $sprout->DumpData();
2311    
2312  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.
2313    
# Line 1545  Line 2319 
2319          # Get the data directory name.          # Get the data directory name.
2320          my $outputDirectory = $self->{_options}->{dataDir};          my $outputDirectory = $self->{_options}->{dataDir};
2321          # Dump the relations.          # Dump the relations.
2322          $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2323  }  }
2324    
2325  =head3 XMLFileName  =head3 XMLFileName
2326    
2327  C<< my $fileName = $sprout->XMLFileName(); >>      my $fileName = $sprout->XMLFileName();
2328    
2329  Return the name of this database's XML definition file.  Return the name of this database's XML definition file.
2330    
# Line 1561  Line 2335 
2335          return $self->{_xmlName};          return $self->{_xmlName};
2336  }  }
2337    
2338    =head3 GetGenomeNameData
2339    
2340        my ($genus, $species, $strain) = $sprout->GenomeNameData($genomeID);
2341    
2342    Return the genus, species, and unique characterization for a genome. This
2343    is similar to L</GenusSpecies>, with the exception that it returns the
2344    values in three seperate fields.
2345    
2346    =over 4
2347    
2348    =item genomeID
2349    
2350    ID of the genome whose name data is desired.
2351    
2352    =item RETURN
2353    
2354    Returns a three-element list, consisting of the genus, species, and strain
2355    of the specified genome. If the genome is not found, an error occurs.
2356    
2357    =back
2358    
2359    =cut
2360    
2361    sub GetGenomeNameData {
2362        # Get the parameters.
2363        my ($self, $genomeID) = @_;
2364        # Get the desired values.
2365        my ($genus, $species, $strain) = $self->GetEntityValues('Genome', $genomeID =>
2366                                                                [qw(Genome(genus) Genome(species) Genome(unique-characterization))]);
2367        # Throw an error if they were not found.
2368        if (! defined $genus) {
2369            Confess("Genome $genomeID not found in database.");
2370        }
2371        # Return the results.
2372        return ($genus, $species, $strain);
2373    }
2374    
2375    =head3 GetGenomeByNameData
2376    
2377        my @genomes = $sprout->GetGenomeByNameData($genus, $species, $strain);
2378    
2379    Return a list of the IDs of the genomes with the specified genus,
2380    species, and strain. In almost every case, there will be either zero or
2381    one IDs returned; however, two or more IDs could be returned if there are
2382    multiple versions of the genome in the database.
2383    
2384    =over 4
2385    
2386    =item genus
2387    
2388    Genus of the desired genome.
2389    
2390    =item species
2391    
2392    Species of the desired genome.
2393    
2394    =item strain
2395    
2396    Strain (unique characterization) of the desired genome. This may be an empty
2397    string, in which case it is presumed that the desired genome has no strain
2398    specified.
2399    
2400    =item RETURN
2401    
2402    Returns a list of the IDs of the genomes having the specified genus, species, and
2403    strain.
2404    
2405    =back
2406    
2407    =cut
2408    
2409    sub GetGenomeByNameData {
2410        # Get the parameters.
2411        my ($self, $genus, $species, $strain) = @_;
2412        # Try to find the genomes.
2413        my @retVal = $self->GetFlat(['Genome'], "Genome(genus) = ? AND Genome(species) = ? AND Genome(unique-characterization) = ?",
2414                                    [$genus, $species, $strain], 'Genome(id)');
2415        # Return the result.
2416        return @retVal;
2417    }
2418    
2419  =head3 Insert  =head3 Insert
2420    
2421  C<< $sprout->Insert($objectType, \%fieldHash); >>      $sprout->Insert($objectType, \%fieldHash);
2422    
2423  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
2424  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 2427 
2427  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
2428  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>.
2429    
2430  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']});
2431    
2432  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
2433  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>.
2434    
2435  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'});
2436    
2437  =over 4  =over 4
2438    
# Line 1597  Line 2452 
2452          # Get the parameters.          # Get the parameters.
2453          my ($self, $objectType, $fieldHash) = @_;          my ($self, $objectType, $fieldHash) = @_;
2454          # Call the underlying method.          # Call the underlying method.
2455          $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2456  }  }
2457    
2458  =head3 Annotate  =head3 Annotate
2459    
2460  C<< my $ok = $sprout->Annotate($fid, $timestamp, $user, $text); >>      my $ok = $sprout->Annotate($fid, $timestamp, $user, $text);
2461    
2462  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
2463  specified feature and user.  specified feature and user.
# Line 1656  Line 2511 
2511    
2512  =head3 AssignFunction  =head3 AssignFunction
2513    
2514  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function); >>      my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser);
2515    
2516  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
2517  format is "XXXX\nset XXXX function to\nYYYYY" where XXXX is the feature type and YYYY is the functional  format is described in L</ParseAssignment>.
 assignment text.  
2518    
2519  =over 4  =over 4
2520    
# Line 1670  Line 2524 
2524    
2525  =item user  =item user
2526    
2527  Name of the user making the assignment. This is frequently a group name, like C<kegg> or C<fig>.  Name of the user group making the assignment, such as C<kegg> or C<fig>.
2528    
2529  =item function  =item function
2530    
2531  Text of the function being assigned.  Text of the function being assigned.
2532    
2533    =item assigningUser (optional)
2534    
2535    Name of the individual user making the assignment. If omitted, defaults to the user group.
2536    
2537  =item RETURN  =item RETURN
2538    
2539  Returns 1 if successful, 0 if an error occurred.  Returns 1 if successful, 0 if an error occurred.
# Line 1686  Line 2544 
2544  #: Return Type $;  #: Return Type $;
2545  sub AssignFunction {  sub AssignFunction {
2546          # Get the parameters.          # Get the parameters.
2547          my ($self, $featureID, $user, $function) = @_;      my ($self, $featureID, $user, $function, $assigningUser) = @_;
2548        # Default the assigning user.
2549        if (! $assigningUser) {
2550            $assigningUser = $user;
2551        }
2552          # Create an annotation string from the parameters.          # Create an annotation string from the parameters.
2553          my $annotationText = "$user\nset $user function to\n$function";      my $annotationText = "$assigningUser\nset $user function to\n$function";
2554          # Get the current time.          # Get the current time.
2555          my $now = time;          my $now = time;
2556          # Declare the return variable.          # Declare the return variable.
# Line 1709  Line 2571 
2571    
2572  =head3 FeaturesByAlias  =head3 FeaturesByAlias
2573    
2574  C<< my @features = $sprout->FeaturesByAlias($alias); >>      my @features = $sprout->FeaturesByAlias($alias);
2575    
2576  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
2577  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 1743  Line 2605 
2605                  push @retVal, $mappedAlias;                  push @retVal, $mappedAlias;
2606          } else {          } else {
2607                  # 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.
2608                  @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');          @retVal = $self->GetFlat(['IsAliasOf'], 'IsAliasOf(from-link) = ?', [$mappedAlias], 'IsAliasOf(to-link)');
2609          }          }
2610          # Return the result.          # Return the result.
2611          return @retVal;          return @retVal;
2612  }  }
2613    
 =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;  
 }  
   
2614  =head3 FeatureTranslation  =head3 FeatureTranslation
2615    
2616  C<< my $translation = $sprout->FeatureTranslation($featureID); >>      my $translation = $sprout->FeatureTranslation($featureID);
2617    
2618  Return the translation of a feature.  Return the translation of a feature.
2619    
# Line 1813  Line 2641 
2641    
2642  =head3 Taxonomy  =head3 Taxonomy
2643    
2644  C<< my @taxonomyList = $sprout->Taxonomy($genome); >>      my @taxonomyList = $sprout->Taxonomy($genome);
2645    
2646  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
2647  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>,
2648  or C<Eukaryote>) to sub-species. For example,  or C<Eukaryote>) to sub-species. For example,
2649    
2650  C<< (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12) >>      (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12)
2651    
2652  =over 4  =over 4
2653    
# Line 1854  Line 2682 
2682    
2683  =head3 CrudeDistance  =head3 CrudeDistance
2684    
2685  C<< my $distance = $sprout->CrudeDistance($genome1, $genome2); >>      my $distance = $sprout->CrudeDistance($genome1, $genome2);
2686    
2687  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
2688  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 1906  Line 2734 
2734    
2735  =head3 RoleName  =head3 RoleName
2736    
2737  C<< my $roleName = $sprout->RoleName($roleID); >>      my $roleName = $sprout->RoleName($roleID);
2738    
2739  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
2740  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 1940  Line 2768 
2768    
2769  =head3 RoleDiagrams  =head3 RoleDiagrams
2770    
2771  C<< my @diagrams = $sprout->RoleDiagrams($roleID); >>      my @diagrams = $sprout->RoleDiagrams($roleID);
2772    
2773  Return a list of the diagrams containing a specified functional role.  Return a list of the diagrams containing a specified functional role.
2774    
# Line 1970  Line 2798 
2798    
2799  =head3 FeatureProperties  =head3 FeatureProperties
2800    
2801  C<< my @properties = $sprout->FeatureProperties($featureID); >>      my @properties = $sprout->FeatureProperties($featureID);
2802    
2803  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
2804  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
2805  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
2806  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
2807  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.  
2808    
2809  =over 4  =over 4
2810    
# Line 1988  Line 2814 
2814    
2815  =item RETURN  =item RETURN
2816    
2817  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.  
2818    
2819  =back  =back
2820    
# Line 1999  Line 2824 
2824          # Get the parameters.          # Get the parameters.
2825          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
2826          # Get the properties.          # Get the properties.
2827          my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],      my @attributes = $self->{_ca}->GetAttributes($featureID);
2828                                                          ['Property(property-name)', 'Property(property-value)',      # Strip the feature ID off each tuple.
2829                                                           'HasProperty(evidence)']);      my @retVal = ();
2830        for my $attributeRow (@attributes) {
2831            shift @{$attributeRow};
2832            push @retVal, $attributeRow;
2833        }
2834          # Return the resulting list.          # Return the resulting list.
2835          return @retVal;          return @retVal;
2836  }  }
2837    
2838  =head3 DiagramName  =head3 DiagramName
2839    
2840  C<< my $diagramName = $sprout->DiagramName($diagramID); >>      my $diagramName = $sprout->DiagramName($diagramID);
2841    
2842  Return the descriptive name of a diagram.  Return the descriptive name of a diagram.
2843    
# Line 2034  Line 2863 
2863          return $retVal;          return $retVal;
2864  }  }
2865    
2866    =head3 PropertyID
2867    
2868        my $id = $sprout->PropertyID($propName, $propValue);
2869    
2870    Return the ID of the specified property name and value pair, if the
2871    pair exists. Only a small subset of the FIG attributes are stored as
2872    Sprout properties, mostly for use in search optimization.
2873    
2874    =over 4
2875    
2876    =item propName
2877    
2878    Name of the desired property.
2879    
2880    =item propValue
2881    
2882    Value expected for the desired property.
2883    
2884    =item RETURN
2885    
2886    Returns the ID of the name/value pair, or C<undef> if the pair does not exist.
2887    
2888    =back
2889    
2890    =cut
2891    
2892    sub PropertyID {
2893        # Get the parameters.
2894        my ($self, $propName, $propValue) = @_;
2895        # Try to find the ID.
2896        my ($retVal) = $self->GetFlat(['Property'],
2897                                      "Property(property-name) = ? AND Property(property-value) = ?",
2898                                      [$propName, $propValue], 'Property(id)');
2899        # Return the result.
2900        return $retVal;
2901    }
2902    
2903  =head3 MergedAnnotations  =head3 MergedAnnotations
2904    
2905  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>      my @annotationList = $sprout->MergedAnnotations(\@list);
2906    
2907  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
2908  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 2085  Line 2951 
2951    
2952  =head3 RoleNeighbors  =head3 RoleNeighbors
2953    
2954  C<< my @roleList = $sprout->RoleNeighbors($roleID); >>      my @roleList = $sprout->RoleNeighbors($roleID);
2955    
2956  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
2957  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 2128  Line 2994 
2994    
2995  =head3 FeatureLinks  =head3 FeatureLinks
2996    
2997  C<< my @links = $sprout->FeatureLinks($featureID); >>      my @links = $sprout->FeatureLinks($featureID);
2998    
2999  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
3000  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 2159  Line 3025 
3025    
3026  =head3 SubsystemsOf  =head3 SubsystemsOf
3027    
3028  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>      my %subsystems = $sprout->SubsystemsOf($featureID);
3029    
3030  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
3031  to the role the feature performs.  to the roles the feature performs.
3032    
3033  =over 4  =over 4
3034    
# Line 2172  Line 3038 
3038    
3039  =item RETURN  =item RETURN
3040    
3041  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.
3042    
3043  =back  =back
3044    
3045  =cut  =cut
3046  #: Return Type %;  #: Return Type %@;
3047  sub SubsystemsOf {  sub SubsystemsOf {
3048          # Get the parameters.          # Get the parameters.
3049          my ($self, $featureID) = @_;          my ($self, $featureID) = @_;
3050          # Use the SSCell to connect features to subsystems.      # Get the subsystem list.
3051          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],          my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'],
3052                                                                          "ContainsFeature(to-link) = ?", [$featureID],                                                                          "ContainsFeature(to-link) = ?", [$featureID],
3053                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                                                          ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
3054          # Create the return value.          # Create the return value.
3055          my %retVal = ();          my %retVal = ();
3056        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
3057        # in two spreadsheet cells.
3058        my %dupHash = ();
3059          # Loop through the results, adding them to the hash.          # Loop through the results, adding them to the hash.
3060          for my $record (@subsystems) {          for my $record (@subsystems) {
3061                  $retVal{$record->[0]} = $record->[1];          # Get this subsystem and role.
3062            my ($subsys, $role) = @{$record};
3063            # Insure it's the first time for both.
3064            my $dupKey = "$subsys\n$role";
3065            if (! exists $dupHash{"$subsys\n$role"}) {
3066                $dupHash{$dupKey} = 1;
3067                push @{$retVal{$subsys}}, $role;
3068            }
3069          }          }
3070          # Return the hash.          # Return the hash.
3071          return %retVal;          return %retVal;
3072  }  }
3073    
3074  =head3 RelatedFeatures  =head3 SubsystemList
3075    
3076  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>      my @subsystems = $sprout->SubsystemList($featureID);
3077    
3078  Return a list of the features which are bi-directional best hits of the specified feature and  Return a list containing the names of the subsystems in which the specified
3079  have been assigned the specified function by the specified user. If no such features exists,  feature participates. Unlike L</SubsystemsOf>, this method only returns the
3080  an empty list will be returned.  subsystem names, not the roles.
3081    
3082  =over 4  =over 4
3083    
3084  =item featureID  =item featureID
3085    
3086  ID of the feature to whom the desired features are related.  ID of the feature whose subsystem names are desired.
   
 =item function  
   
 Functional assignment (as returned by C</FunctionOf>) that is used to determine which related  
 features should be selected.  
   
 =item userID  
   
 ID of the user whose functional assignments are to be used. If omitted, C<FIG> is assumed.  
3087    
3088  =item RETURN  =item RETURN
3089    
3090  Returns a list of the related features with the specified function.  Returns a list of the names of the subsystems in which the feature participates.
3091    
3092  =back  =back
3093    
3094  =cut  =cut
3095  #: Return Type @;  #: Return Type @;
3096  sub RelatedFeatures {  sub SubsystemList {
3097          # Get the parameters.          # Get the parameters.
3098          my ($self, $featureID, $function, $userID) = @_;      my ($self, $featureID) = @_;
3099          # Get a list of the features that are BBHs of the incoming feature.      # Get the list of names. We do a join to the Subsystem table because we have missing subsystems in
3100          my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],      # the Sprout database!
3101                                                                           "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],      my @retVal = $self->GetFlat(['HasRoleInSubsystem', 'Subsystem'], "HasRoleInSubsystem(from-link) = ?",
3102                                                                           'IsBidirectionalBestHitOf(to-link)');                                  [$featureID], 'HasRoleInSubsystem(to-link)');
3103          # Now we loop through the features, pulling out the ones that have the correct      # Return the result, sorted.
3104          # functional assignment.      return sort @retVal;
         my @retVal = ();  
         for my $bbhFeature (@bbhFeatures) {  
                 # Get this feature's functional assignment.  
                 my $newFunction = $self->FunctionOf($bbhFeature, $userID);  
                 # If it matches, add it to the result list.  
                 if ($newFunction eq $function) {  
                         push @retVal, $bbhFeature;  
                 }  
         }  
         # Return the result list.  
         return @retVal;  
3105  }  }
3106    
3107  =head3 TaxonomySort  =head3 GenomeSubsystemData
3108    
3109  C<< my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs); >>      my %featureData = $sprout->GenomeSubsystemData($genomeID);
3110    
3111  Return a list formed by sorting the specified features by the taxonomy of the containing  Return a hash mapping genome features to their subsystem roles.
 genome. This will cause genomes from similar organisms to float close to each other.  
   
 This task could almost be handled by the database; however, the taxonomy string in the  
 database is a text field and can't be indexed. Instead, we create a hash table that maps  
 taxonomy strings to lists of features. We then process the hash table using a key sort  
 and merge the feature lists together to create the output.  
3112    
3113  =over 4  =over 4
3114    
3115  =item $featureIDs  =item genomeID
3116    
3117  List of features to be taxonomically sorted.  ID of the genome whose subsystem feature map is desired.
3118    
3119  =item RETURN  =item RETURN
3120    
3121  Returns the list of features sorted by the taxonomies of the containing genomes.  Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb
3122    2-tuple contains a subsystem name followed by a role ID.
3123    
3124  =back  =back
3125    
3126  =cut  =cut
3127  #: Return Type @;  
3128  sub TaxonomySort {  sub GenomeSubsystemData {
3129          # Get the parameters.          # Get the parameters.
3130          my ($self, $featureIDs) = @_;      my ($self, $genomeID) = @_;
3131          # Create the working hash table.      # Declare the return variable.
3132          my %hashBuffer = ();      my %retVal = ();
3133          # Loop through the features.      # Get a list of the genome features that participate in subsystems. For each
3134          for my $fid (@{$featureIDs}) {      # feature we get its subsystem ID and the corresponding roles.
3135                  # Get the taxonomy of the feature's genome.      my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf', 'HasSSCell'],
3136                  my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",                                   "HasFeature(from-link) = ?", [$genomeID],
3137                                                                                  [$fid], 'Genome(taxonomy)');                                   ['HasFeature(to-link)', 'IsRoleOf(from-link)',  'HasSSCell(from-link)']);
3138                  # Add this feature to the hash buffer.      # Now we get a list of valid subsystems. These are the subsystems connected to the genome with
3139          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);      # a non-negative variant code.
3140        my %subs = map { $_ => 1 } $self->GetFlat(['ParticipatesIn'],
3141                                                    "ParticipatesIn(from-link) = ? AND ParticipatesIn(variant-code) >= 0",
3142                                                    [$genomeID], 'ParticipatesIn(to-link)');
3143        # We loop through @roleData to build the hash.
3144        for my $roleEntry (@roleData) {
3145            # Get the data for this feature and cell.
3146            my ($fid, $role, $subsys) = @{$roleEntry};
3147            Trace("Subsystem for $fid is $subsys.") if T(4);
3148            # Check the subsystem;
3149            if ($subs{$subsys}) {
3150                Trace("Subsystem found.") if T(4);
3151                # Insure this feature has an entry in the return hash.
3152                if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
3153                # Merge in this new data.
3154                push @{$retVal{$fid}}, [$subsys, $role];
3155          }          }
         # Sort the keys and get the elements.  
         my @retVal = ();  
         for my $taxon (sort keys %hashBuffer) {  
                 push @retVal, @{$hashBuffer{$taxon}};  
3156          }          }
3157          # Return the result.          # Return the result.
3158          return @retVal;      return %retVal;
3159  }  }
3160    
3161  =head3 GetAll  =head3 RelatedFeatures
   
 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.  
3162    
3163  The list returned will be a list of lists. Each element of the list will contain      my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID);
 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.  
3164    
3165  C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>  Return a list of the features which are bi-directional best hits of the specified feature and
3166    have been assigned the specified function by the specified user. If no such features exists,
3167    an empty list will be returned.
3168    
3169  =over 4  =over 4
3170    
3171  =item objectNames  =item featureID
   
 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  
3172    
3173  List of the parameters to be substituted in for the parameters marks in the filter clause.  ID of the feature to whom the desired features are related.
3174    
3175  =item fields  =item function
3176    
3177  List of the fields to be returned in each element of the list returned.  Functional assignment (as returned by C</FunctionOf>) that is used to determine which related
3178    features should be selected.
3179    
3180  =item count  =item userID
3181    
3182  Maximum number of records to return. If omitted or 0, all available records will be returned.  ID of the user whose functional assignments are to be used. If omitted, C<FIG> is assumed.
3183    
3184  =item RETURN  =item RETURN
3185    
3186  Returns a list of list references. Each element of the return list contains the values for the  Returns a list of the related features with the specified function.
 fields specified in the B<fields> parameter.  
3187    
3188  =back  =back
3189    
3190  =cut  =cut
3191  #: Return Type @@;  #: Return Type @;
3192  sub GetAll {  sub RelatedFeatures {
3193          # Get the parameters.          # Get the parameters.
3194          my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;      my ($self, $featureID, $function, $userID) = @_;
3195          # Create the query.      # Get a list of the features that are BBHs of the incoming feature.
3196          my $query = $self->Get($objectNames, $filterClause, $parameterList);      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
3197          # Set up a counter of the number of records read.      # Now we loop through the features, pulling out the ones that have the correct
3198          my $fetched = 0;      # functional assignment.
         # 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.  
3199          my @retVal = ();          my @retVal = ();
3200          while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {      for my $bbhFeature (@bbhFeatures) {
3201                  my @rowData = $row->Values($fields);          # Get this feature's functional assignment.
3202                  push @retVal, \@rowData;          my $newFunction = $self->FunctionOf($bbhFeature, $userID);
3203                  $fetched++;          # If it matches, add it to the result list.
3204            if ($newFunction eq $function) {
3205                push @retVal, $bbhFeature;
3206          }          }
3207          # Return the resulting list.      }
3208        # Return the result list.
3209          return @retVal;          return @retVal;
3210  }  }
3211    
3212  =head3 GetFlat  =head3 TaxonomySort
   
 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.  
3213    
3214  =item filterClause      my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs);
3215    
3216  WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  Return a list formed by sorting the specified features by the taxonomy of the containing
3217  be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  genome. This will cause genomes from similar organisms to float close to each other.
 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.  
3218    
3219  =item parameterList  This task could almost be handled by the database; however, the taxonomy string in the
3220    database is a text field and can't be indexed. Instead, we create a hash table that maps
3221    taxonomy strings to lists of features. We then process the hash table using a key sort
3222    and merge the feature lists together to create the output.
3223    
3224  List of the parameters to be substituted in for the parameters marks in the filter clause.  =over 4
3225    
3226  =item field  =item $featureIDs
3227    
3228  Name of the field to be used to get the elements of the list returned.  List of features to be taxonomically sorted.
3229    
3230  =item RETURN  =item RETURN
3231    
3232  Returns a list of values.  Returns the list of features sorted by the taxonomies of the containing genomes.
3233    
3234  =back  =back
3235    
3236  =cut  =cut
3237  #: Return Type @;  #: Return Type @;
3238  sub GetFlat {  sub TaxonomySort {
3239          # Get the parameters.          # Get the parameters.
3240          my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;      my ($self, $featureIDs) = @_;
3241          # Construct the query.      # Create the working hash table.
3242          my $query = $self->Get($objectNames, $filterClause, $parameterList);      my %hashBuffer = ();
3243          # Create the result list.      # Loop through the features.
3244        for my $fid (@{$featureIDs}) {
3245            # Get the taxonomy of the feature's genome.
3246            my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
3247                                            [$fid], 'Genome(taxonomy)');
3248            # Add this feature to the hash buffer.
3249            push @{$hashBuffer{$taxonomy}}, $fid;
3250        }
3251        # Sort the keys and get the elements.
3252          my @retVal = ();          my @retVal = ();
3253          # Loop through the records, adding the field values found to the result list.      for my $taxon (sort keys %hashBuffer) {
3254          while (my $row = $query->Fetch()) {          push @retVal, @{$hashBuffer{$taxon}};
                 push @retVal, $row->Value($field);  
3255          }          }
3256          # Return the list created.      # Return the result.
3257          return @retVal;          return @retVal;
3258  }  }
3259    
3260  =head3 Protein  =head3 Protein
3261    
3262  C<< my $protein = Sprout::Protein($sequence, $table); >>      my $protein = Sprout::Protein($sequence, $table);
3263    
3264  Translate a DNA sequence into a protein sequence.  Translate a DNA sequence into a protein sequence.
3265    
# Line 2500  Line 3329 
3329          # Loop through the input triples.          # Loop through the input triples.
3330          my $n = length $sequence;          my $n = length $sequence;
3331          for (my $i = 0; $i < $n; $i += 3) {          for (my $i = 0; $i < $n; $i += 3) {
3332                  # Get the current triple from the sequence.          # Get the current triple from the sequence. Note we convert to
3333                  my $triple = substr($sequence, $i, 3);          # upper case to insure a match.
3334            my $triple = uc substr($sequence, $i, 3);
3335                  # Translate it using the table.                  # Translate it using the table.
3336                  my $protein = "X";                  my $protein = "X";
3337                  if (exists $table->{$triple}) { $protein = $table->{$triple}; }                  if (exists $table->{$triple}) { $protein = $table->{$triple}; }
# Line 2515  Line 3345 
3345    
3346  =head3 LoadInfo  =head3 LoadInfo
3347    
3348  C<< my ($dirName, @relNames) = $sprout->LoadInfo(); >>      my ($dirName, @relNames) = $sprout->LoadInfo();
3349    
3350  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
3351  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 2529  Line 3359 
3359          # 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.
3360          my @retVal = ($self->{_options}->{dataDir});          my @retVal = ($self->{_options}->{dataDir});
3361          # Concatenate the table names.          # Concatenate the table names.
3362          push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
3363          # Return the result.          # Return the result.
3364          return @retVal;          return @retVal;
3365  }  }
3366    
3367    =head3 BBHMatrix
3368    
3369        my %bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets);
3370    
3371    Find all the bidirectional best hits for the features of a genome in a
3372    specified list of target genomes. The return value will be a hash mapping
3373    features in the original genome to their bidirectional best hits in the
3374    target genomes.
3375    
3376    =over 4
3377    
3378    =item genomeID
3379    
3380    ID of the genome whose features are to be examined for bidirectional best hits.
3381    
3382    =item cutoff
3383    
3384    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3385    
3386    =item targets
3387    
3388    List of target genomes. Only pairs originating in the original
3389    genome and landing in one of the target genomes will be returned.
3390    
3391    =item RETURN
3392    
3393    Returns a hash mapping each feature in the original genome to a hash mapping its
3394    BBH pegs in the target genomes to their scores.
3395    
3396    =back
3397    
3398    =cut
3399    
3400    sub BBHMatrix {
3401        # Get the parameters.
3402        my ($self, $genomeID, $cutoff, @targets) = @_;
3403        # Declare the return variable.
3404        my %retVal = ();
3405        # Ask for the BBHs.
3406        my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets);
3407        # We now have a set of 4-tuples that we need to convert into a hash of hashes.
3408        for my $bbhData (@bbhList) {
3409            my ($peg1, $peg2, $score) = @{$bbhData};
3410            if (! exists $retVal{$peg1}) {
3411                $retVal{$peg1} = { $peg2 => $score };
3412            } else {
3413                $retVal{$peg1}->{$peg2} = $score;
3414            }
3415        }
3416        # Return the result.
3417        return %retVal;
3418    }
3419    
3420    
3421    =head3 SimMatrix
3422    
3423        my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets);
3424    
3425    Find all the similarities for the features of a genome in a
3426    specified list of target genomes. The return value will be a hash mapping
3427    features in the original genome to their similarites in the
3428    target genomes.
3429    
3430    =over 4
3431    
3432    =item genomeID
3433    
3434    ID of the genome whose features are to be examined for similarities.
3435    
3436    =item cutoff
3437    
3438    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3439    
3440    =item targets
3441    
3442    List of target genomes. Only pairs originating in the original
3443    genome and landing in one of the target genomes will be returned.
3444    
3445    =item RETURN
3446    
3447    Returns a hash mapping each feature in the original genome to a hash mapping its
3448    similar pegs in the target genomes to their scores.
3449    
3450    =back
3451    
3452    =cut
3453    
3454    sub SimMatrix {
3455        # Get the parameters.
3456        my ($self, $genomeID, $cutoff, @targets) = @_;
3457        # Declare the return variable.
3458        my %retVal = ();
3459        # Get the list of features in the source organism.
3460        my @fids = $self->FeaturesOf($genomeID);
3461        # Ask for the sims. We only want similarities to fig features.
3462        my $simList = FIGRules::GetNetworkSims($self, \@fids, {}, 1000, $cutoff, "fig");
3463        if (! defined $simList) {
3464            Confess("Unable to retrieve similarities from server.");
3465        } else {
3466            Trace("Processing sims.") if T(3);
3467            # We now have a set of sims that we need to convert into a hash of hashes. First, we
3468            # Create a hash for the target genomes.
3469            my %targetHash = map { $_ => 1 } @targets;
3470            for my $simData (@{$simList}) {
3471                # Get the PEGs and the score.
3472                my ($peg1, $peg2, $score) = ($simData->id1, $simData->id2, $simData->psc);
3473                # Insure the second ID is in the target list.
3474                my ($genome2) = FIGRules::ParseFeatureID($peg2);
3475                if (exists $targetHash{$genome2}) {
3476                    # Here it is. Now we need to add it to the return hash. How we do that depends
3477                    # on whether or not $peg1 is new to us.
3478                    if (! exists $retVal{$peg1}) {
3479                        $retVal{$peg1} = { $peg2 => $score };
3480                    } else {
3481                        $retVal{$peg1}->{$peg2} = $score;
3482                    }
3483                }
3484            }
3485        }
3486        # Return the result.
3487        return %retVal;
3488    }
3489    
3490    
3491  =head3 LowBBHs  =head3 LowBBHs
3492    
3493  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>      my %bbhMap = $sprout->LowBBHs($featureID, $cutoff);
3494    
3495  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
3496  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 2565  Line 3519 
3519          my ($self, $featureID, $cutoff) = @_;          my ($self, $featureID, $cutoff) = @_;
3520          # Create the return hash.          # Create the return hash.
3521          my %retVal = ();          my %retVal = ();
3522          # Create a query to get the desired BBHs.      # Query for the desired BBHs.
3523          my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BBHData($featureID, $cutoff);
                                                                 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',  
                                                                 [$cutoff, $featureID],  
                                                                 ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);  
3524          # Form the results into the return hash.          # Form the results into the return hash.
3525          for my $pair (@bbhList) {          for my $pair (@bbhList) {
3526                  $retVal{$pair->[0]} = $pair->[1];          my $fid = $pair->[0];
3527            if ($self->Exists('Feature', $fid)) {
3528                $retVal{$fid} = $pair->[1];
3529            }
3530          }          }
3531          # Return the result.          # Return the result.
3532          return %retVal;          return %retVal;
3533  }  }
3534    
3535    =head3 Sims
3536    
3537        my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters);
3538    
3539    Get a list of similarities for a specified feature. Similarity information is not kept in the
3540    Sprout database; rather, they are retrieved from a network server. The similarities are
3541    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3542    so that its elements can be accessed by name.
3543    
3544    Similarities can be either raw or expanded. The raw similarities are basic
3545    hits between features with similar DNA. Expanding a raw similarity drags in any
3546    features considered substantially identical. So, for example, if features B<A1>,
3547    B<A2>, and B<A3> are all substantially identical to B<A>, then a raw similarity
3548    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3549    
3550    =over 4
3551    
3552    =item fid
3553    
3554    ID of the feature whose similarities are desired, or reference to a list of IDs
3555    of features whose similarities are desired.
3556    
3557    =item maxN
3558    
3559    Maximum number of similarities to return.
3560    
3561    =item maxP
3562    
3563    Minumum allowable similarity score.
3564    
3565    =item select
3566    
3567    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3568    means only similarities to FIG features are returned; C<all> means all expanded
3569    similarities are returned; and C<figx> means similarities are expanded until the
3570    number of FIG features equals the maximum.
3571    
3572    =item max_expand
3573    
3574    The maximum number of features to expand.
3575    
3576    =item filters
3577    
3578    Reference to a hash containing filter information, or a subroutine that can be
3579    used to filter the sims.
3580    
3581    =item RETURN
3582    
3583    Returns a reference to a list of similarity objects, or C<undef> if an error
3584    occurred.
3585    
3586    =back
3587    
3588    =cut
3589    
3590    sub Sims {
3591        # Get the parameters.
3592        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3593        # Create the shim object to test for deleted FIDs.
3594        my $shim = FidCheck->new($self);
3595        # Ask the network for sims.
3596        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3597        # Return the result.
3598        return $retVal;
3599    }
3600    
3601    =head3 IsAllGenomes
3602    
3603        my $flag = $sprout->IsAllGenomes(\@list, \@checkList);
3604    
3605    Return TRUE if all genomes in the second list are represented in the first list at
3606    least one. Otherwise, return FALSE. If the second list is omitted, the first list is
3607    compared to a list of all the genomes.
3608    
3609    =over 4
3610    
3611    =item list
3612    
3613    Reference to the list to be compared to the second list.
3614    
3615    =item checkList (optional)
3616    
3617    Reference to the comparison target list. Every genome ID in this list must occur at
3618    least once in the first list. If this parameter is omitted, a list of all the genomes
3619    is used.
3620    
3621    =item RETURN
3622    
3623    Returns TRUE if every item in the second list appears at least once in the
3624    first list, else FALSE.
3625    
3626    =back
3627    
3628    =cut
3629    
3630    sub IsAllGenomes {
3631        # Get the parameters.
3632        my ($self, $list, $checkList) = @_;
3633        # Supply the checklist if it was omitted.
3634        $checkList = [$self->Genomes()] if ! defined($checkList);
3635        # Create a hash of the original list.
3636        my %testList = map { $_ => 1 } @{$list};
3637        # Declare the return variable. We assume that the representation
3638        # is complete and stop at the first failure.
3639        my $retVal = 1;
3640        my $n = scalar @{$checkList};
3641        for (my $i = 0; $retVal && $i < $n; $i++) {
3642            if (! $testList{$checkList->[$i]}) {
3643                $retVal = 0;
3644            }
3645        }
3646        # Return the result.
3647        return $retVal;
3648    }
3649    
3650  =head3 GetGroups  =head3 GetGroups
3651    
3652  C<< my %groups = $sprout->GetGroups(\@groupList); >>      my %groups = $sprout->GetGroups(\@groupList);
3653    
3654  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.
3655  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 2599  Line 3668 
3668          # Here we have a group list. Loop through them individually,          # Here we have a group list. Loop through them individually,
3669          # getting a list of the relevant genomes.          # getting a list of the relevant genomes.
3670          for my $group (@{$groupList}) {          for my $group (@{$groupList}) {
3671              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3672                  [$group], "Genome(id)");                  [$group], "Genome(id)");
3673              $retVal{$group} = \@genomeIDs;              $retVal{$group} = \@genomeIDs;
3674          }          }
# Line 2607  Line 3676 
3676          # 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
3677          # of the genome records, putting each one found into the appropriate          # of the genome records, putting each one found into the appropriate
3678          # 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
3679          # in groups are included in the return set.          # in real NMPDR groups are included in the return set.
3680          my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],          my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3681                                      ['Genome(id)', 'Genome(group-name)']);                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3682          # Loop through the genomes found.          # Loop through the genomes found.
3683          for my $genome (@genomes) {          for my $genome (@genomes) {
3684              # Pop this genome's ID off the current list.              # Get the genome ID and group, and add this genome to the group's list.
3685              my @groups = @{$genome};              my ($genomeID, $group) = @{$genome};
3686              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);  
             }  
3687          }          }
3688      }      }
3689      # Return the hash we just built.      # Return the hash we just built.
3690      return %retVal;      return %retVal;
3691  }  }
3692    
3693    =head3 MyGenomes
3694    
3695        my @genomes = Sprout::MyGenomes($dataDir);
3696    
3697    Return a list of the genomes to be included in the Sprout.
3698    
3699    This method is provided for use during the Sprout load. It presumes the Genome load file has
3700    already been created. (It will be in the Sprout data directory and called either C<Genome>
3701    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3702    IDs.
3703    
3704    =over 4
3705    
3706    =item dataDir
3707    
3708    Directory containing the Sprout load files.
3709    
3710    =back
3711    
3712    =cut
3713    #: Return Type @;
3714    sub MyGenomes {
3715        # Get the parameters.
3716        my ($dataDir) = @_;
3717        # Compute the genome file name.
3718        my $genomeFileName = LoadFileName($dataDir, "Genome");
3719        # Extract the genome IDs from the files.
3720        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3721        # Return the result.
3722        return @retVal;
3723    }
3724    
3725    =head3 LoadFileName
3726    
3727        my $fileName = Sprout::LoadFileName($dataDir, $tableName);
3728    
3729    Return the name of the load file for the specified table in the specified data
3730    directory.
3731    
3732    =over 4
3733    
3734    =item dataDir
3735    
3736    Directory containing the Sprout load files.
3737    
3738    =item tableName
3739    
3740    Name of the table whose load file is desired.
3741    
3742    =item RETURN
3743    
3744    Returns the name of the file containing the load data for the specified table, or
3745    C<undef> if no load file is present.
3746    
3747    =back
3748    
3749    =cut
3750    #: Return Type $;
3751    sub LoadFileName {
3752        # Get the parameters.
3753        my ($dataDir, $tableName) = @_;
3754        # Declare the return variable.
3755        my $retVal;
3756        # Check for the various file names.
3757        if (-e "$dataDir/$tableName") {
3758            $retVal = "$dataDir/$tableName";
3759        } elsif (-e "$dataDir/$tableName.dtx") {
3760            $retVal = "$dataDir/$tableName.dtx";
3761        }
3762        # Return the result.
3763        return $retVal;
3764    }
3765    
3766    =head3 DeleteGenome
3767    
3768        my $stats = $sprout->DeleteGenome($genomeID, $testFlag);
3769    
3770    Delete a genome from the database.
3771    
3772    =over 4
3773    
3774    =item genomeID
3775    
3776    ID of the genome to delete
3777    
3778    =item testFlag
3779    
3780    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3781    
3782    =item RETURN
3783    
3784    Returns a statistics object describing the rows deleted.
3785    
3786    =back
3787    
3788    =cut
3789    #: Return Type $%;
3790    sub DeleteGenome {
3791        # Get the parameters.
3792        my ($self, $genomeID, $testFlag) = @_;
3793        # Perform the delete for the genome's features.
3794        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", testMode => $testFlag);
3795        # Perform the delete for the primary genome data.
3796        my $stats = $self->Delete('Genome', $genomeID, testMode => $testFlag);
3797        $retVal->Accumulate($stats);
3798        # Return the result.
3799        return $retVal;
3800    }
3801    
3802    =head3 Fix
3803    
3804        my %fixedHash = $sprout->Fix(%groupHash);
3805    
3806    Prepare a genome group hash (like that returned by L</GetGroups>) for processing.
3807    The groups will be combined into the appropriate super-groups.
3808    
3809    =over 4
3810    
3811    =item groupHash
3812    
3813    Hash to be fixed up.
3814    
3815    =item RETURN
3816    
3817    Returns a fixed-up version of the hash.
3818    
3819    =back
3820    
3821    =cut
3822    
3823    sub Fix {
3824        # Get the parameters.
3825        my ($self, %groupHash) = @_;
3826        # Create the result hash.
3827        my %retVal = ();
3828        # Copy over the genomes.
3829        for my $groupID (keys %groupHash) {
3830            # Get the super-group name.
3831            my $realGroupID = $self->SuperGroup($groupID);
3832            # Append this group's genomes into the result hash
3833            # using the super-group name.
3834            push @{$retVal{$realGroupID}}, @{$groupHash{$groupID}};
3835        }
3836        # Return the result hash.
3837        return %retVal;
3838    }
3839    
3840    =head3 GroupPageName
3841    
3842        my $name = $sprout->GroupPageName($group);
3843    
3844    Return the name of the page for the specified NMPDR group.
3845    
3846    =over 4
3847    
3848    =item group
3849    
3850    Name of the relevant group.
3851    
3852    =item RETURN
3853    
3854    Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3855    memory it will be read in.
3856    
3857    =back
3858    
3859    =cut
3860    
3861    sub GroupPageName {
3862        # Get the parameters.
3863        my ($self, $group) = @_;
3864        # Check for the group file data.
3865        my %superTable = $self->CheckGroupFile();
3866        # Compute the real group name.
3867        my $realGroup = $self->SuperGroup($group);
3868        # Get the associated page name.
3869        my $retVal = "../content/$superTable{$realGroup}->{page}";
3870        # Return the result.
3871        return $retVal;
3872    }
3873    
3874    
3875    =head3 AddProperty
3876    
3877        $sprout->AddProperty($featureID, $key, @values);
3878    
3879    Add a new attribute value (Property) to a feature.
3880    
3881    =over 4
3882    
3883    =item peg
3884    
3885    ID of the feature to which the attribute is to be added.
3886    
3887    =item key
3888    
3889    Name of the attribute (key).
3890    
3891    =item values
3892    
3893    Values of the attribute.
3894    
3895    =back
3896    
3897    =cut
3898    #: Return Type ;
3899    sub AddProperty {
3900        # Get the parameters.
3901        my ($self, $featureID, $key, @values) = @_;
3902        # Add the property using the attached attributes object.
3903        $self->{_ca}->AddAttribute($featureID, $key, @values);
3904    }
3905    
3906    =head3 CheckGroupFile
3907    
3908        my %groupData = $sprout->CheckGroupFile();
3909    
3910    Get the group file hash. The group file hash describes the relationship
3911    between a group and the super-group to which it belongs for purposes of
3912    display. The super-group name is computed from the first capitalized word
3913    in the actual group name. For each super-group, the group file contains
3914    the page name and a list of the species expected to be in the group.
3915    Each species is specified by a genus and a species name. A species name
3916    of C<0> implies an entire genus.
3917    
3918    This method returns a hash from super-group names to a hash reference. Each
3919    resulting hash reference contains the following fields.
3920    
3921    =over 4
3922    
3923    =item page
3924    
3925    The super-group's web page in the NMPDR.
3926    
3927    =item contents
3928    
3929    A list of 2-tuples, each containing a genus name followed by a species name
3930    (or 0, indicating all species). This list indicates which organisms belong
3931    in the super-group.
3932    
3933    =back
3934    
3935    =cut
3936    
3937    sub CheckGroupFile {
3938        # Get the parameters.
3939        my ($self) = @_;
3940        # Check to see if we already have this hash.
3941        if (! defined $self->{groupHash}) {
3942            # We don't, so we need to read it in.
3943            my %groupHash;
3944            # Read the group file.
3945            my @groupLines = Tracer::GetFile("$FIG_Config::sproutData/groups.tbl");
3946            # Loop through the list of sort-of groups.
3947            for my $groupLine (@groupLines) {
3948                my ($name, $page, @contents) = split /\t/, $groupLine;
3949                $groupHash{$name} = { page => $page,
3950                                      contents => [ map { [ split /\s*,\s*/, $_ ] } @contents ]
3951                                    };
3952            }
3953            # Save the hash.
3954            $self->{groupHash} = \%groupHash;
3955        }
3956        # Return the result.
3957        return %{$self->{groupHash}};
3958    }
3959    
3960    =head2 Virtual Methods
3961    
3962    =head3 CleanKeywords
3963    
3964        my $cleanedString = $sprout->CleanKeywords($searchExpression);
3965    
3966    Clean up a search expression or keyword list. This involves converting the periods
3967    in EC numbers to underscores, converting non-leading minus signs to underscores,
3968    a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
3969    characters. In addition, any extra spaces are removed.
3970    
3971    =over 4
3972    
3973    =item searchExpression
3974    
3975    Search expression or keyword list to clean. Note that a search expression may
3976    contain boolean operators which need to be preserved. This includes leading
3977    minus signs.
3978    
3979    =item RETURN
3980    
3981    Cleaned expression or keyword list.
3982    
3983    =back
3984    
3985    =cut
3986    
3987    sub CleanKeywords {
3988        # Get the parameters.
3989        my ($self, $searchExpression) = @_;
3990        # Get the stemmer.
3991        my $stemmer = $self->GetStemmer();
3992        # Convert the search expression using the stemmer.
3993        my $retVal = $stemmer->PrepareSearchExpression($searchExpression);
3994        Trace("Cleaned keyword list for \"$searchExpression\" is \"$retVal\".") if T(3);
3995        # Return the result.
3996        return $retVal;
3997    }
3998    
3999    =head3 GetSourceObject
4000    
4001        my $source = $erdb->GetSourceObject();
4002    
4003    Return the object to be used in creating load files for this database.
4004    
4005    =cut
4006    
4007    sub GetSourceObject {
4008        # Get access to the FIG code.
4009        require FIG;
4010        # Return a FIG object.
4011        return FIG->new();
4012    }
4013    
4014    =head3 SectionList
4015    
4016        my @sections = $erdb->SectionList($source);
4017    
4018    Return a list of the names for the different data sections used when loading this database.
4019    The default is an empty string, in which case there is only one section representing the
4020    entire database.
4021    
4022    =over 4
4023    
4024    =item source
4025    
4026    Source object used to access the data from which the database is loaded. This is the
4027    same object returned by L</GetSourceObject>; however, we ask the caller to pass it
4028    in as a parameter so that we don't end up creating multiple copies of a potentially
4029    expensive data structure.
4030    
4031    =item RETURN
4032    
4033    Returns a list of section names.
4034    
4035    =back
4036    
4037    =cut
4038    
4039    sub SectionList {
4040        # Get the parameters.
4041        my ($self, $source) = @_;
4042        # Ask the BaseSproutLoader for a section list.
4043        require BaseSproutLoader;
4044        my @retVal = BaseSproutLoader::GetSectionList($self, $source);
4045        # Return the list.
4046        return @retVal;
4047    }
4048    
4049    =head3 Loader
4050    
4051        my $groupLoader = $erdb->Loader($groupName, $source, $options);
4052    
4053    Return an [[ERDBLoadGroupPm]] object for the specified load group. This method is used
4054    by [[ERDBGeneratorPl]] to create the load group objects. If you are not using
4055    [[ERDBGeneratorPl]], you don't need to override this method.
4056    
4057    =over 4
4058    
4059    =item groupName
4060    
4061    Name of the load group whose object is to be returned. The group name is
4062    guaranteed to be a single word with only the first letter capitalized.
4063    
4064    =item source
4065    
4066    The source object used to access the data from which the load file is derived. This
4067    is the same object returned by L</GetSourceObject>; however, we ask the caller to pass
4068    it in as a parameter so that we don't end up creating multiple copies of a potentially
4069    expensive data structure.
4070    
4071    =item options
4072    
4073    Reference to a hash of command-line options.
4074    
4075    =item RETURN
4076    
4077    Returns an [[ERDBLoadGroupPm]] object that can be used to process the specified load group
4078    for this database.
4079    
4080    =back
4081    
4082    =cut
4083    
4084    sub Loader {
4085        # Get the parameters.
4086        my ($self, $groupName, $source, $options) = @_;
4087        # Compute the loader name.
4088        my $loaderClass = "${groupName}SproutLoader";
4089        # Pull in its definition.
4090        require "$loaderClass.pm";
4091        # Create an object for it.
4092        my $retVal = eval("$loaderClass->new(\$self, \$source, \$options)");
4093        # Insure it worked.
4094        Confess("Could not create $loaderClass object: $@") if $@;
4095        # Return it to the caller.
4096        return $retVal;
4097    }
4098    
4099    =head3 LoadGroupList
4100    
4101        my @groups = $erdb->LoadGroupList();
4102    
4103    Returns a list of the names for this database's load groups. This method is used
4104    by [[ERDBGeneratorPl]] when the user wishes to load all table groups. The default
4105    is a single group called 'All' that loads everything.
4106    
4107    =cut
4108    
4109    sub LoadGroupList {
4110        # Return the list.
4111        return qw(Genome Subsystem Feature Annotation Property Source Reaction Synonym Drug);
4112    }
4113    
4114    =head3 LoadDirectory
4115    
4116        my $dirName = $erdb->LoadDirectory();
4117    
4118    Return the name of the directory in which load files are kept. The default is
4119    the FIG temporary directory, which is a really bad choice, but it's always there.
4120    
4121    =cut
4122    
4123    sub LoadDirectory {
4124        # Get the parameters.
4125        my ($self) = @_;
4126        # Return the directory name.
4127        return $self->{dataDir};
4128    }
4129    
4130  =head2 Internal Utility Methods  =head2 Internal Utility Methods
4131    
4132    =head3 GetStemmer
4133    
4134        my $stermmer = $sprout->GetStemmer();
4135    
4136    Return the stemmer object for this database.
4137    
4138    =cut
4139    
4140    sub GetStemmer {
4141        # Get the parameters.
4142        my ($self) = @_;
4143        # Declare the return variable.
4144        my $retVal = $self->{stemmer};
4145        if (! defined $retVal) {
4146            # We don't have one pre-built, so we build and save it now.
4147            $retVal = BioWords->new(exceptions => "$FIG_Config::sproutData/Exceptions.txt",
4148                                     stops => "$FIG_Config::sproutData/StopWords.txt",
4149                                     cache => 1);
4150            $self->{stemmer} = $retVal;
4151        }
4152        # Return the result.
4153        return $retVal;
4154    }
4155    
4156  =head3 ParseAssignment  =head3 ParseAssignment
4157    
4158  Parse annotation text to determine whether or not it is a functional assignment. If it is,  Parse annotation text to determine whether or not it is a functional assignment. If it is,
4159  the user and function text will be returned as a 2-element list. If it isn't, an empty list  the user, function text, and assigning user will be returned as a 3-element list. If it
4160  will be returned.  isn't, an empty list will be returned.
4161    
4162    A functional assignment is always of the form
4163    
4164        set YYYY function to
4165        ZZZZ
4166    
4167    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
4168    the user and the assigning user (from MadeAnnotation) will be the same, but that is
4169    not always the case.
4170    
4171    In addition, the functional role may contain extra data that is stripped, such as
4172    terminating spaces or a comment separated from the rest of the text by a tab.
4173    
4174  This is a static method.  This is a static method.
4175    
4176  =over 4  =over 4
4177    
4178    =item user
4179    
4180    Name of the assigning user.
4181    
4182  =item text  =item text
4183    
4184  Text of the annotation.  Text of the annotation.
# Line 2651  Line 4192 
4192    
4193  =cut  =cut
4194    
4195  sub ParseAssignment {  sub _ParseAssignment {
4196          # Get the parameters.          # Get the parameters.
4197          my ($text) = @_;      my ($user, $text) = @_;
4198          # Declare the return value.          # Declare the return value.
4199          my @retVal = ();          my @retVal = ();
4200          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
4201          my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
4202          if ($type =~ m/^set $user function to$/i) {      if ($type =~ m/^set function to$/i) {
4203                  # Here it is, so we return the user name and function text.          # Here we have an assignment without a user, so we use the incoming user ID.
4204                  @retVal = ($user, $function);                  @retVal = ($user, $function);
4205        } elsif ($type =~ m/^set (\S+) function to$/i) {
4206            # Here we have an assignment with a user that is passed back to the caller.
4207            @retVal = ($1, $function);
4208        }
4209        # If we have an assignment, we need to clean the function text. There may be
4210        # extra junk at the end added as a note from the user.
4211        if (defined( $retVal[1] )) {
4212            $retVal[1] =~ s/(\t\S)?\s*$//;
4213          }          }
4214          # Return the result list.          # Return the result list.
4215          return @retVal;          return @retVal;
4216  }  }
4217    
4218    =head3 _CheckFeature
4219    
4220        my $flag = $sprout->_CheckFeature($fid);
4221    
4222    Return TRUE if the specified FID is probably an NMPDR feature ID, else FALSE.
4223    
4224    =over 4
4225    
4226    =item fid
4227    
4228    Feature ID to check.
4229    
4230    =item RETURN
4231    
4232    Returns TRUE if the FID is for one of the NMPDR genomes, else FALSE.
4233    
4234    =back
4235    
4236    =cut
4237    
4238    sub _CheckFeature {
4239        # Get the parameters.
4240        my ($self, $fid) = @_;
4241        # Insure we have a genome hash.
4242        if (! defined $self->{genomeHash}) {
4243            my %genomeHash = map { $_ => 1 } $self->GetFlat(['Genome'], "", [], 'Genome(id)');
4244            $self->{genomeHash} = \%genomeHash;
4245        }
4246        # Get the feature's genome ID.
4247        my ($genomeID) = FIGRules::ParseFeatureID($fid);
4248        # Return an indicator of whether or not the genome ID is in the hash.
4249        return ($self->{genomeHash}->{$genomeID} ? 1 : 0);
4250    }
4251    
4252  =head3 FriendlyTimestamp  =head3 FriendlyTimestamp
4253    
4254  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 2688  Line 4271 
4271    
4272  sub FriendlyTimestamp {  sub FriendlyTimestamp {
4273      my ($timeValue) = @_;      my ($timeValue) = @_;
4274      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my $retVal = localtime($timeValue);
4275        return $retVal;
4276    }
4277    
4278    
4279    =head3 Hint
4280    
4281        my $htmlText = SearchHelper::Hint($wikiPage, $hintText);
4282    
4283    Return the HTML for a small question mark that displays the specified hint text when it is clicked.
4284    This HTML can be put in forms to provide a useful hinting mechanism.
4285    
4286    =over 4
4287    
4288    =item wikiPage
4289    
4290    Name of the wiki page to be popped up when the hint mark is clicked.
4291    
4292    =item hintText
4293    
4294    Text to display for the hint. It is raw html, but may not contain any double quotes.
4295    
4296    =item RETURN
4297    
4298    Returns the html for the hint facility. The resulting html shows a small button-like thing that
4299    uses the standard FIG popup technology.
4300    
4301    =back
4302    
4303    =cut
4304    
4305    sub Hint {
4306        # Get the parameters.
4307        my ($wikiPage, $hintText) = @_;
4308        # Escape the single quotes in the hint text.
4309        my $quotedText = $hintText;
4310        $quotedText =~ s/'/\\'/g;
4311        # Convert the wiki page name to a URL.
4312        my $wikiURL = join("", map { ucfirst $_ } split /\s+/, $wikiPage);
4313        $wikiURL = "$FIG_Config::cgi_url/wiki/view.cgi/FIG/$wikiURL";
4314        # Compute the mouseover script.
4315        my $mouseOver = "doTooltip(this, '$quotedText')";
4316        # Create the html.
4317        my $retVal = "&nbsp;<a href=\"$wikiURL\"><img src=\"$FIG_Config::cgi_url/Html/button-h.png\" class=\"helpicon\" onmouseover=\"$mouseOver\"/></a>";
4318        # Return it.
4319      return $retVal;      return $retVal;
4320  }  }
4321    

Legend:
Removed from v.1.10  
changed lines
  Added in v.1.119

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3