[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.44, Thu Oct 20 09:32:18 2005 UTC revision 1.107, Thu Feb 7 00:06:16 2008 UTC
# Line 2  Line 2 
2    
3      use Data::Dumper;      use Data::Dumper;
4      use strict;      use strict;
     use Carp;  
5      use DBKernel;      use DBKernel;
6      use XML::Simple;      use XML::Simple;
7      use DBQuery;      use DBQuery;
8      use DBObject;      use ERDBObject;
     use ERDB;  
9      use Tracer;      use Tracer;
10      use FIGRules;      use FIGRules;
11        use FidCheck;
12      use Stats;      use Stats;
13      use POSIX qw(strftime);      use POSIX qw(strftime);
14        use BasicLocation;
15        use CustomAttributes;
16        use RemoteCustomAttributes;
17        use base qw(ERDB);
18    
19  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
20    
# Line 25  Line 27 
27  on the constructor. For example, the following invocation specifies a PostgreSQL database named I<GenDB>  on the constructor. For example, the following invocation specifies a PostgreSQL database named I<GenDB>
28  whose definition and data files are in a co-directory named F<Data>.  whose definition and data files are in a co-directory named F<Data>.
29    
30  C<< my $sprout = Sprout->new('GenDB', { dbType => 'pg', dataDir => '../Data', xmlFileName => '../Data/SproutDBD.xml' }); >>      my $sprout = Sprout->new('GenDB', { dbType => 'pg', dataDir => '../Data', xmlFileName => '../Data/SproutDBD.xml' });
31    
32  Once you have a sprout object, you may use it to re-create the database, load the tables from  Once you have a sprout object, you may use it to re-create the database, load the tables from
33  tab-delimited flat files and perform queries. Several special methods are provided for common  tab-delimited flat files and perform queries. Several special methods are provided for common
34  query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and  query tasks. For example, L</Genomes> lists the IDs of all the genomes in the database and
35  L</dna_seq> returns the DNA sequence for a specified genome location.  L</DNASeq> returns the DNA sequence for a specified genome location.
36    
37    The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.
38    
39  =cut  =cut
40    
# Line 40  Line 44 
44    
45  =head3 new  =head3 new
46    
47  C<< my $sprout = Sprout->new($dbName, \%options); >>      my $sprout = Sprout->new($dbName, \%options);
48    
49  This is the constructor for a sprout object. It connects to the database and loads the  This is the constructor for a sprout object. It connects to the database and loads the
50  database definition into memory. The positional first parameter specifies the name of the  database definition into memory. The positional first parameter specifies the name of the
# Line 62  Line 66 
66    
67  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)
68    
69  * B<userData> user name and password, delimited by a slash (default C<root/>)  * B<userData> user name and password, delimited by a slash (default same as SEED)
70    
71  * B<port> connection port (default C<0>)  * B<port> connection port (default C<0>)
72    
73    * B<sock> connection socket (default same as SEED)
74    
75  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
76    
77  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
78    
79  * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE  * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
80    
81    * B<host> name of the database host
82    
83  =back  =back
84    
85  For example, the following constructor call specifies a database named I<Sprout> and a user name of  For example, the following constructor call specifies a database named I<Sprout> and a user name of
86  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
87  F</usr/fig/SproutData>.  F</usr/fig/SproutData>.
88    
89  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' });
90    
91  =cut  =cut
92    
93  sub new {  sub new {
94      # Get the parameters.      # Get the parameters.
95      my ($class, $dbName, $options) = @_;      my ($class, $dbName, $options) = @_;
96        # Compute the DBD directory.
97        my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
98                                                      $FIG_Config::fig );
99      # Compute the options. We do this by starting with a table of defaults and overwriting with      # Compute the options. We do this by starting with a table of defaults and overwriting with
100      # the incoming data.      # the incoming data.
101      my $optionTable = Tracer::GetOptions({      my $optionTable = Tracer::GetOptions({
# Line 92  Line 103 
103                                                          # database type                                                          # database type
104                         dataDir      => $FIG_Config::sproutData,                         dataDir      => $FIG_Config::sproutData,
105                                                          # data file directory                                                          # data file directory
106                         xmlFileName  => "$FIG_Config::sproutData/SproutDBD.xml",                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
107                                                          # database definition file name                                                          # database definition file name
108                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
109                                                          # user name and password                                                          # user name and password
110                         port         => $FIG_Config::dbport,                         port         => $FIG_Config::dbport,
111                                                          # database connection port                                                          # database connection port
112                           sock         => $FIG_Config::dbsock,
113                           host         => $FIG_Config::sprout_host,
114                         maxSegmentLength => 4500,        # maximum feature segment length                         maxSegmentLength => 4500,        # maximum feature segment length
115                         maxSequenceLength => 8000,       # maximum contig sequence length                         maxSequenceLength => 8000,       # maximum contig sequence length
116                         noDBOpen     => 0,               # 1 to suppress the database open                         noDBOpen     => 0,               # 1 to suppress the database open
# Line 110  Line 123 
123      # Connect to the database.      # Connect to the database.
124      my $dbh;      my $dbh;
125      if (! $optionTable->{noDBOpen}) {      if (! $optionTable->{noDBOpen}) {
126            Trace("Connect data: host = $optionTable->{host}, port = $optionTable->{port}.") if T(3);
127          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
128                                  $password, $optionTable->{port});                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
129      }      }
130      # Create the ERDB object.      # Create the ERDB object.
131      my $xmlFileName = "$optionTable->{xmlFileName}";      my $xmlFileName = "$optionTable->{xmlFileName}";
132      my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
133      # Create this object.      # Add the option table and XML file name.
134      my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
135      # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
136      bless $self;      # Set up space for the group file data.
137      return $self;      $retVal->{groupHash} = undef;
138        # Set up space for the genome hash. We use this to identify NMPDR genomes.
139        $retVal->{genomeHash} = undef;
140        # Connect to the attributes.
141        if ($FIG_Config::attrURL) {
142            Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);
143            $retVal->{_ca} = RemoteCustomAttributes->new($FIG_Config::attrURL);
144        } elsif ($FIG_Config::attrDbName) {
145            Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);
146            my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));
147            $retVal->{_ca} = CustomAttributes->new(user => $user);
148        }
149        # Return it.
150        return $retVal;
151    }
152    
153    =head3 RealCoreGenomes
154    
155        my @genomes = $sprout->RealCoreGenomes();
156    
157    Return the IDs of the original core NMPDR genomes. These are the ones
158    in the major groups indicated in the C<$realCoreGroups> member of the
159    B<FIG_Config> file.
160    
161    =cut
162    
163    sub RealCoreGenomes {
164        # Get the parameters.
165        my ($self) = @_;
166        # Declare the return variable.
167        my @retVal = ();
168        # Get the hash of all the genome groups.
169        my %groups = $self->GetGroups();
170        # Loop through the groups, keeping the ones that belong to real core
171        # organisms.
172        for my $group (keys %groups) {
173            if (grep { $group =~ /$_/ } @{$FIG_Config::realCoreGroups}) {
174                push @retVal, @{$groups{$group}};
175            }
176        }
177        # Return the result.
178        return @retVal;
179  }  }
180    
181  =head3 MaxSegment  =head3 MaxSegment
182    
183  C<< my $length = $sprout->MaxSegment(); >>      my $length = $sprout->MaxSegment();
184    
185  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
186  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 142  Line 197 
197    
198  =head3 MaxSequence  =head3 MaxSequence
199    
200  C<< my $length = $sprout->MaxSequence(); >>      my $length = $sprout->MaxSequence();
201    
202  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
203  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 155  Line 210 
210      return $self->{_options}->{maxSequenceLength};      return $self->{_options}->{maxSequenceLength};
211  }  }
212    
 =head3 Get  
   
 C<< my $query = $sprout->Get(\@objectNames, $filterClause, \@parameterList); >>  
   
 This method allows a general query against the Sprout data using a specified filter clause.  
   
 The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each  
 field name represented in the form B<I<objectName>(I<fieldName>)>. For example, the  
 following call requests all B<Genome> objects for the genus specified in the variable  
 $genus.  
   
 C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>  
   
 The WHERE clause contains a single question mark, so there is a single additional  
 parameter representing the parameter value. It would also be possible to code  
   
 C<< $query = $sprout->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>  
   
 however, this version of the call would generate a syntax error if there were any quote  
 characters inside the variable C<$genus>.  
   
 The use of the strange parenthesized notation for field names enables us to distinguish  
 hyphens contained within field names from minus signs that participate in the computation  
 of the WHERE clause. All of the methods that manipulate fields will use this same notation.  
   
 It is possible to specify multiple entity and relationship names in order to retrieve more than  
 one object's data at the same time, which allows highly complex joined queries. For example,  
   
 C<< $query = $sprout->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>  
   
 This query returns all the genomes for a particular genus and allows access to the  
 sources from which they came. The join clauses to go from Genome to Source are generated  
 automatically.  
   
 Finally, the filter clause can contain sort information. To do this, simply put an C<ORDER BY>  
 clause at the end of the filter. Field references in the ORDER BY section follow the same rules  
 as they do in the filter itself; in other words, each one must be of the form B<I<objectName>(I<fieldName>)>.  
 For example, the following filter string gets all genomes for a particular genus and sorts  
 them by species name.  
   
 C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ? ORDER BY Genome(species)", [$genus]); >>  
   
 It is also permissible to specify I<only> an ORDER BY clause. For example, the following invocation gets  
 all genomes ordered by genus and species.  
   
 C<< $query = $sprout->Get(['Genome'], "ORDER BY Genome(genus), Genome(species)"); >>  
   
 Odd things may happen if one of the ORDER BY fields is in a secondary relation. So, for example, an  
 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.  
   
 If multiple names are specified, then the query processor will automatically determine a  
 join path between the entities and relationships. The algorithm used is very simplistic.  
 In particular, you can't specify any entity or relationship more than once, and if a  
 relationship is recursive, the path is determined by the order in which the entity  
 and the relationship appear. For example, consider a recursive relationship B<IsParentOf>  
 which relates B<People> objects to other B<People> objects. If the join path is  
 coded as C<['People', 'IsParentOf']>, then the people returned will be parents. If, however,  
 the join path is C<['IsParentOf', 'People']>, then the people returned will be children.  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item RETURN  
   
 Returns a B<DBQuery> that can be used to iterate through all of the results.  
   
 =back  
   
 =cut  
   
 sub Get {  
     # Get the parameters.  
     my ($self, $objectNames, $filterClause, $parameterList) = @_;  
     # We differ from the ERDB Get method in that the parameter list is passed in as a list reference  
     # rather than a list of parameters. The next step is to convert the parameters from a reference  
     # to a real list. We can only do this if the parameters have been specified.  
     my @parameters;  
     if ($parameterList) { @parameters = @{$parameterList}; }  
     return $self->{_erdb}->Get($objectNames, $filterClause, @parameters);  
 }  
   
 =head3 GetEntity  
   
 C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>  
   
 Return an object describing the entity instance with a specified ID.  
   
 =over 4  
   
 =item entityType  
   
 Entity type name.  
   
 =item ID  
   
 ID of the desired entity.  
   
 =item RETURN  
   
 Returns a B<DBObject> representing the desired entity instance, or an undefined value if no  
 instance is found with the specified key.  
   
 =back  
   
 =cut  
   
 sub GetEntity {  
     # Get the parameters.  
     my ($self, $entityType, $ID) = @_;  
     # Call the ERDB method.  
     return $self->{_erdb}->GetEntity($entityType, $ID);  
 }  
   
 =head3 GetEntityValues  
   
 C<< my @values = GetEntityValues($entityType, $ID, \@fields); >>  
   
 Return a list of values from a specified entity instance.  
   
 =over 4  
   
 =item entityType  
   
 Entity type name.  
   
 =item ID  
   
 ID of the desired entity.  
   
 =item fields  
   
 List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.  
   
 =item RETURN  
   
 Returns a flattened list of the values of the specified fields for the specified entity.  
   
 =back  
   
 =cut  
 #: Return Type @;  
 sub GetEntityValues {  
     # Get the parameters.  
     my ($self, $entityType, $ID, $fields) = @_;  
     # Call the ERDB method.  
     return $self->{_erdb}->GetEntityValues($entityType, $ID, $fields);  
 }  
   
 =head3 ShowMetaData  
   
 C<< $sprout->ShowMetaData($fileName); >>  
   
 This method outputs a description of the database to an HTML file in the data directory.  
   
 =over 4  
   
 =item fileName  
   
 Fully-qualified name to give to the output file.  
   
 =back  
   
 =cut  
   
 sub ShowMetaData {  
     # 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);  
 }  
   
213  =head3 Load  =head3 Load
214    
215  C<< $sprout->Load($rebuild); >>;      $sprout->Load($rebuild);;
216    
217  Load the database from files in the data directory, optionally re-creating the tables.  Load the database from files in the data directory, optionally re-creating the tables.
218    
# Line 379  Line 244 
244  sub Load {  sub Load {
245      # Get the parameters.      # Get the parameters.
246      my ($self, $rebuild) = @_;      my ($self, $rebuild) = @_;
     # Get the database object.  
     my $erdb = $self->{_erdb};  
247      # Load the tables from the data directory.      # Load the tables from the data directory.
248      my $retVal = $erdb->LoadTables($self->{_options}->{dataDir}, $rebuild);      my $retVal = $self->LoadTables($self->{_options}->{dataDir}, $rebuild);
249      # Return the statistics.      # Return the statistics.
250      return $retVal;      return $retVal;
251  }  }
252    
253  =head3 LoadUpdate  =head3 LoadUpdate
254    
255  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>      my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList);
256    
257  Load updates to one or more database tables. This method enables the client to make changes to one  Load updates to one or more database tables. This method enables the client to make changes to one
258  or two tables without reloading the whole database. For each table, there must be a corresponding  or two tables without reloading the whole database. For each table, there must be a corresponding
# Line 422  Line 285 
285  sub LoadUpdate {  sub LoadUpdate {
286      # Get the parameters.      # Get the parameters.
287      my ($self, $truncateFlag, $tableList) = @_;      my ($self, $truncateFlag, $tableList) = @_;
     # Get the database object.  
     my $erdb = $self->{_erdb};  
288      # Declare the return value.      # Declare the return value.
289      my $retVal = Stats->new();      my $retVal = Stats->new();
290      # Get the data directory.      # Get the data directory.
# Line 437  Line 298 
298              Trace("No load file found for $tableName in $dataDir.") if T(0);              Trace("No load file found for $tableName in $dataDir.") if T(0);
299          } else {          } else {
300              # Attempt to load this table.              # Attempt to load this table.
301              my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);              my $result = $self->LoadTable($fileName, $tableName, truncate => $truncateFlag);
302              # Accumulate the resulting statistics.              # Accumulate the resulting statistics.
303              $retVal->Accumulate($result);              $retVal->Accumulate($result);
304          }          }
# Line 446  Line 307 
307      return $retVal;      return $retVal;
308  }  }
309    
310    =head3 GenomeCounts
311    
312        my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete);
313    
314    Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
315    genomes will be included in the counts.
316    
317    =over 4
318    
319    =item complete
320    
321    TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
322    counted
323    
324    =item RETURN
325    
326    A six-element list containing the number of genomes in each of six categories--
327    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
328    
329    =back
330    
331    =cut
332    
333    sub GenomeCounts {
334        # Get the parameters.
335        my ($self, $complete) = @_;
336        # Set the filter based on the completeness flag.
337        my $filter = ($complete ? "Genome(complete) = 1" : "");
338        # Get all the genomes and the related taxonomy information.
339        my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
340        # Clear the counters.
341        my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
342        # Loop through, counting the domains.
343        for my $genome (@genomes) {
344            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
345            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
346            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
347            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
348            elsif ($genome->[1] =~ /^env/i)      { ++$env }
349            else  { ++$unk }
350        }
351        # Return the counts.
352        return ($arch, $bact, $euk, $vir, $env, $unk);
353    }
354    
355    =head3 ContigCount
356    
357        my $count = $sprout->ContigCount($genomeID);
358    
359    Return the number of contigs for the specified genome ID.
360    
361    =over 4
362    
363    =item genomeID
364    
365    ID of the genome whose contig count is desired.
366    
367    =item RETURN
368    
369    Returns the number of contigs for the specified genome.
370    
371    =back
372    
373    =cut
374    
375    sub ContigCount {
376        # Get the parameters.
377        my ($self, $genomeID) = @_;
378        # Get the contig count.
379        my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
380        # Return the result.
381        return $retVal;
382    }
383    
384    =head3 GeneMenu
385    
386        my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected);
387    
388    Return an HTML select menu of genomes. Each genome will be an option in the menu,
389    and will be displayed by name with the ID and a contig count attached. The selection
390    value will be the genome ID. The genomes will be sorted by genus/species name.
391    
392    =over 4
393    
394    =item attributes
395    
396    Reference to a hash mapping attributes to values for the SELECT tag generated.
397    
398    =item filterString
399    
400    A filter string for use in selecting the genomes. The filter string must conform
401    to the rules for the C<< ERDB->Get >> method.
402    
403    =item params
404    
405    Reference to a list of values to be substituted in for the parameter marks in
406    the filter string.
407    
408    =item selected (optional)
409    
410    ID of the genome to be initially selected.
411    
412    =item fast (optional)
413    
414    If specified and TRUE, the contig counts will be omitted to improve performance.
415    
416    =item RETURN
417    
418    Returns an HTML select menu with the specified genomes as selectable options.
419    
420    =back
421    
422    =cut
423    
424    sub GeneMenu {
425        # Get the parameters.
426        my ($self, $attributes, $filterString, $params, $selected, $fast) = @_;
427        my $slowMode = ! $fast;
428        # Default to nothing selected. This prevents an execution warning if "$selected"
429        # is undefined.
430        $selected = "" unless defined $selected;
431        Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3);
432        # Start the menu.
433        my $retVal = "<select " .
434            join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
435            ">\n";
436        # Get the genomes.
437        my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
438                                                                         'Genome(genus)',
439                                                                         'Genome(species)',
440                                                                         'Genome(unique-characterization)']);
441        # Sort them by name.
442        my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
443        # Loop through the genomes, creating the option tags.
444        for my $genomeData (@sorted) {
445            # Get the data for this genome.
446            my ($genomeID, $genus, $species, $strain) = @{$genomeData};
447            # Get the contig count.
448            my $contigInfo = "";
449            if ($slowMode) {
450                my $count = $self->ContigCount($genomeID);
451                my $counting = ($count == 1 ? "contig" : "contigs");
452                $contigInfo = "[$count $counting]";
453            }
454            # Find out if we're selected.
455            my $selectOption = ($selected eq $genomeID ? " selected" : "");
456            # Build the option tag.
457            $retVal .= "<option value=\"$genomeID\"$selectOption>$genus $species $strain ($genomeID)$contigInfo</option>\n";
458        }
459        # Close the SELECT tag.
460        $retVal .= "</select>\n";
461        # Return the result.
462        return $retVal;
463    }
464    
465  =head3 Build  =head3 Build
466    
467  C<< $sprout->Build(); >>      $sprout->Build();
468    
469  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.
470  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 460  Line 476 
476      # Get the parameters.      # Get the parameters.
477      my ($self) = @_;      my ($self) = @_;
478      # Create the tables.      # Create the tables.
479      $self->{_erdb}->CreateTables;      $self->CreateTables();
480  }  }
481    
482  =head3 Genomes  =head3 Genomes
483    
484  C<< my @genomes = $sprout->Genomes(); >>      my @genomes = $sprout->Genomes();
485    
486  Return a list of all the genome IDs.  Return a list of all the genome IDs.
487    
# Line 482  Line 498 
498    
499  =head3 GenusSpecies  =head3 GenusSpecies
500    
501  C<< my $infoString = $sprout->GenusSpecies($genomeID); >>      my $infoString = $sprout->GenusSpecies($genomeID);
502    
503  Return the genus, species, and unique characterization for a genome.  Return the genus, species, and unique characterization for a genome.
504    
# Line 514  Line 530 
530    
531  =head3 FeaturesOf  =head3 FeaturesOf
532    
533  C<< my @features = $sprout->FeaturesOf($genomeID, $ftype); >>      my @features = $sprout->FeaturesOf($genomeID, $ftype);
534    
535  Return a list of the features relevant to a specified genome.  Return a list of the features relevant to a specified genome.
536    
# Line 559  Line 575 
575    
576  =head3 FeatureLocation  =head3 FeatureLocation
577    
578  C<< my @locations = $sprout->FeatureLocation($featureID); >>      my @locations = $sprout->FeatureLocation($featureID);
579    
580  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
581  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 588  Line 604 
604  =back  =back
605    
606  =cut  =cut
607  #: Return Type @;  
 #: Return Type $;  
608  sub FeatureLocation {  sub FeatureLocation {
609      # Get the parameters.      # Get the parameters.
610      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
611      # Create a query for the feature locations.      # Get the feature record.
612      my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",      my $object = $self->GetEntity('Feature', $featureID);
613                             [$featureID]);      Confess("Feature $featureID not found.") if ! defined($object);
614        # Get the location string.
615        my $locString = $object->PrimaryValue('Feature(location-string)');
616      # Create the return list.      # Create the return list.
617      my @retVal = ();      my @retVal = split /\s*,\s*/, $locString;
     # Set up the variables used to determine if we have adjacent segments. This initial setup will  
     # not match anything.  
     my ($prevContig, $prevBeg, $prevDir, $prevLen) = ("", 0, "0", 0);  
     # Loop through the query results, creating location specifiers.  
     while (my $location = $query->Fetch()) {  
         # Get the location parameters.  
         my ($contigID, $beg, $dir, $len) = $location->Values(['IsLocatedIn(to-link)',  
             'IsLocatedIn(beg)', 'IsLocatedIn(dir)', 'IsLocatedIn(len)']);  
         # Check to see if we are adjacent to the previous segment.  
         if ($prevContig eq $contigID && $dir eq $prevDir) {  
             # Here the new segment is in the same direction on the same contig. Insure the  
             # new segment's beginning is next to the old segment's end.  
             if ($dir eq "-" && $beg + $len == $prevBeg) {  
                 # Here we're merging two backward blocks, so we keep the new begin point  
                 # and adjust the length.  
                 $len += $prevLen;  
                 # Pop the old segment off. The new one will replace it later.  
                 pop @retVal;  
             } elsif ($dir eq "+" && $beg == $prevBeg + $prevLen) {  
                 # Here we need to merge two forward blocks. 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);  
         # Compute the initial base pair.  
         my $start = ($dir eq "+" ? $beg : $beg + $len - 1);  
         # Add the specifier to the list.  
         push @retVal, "${contigID}_$start$dir$len";  
     }  
618      # Return the list in the format indicated by the context.      # Return the list in the format indicated by the context.
619      return (wantarray ? @retVal : join(',', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
620  }  }
621    
622  =head3 ParseLocation  =head3 ParseLocation
623    
624  C<< my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location); >>      my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location);
625    
626  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
627  length.  length.
# Line 657  Line 640 
640  =back  =back
641    
642  =cut  =cut
643  #: Return Type @;  
644  sub ParseLocation {  sub ParseLocation {
645      # 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
646      # the first parameter.      # the first parameter.
# Line 680  Line 663 
663      return ($contigID, $start, $dir, $len);      return ($contigID, $start, $dir, $len);
664  }  }
665    
666    
667    
668  =head3 PointLocation  =head3 PointLocation
669    
670  C<< my $found = Sprout::PointLocation($location, $point); >>      my $found = Sprout::PointLocation($location, $point);
671    
672  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
673  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 711  Line 696 
696  =back  =back
697    
698  =cut  =cut
699  #: Return Type $;  
700  sub PointLocation {  sub PointLocation {
701      # 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
702      # the first parameter.      # the first parameter.
# Line 734  Line 719 
719    
720  =head3 DNASeq  =head3 DNASeq
721    
722  C<< my $sequence = $sprout->DNASeq(\@locationList); >>      my $sequence = $sprout->DNASeq(\@locationList);
723    
724  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
725  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,
726  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>.
727    
728    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
729    between positions 1401 and 1532, inclusive.
730    
731        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
732    
733  =over 4  =over 4
734    
735  =item locationList  =item locationList
736    
737  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
738  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
739    
740  =item RETURN  =item RETURN
741    
# Line 813  Line 803 
803    
804  =head3 AllContigs  =head3 AllContigs
805    
806  C<< my @idList = $sprout->AllContigs($genomeID); >>      my @idList = $sprout->AllContigs($genomeID);
807    
808  Return a list of all the contigs for a genome.  Return a list of all the contigs for a genome.
809    
# Line 841  Line 831 
831      return @retVal;      return @retVal;
832  }  }
833    
834  =head3 ContigLength  =head3 GenomeLength
835    
836  C<< my $length = $sprout->ContigLength($contigID); >>      my $length = $sprout->GenomeLength($genomeID);
837    
838  Compute the length of a contig.  Return the length of the specified genome in base pairs.
839    
840  =over 4  =over 4
841    
842  =item contigID  =item genomeID
843    
844  ID of the contig whose length is desired.  ID of the genome whose base pair count is desired.
845    
846  =item RETURN  =item RETURN
847    
848  Returns the number of positions in the contig.  Returns the number of base pairs in all the contigs of the specified
849    genome.
850    
851  =back  =back
852    
853  =cut  =cut
854  #: Return Type $;  
855  sub ContigLength {  sub GenomeLength {
856      # Get the parameters.      # Get the parameters.
857      my ($self, $contigID) = @_;      my ($self, $genomeID) = @_;
858      # Get the contig's last sequence.      # Declare the return variable.
     my $query = $self->Get(['IsMadeUpOf'],  
         "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",  
         [$contigID]);  
     my $sequence = $query->Fetch();  
     # Declare the return value.  
859      my $retVal = 0;      my $retVal = 0;
860      # Set it from the sequence data, if any.      # Get the genome's contig sequence lengths.
861      if ($sequence) {      my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
862          my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);                         [$genomeID], 'IsMadeUpOf(len)');
863          $retVal = $start + $len - 1;      # Sum the lengths.
864      }      map { $retVal += $_ } @lens;
865      # Return the result.      # Return the result.
866      return $retVal;      return $retVal;
867  }  }
868    
869  =head3 ClusterPEGs  =head3 FeatureCount
870    
871  C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>      my $count = $sprout->FeatureCount($genomeID, $type);
872    
873  Cluster the PEGs in a list according to the cluster coding scheme of the specified  Return the number of features of the specified type in the specified genome.
 subsystem. In order for this to work properly, the subsystem object must have  
 been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.  
 This causes the cluster numbers to be pulled into the subsystem's color hash.  
 If a PEG is not found in the color hash, it will not appear in the output  
 sequence.  
874    
875  =over 4  =over 4
876    
877  =item sub  =item genomeID
878    
879  Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>  ID of the genome whose feature count is desired.
 method.  
880    
881  =item pegs  =item type
882    
883  Reference to the list of PEGs to be clustered.  Type of feature to count (eg. C<peg>, C<rna>, etc.).
884    
885  =item RETURN  =item RETURN
886    
887  Returns a list of the PEGs, grouped into smaller lists by cluster number.  Returns the number of features of the specified type for the specified genome.
888    
889  =back  =back
890    
891  =cut  =cut
892  #: Return Type $@@;  
893  sub ClusterPEGs {  sub FeatureCount {
894      # Get the parameters.      # Get the parameters.
895      my ($self, $sub, $pegs) = @_;      my ($self, $genomeID, $type) = @_;
896      # Declare the return variable.      # Compute the count.
897      my $retVal = [];      my $retVal = $self->GetCount(['HasFeature', 'Feature'],
898      # Loop through the PEGs, creating arrays for each cluster.                                  "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
899      for my $pegID (@{$pegs}) {                                  [$genomeID, $type]);
         my $clusterNumber = $sub->get_cluster_number($pegID);  
         # Only proceed if the PEG is in a cluster.  
         if ($clusterNumber >= 0) {  
             # Push this PEG onto the sub-list for the specified cluster number.  
             push @{$retVal->[$clusterNumber]}, $pegID;  
         }  
     }  
900      # Return the result.      # Return the result.
901      return $retVal;      return $retVal;
902  }  }
903    
904  =head3 GenesInRegion  =head3 GenomeAssignments
905    
906  C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>      my $fidHash = $sprout->GenomeAssignments($genomeID);
907    
908  List the features which overlap a specified region in a contig.  Return a list of a genome's assigned features. The return hash will contain each
909    assigned feature of the genome mapped to the text of its most recent functional
910    assignment.
911    
912  =over 4  =over 4
913    
914  =item contigID  =item genomeID
915    
916  ID of the contig containing the region of interest.  ID of the genome whose functional assignments are desired.
917    
918  =item start  =item RETURN
919    
920  Offset of the first residue in the region of interest.  Returns a reference to a hash which maps each feature to its most recent
921    functional assignment.
922    
923  =item stop  =back
924    
925  Offset of the last residue in the region of interest.  =cut
926    
927  =item RETURN  sub GenomeAssignments {
928        # Get the parameters.
929        my ($self, $genomeID) = @_;
930        # Declare the return variable.
931        my $retVal = {};
932        # Query the genome's features.
933        my $query = $self->Get(['HasFeature', 'Feature'], "HasFeature(from-link) = ?",
934                               [$genomeID]);
935        # Loop through the features.
936        while (my $data = $query->Fetch) {
937            # Get the feature ID and assignment.
938            my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']);
939            if ($assignment) {
940                $retVal->{$fid} = $assignment;
941            }
942        }
943        # Return the result.
944        return $retVal;
945    }
946    
947    =head3 ContigLength
948    
949        my $length = $sprout->ContigLength($contigID);
950    
951    Compute the length of a contig.
952    
953    =over 4
954    
955    =item contigID
956    
957    ID of the contig whose length is desired.
958    
959    =item RETURN
960    
961    Returns the number of positions in the contig.
962    
963    =back
964    
965    =cut
966    #: Return Type $;
967    sub ContigLength {
968        # Get the parameters.
969        my ($self, $contigID) = @_;
970        # Get the contig's last sequence.
971        my $query = $self->Get(['IsMadeUpOf'],
972            "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
973            [$contigID]);
974        my $sequence = $query->Fetch();
975        # Declare the return value.
976        my $retVal = 0;
977        # Set it from the sequence data, if any.
978        if ($sequence) {
979            my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
980            $retVal = $start + $len - 1;
981        }
982        # Return the result.
983        return $retVal;
984    }
985    
986    =head3 ClusterPEGs
987    
988        my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs);
989    
990    Cluster the PEGs in a list according to the cluster coding scheme of the specified
991    subsystem. In order for this to work properly, the subsystem object must have
992    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> or
993    B<get_row> methods. This causes the cluster numbers to be pulled into the
994    subsystem's color hash. If a PEG is not found in the color hash, it will not
995    appear in the output sequence.
996    
997    =over 4
998    
999    =item sub
1000    
1001    Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
1002    method.
1003    
1004    =item pegs
1005    
1006    Reference to the list of PEGs to be clustered.
1007    
1008    =item RETURN
1009    
1010    Returns a list of the PEGs, grouped into smaller lists by cluster number.
1011    
1012    =back
1013    
1014    =cut
1015    #: Return Type $@@;
1016    sub ClusterPEGs {
1017        # Get the parameters.
1018        my ($self, $sub, $pegs) = @_;
1019        # Declare the return variable.
1020        my $retVal = [];
1021        # Loop through the PEGs, creating arrays for each cluster.
1022        for my $pegID (@{$pegs}) {
1023            my $clusterNumber = $sub->get_cluster_number($pegID);
1024            # Only proceed if the PEG is in a cluster.
1025            if ($clusterNumber >= 0) {
1026                # Push this PEG onto the sub-list for the specified cluster number.
1027                push @{$retVal->[$clusterNumber]}, $pegID;
1028            }
1029        }
1030        # Return the result.
1031        return $retVal;
1032    }
1033    
1034    =head3 GenesInRegion
1035    
1036        my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop);
1037    
1038    List the features which overlap a specified region in a contig.
1039    
1040    =over 4
1041    
1042    =item contigID
1043    
1044    ID of the contig containing the region of interest.
1045    
1046    =item start
1047    
1048    Offset of the first residue in the region of interest.
1049    
1050    =item stop
1051    
1052    Offset of the last residue in the region of interest.
1053    
1054    =item RETURN
1055    
1056  Returns a three-element list. The first element is a list of feature IDs for the features that  Returns a three-element list. The first element is a list of feature IDs for the features that
1057  overlap the region of interest. The second and third elements are the minimum and maximum  overlap the region of interest. The second and third elements are the minimum and maximum
# Line 959  Line 1062 
1062  =back  =back
1063    
1064  =cut  =cut
1065  #: Return Type @@;  
1066  sub GenesInRegion {  sub GenesInRegion {
1067      # Get the parameters.      # Get the parameters.
1068      my ($self, $contigID, $start, $stop) = @_;      my ($self, $contigID, $start, $stop) = @_;
1069      # Get the maximum segment length.      # Get the maximum segment length.
1070      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 = ();  
1071      # Prime the values we'll use for the returned beginning and end.      # Prime the values we'll use for the returned beginning and end.
1072      my @initialMinMax = ($self->ContigLength($contigID), 0);      my @initialMinMax = ($self->ContigLength($contigID), 0);
1073      my ($min, $max) = @initialMinMax;      my ($min, $max) = @initialMinMax;
1074      # Create a table of parameters for each query. Each query looks for features travelling in      # Get the overlapping features.
1075        my @featureObjects = $self->GeneDataInRegion($contigID, $start, $stop);
1076        # We'l use this hash to help us track the feature IDs and sort them. The key is the
1077        # feature ID and the value is a [$left,$right] pair indicating the maximum extent
1078        # of the feature's locations.
1079        my %featureMap = ();
1080        # Loop through them to do the begin/end analysis.
1081        for my $featureObject (@featureObjects) {
1082            # Get the feature's location string. This may contain multiple actual locations.
1083            my ($locations, $fid) = $featureObject->Values([qw(Feature(location-string) Feature(id))]);
1084            my @locationSegments = split /\s*,\s*/, $locations;
1085            # Loop through the locations.
1086            for my $locationSegment (@locationSegments) {
1087                # Construct an object for the location.
1088                my $locationObject = BasicLocation->new($locationSegment);
1089                # Merge the current segment's begin and end into the min and max.
1090                my ($left, $right) = ($locationObject->Left, $locationObject->Right);
1091                my ($beg, $end);
1092                if (exists $featureMap{$fid}) {
1093                    ($beg, $end) = @{$featureMap{$fid}};
1094                    $beg = $left if $left < $beg;
1095                    $end = $right if $right > $end;
1096                } else {
1097                    ($beg, $end) = ($left, $right);
1098                }
1099                $min = $beg if $beg < $min;
1100                $max = $end if $end > $max;
1101                # Store the feature's new extent back into the hash table.
1102                $featureMap{$fid} = [$beg, $end];
1103            }
1104        }
1105        # Now we must compute the list of the IDs for the features found. We start with a list
1106        # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1107        # but the result of the sort will be the same.)
1108        my @list = map { [$featureMap{$_}->[0] + $featureMap{$_}->[1], $_] } keys %featureMap;
1109        # Now we sort by midpoint and yank out the feature IDs.
1110        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1111        # Return it along with the min and max.
1112        return (\@retVal, $min, $max);
1113    }
1114    
1115    =head3 GeneDataInRegion
1116    
1117        my @featureList = $sprout->GenesInRegion($contigID, $start, $stop);
1118    
1119    List the features which overlap a specified region in a contig.
1120    
1121    =over 4
1122    
1123    =item contigID
1124    
1125    ID of the contig containing the region of interest.
1126    
1127    =item start
1128    
1129    Offset of the first residue in the region of interest.
1130    
1131    =item stop
1132    
1133    Offset of the last residue in the region of interest.
1134    
1135    =item RETURN
1136    
1137    Returns a list of B<ERDBObjects> for the desired features. Each object will
1138    contain a B<Feature> record.
1139    
1140    =back
1141    
1142    =cut
1143    
1144    sub GeneDataInRegion {
1145        # Get the parameters.
1146        my ($self, $contigID, $start, $stop) = @_;
1147        # Get the maximum segment length.
1148        my $maximumSegmentLength = $self->MaxSegment;
1149        # Create a hash to receive the feature list. We use a hash so that we can eliminate
1150        # duplicates easily. The hash key will be the feature ID. The value will be the feature's
1151        # ERDBObject from the query.
1152        my %featuresFound = ();
1153        # Create a table of parameters for the queries. Each query looks for features travelling in
1154      # 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,
1155      # 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
1156      # 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 982  Line 1159 
1159      # Loop through the query parameters.      # Loop through the query parameters.
1160      for my $parms (values %queryParms) {      for my $parms (values %queryParms) {
1161          # Create the query.          # Create the query.
1162          my $query = $self->Get(['IsLocatedIn'],          my $query = $self->Get([qw(Feature IsLocatedIn)],
1163              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
1164              $parms);              $parms);
1165          # Loop through the feature segments found.          # Loop through the feature segments found.
1166          while (my $segment = $query->Fetch) {          while (my $segment = $query->Fetch) {
1167              # Get the data about this segment.              # Get the data about this segment.
1168              my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',              my ($featureID, $contig, $dir, $beg, $len) = $segment->Values([qw(IsLocatedIn(from-link)
1169                  'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);                  IsLocatedIn(to-link) IsLocatedIn(dir) IsLocatedIn(beg) IsLocatedIn(len))]);
1170              # 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
1171              # 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
1172              # 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
1173              # length.              # length.
1174              my ($found, $end) = (0, 0);              my $loc = BasicLocation->new($contig, $beg, $dir, $len);
1175              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;  
                 }  
             }  
1176              if ($found) {              if ($found) {
1177                  # Here we need to record the feature and update the minima and maxima. First,                  # Save this feature in the result list.
1178                  # get the current entry for the specified feature.                  $featuresFound{$featureID} = $segment;
                 my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :  
                                      @initialMinMax);  
                 # Merge the current segment's begin and end into the feature begin and end and the  
                 # global min and max.  
                 if ($beg < $loc1) {  
                     $loc1 = $beg;  
                     $min = $beg if $beg < $min;  
                 }  
                 if ($end > $loc2) {  
                     $loc2 = $end;  
                     $max = $end if $end > $max;  
1179                  }                  }
                 # Store the entry back into the hash table.  
                 $featuresFound{$featureID} = [$loc1, $loc2];  
1180              }              }
1181          }          }
1182      }      # Return the ERDB objects for the features found.
1183      # 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);  
1184  }  }
1185    
1186  =head3 FType  =head3 FType
1187    
1188  C<< my $ftype = $sprout->FType($featureID); >>      my $ftype = $sprout->FType($featureID);
1189    
1190  Return the type of a feature.  Return the type of a feature.
1191    
# Line 1072  Line 1215 
1215    
1216  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1217    
1218  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>      my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag);
1219    
1220  Return the annotations of a feature.  Return the annotations of a feature.
1221    
# Line 1135  Line 1278 
1278    
1279  =head3 AllFunctionsOf  =head3 AllFunctionsOf
1280    
1281  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>      my %functions = $sprout->AllFunctionsOf($featureID);
1282    
1283  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
1284  hash of functional assignments to user IDs. A functional assignment is a type of annotation,  hash of functional assignments to user IDs. A functional assignment is a type of annotation,
# Line 1153  Line 1296 
1296    
1297  =item RETURN  =item RETURN
1298    
1299  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1300    
1301  =back  =back
1302    
# Line 1163  Line 1306 
1306      # Get the parameters.      # Get the parameters.
1307      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1308      # Get all of the feature's annotations.      # Get all of the feature's annotations.
1309      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1310                              "IsTargetOfAnnotation(from-link) = ?",                              "IsTargetOfAnnotation(from-link) = ?",
1311                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1312                                               'MadeAnnotation(from-link)']);
1313      # Declare the return hash.      # Declare the return hash.
1314      my %retVal;      my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1315      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1316      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1317      # Loop until we run out of annotations.      # Loop until we run out of annotations.
1318      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1319          # Get the annotation fields.          # Get the annotation fields.
1320          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1321          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
1322          my ($user, $function) = _ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1323          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1324              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1325              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1326              # return hash.              # return hash.
1327              $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1328          }          }
1329      }      }
1330      # Return the hash of assignments found.      # Return the hash of assignments found.
# Line 1193  Line 1333 
1333    
1334  =head3 FunctionOf  =head3 FunctionOf
1335    
1336  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>      my $functionText = $sprout->FunctionOf($featureID, $userID);
1337    
1338  Return the most recently-determined functional assignment of a particular feature.  Return the most recently-determined functional assignment of a particular feature.
1339    
1340  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
1341  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
1342  assignment is a type of annotation. The format of an assignment is described in  assignment is taken from the B<Feature> or C<Annotation> table, depending.
 L</ParseLocation>. Its worth noting that we cannot filter on the content of the  
 annotation itself because it's a text field; however, this is not a big problem because  
 most features only have a small number of annotations.  
1343    
1344  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
1345  recent one by at least one of the trusted users. If no trusted user list is available, then  recent one by at least one of the trusted users. If no trusted user list is available, then
# Line 1221  Line 1358 
1358    
1359  =item userID (optional)  =item userID (optional)
1360    
1361  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
1362  C<FIG> assignment will be returned.  functional assignment in the B<Feature> table will be returned.
1363    
1364  =item RETURN  =item RETURN
1365    
# Line 1239  Line 1376 
1376      my $retVal;      my $retVal;
1377      # Determine the ID type.      # Determine the ID type.
1378      if ($featureID =~ m/^fig\|/) {      if ($featureID =~ m/^fig\|/) {
1379          # Here we have a FIG feature ID. We must build the list of trusted          # Here we have a FIG feature ID.
1380          # users.          if (!$userID) {
1381                # Use the primary assignment.
1382                ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']);
1383            } else {
1384                # We must build the list of trusted users.
1385          my %trusteeTable = ();          my %trusteeTable = ();
1386          # Check the user ID.          # Check the user ID.
1387          if (!$userID) {          if (!$userID) {
# Line 1262  Line 1403 
1403              }              }
1404          }          }
1405          # 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.
1406          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],              my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1407                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1408                                 [$featureID]);                                 [$featureID]);
1409          my $timeSelected = 0;          my $timeSelected = 0;
1410          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1411          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1412              # Get the annotation text.              # Get the annotation text.
1413              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);                  my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1414                                                             'Annotation(time)', 'MadeAnnotation(from-link)']);
1415              # 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.
1416              my ($user, $function) = _ParseAssignment($text);                  my ($actualUser, $function) = _ParseAssignment($user, $text);
1417              if ($user) {                  Trace("Assignment user is $actualUser, text is $function.") if T(4);
1418                    if ($actualUser) {
1419                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1420                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1421                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                      if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1422                      $retVal = $function;                      $retVal = $function;
1423                      $timeSelected = $time;                      $timeSelected = $time;
1424                  }                  }
1425              }              }
1426          }          }
1427            }
1428      } else {      } else {
1429          # Here we have a non-FIG feature ID. In this case the user ID does not          # Here we have a non-FIG feature ID. In this case the user ID does not
1430          # matter. We simply get the information from the External Alias Function          # matter. We simply get the information from the External Alias Function
# Line 1291  Line 1435 
1435      return $retVal;      return $retVal;
1436  }  }
1437    
1438    =head3 FunctionsOf
1439    
1440        my @functionList = $sprout->FunctionOf($featureID, $userID);
1441    
1442    Return the functional assignments of a particular feature.
1443    
1444    The functional assignment is handled differently depending on the type of feature. If
1445    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1446    assignment is a type of annotation. The format of an assignment is described in
1447    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1448    annotation itself because it's a text field; however, this is not a big problem because
1449    most features only have a small number of annotations.
1450    
1451    If the feature is B<not> identified by a FIG ID, then the functional assignment
1452    information is taken from the B<ExternalAliasFunc> table. If the table does
1453    not contain an entry for the feature, an empty list is returned.
1454    
1455    =over 4
1456    
1457    =item featureID
1458    
1459    ID of the feature whose functional assignments are desired.
1460    
1461    =item RETURN
1462    
1463    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1464    that user.
1465    
1466    =back
1467    
1468    =cut
1469    #: Return Type @@;
1470    sub FunctionsOf {
1471        # Get the parameters.
1472        my ($self, $featureID) = @_;
1473        # Declare the return value.
1474        my @retVal = ();
1475        # Determine the ID type.
1476        if ($featureID =~ m/^fig\|/) {
1477            # Here we have a FIG feature ID. We must build the list of trusted
1478            # users.
1479            my %trusteeTable = ();
1480            # Build a query for all of the feature's annotations, sorted by date.
1481            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1482                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1483                                   [$featureID]);
1484            my $timeSelected = 0;
1485            # Loop until we run out of annotations.
1486            while (my $annotation = $query->Fetch()) {
1487                # Get the annotation text.
1488                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1489                                                                'Annotation(time)',
1490                                                                'MadeAnnotation(user)']);
1491                # Check to see if this is a functional assignment for a trusted user.
1492                my ($actualUser, $function) = _ParseAssignment($user, $text);
1493                if ($actualUser) {
1494                    # Here it is a functional assignment.
1495                    push @retVal, [$actualUser, $function];
1496                }
1497            }
1498        } else {
1499            # Here we have a non-FIG feature ID. In this case the user ID does not
1500            # matter. We simply get the information from the External Alias Function
1501            # table.
1502            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1503                                                     ['ExternalAliasFunc(func)']);
1504            push @retVal, map { ['master', $_] } @assignments;
1505        }
1506        # Return the assignments found.
1507        return @retVal;
1508    }
1509    
1510  =head3 BBHList  =head3 BBHList
1511    
1512  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>      my $bbhHash = $sprout->BBHList($genomeID, \@featureList);
1513    
1514  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
1515  on a specified target genome.  on a specified target genome.
# Line 1324  Line 1540 
1540      my %retVal = ();      my %retVal = ();
1541      # Loop through the incoming features.      # Loop through the incoming features.
1542      for my $featureID (@{$featureList}) {      for my $featureID (@{$featureList}) {
1543          # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1544          my $query = $self->Get(['IsBidirectionalBestHitOf'],          my @bbhData = FIGRules::BBHData($featureID);
                                "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",  
                                [$featureID, $genomeID]);  
1545          # Peel off the BBHs found.          # Peel off the BBHs found.
1546          my @found = ();          my @found = ();
1547          while (my $bbh = $query->Fetch) {          for my $bbh (@bbhData) {
1548              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');              my $fid = $bbh->[0];
1549                my $bbGenome = $self->GenomeOf($fid);
1550                if ($bbGenome eq $genomeID) {
1551                    push @found, $fid;
1552                }
1553          }          }
1554          $retVal{$featureID} = \@found;          $retVal{$featureID} = \@found;
1555      }      }
# Line 1341  Line 1559 
1559    
1560  =head3 SimList  =head3 SimList
1561    
1562  C<< my %similarities = $sprout->SimList($featureID, $count); >>      my %similarities = $sprout->SimList($featureID, $count);
1563    
1564  Return a list of the similarities to the specified feature.  Return a list of the similarities to the specified feature.
1565    
1566  Sprout does not support real similarities, so this method just returns the bidirectional  This method just returns the bidirectional best hits for performance reasons.
 best hits.  
1567    
1568  =over 4  =over 4
1569    
# Line 1366  Line 1583 
1583      # Get the parameters.      # Get the parameters.
1584      my ($self, $featureID, $count) = @_;      my ($self, $featureID, $count) = @_;
1585      # Ask for the best hits.      # Ask for the best hits.
1586      my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],      my @lists = FIGRules::BBHData($featureID);
                               "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",  
                               [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],  
                               $count);  
1587      # Create the return value.      # Create the return value.
1588      my %retVal = ();      my %retVal = ();
1589      for my $tuple (@lists) {      for my $tuple (@lists) {
# Line 1379  Line 1593 
1593      return %retVal;      return %retVal;
1594  }  }
1595    
   
   
1596  =head3 IsComplete  =head3 IsComplete
1597    
1598  C<< my $flag = $sprout->IsComplete($genomeID); >>      my $flag = $sprout->IsComplete($genomeID);
1599    
1600  Return TRUE if the specified genome is complete, else FALSE.  Return TRUE if the specified genome is complete, else FALSE.
1601    
# Line 1411  Line 1623 
1623      my $genomeData = $self->GetEntity('Genome', $genomeID);      my $genomeData = $self->GetEntity('Genome', $genomeID);
1624      if ($genomeData) {      if ($genomeData) {
1625          # The genome exists, so get the completeness flag.          # The genome exists, so get the completeness flag.
1626          ($retVal) = $genomeData->Value('complete');          $retVal = $genomeData->PrimaryValue('Genome(complete)');
1627      }      }
1628      # Return the result.      # Return the result.
1629      return $retVal;      return $retVal;
# Line 1419  Line 1631 
1631    
1632  =head3 FeatureAliases  =head3 FeatureAliases
1633    
1634  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>      my @aliasList = $sprout->FeatureAliases($featureID);
1635    
1636  Return a list of the aliases for a specified feature.  Return a list of the aliases for a specified feature.
1637    
# Line 1442  Line 1654 
1654      # Get the parameters.      # Get the parameters.
1655      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1656      # Get the desired feature's aliases      # Get the desired feature's aliases
1657      my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);      my @retVal = $self->GetFlat(['IsAliasOf'], "IsAliasOf(to-link) = ?", [$featureID], 'IsAliasOf(from-link)');
1658      # Return the result.      # Return the result.
1659      return @retVal;      return @retVal;
1660  }  }
1661    
1662  =head3 GenomeOf  =head3 GenomeOf
1663    
1664  C<< my $genomeID = $sprout->GenomeOf($featureID); >>      my $genomeID = $sprout->GenomeOf($featureID);
1665    
1666  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1667    
1668  =over 4  =over 4
1669    
1670  =item featureID  =item featureID
1671    
1672  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1673    
1674  =item RETURN  =item RETURN
1675    
1676  Returns the ID of the genome for the specified feature. If the feature is not found, returns  Returns the ID of the genome for the specified feature or contig. If the feature or contig is not
1677  an undefined value.  found, returns an undefined value.
1678    
1679  =back  =back
1680    
# Line 1471  Line 1683 
1683  sub GenomeOf {  sub GenomeOf {
1684      # Get the parameters.      # Get the parameters.
1685      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
     # Create a query to find the genome associated with the feature.  
     my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);  
1686      # Declare the return value.      # Declare the return value.
1687      my $retVal;      my $retVal;
1688      # Get the genome ID.      # Parse the genome ID from the feature ID.
1689      if (my $relationship = $query->Fetch()) {      if ($featureID =~ /^fig\|(\d+\.\d+)/) {
1690          ($retVal) = $relationship->Value('HasContig(from-link)');          $retVal = $1;
1691        } else {
1692            Confess("Invalid feature ID $featureID.");
1693      }      }
1694      # Return the value found.      # Return the value found.
1695      return $retVal;      return $retVal;
# Line 1485  Line 1697 
1697    
1698  =head3 CoupledFeatures  =head3 CoupledFeatures
1699    
1700  C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >>      my %coupleHash = $sprout->CoupledFeatures($featureID);
1701    
1702  Return the features functionally coupled with a specified feature. Features are considered  Return the features functionally coupled with a specified feature. Features are considered
1703  functionally coupled if they tend to be clustered on the same chromosome.  functionally coupled if they tend to be clustered on the same chromosome.
# Line 1507  Line 1719 
1719  sub CoupledFeatures {  sub CoupledFeatures {
1720      # Get the parameters.      # Get the parameters.
1721      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1722      # Create a query to retrieve the functionally-coupled features.      # Ask the coupling server for the data.
1723      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1724                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);      my @rawPairs = FIGRules::NetCouplingData('coupled_to', id1 => $featureID);
1725      # This value will be set to TRUE if we find at least one coupled feature.      Trace(scalar(@rawPairs) . " couplings returned.") if T(coupling => 3);
1726      my $found = 0;      # Form them into a hash.
     # Create the return hash.  
1727      my %retVal = ();      my %retVal = ();
1728      # Retrieve the relationship records and store them in the hash.      for my $pair (@rawPairs) {
1729      while (my $clustering = $query->Fetch()) {          # Get the feature ID and score.
1730          # Get the ID and score of the coupling.          my ($featureID2, $score) = @{$pair};
1731          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          # Only proceed if the feature is in NMPDR.
1732                                                          'Coupling(score)']);          if ($self->_CheckFeature($featureID2)) {
1733          # The coupling ID contains the two feature IDs separated by a space. We use              $retVal{$featureID2} = $score;
1734          # this information to find the ID of the other feature.          }
         my ($fid1, $fid2) = split / /, $couplingID;  
         my $otherFeatureID = ($featureID eq $fid1 ? $fid2 : $fid1);  
         # Attach the other feature's score to its ID.  
         $retVal{$otherFeatureID} = $score;  
         $found = 1;  
1735      }      }
1736      # 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
1737      # the incoming feature as well.      # the incoming feature as well.
1738      if ($found) {      if (keys %retVal) {
1739          $retVal{$featureID} = 9999;          $retVal{$featureID} = 9999;
1740      }      }
1741      # Return the hash.      # Return the hash.
# Line 1538  Line 1744 
1744    
1745  =head3 CouplingEvidence  =head3 CouplingEvidence
1746    
1747  C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>      my @evidence = $sprout->CouplingEvidence($peg1, $peg2);
1748    
1749  Return the evidence for a functional coupling.  Return the evidence for a functional coupling.
1750    
# Line 1586  Line 1792 
1792      my ($self, $peg1, $peg2) = @_;      my ($self, $peg1, $peg2) = @_;
1793      # Declare the return variable.      # Declare the return variable.
1794      my @retVal = ();      my @retVal = ();
1795      # Our first task is to find out the nature of the coupling: whether or not      # Get the coupling and evidence data.
1796      # it exists, its score, and whether the features are stored in the same      my @rawData = FIGRules::NetCouplingData('coupling_evidence', id1 => $peg1, id2 => $peg2);
1797      # order as the ones coming in.      # Loop through the raw data, saving the ones that are in NMPDR genomes.
1798      my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);      for my $rawTuple (@rawData) {
1799      # Only proceed if a coupling exists.          if ($self->_CheckFeature($rawTuple->[0]) && $self->_CheckFeature($rawTuple->[1])) {
1800      if ($couplingID) {              push @retVal, $rawTuple;
1801          # Determine the ordering to place on the evidence items. If we're          }
         # inverted, we want to see feature 2 before feature 1 (descending); otherwise,  
         # we want feature 1 before feature 2 (normal).  
         Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);  
         my $ordering = ($inverted ? "DESC" : "");  
         # Get the coupling evidence.  
         my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],  
                                           "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",  
                                           [$couplingID],  
                                           ['PCH(used)', 'UsesAsEvidence(to-link)']);  
         # Loop through the evidence items. Each piece of evidence is represented by two  
         # positions in the evidence list, one for each feature on the other side of the  
         # evidence link. If at some point we want to generalize to couplings with  
         # more than two positions, this section of code will need to be re-done.  
         while (@evidenceList > 0) {  
             my $peg1Data = shift @evidenceList;  
             my $peg2Data = shift @evidenceList;  
             Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);  
             push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];  
         }  
         Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);  
1802      }      }
1803      # Return the result.      # Return the result.
1804      return @retVal;      return @retVal;
1805  }  }
1806    
1807  =head3 GetCoupling  =head3 GetSynonymGroup
   
 C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>  
   
 Return the coupling (if any) for the specified pair of PEGs. If a coupling  
 exists, we return the coupling ID along with an indicator of whether the  
 coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.  
 In the second case, we say the coupling is I<inverted>. The importance of an  
 inverted coupling is that the PEGs in the evidence will appear in reverse order.  
1808    
1809  =over 4      my $id = $sprout->GetSynonymGroup($fid);
1810    
1811  =item peg1  Return the synonym group name for the specified feature.
1812    
1813  ID of the feature of interest.  =over 4
1814    
1815  =item peg2  =item fid
1816    
1817  ID of the potentially coupled feature.  ID of the feature whose synonym group is desired.
1818    
1819  =item RETURN  =item RETURN
1820    
1821  Returns a three-element list. The first element contains the database ID of  The name of the synonym group to which the feature belongs. If the feature does
1822  the coupling. The second element is FALSE if the coupling is stored in the  not belong to a synonym group, the feature ID itself is returned.
 database in the caller specified order and TRUE if it is stored in the  
 inverted order. The third element is the coupling's score. If the coupling  
 does not exist, all three list elements will be C<undef>.  
1823    
1824  =back  =back
1825    
1826  =cut  =cut
1827  #: Return Type $%@;  
1828  sub GetCoupling {  sub GetSynonymGroup {
1829      # Get the parameters.      # Get the parameters.
1830      my ($self, $peg1, $peg2) = @_;      my ($self, $fid) = @_;
1831      # Declare the return values. We'll start with the coupling ID and undefine the      # Declare the return variable.
1832      # flag and score until we have more information.      my $retVal;
1833      my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);      # Find the synonym group.
1834      # Find the coupling data.      my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1835      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],                                     [$fid], 'IsSynonymGroupFor(from-link)');
1836                                   "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",      # Check to see if we found anything.
1837                                   [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);      if (@groups) {
1838      # Check to see if we found anything.          $retVal = $groups[0];
     if (!@pegs) {  
         Trace("No coupling found.") if T(Coupling => 4);  
         # No coupling, so undefine the return value.  
         $retVal = undef;  
1839      } else {      } else {
1840          # We have a coupling! Get the score and check for inversion.          $retVal = $fid;
         $score = $pegs[0]->[1];  
         my $firstFound = $pegs[0]->[0];  
         $inverted = ($firstFound ne $peg1);  
         Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);  
1841      }      }
1842      # Return the result.      # Return the result.
1843      return ($retVal, $inverted, $score);      return $retVal;
1844  }  }
1845    
1846  =head3 CouplingID  =head3 GetBoundaries
1847    
1848  C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>      my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList);
1849    
1850  Return the coupling ID for a pair of feature IDs.  Determine the begin and end boundaries for the locations in a list. All of the
1851    locations must belong to the same contig and have mostly the same direction in
1852  The coupling ID is currently computed by joining the feature IDs in  order for this method to produce a meaningful result. The resulting
1853  sorted order with a space. Client modules (that is, modules which  begin/end pair will contain all of the bases in any of the locations.
 use Sprout) should not, however, count on this always being the  
 case. This method provides a way for abstracting the concept of a  
 coupling ID. All that we know for sure about it is that it can be  
 generated easily from the feature IDs and the order of the IDs  
 in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>  
 will have the same value as C<CouplingID("b1", "a1")>.  
1854    
1855  =over 4  =over 4
1856    
1857  =item peg1  =item locList
   
 First feature of interest.  
   
 =item peg2  
1858    
1859  Second feature of interest.  List of locations to process.
1860    
1861  =item RETURN  =item RETURN
1862    
1863  Returns the ID that would be used to represent a functional coupling of  Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1864  the two specified PEGs.  and the ending boundary. The beginning boundary will be left of the
1865    end for mostly-forward locations and right of the end for mostly-backward
1866    locations.
1867    
1868  =back  =back
1869    
1870  =cut  =cut
 #: Return Type $;  
 sub CouplingID {  
     return join " ", sort @_;  
 }  
   
 =head3 GetEntityTypes  
1871    
1872  C<< my @entityList = $sprout->GetEntityTypes(); >>  sub GetBoundaries {
   
 Return the list of supported entity types.  
   
 =cut  
 #: Return Type @;  
 sub GetEntityTypes {  
1873      # Get the parameters.      # Get the parameters.
1874      my ($self) = @_;      my ($self, @locList) = @_;
1875      # Get the underlying database object.      # Set up the counters used to determine the most popular direction.
1876      my $erdb = $self->{_erdb};      my %counts = ( '+' => 0, '-' => 0 );
1877      # Get its entity type list.      # Get the last location and parse it.
1878      my @retVal = $erdb->GetEntityTypes();      my $locObject = BasicLocation->new(pop @locList);
1879        # Prime the loop with its data.
1880        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
1881        # Count its direction.
1882        $counts{$locObject->Dir}++;
1883        # Loop through the remaining locations. Note that in most situations, this loop
1884        # will not iterate at all, because most of the time we will be dealing with a
1885        # singleton list.
1886        for my $loc (@locList) {
1887            # Create a location object.
1888            my $locObject = BasicLocation->new($loc);
1889            # Count the direction.
1890            $counts{$locObject->Dir}++;
1891            # Get the left end and the right end.
1892            my $left = $locObject->Left;
1893            my $right = $locObject->Right;
1894            # Merge them into the return variables.
1895            if ($left < $beg) {
1896                $beg = $left;
1897            }
1898            if ($right > $end) {
1899                $end = $right;
1900            }
1901        }
1902        # If the most common direction is reverse, flip the begin and end markers.
1903        if ($counts{'-'} > $counts{'+'}) {
1904            ($beg, $end) = ($end, $beg);
1905        }
1906        # Return the result.
1907        return ($contig, $beg, $end);
1908  }  }
1909    
1910  =head3 ReadFasta  =head3 ReadFasta
1911    
1912  C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>      my %sequenceData = Sprout::ReadFasta($fileName, $prefix);
1913    
1914  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
1915  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 1799  Line 1975 
1975    
1976  =head3 FormatLocations  =head3 FormatLocations
1977    
1978  C<< my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat); >>      my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat);
1979    
1980  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
1981  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 1864  Line 2040 
2040    
2041  =head3 DumpData  =head3 DumpData
2042    
2043  C<< $sprout->DumpData(); >>      $sprout->DumpData();
2044    
2045  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.
2046    
# Line 1876  Line 2052 
2052      # Get the data directory name.      # Get the data directory name.
2053      my $outputDirectory = $self->{_options}->{dataDir};      my $outputDirectory = $self->{_options}->{dataDir};
2054      # Dump the relations.      # Dump the relations.
2055      $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2056  }  }
2057    
2058  =head3 XMLFileName  =head3 XMLFileName
2059    
2060  C<< my $fileName = $sprout->XMLFileName(); >>      my $fileName = $sprout->XMLFileName();
2061    
2062  Return the name of this database's XML definition file.  Return the name of this database's XML definition file.
2063    
# Line 1892  Line 2068 
2068      return $self->{_xmlName};      return $self->{_xmlName};
2069  }  }
2070    
2071    =head3 GetGenomeNameData
2072    
2073        my ($genus, $species, $strain) = $sprout->GenomeNameData($genomeID);
2074    
2075    Return the genus, species, and unique characterization for a genome. This
2076    is similar to L</GenusSpecies>, with the exception that it returns the
2077    values in three seperate fields.
2078    
2079    =over 4
2080    
2081    =item genomeID
2082    
2083    ID of the genome whose name data is desired.
2084    
2085    =item RETURN
2086    
2087    Returns a three-element list, consisting of the genus, species, and strain
2088    of the specified genome. If the genome is not found, an error occurs.
2089    
2090    =back
2091    
2092    =cut
2093    
2094    sub GetGenomeNameData {
2095        # Get the parameters.
2096        my ($self, $genomeID) = @_;
2097        # Get the desired values.
2098        my ($genus, $species, $strain) = $self->GetEntityValues('Genome', $genomeID =>
2099                                                                [qw(Genome(genus) Genome(species) Genome(unique-characterization))]);
2100        # Throw an error if they were not found.
2101        if (! defined $genus) {
2102            Confess("Genome $genomeID not found in database.");
2103        }
2104        # Return the results.
2105        return ($genus, $species, $strain);
2106    }
2107    
2108    =head3 GetGenomeByNameData
2109    
2110        my @genomes = $sprout->GetGenomeByNameData($genus, $species, $strain);
2111    
2112    Return a list of the IDs of the genomes with the specified genus,
2113    species, and strain. In almost every case, there will be either zero or
2114    one IDs returned; however, two or more IDs could be returned if there are
2115    multiple versions of the genome in the database.
2116    
2117    =over 4
2118    
2119    =item genus
2120    
2121    Genus of the desired genome.
2122    
2123    =item species
2124    
2125    Species of the desired genome.
2126    
2127    =item strain
2128    
2129    Strain (unique characterization) of the desired genome. This may be an empty
2130    string, in which case it is presumed that the desired genome has no strain
2131    specified.
2132    
2133    =item RETURN
2134    
2135    Returns a list of the IDs of the genomes having the specified genus, species, and
2136    strain.
2137    
2138    =back
2139    
2140    =cut
2141    
2142    sub GetGenomeByNameData {
2143        # Get the parameters.
2144        my ($self, $genus, $species, $strain) = @_;
2145        # Try to find the genomes.
2146        my @retVal = $self->GetFlat(['Genome'], "Genome(genus) = ? AND Genome(species) = ? AND Genome(unique-characterization) = ?",
2147                                    [$genus, $species, $strain], 'Genome(id)');
2148        # Return the result.
2149        return @retVal;
2150    }
2151    
2152  =head3 Insert  =head3 Insert
2153    
2154  C<< $sprout->Insert($objectType, \%fieldHash); >>      $sprout->Insert($objectType, \%fieldHash);
2155    
2156  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
2157  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 1903  Line 2160 
2160  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
2161  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>.
2162    
2163  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']});
2164    
2165  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
2166  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>.
2167    
2168  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'});
2169    
2170  =over 4  =over 4
2171    
# Line 1928  Line 2185 
2185      # Get the parameters.      # Get the parameters.
2186      my ($self, $objectType, $fieldHash) = @_;      my ($self, $objectType, $fieldHash) = @_;
2187      # Call the underlying method.      # Call the underlying method.
2188      $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2189  }  }
2190    
2191  =head3 Annotate  =head3 Annotate
2192    
2193  C<< my $ok = $sprout->Annotate($fid, $timestamp, $user, $text); >>      my $ok = $sprout->Annotate($fid, $timestamp, $user, $text);
2194    
2195  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
2196  specified feature and user.  specified feature and user.
# Line 1987  Line 2244 
2244    
2245  =head3 AssignFunction  =head3 AssignFunction
2246    
2247  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>      my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser);
2248    
2249  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
2250  format is described in L</ParseAssignment>.  format is described in L</ParseAssignment>.
# Line 2047  Line 2304 
2304    
2305  =head3 FeaturesByAlias  =head3 FeaturesByAlias
2306    
2307  C<< my @features = $sprout->FeaturesByAlias($alias); >>      my @features = $sprout->FeaturesByAlias($alias);
2308    
2309  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
2310  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 2081  Line 2338 
2338          push @retVal, $mappedAlias;          push @retVal, $mappedAlias;
2339      } else {      } else {
2340          # 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.
2341          @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');          @retVal = $self->GetFlat(['IsAliasOf'], 'IsAliasOf(from-link) = ?', [$mappedAlias], 'IsAliasOf(to-link)');
2342      }      }
2343      # Return the result.      # Return the result.
2344      return @retVal;      return @retVal;
2345  }  }
2346    
 =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.  
     Trace("Checking existence of $entityName with ID=$entityID.") if T(4);  
     my $testInstance = $self->GetEntity($entityName, $entityID);  
     # Return an existence indicator.  
     my $retVal = ($testInstance ? 1 : 0);  
     return $retVal;  
 }  
   
2347  =head3 FeatureTranslation  =head3 FeatureTranslation
2348    
2349  C<< my $translation = $sprout->FeatureTranslation($featureID); >>      my $translation = $sprout->FeatureTranslation($featureID);
2350    
2351  Return the translation of a feature.  Return the translation of a feature.
2352    
# Line 2152  Line 2374 
2374    
2375  =head3 Taxonomy  =head3 Taxonomy
2376    
2377  C<< my @taxonomyList = $sprout->Taxonomy($genome); >>      my @taxonomyList = $sprout->Taxonomy($genome);
2378    
2379  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
2380  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>,
2381  or C<Eukaryote>) to sub-species. For example,  or C<Eukaryote>) to sub-species. For example,
2382    
2383  C<< (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12) >>      (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12)
2384    
2385  =over 4  =over 4
2386    
# Line 2193  Line 2415 
2415    
2416  =head3 CrudeDistance  =head3 CrudeDistance
2417    
2418  C<< my $distance = $sprout->CrudeDistance($genome1, $genome2); >>      my $distance = $sprout->CrudeDistance($genome1, $genome2);
2419    
2420  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
2421  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 2245  Line 2467 
2467    
2468  =head3 RoleName  =head3 RoleName
2469    
2470  C<< my $roleName = $sprout->RoleName($roleID); >>      my $roleName = $sprout->RoleName($roleID);
2471    
2472  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
2473  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 2279  Line 2501 
2501    
2502  =head3 RoleDiagrams  =head3 RoleDiagrams
2503    
2504  C<< my @diagrams = $sprout->RoleDiagrams($roleID); >>      my @diagrams = $sprout->RoleDiagrams($roleID);
2505    
2506  Return a list of the diagrams containing a specified functional role.  Return a list of the diagrams containing a specified functional role.
2507    
# Line 2309  Line 2531 
2531    
2532  =head3 GetProperties  =head3 GetProperties
2533    
2534  C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>      my @list = $sprout->GetProperties($fid, $key, $value, $url);
2535    
2536  Return a list of the properties with the specified characteristics.  Return a list of the properties with the specified characteristics.
2537    
2538  Properties are arbitrary key-value pairs associated with a feature. (At some point they  Properties are the Sprout analog of the FIG attributes. The call is
2539  will also be associated with genomes.) A property value is represented by a 4-tuple of  passed directly to the CustomAttributes or RemoteCustomAttributes object
2540  the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter  contained in this object.
2541    
2542  =over 4  This method returns a series of tuples that match the specified criteria. Each tuple
2543    will contain an object ID, a key, and one or more values. The parameters to this
2544    method therefore correspond structurally to the values expected in each tuple. In
2545    addition, you can ask for a generic search by suffixing a percent sign (C<%>) to any
2546    of the parameters. So, for example,
2547    
2548  =item fid      my @attributeList = $sprout->GetProperties('fig|100226.1.peg.1004', 'structure%', 1, 2);
2549    
2550  ID of the feature possessing the property.  would return something like
2551    
2552  =item key      ['fig}100226.1.peg.1004', 'structure', 1, 2]
2553        ['fig}100226.1.peg.1004', 'structure1', 1, 2]
2554        ['fig}100226.1.peg.1004', 'structure2', 1, 2]
2555        ['fig}100226.1.peg.1004', 'structureA', 1, 2]
2556    
2557  Name or key of the property.  Use of C<undef> in any position acts as a wild card (all values). You can also specify
2558    a list reference in the ID column. Thus,
2559    
2560  =item value      my @attributeList = $sprout->GetProperties(['100226.1', 'fig|100226.1.%'], 'PUBMED');
2561    
2562  Value of the property.  would get the PUBMED attribute data for Streptomyces coelicolor A3(2) and all its
2563    features.
2564    
2565  =item url  In addition to values in multiple sections, a single attribute key can have multiple
2566    values, so even
2567    
2568  URL of the document that indicated the property should have this particular value, or an      my @attributeList = $sprout->GetProperties($peg, 'virulent');
 empty string if no such document exists.  
2569    
2570  =back  which has no wildcard in the key or the object ID, may return multiple tuples.
2571    
2572    =over 4
2573    
2574    =item objectID
2575    
2576  The parameters act as a filter for the desired data. Any non-null parameter will  ID of object whose attributes are desired. If the attributes are desired for multiple
2577  automatically match all the tuples returned. So, specifying just the I<$fid> will  objects, this parameter can be specified as a list reference. If the attributes are
2578  return all the properties of the specified feature; similarly, specifying the I<$key>  desired for all objects, specify C<undef> or an empty string. Finally, you can specify
2579  and I<$value> parameters will return all the features having the specified property  attributes for a range of object IDs by putting a percent sign (C<%>) at the end.
 value.  
2580    
2581  A single property key can have many values, representing different ideas about the  =item key
2582  feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is  
2583  virulent, and another may declare that it is not virulent. A query about the virulence of  Attribute key name. A value of C<undef> or an empty string will match all
2584  C<fig|83333.1.peg.10> would be coded as  attribute keys. If the values are desired for multiple keys, this parameter can be
2585    specified as a list reference. Finally, you can specify attributes for a range of
2586    keys by putting a percent sign (C<%>) at the end.
2587    
2588    =item values
2589    
2590    List of the desired attribute values, section by section. If C<undef>
2591    or an empty string is specified, all values in that section will match. A
2592    generic match can be requested by placing a percent sign (C<%>) at the end.
2593    In that case, all values that match up to and not including the percent sign
2594    will match. You may also specify a regular expression enclosed
2595    in slashes. All values that match the regular expression will be returned. For
2596    performance reasons, only values have this extra capability.
2597    
2598      my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');  =item RETURN
2599    
2600  Here the I<$value> and I<$url> fields are left blank, indicating that those fields are  Returns a list of tuples. The first element in the tuple is an object ID, the
2601  not to be filtered. The tuples returned would be  second is an attribute key, and the remaining elements are the sections of
2602    the attribute value. All of the tuples will match the criteria set forth in
2603    the parameter list.
2604    
2605      ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')  =back
     ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')  
2606    
2607  =cut  =cut
2608  #: Return Type @@;  
2609  sub GetProperties {  sub GetProperties {
2610      # Get the parameters.      # Get the parameters.
2611      my ($self, @parms) = @_;      my ($self, @parms) = @_;
2612      # Declare the return variable.      # Declare the return variable.
2613      my @retVal = ();      my @retVal = $self->{_ca}->GetAttributes(@parms);
     # Now we need to create a WHERE clause that will get us the data we want. First,  
     # we create a list of the columns containing the data for each parameter.  
     my @colNames = ('HasProperty(from-link)', 'Property(property-name)',  
                     'Property(property-value)', 'HasProperty(evidence)');  
     # Now we build the WHERE clause and the list of parameter values.  
     my @where = ();  
     my @values = ();  
     for (my $i = 0; $i <= $#colNames; $i++) {  
         my $parm = $parms[$i];  
         if (defined $parm && ($parm ne '')) {  
             push @where, "$colNames[$i] = ?";  
             push @values, $parm;  
         }  
     }  
     # Format the WHERE clause.  
     my $filter = (@values > 0 ? (join " AND ", @where) : undef);  
     # Ask for all the propertie values with the desired characteristics.  
     my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);  
     while (my $valueObject = $query->Fetch()) {  
         my @tuple = $valueObject->Values(\@colNames);  
         push @retVal, \@tuple;  
     }  
2614      # Return the result.      # Return the result.
2615      return @retVal;      return @retVal;
2616  }  }
2617    
2618  =head3 FeatureProperties  =head3 FeatureProperties
2619    
2620  C<< my @properties = $sprout->FeatureProperties($featureID); >>      my @properties = $sprout->FeatureProperties($featureID);
2621    
2622  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
2623  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
2624  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
2625  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
2626  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.  
2627    
2628  =over 4  =over 4
2629    
# Line 2410  Line 2633 
2633    
2634  =item RETURN  =item RETURN
2635    
2636  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.  
2637    
2638  =back  =back
2639    
# Line 2421  Line 2643 
2643      # Get the parameters.      # Get the parameters.
2644      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2645      # Get the properties.      # Get the properties.
2646      my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],      my @attributes = $self->{_ca}->GetAttributes($featureID);
2647                              ['Property(property-name)', 'Property(property-value)',      # Strip the feature ID off each tuple.
2648                               'HasProperty(evidence)']);      my @retVal = ();
2649        for my $attributeRow (@attributes) {
2650            shift @{$attributeRow};
2651            push @retVal, $attributeRow;
2652        }
2653      # Return the resulting list.      # Return the resulting list.
2654      return @retVal;      return @retVal;
2655  }  }
2656    
2657  =head3 DiagramName  =head3 DiagramName
2658    
2659  C<< my $diagramName = $sprout->DiagramName($diagramID); >>      my $diagramName = $sprout->DiagramName($diagramID);
2660    
2661  Return the descriptive name of a diagram.  Return the descriptive name of a diagram.
2662    
# Line 2456  Line 2682 
2682      return $retVal;      return $retVal;
2683  }  }
2684    
2685    =head3 PropertyID
2686    
2687        my $id = $sprout->PropertyID($propName, $propValue);
2688    
2689    Return the ID of the specified property name and value pair, if the
2690    pair exists. Only a small subset of the FIG attributes are stored as
2691    Sprout properties, mostly for use in search optimization.
2692    
2693    =over 4
2694    
2695    =item propName
2696    
2697    Name of the desired property.
2698    
2699    =item propValue
2700    
2701    Value expected for the desired property.
2702    
2703    =item RETURN
2704    
2705    Returns the ID of the name/value pair, or C<undef> if the pair does not exist.
2706    
2707    =back
2708    
2709    =cut
2710    
2711    sub PropertyID {
2712        # Get the parameters.
2713        my ($self, $propName, $propValue) = @_;
2714        # Try to find the ID.
2715        my ($retVal) = $self->GetFlat(['Property'],
2716                                      "Property(property-name) = ? AND Property(property-value) = ?",
2717                                      [$propName, $propValue], 'Property(id)');
2718        # Return the result.
2719        return $retVal;
2720    }
2721    
2722  =head3 MergedAnnotations  =head3 MergedAnnotations
2723    
2724  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>      my @annotationList = $sprout->MergedAnnotations(\@list);
2725    
2726  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
2727  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 2507  Line 2770 
2770    
2771  =head3 RoleNeighbors  =head3 RoleNeighbors
2772    
2773  C<< my @roleList = $sprout->RoleNeighbors($roleID); >>      my @roleList = $sprout->RoleNeighbors($roleID);
2774    
2775  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
2776  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 2550  Line 2813 
2813    
2814  =head3 FeatureLinks  =head3 FeatureLinks
2815    
2816  C<< my @links = $sprout->FeatureLinks($featureID); >>      my @links = $sprout->FeatureLinks($featureID);
2817    
2818  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
2819  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 2581  Line 2844 
2844    
2845  =head3 SubsystemsOf  =head3 SubsystemsOf
2846    
2847  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>      my %subsystems = $sprout->SubsystemsOf($featureID);
2848    
2849  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
2850  to the roles the feature performs.  to the roles the feature performs.
# Line 2629  Line 2892 
2892    
2893  =head3 SubsystemList  =head3 SubsystemList
2894    
2895  C<< my @subsystems = $sprout->SubsystemList($featureID); >>      my @subsystems = $sprout->SubsystemList($featureID);
2896    
2897  Return a list containing the names of the subsystems in which the specified  Return a list containing the names of the subsystems in which the specified
2898  feature participates. Unlike L</SubsystemsOf>, this method only returns the  feature participates. Unlike L</SubsystemsOf>, this method only returns the
# Line 2653  Line 2916 
2916      # Get the parameters.      # Get the parameters.
2917      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2918      # Get the list of names.      # Get the list of names.
2919      my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",      my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?",
2920                                  [$featureID], 'HasSSCell(from-link)');                                  [$featureID], 'HasRoleInSubsystem(to-link)');
2921        # Return the result, sorted.
2922        return sort @retVal;
2923    }
2924    
2925    =head3 GenomeSubsystemData
2926    
2927        my %featureData = $sprout->GenomeSubsystemData($genomeID);
2928    
2929    Return a hash mapping genome features to their subsystem roles.
2930    
2931    =over 4
2932    
2933    =item genomeID
2934    
2935    ID of the genome whose subsystem feature map is desired.
2936    
2937    =item RETURN
2938    
2939    Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb
2940    2-tuple contains a subsystem name followed by a role ID.
2941    
2942    =back
2943    
2944    =cut
2945    
2946    sub GenomeSubsystemData {
2947        # Get the parameters.
2948        my ($self, $genomeID) = @_;
2949        # Declare the return variable.
2950        my %retVal = ();
2951        # Get a list of the genome features that participate in subsystems. For each
2952        # feature we get its spreadsheet cells and the corresponding roles.
2953        my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],
2954                                 "HasFeature(from-link) = ?", [$genomeID],
2955                                 ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);
2956        # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems
2957        # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the
2958        # list. We use it at the beginning to get all the spreadsheet cells for the genome and
2959        # again at the end to filter out participation in subsystems with a negative variant code.
2960        my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],
2961                                     "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?",
2962                                     [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']);
2963        # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features.
2964        # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We
2965        # link these two lists together to create the result. First, we want a hash mapping
2966        # spreadsheet cells to subsystem names.
2967        my %subHash = map { $_->[0] => $_->[1] } @cellData;
2968        # We loop through @cellData to build the hash.
2969        for my $roleEntry (@roleData) {
2970            # Get the data for this feature and cell.
2971            my ($fid, $cellID, $role) = @{$roleEntry};
2972            # Check for a subsystem name.
2973            my $subsys = $subHash{$cellID};
2974            if ($subsys) {
2975                # Insure this feature has an entry in the return hash.
2976                if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
2977                # Merge in this new data.
2978                push @{$retVal{$fid}}, [$subsys, $role];
2979            }
2980        }
2981      # Return the result.      # Return the result.
2982      return @retVal;      return %retVal;
2983  }  }
2984    
2985  =head3 RelatedFeatures  =head3 RelatedFeatures
2986    
2987  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>      my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID);
2988    
2989  Return a list of the features which are bi-directional best hits of the specified feature and  Return a list of the features which are bi-directional best hits of the specified feature and
2990  have been assigned the specified function by the specified user. If no such features exists,  have been assigned the specified function by the specified user. If no such features exists,
# Line 2694  Line 3017 
3017      # Get the parameters.      # Get the parameters.
3018      my ($self, $featureID, $function, $userID) = @_;      my ($self, $featureID, $function, $userID) = @_;
3019      # Get a list of the features that are BBHs of the incoming feature.      # Get a list of the features that are BBHs of the incoming feature.
3020      my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
                                      "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],  
                                      'IsBidirectionalBestHitOf(to-link)');  
3021      # Now we loop through the features, pulling out the ones that have the correct      # Now we loop through the features, pulling out the ones that have the correct
3022      # functional assignment.      # functional assignment.
3023      my @retVal = ();      my @retVal = ();
# Line 2714  Line 3035 
3035    
3036  =head3 TaxonomySort  =head3 TaxonomySort
3037    
3038  C<< my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs); >>      my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs);
3039    
3040  Return a list formed by sorting the specified features by the taxonomy of the containing  Return a list formed by sorting the specified features by the taxonomy of the containing
3041  genome. This will cause genomes from similar organisms to float close to each other.  genome. This will cause genomes from similar organisms to float close to each other.
# Line 2749  Line 3070 
3070          my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",          my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
3071                                          [$fid], 'Genome(taxonomy)');                                          [$fid], 'Genome(taxonomy)');
3072          # Add this feature to the hash buffer.          # Add this feature to the hash buffer.
3073          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);          push @{$hashBuffer{$taxonomy}}, $fid;
3074      }      }
3075      # Sort the keys and get the elements.      # Sort the keys and get the elements.
3076      my @retVal = ();      my @retVal = ();
# Line 2760  Line 3081 
3081      return @retVal;      return @retVal;
3082  }  }
3083    
 =head3 GetAll  
   
 C<< my @list = $sprout->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>  
   
 Return a list of values taken from the objects returned by a query. The first three  
 parameters correspond to the parameters of the L</Get> method. The final parameter is  
 a list of the fields desired from each record found by the query. The field name  
 syntax is the standard syntax used for fields in the B<ERDB> system--  
 B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity  
 or relationship and I<fieldName> is the name of the field.  
   
 The list returned will be a list of lists. Each element of the list will contain  
 the values returned for the fields specified in the fourth parameter. If one of the  
 fields specified returns multiple values, they are flattened in with the rest. For  
 example, the following call will return a list of the features in a particular  
 spreadsheet cell, and each feature will be represented by a list containing the  
 feature ID followed by all of its aliases.  
   
 C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item fields  
   
 List of the fields to be returned in each element of the list returned.  
   
 =item count  
   
 Maximum number of records to return. If omitted or 0, all available records will be returned.  
   
 =item RETURN  
   
 Returns a list of list references. Each element of the return list contains the values for the  
 fields specified in the B<fields> parameter.  
   
 =back  
   
 =cut  
 #: Return Type @@;  
 sub GetAll {  
     # Get the parameters.  
     my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;  
     # Call the ERDB method.  
     my @retVal = $self->{_erdb}->GetAll($objectNames, $filterClause, $parameterList,  
                                         $fields, $count);  
     # Return the resulting list.  
     return @retVal;  
 }  
   
 =head3 GetFlat  
   
 C<< my @list = $sprout->GetFlat(\@objectNames, $filterClause, $parameterList, $field); >>  
   
 This is a variation of L</GetAll> that asks for only a single field per record and  
 returns a single flattened list.  
   
 =over 4  
   
 =item objectNames  
   
 List containing the names of the entity and relationship objects to be retrieved.  
   
 =item filterClause  
   
 WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  
 be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  
 B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  
 parameter list as additional parameters. The fields in a filter clause can come from primary  
 entity relations, relationship relations, or secondary entity relations; however, all of the  
 entities and relationships involved must be included in the list of object names.  
   
 =item parameterList  
   
 List of the parameters to be substituted in for the parameters marks in the filter clause.  
   
 =item field  
   
 Name of the field to be used to get the elements of the list returned.  
   
 =item RETURN  
   
 Returns a list of values.  
   
 =back  
   
 =cut  
 #: Return Type @;  
 sub GetFlat {  
     # Get the parameters.  
     my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;  
     # Construct the query.  
     my $query = $self->Get($objectNames, $filterClause, $parameterList);  
     # Create the result list.  
     my @retVal = ();  
     # Loop through the records, adding the field values found to the result list.  
     while (my $row = $query->Fetch()) {  
         push @retVal, $row->Value($field);  
     }  
     # Return the list created.  
     return @retVal;  
 }  
   
3084  =head3 Protein  =head3 Protein
3085    
3086  C<< my $protein = Sprout::Protein($sequence, $table); >>      my $protein = Sprout::Protein($sequence, $table);
3087    
3088  Translate a DNA sequence into a protein sequence.  Translate a DNA sequence into a protein sequence.
3089    
# Line 2951  Line 3153 
3153      # Loop through the input triples.      # Loop through the input triples.
3154      my $n = length $sequence;      my $n = length $sequence;
3155      for (my $i = 0; $i < $n; $i += 3) {      for (my $i = 0; $i < $n; $i += 3) {
3156          # Get the current triple from the sequence.          # Get the current triple from the sequence. Note we convert to
3157          my $triple = substr($sequence, $i, 3);          # upper case to insure a match.
3158            my $triple = uc substr($sequence, $i, 3);
3159          # Translate it using the table.          # Translate it using the table.
3160          my $protein = "X";          my $protein = "X";
3161          if (exists $table->{$triple}) { $protein = $table->{$triple}; }          if (exists $table->{$triple}) { $protein = $table->{$triple}; }
# Line 2966  Line 3169 
3169    
3170  =head3 LoadInfo  =head3 LoadInfo
3171    
3172  C<< my ($dirName, @relNames) = $sprout->LoadInfo(); >>      my ($dirName, @relNames) = $sprout->LoadInfo();
3173    
3174  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
3175  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 2980  Line 3183 
3183      # 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.
3184      my @retVal = ($self->{_options}->{dataDir});      my @retVal = ($self->{_options}->{dataDir});
3185      # Concatenate the table names.      # Concatenate the table names.
3186      push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
3187      # Return the result.      # Return the result.
3188      return @retVal;      return @retVal;
3189  }  }
3190    
3191    =head3 BBHMatrix
3192    
3193        my %bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets);
3194    
3195    Find all the bidirectional best hits for the features of a genome in a
3196    specified list of target genomes. The return value will be a hash mapping
3197    features in the original genome to their bidirectional best hits in the
3198    target genomes.
3199    
3200    =over 4
3201    
3202    =item genomeID
3203    
3204    ID of the genome whose features are to be examined for bidirectional best hits.
3205    
3206    =item cutoff
3207    
3208    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3209    
3210    =item targets
3211    
3212    List of target genomes. Only pairs originating in the original
3213    genome and landing in one of the target genomes will be returned.
3214    
3215    =item RETURN
3216    
3217    Returns a hash mapping each feature in the original genome to a hash mapping its
3218    BBH pegs in the target genomes to their scores.
3219    
3220    =back
3221    
3222    =cut
3223    
3224    sub BBHMatrix {
3225        # Get the parameters.
3226        my ($self, $genomeID, $cutoff, @targets) = @_;
3227        # Declare the return variable.
3228        my %retVal = ();
3229        # Ask for the BBHs.
3230        my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets);
3231        # We now have a set of 4-tuples that we need to convert into a hash of hashes.
3232        for my $bbhData (@bbhList) {
3233            my ($peg1, $peg2, $score) = @{$bbhData};
3234            if (! exists $retVal{$peg1}) {
3235                $retVal{$peg1} = { $peg2 => $score };
3236            } else {
3237                $retVal{$peg1}->{$peg2} = $score;
3238            }
3239        }
3240        # Return the result.
3241        return %retVal;
3242    }
3243    
3244    
3245    =head3 SimMatrix
3246    
3247        my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets);
3248    
3249    Find all the similarities for the features of a genome in a
3250    specified list of target genomes. The return value will be a hash mapping
3251    features in the original genome to their similarites in the
3252    target genomes.
3253    
3254    =over 4
3255    
3256    =item genomeID
3257    
3258    ID of the genome whose features are to be examined for similarities.
3259    
3260    =item cutoff
3261    
3262    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3263    
3264    =item targets
3265    
3266    List of target genomes. Only pairs originating in the original
3267    genome and landing in one of the target genomes will be returned.
3268    
3269    =item RETURN
3270    
3271    Returns a hash mapping each feature in the original genome to a hash mapping its
3272    similar pegs in the target genomes to their scores.
3273    
3274    =back
3275    
3276    =cut
3277    
3278    sub SimMatrix {
3279        # Get the parameters.
3280        my ($self, $genomeID, $cutoff, @targets) = @_;
3281        # Declare the return variable.
3282        my %retVal = ();
3283        # Get the list of features in the source organism.
3284        my @fids = $self->FeaturesOf($genomeID);
3285        # Ask for the sims. We only want similarities to fig features.
3286        my $simList = FIGRules::GetNetworkSims($self, \@fids, {}, 1000, $cutoff, "fig");
3287        if (! defined $simList) {
3288            Confess("Unable to retrieve similarities from server.");
3289        } else {
3290            Trace("Processing sims.") if T(3);
3291            # We now have a set of sims that we need to convert into a hash of hashes. First, we
3292            # Create a hash for the target genomes.
3293            my %targetHash = map { $_ => 1 } @targets;
3294            for my $simData (@{$simList}) {
3295                # Get the PEGs and the score.
3296                my ($peg1, $peg2, $score) = ($simData->id1, $simData->id2, $simData->psc);
3297                # Insure the second ID is in the target list.
3298                my ($genome2) = FIGRules::ParseFeatureID($peg2);
3299                if (exists $targetHash{$genome2}) {
3300                    # Here it is. Now we need to add it to the return hash. How we do that depends
3301                    # on whether or not $peg1 is new to us.
3302                    if (! exists $retVal{$peg1}) {
3303                        $retVal{$peg1} = { $peg2 => $score };
3304                    } else {
3305                        $retVal{$peg1}->{$peg2} = $score;
3306                    }
3307                }
3308            }
3309        }
3310        # Return the result.
3311        return %retVal;
3312    }
3313    
3314    
3315  =head3 LowBBHs  =head3 LowBBHs
3316    
3317  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>      my %bbhMap = $sprout->LowBBHs($featureID, $cutoff);
3318    
3319  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
3320  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 3016  Line 3343 
3343      my ($self, $featureID, $cutoff) = @_;      my ($self, $featureID, $cutoff) = @_;
3344      # Create the return hash.      # Create the return hash.
3345      my %retVal = ();      my %retVal = ();
3346      # Create a query to get the desired BBHs.      # Query for the desired BBHs.
3347      my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BBHData($featureID, $cutoff);
                                 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',  
                                 [$cutoff, $featureID],  
                                 ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);  
3348      # Form the results into the return hash.      # Form the results into the return hash.
3349      for my $pair (@bbhList) {      for my $pair (@bbhList) {
3350          $retVal{$pair->[0]} = $pair->[1];          my $fid = $pair->[0];
3351            if ($self->Exists('Feature', $fid)) {
3352                $retVal{$fid} = $pair->[1];
3353            }
3354      }      }
3355      # Return the result.      # Return the result.
3356      return %retVal;      return %retVal;
3357  }  }
3358    
3359    =head3 Sims
3360    
3361        my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters);
3362    
3363    Get a list of similarities for a specified feature. Similarity information is not kept in the
3364    Sprout database; rather, they are retrieved from a network server. The similarities are
3365    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3366    so that its elements can be accessed by name.
3367    
3368    Similarities can be either raw or expanded. The raw similarities are basic
3369    hits between features with similar DNA. Expanding a raw similarity drags in any
3370    features considered substantially identical. So, for example, if features B<A1>,
3371    B<A2>, and B<A3> are all substantially identical to B<A>, then a raw similarity
3372    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3373    
3374    =over 4
3375    
3376    =item fid
3377    
3378    ID of the feature whose similarities are desired, or reference to a list of IDs
3379    of features whose similarities are desired.
3380    
3381    =item maxN
3382    
3383    Maximum number of similarities to return.
3384    
3385    =item maxP
3386    
3387    Minumum allowable similarity score.
3388    
3389    =item select
3390    
3391    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3392    means only similarities to FIG features are returned; C<all> means all expanded
3393    similarities are returned; and C<figx> means similarities are expanded until the
3394    number of FIG features equals the maximum.
3395    
3396    =item max_expand
3397    
3398    The maximum number of features to expand.
3399    
3400    =item filters
3401    
3402    Reference to a hash containing filter information, or a subroutine that can be
3403    used to filter the sims.
3404    
3405    =item RETURN
3406    
3407    Returns a reference to a list of similarity objects, or C<undef> if an error
3408    occurred.
3409    
3410    =back
3411    
3412    =cut
3413    
3414    sub Sims {
3415        # Get the parameters.
3416        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3417        # Create the shim object to test for deleted FIDs.
3418        my $shim = FidCheck->new($self);
3419        # Ask the network for sims.
3420        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3421        # Return the result.
3422        return $retVal;
3423    }
3424    
3425    =head3 IsAllGenomes
3426    
3427        my $flag = $sprout->IsAllGenomes(\@list, \@checkList);
3428    
3429    Return TRUE if all genomes in the second list are represented in the first list at
3430    least one. Otherwise, return FALSE. If the second list is omitted, the first list is
3431    compared to a list of all the genomes.
3432    
3433    =over 4
3434    
3435    =item list
3436    
3437    Reference to the list to be compared to the second list.
3438    
3439    =item checkList (optional)
3440    
3441    Reference to the comparison target list. Every genome ID in this list must occur at
3442    least once in the first list. If this parameter is omitted, a list of all the genomes
3443    is used.
3444    
3445    =item RETURN
3446    
3447    Returns TRUE if every item in the second list appears at least once in the
3448    first list, else FALSE.
3449    
3450    =back
3451    
3452    =cut
3453    
3454    sub IsAllGenomes {
3455        # Get the parameters.
3456        my ($self, $list, $checkList) = @_;
3457        # Supply the checklist if it was omitted.
3458        $checkList = [$self->Genomes()] if ! defined($checkList);
3459        # Create a hash of the original list.
3460        my %testList = map { $_ => 1 } @{$list};
3461        # Declare the return variable. We assume that the representation
3462        # is complete and stop at the first failure.
3463        my $retVal = 1;
3464        my $n = scalar @{$checkList};
3465        for (my $i = 0; $retVal && $i < $n; $i++) {
3466            if (! $testList{$checkList->[$i]}) {
3467                $retVal = 0;
3468            }
3469        }
3470        # Return the result.
3471        return $retVal;
3472    }
3473    
3474  =head3 GetGroups  =head3 GetGroups
3475    
3476  C<< my %groups = $sprout->GetGroups(\@groupList); >>      my %groups = $sprout->GetGroups(\@groupList);
3477    
3478  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.
3479  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 3050  Line 3492 
3492          # Here we have a group list. Loop through them individually,          # Here we have a group list. Loop through them individually,
3493          # getting a list of the relevant genomes.          # getting a list of the relevant genomes.
3494          for my $group (@{$groupList}) {          for my $group (@{$groupList}) {
3495              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3496                  [$group], "Genome(id)");                  [$group], "Genome(id)");
3497              $retVal{$group} = \@genomeIDs;              $retVal{$group} = \@genomeIDs;
3498          }          }
# Line 3058  Line 3500 
3500          # 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
3501          # of the genome records, putting each one found into the appropriate          # of the genome records, putting each one found into the appropriate
3502          # 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
3503          # in groups are included in the return set.          # in real NMPDR groups are included in the return set.
3504          my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],          my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3505                                      ['Genome(id)', 'Genome(group-name)']);                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3506          # Loop through the genomes found.          # Loop through the genomes found.
3507          for my $genome (@genomes) {          for my $genome (@genomes) {
3508              # Pop this genome's ID off the current list.              # Get the genome ID and group, and add this genome to the group's list.
3509              my @groups = @{$genome};              my ($genomeID, $group) = @{$genome};
3510              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);  
             }  
3511          }          }
3512      }      }
3513      # Return the hash we just built.      # Return the hash we just built.
# Line 3079  Line 3516 
3516    
3517  =head3 MyGenomes  =head3 MyGenomes
3518    
3519  C<< my @genomes = Sprout::MyGenomes($dataDir); >>      my @genomes = Sprout::MyGenomes($dataDir);
3520    
3521  Return a list of the genomes to be included in the Sprout.  Return a list of the genomes to be included in the Sprout.
3522    
# Line 3111  Line 3548 
3548    
3549  =head3 LoadFileName  =head3 LoadFileName
3550    
3551  C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>      my $fileName = Sprout::LoadFileName($dataDir, $tableName);
3552    
3553  Return the name of the load file for the specified table in the specified data  Return the name of the load file for the specified table in the specified data
3554  directory.  directory.
# Line 3150  Line 3587 
3587      return $retVal;      return $retVal;
3588  }  }
3589    
3590    =head3 DeleteGenome
3591    
3592        my $stats = $sprout->DeleteGenome($genomeID, $testFlag);
3593    
3594    Delete a genome from the database.
3595    
3596    =over 4
3597    
3598    =item genomeID
3599    
3600    ID of the genome to delete
3601    
3602    =item testFlag
3603    
3604    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3605    
3606    =item RETURN
3607    
3608    Returns a statistics object describing the rows deleted.
3609    
3610    =back
3611    
3612    =cut
3613    #: Return Type $%;
3614    sub DeleteGenome {
3615        # Get the parameters.
3616        my ($self, $genomeID, $testFlag) = @_;
3617        # Perform the delete for the genome's features.
3618        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", testMode => $testFlag);
3619        # Perform the delete for the primary genome data.
3620        my $stats = $self->Delete('Genome', $genomeID, testMode => $testFlag);
3621        $retVal->Accumulate($stats);
3622        # Return the result.
3623        return $retVal;
3624    }
3625    
3626    =head3 Fix
3627    
3628        my %fixedHash = $sprout->Fix(%groupHash);
3629    
3630    Prepare a genome group hash (like that returned by L</GetGroups>) for processing.
3631    The groups will be combined into the appropriate super-groups.
3632    
3633    =over 4
3634    
3635    =item groupHash
3636    
3637    Hash to be fixed up.
3638    
3639    =item RETURN
3640    
3641    Returns a fixed-up version of the hash.
3642    
3643    =back
3644    
3645    =cut
3646    
3647    sub Fix {
3648        # Get the parameters.
3649        my ($self, %groupHash) = @_;
3650        # Create the result hash.
3651        my %retVal = ();
3652        # Get the super-group table.
3653        my %superTable = $self->CheckGroupFile();
3654        # Copy over the genomes.
3655        for my $groupID (keys %groupHash) {
3656            # Get the super-group name.
3657            my $realGroupID;
3658            if ($groupID =~ /([A-Z]\w+)/) {
3659                if (! defined($superTable{$1})) {
3660                    Confess("Super-group name not found for group $groupID.");
3661                } else {
3662                    $realGroupID = $1;
3663                }
3664            } else {
3665                Confess("Invalid group name $groupID.");
3666            }
3667            # Append this group's genomes into the result hash.
3668            push @{$retVal{$realGroupID}}, @{$groupHash{$groupID}};
3669        }
3670        # Return the result hash.
3671        return %retVal;
3672    }
3673    
3674    =head3 GroupPageName
3675    
3676        my $name = $sprout->GroupPageName($group);
3677    
3678    Return the name of the page for the specified NMPDR group.
3679    
3680    =over 4
3681    
3682    =item group
3683    
3684    Name of the relevant group.
3685    
3686    =item RETURN
3687    
3688    Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3689    memory it will be read in.
3690    
3691    =back
3692    
3693    =cut
3694    
3695    sub GroupPageName {
3696        # Get the parameters.
3697        my ($self, $group) = @_;
3698        # Declare the return variable.
3699        my $retVal;
3700        # Check for the group file data.
3701        my %superTable = $self->CheckGroupFile();
3702        # Compute the real group name.
3703        if ($group =~ /([A-Z]\w+)/) {
3704            my $realGroup = $1;
3705            if (! defined($superTable{$1})) {
3706                Confess("No super-group found for \"$group\".");
3707            } else {
3708                $retVal = "../content/$superTable{$1}->{page}";
3709            }
3710        } else {
3711            Confess("\"group\" is not a valid group name.");
3712        }
3713        # Return the result.
3714        return $retVal;
3715    }
3716    
3717    
3718    =head3 AddProperty
3719    
3720        $sprout->AddProperty($featureID, $key, @values);
3721    
3722    Add a new attribute value (Property) to a feature.
3723    
3724    =over 4
3725    
3726    =item peg
3727    
3728    ID of the feature to which the attribute is to be added.
3729    
3730    =item key
3731    
3732    Name of the attribute (key).
3733    
3734    =item values
3735    
3736    Values of the attribute.
3737    
3738    =back
3739    
3740    =cut
3741    #: Return Type ;
3742    sub AddProperty {
3743        # Get the parameters.
3744        my ($self, $featureID, $key, @values) = @_;
3745        # Add the property using the attached attributes object.
3746        $self->{_ca}->AddAttribute($featureID, $key, @values);
3747    }
3748    
3749    =head3 CheckGroupFile
3750    
3751        my %groupData = $sprout->CheckGroupFile();
3752    
3753    Get the group file hash. The group file hash describes the relationship
3754    between a group and the super-group to which it belongs for purposes of
3755    display. The super-group name is computed from the first capitalized word
3756    in the actual group name. For each super-group, the group file contains
3757    the page name and a list of the species expected to be in the group.
3758    Each species is specified by a genus and a species name. A species name
3759    of C<0> implies an entire genus.
3760    
3761    This method returns a hash from super-group names to a hash reference. Each
3762    resulting hash reference contains the following fields.
3763    
3764    =over 4
3765    
3766    =item page
3767    
3768    The super-group's web page in the NMPDR.
3769    
3770    =item contents
3771    
3772    A list of 2-tuples, each containing a genus name followed by a species name
3773    (or 0, indicating all species). This list indicates which organisms belong
3774    in the super-group.
3775    
3776    =back
3777    
3778    =cut
3779    
3780    sub CheckGroupFile{
3781        # Get the parameters.
3782        my ($self) = @_;
3783        # Check to see if we already have this hash.
3784        if (! defined $self->{groupHash}) {
3785            # We don't, so we need to read it in.
3786            my %groupHash;
3787            # Read the group file.
3788            my @groupLines = Tracer::GetFile("$FIG_Config::sproutData/groups.tbl");
3789            # Loop through the list of sort-of groups.
3790            for my $groupLine (@groupLines) {
3791                my ($name, $page, @contents) = split /\t/, $groupLine;
3792                $groupHash{$name} = { page => $page,
3793                                      contents => [ map { [ split /\s*,\s*/, $_ ] } @contents ]
3794                                    };
3795            }
3796            # Save the hash.
3797            $self->{groupHash} = \%groupHash;
3798        }
3799        # Return the result.
3800        return %{$self->{groupHash}};
3801    }
3802    
3803    =head2 Virtual Methods
3804    
3805    =head3 CleanKeywords
3806    
3807        my $cleanedString = $sprout->CleanKeywords($searchExpression);
3808    
3809    Clean up a search expression or keyword list. This involves converting the periods
3810    in EC numbers to underscores, converting non-leading minus signs to underscores,
3811    a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
3812    characters. In addition, any extra spaces are removed.
3813    
3814    =over 4
3815    
3816    =item searchExpression
3817    
3818    Search expression or keyword list to clean. Note that a search expression may
3819    contain boolean operators which need to be preserved. This includes leading
3820    minus signs.
3821    
3822    =item RETURN
3823    
3824    Cleaned expression or keyword list.
3825    
3826    =back
3827    
3828    =cut
3829    
3830    sub CleanKeywords {
3831        # Get the parameters.
3832        my ($self, $searchExpression) = @_;
3833        # Perform the standard cleanup.
3834        my $retVal = $self->ERDB::CleanKeywords($searchExpression);
3835        # Fix the periods in EC and TC numbers.
3836        $retVal =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g;
3837        # Fix non-trailing periods.
3838        $retVal =~ s/\.(\w)/_$1/g;
3839        # Fix non-leading minus signs.
3840        $retVal =~ s/(\w)[\-]/$1_/g;
3841        # Fix the vertical bars and colons
3842        $retVal =~ s/(\w)[|:](\w)/$1'$2/g;
3843        # Return the result.
3844        return $retVal;
3845    }
3846    
3847  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3848    
3849  =head3 ParseAssignment  =head3 ParseAssignment
# Line 3160  Line 3854 
3854    
3855  A functional assignment is always of the form  A functional assignment is always of the form
3856    
3857      I<XXXX>C<\nset >I<YYYY>C< function to\n>I<ZZZZZ>      set YYYY function to
3858        ZZZZ
3859    
3860    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3861    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3862    not always the case.
3863    
3864  where I<XXXX> is the B<assigning user>, I<YYYY> is the B<user>, and I<ZZZZ> is the  In addition, the functional role may contain extra data that is stripped, such as
3865  actual functional role. In most cases, the user and the assigning user will be the  terminating spaces or a comment separated from the rest of the text by a tab.
 same, but that is not always the case.  
3866    
3867  This is a static method.  This is a static method.
3868    
3869  =over 4  =over 4
3870    
3871    =item user
3872    
3873    Name of the assigning user.
3874    
3875  =item text  =item text
3876    
3877  Text of the annotation.  Text of the annotation.
# Line 3185  Line 3887 
3887    
3888  sub _ParseAssignment {  sub _ParseAssignment {
3889      # Get the parameters.      # Get the parameters.
3890      my ($text) = @_;      my ($user, $text) = @_;
3891      # Declare the return value.      # Declare the return value.
3892      my @retVal = ();      my @retVal = ();
3893      # Check to see if this is a functional assignment.      # Check to see if this is a functional assignment.
3894      my ($type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3895      if ($type =~ m/^set ([^ ]+) function to$/i) {      if ($type =~ m/^set function to$/i) {
3896          # Here it is, so we return the user name (which is in $1), the functional role text,          # Here we have an assignment without a user, so we use the incoming user ID.
3897          # and the assigning user.          @retVal = ($user, $function);
3898        } elsif ($type =~ m/^set (\S+) function to$/i) {
3899            # Here we have an assignment with a user that is passed back to the caller.
3900          @retVal = ($1, $function);          @retVal = ($1, $function);
3901      }      }
3902        # If we have an assignment, we need to clean the function text. There may be
3903        # extra junk at the end added as a note from the user.
3904        if (defined( $retVal[1] )) {
3905            $retVal[1] =~ s/(\t\S)?\s*$//;
3906        }
3907      # Return the result list.      # Return the result list.
3908      return @retVal;      return @retVal;
3909  }  }
3910    
3911  =head3 FriendlyTimestamp  =head3 _CheckFeature
3912    
3913  Convert a time number to a user-friendly time stamp for display.      my $flag = $sprout->_CheckFeature($fid);
3914    
3915  This is a static method.  Return TRUE if the specified FID is probably an NMPDR feature ID, else FALSE.
3916    
3917  =over 4  =over 4
3918    
3919  =item timeValue  =item fid
3920    
3921  Numeric time value.  Feature ID to check.
3922    
3923  =item RETURN  =item RETURN
3924    
3925  Returns a string containing the same time in user-readable format.  Returns TRUE if the FID is for one of the NMPDR genomes, else FALSE.
3926    
3927  =back  =back
3928    
3929  =cut  =cut
3930    
3931  sub FriendlyTimestamp {  sub _CheckFeature {
3932      my ($timeValue) = @_;      # Get the parameters.
3933      my $retVal = localtime($timeValue);      my ($self, $fid) = @_;
3934      return $retVal;      # Insure we have a genome hash.
3935        if (! defined $self->{genomeHash}) {
3936            my %genomeHash = map { $_ => 1 } $self->GetFlat(['Genome'], "", [], 'Genome(id)');
3937            $self->{genomeHash} = \%genomeHash;
3938        }
3939        # Get the feature's genome ID.
3940        my ($genomeID) = FIGRules::ParseFeatureID($fid);
3941        # Return an indicator of whether or not the genome ID is in the hash.
3942        return ($self->{genomeHash}->{$genomeID} ? 1 : 0);
3943  }  }
3944    
3945  =head3 AddProperty  =head3 FriendlyTimestamp
3946    
3947  C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>  Convert a time number to a user-friendly time stamp for display.
3948    
3949  Add a new attribute value (Property) to a feature. In the SEED system, attributes can  This is a static method.
 be added to almost any object. In Sprout, they can only be added to features. In  
 Sprout, attributes are implemented using I<properties>. A property represents a key/value  
 pair. If the particular key/value pair coming in is not already in the database, a new  
 B<Property> record is created to hold it.  
3950    
3951  =over 4  =over 4
3952    
3953  =item peg  =item timeValue
   
 ID of the feature to which the attribute is to be replied.  
   
 =item key  
   
 Name of the attribute (key).  
   
 =item value  
3954    
3955  Value of the attribute.  Numeric time value.
3956    
3957  =item url  =item RETURN
3958    
3959  URL or text citation from which the property was obtained.  Returns a string containing the same time in user-readable format.
3960    
3961  =back  =back
3962    
3963  =cut  =cut
 #: Return Type ;  
 sub AddProperty {  
     # Get the parameters.  
     my ($self, $featureID, $key, $value, $url) = @_;  
     # Declare the variable to hold the desired property ID.  
     my $propID;  
     # Attempt to find a property record for this key/value pair.  
     my @properties = $self->GetFlat(['Property'],  
                                    "Property(property-name) = ? AND Property(property-value) = ?",  
                                    [$key, $value], 'Property(id)');  
     if (@properties) {  
         # Here the property is already in the database. We save its ID.  
         $propID = $properties[0];  
         # Here the property value does not exist. We need to generate an ID. It will be set  
         # to a number one greater than the maximum value in the database. This call to  
         # GetAll will stop after one record.  
         my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],  
                                         1);  
         $propID = $maxProperty[0]->[0] + 1;  
         # Insert the new property value.  
         $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });  
     }  
     # Now we connect the incoming feature to the property.  
     $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });  
 }  
3964    
3965    sub FriendlyTimestamp {
3966        my ($timeValue) = @_;
3967        my $retVal = localtime($timeValue);
3968        return $retVal;
3969    }
3970    
3971    
3972  1;  1;

Legend:
Removed from v.1.44  
changed lines
  Added in v.1.107

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3