[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.94, Fri Nov 3 00:42:25 2006 UTC revision 1.124, Wed Mar 4 00:09:43 2009 UTC
# Line 1  Line 1 
1  package Sprout;  package Sprout;
2    
     require Exporter;  
     use ERDB;  
     @ISA = qw(Exporter ERDB);  
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 ERDBQuery;
8      use DBObject;      use ERDBObject;
9      use Tracer;      use Tracer;
10      use FIGRules;      use FIGRules;
11      use FidCheck;      use FidCheck;
12      use Stats;      use Stats;
13      use POSIX qw(strftime);      use POSIX qw(strftime);
14      use BasicLocation;      use BasicLocation;
15        use CustomAttributes;
16        use RemoteCustomAttributes;
17        use CGI qw(-nosticky);
18        use WikiTools;
19        use BioWords;
20        use base qw(ERDB);
21    
22  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
23    
# Line 28  Line 30 
30  on the constructor. For example, the following invocation specifies a PostgreSQL database named I<GenDB>  on the constructor. For example, the following invocation specifies a PostgreSQL database named I<GenDB>
31  whose definition and data files are in a co-directory named F<Data>.  whose definition and data files are in a co-directory named F<Data>.
32    
33  C<< my $sprout = Sprout->new('GenDB', { dbType => 'pg', dataDir => '../Data', xmlFileName => '../Data/SproutDBD.xml' }); >>      my $sprout = Sprout->new('GenDB', { dbType => 'pg', dataDir => '../Data', xmlFileName => '../Data/SproutDBD.xml' });
34    
35  Once you have a sprout object, you may use it to re-create the database, load the tables from  Once you have a sprout object, you may use it to re-create the database, load the tables from
36  tab-delimited flat files and perform queries. Several special methods are provided for common  tab-delimited flat files and perform queries. Several special methods are provided for common
37  query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and  query tasks. For example, L</Genomes> lists the IDs of all the genomes in the database and
38  L</dna_seq> returns the DNA sequence for a specified genome location.  L</DNASeq> returns the DNA sequence for a specified genome location.
39    
40  The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.  The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.
41    
42  =cut  =cut
43    
 #: Constructor SFXlate->new_sprout_only();  
   
44  =head2 Public Methods  =head2 Public Methods
45    
46  =head3 new  =head3 new
47    
48  C<< my $sprout = Sprout->new($dbName, \%options); >>      my $sprout = Sprout->new($dbName, \%options);
49    
50  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
51  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 55  Line 55 
55    
56  =item dbName  =item dbName
57    
58  Name of the database.  Name of the database. If omitted, the default Sprout database name is used.
59    
60  =item options  =item options
61    
# Line 79  Line 79 
79    
80  * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE  * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
81    
82    * B<host> name of the database host
83    
84  =back  =back
85    
86  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
87  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
88  F</usr/fig/SproutData>.  F</usr/fig/SproutData>.
89    
90  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' });
91    
92    In order to work properly with [[ERDBGeneratorPl]], the constructor has an alternate
93    form.
94    
95        my $sprout = Sprout->new(dbd => $filename);
96    
97    Where I<$fileName> is the name of the DBD file. This enables us to specify an alternate
98    DBD for the loader, which is important when the database format changes.
99    
100  =cut  =cut
101    
102  sub new {  sub new {
103      # Get the parameters.      # Get the parameters.
104      my ($class, $dbName, $options) = @_;      my ($class, $dbName, $options) = @_;
105        # Check for the alternate signature, and default the database name if it is missing.
106        if ($dbName eq 'dbd') {
107            $dbName = $FIG_Config::sproutDB;
108            $options = { xmlFileName => $options };
109        } elsif (! defined $dbName) {
110            $dbName = $FIG_Config::sproutDB;
111        } elsif (ref $dbName eq 'HASH') {
112            $options = $dbName;
113            $dbName = $FIG_Config::sproutDB;
114        }
115      # Compute the DBD directory.      # Compute the DBD directory.
116      my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :      my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
117                                                    $FIG_Config::fig );                                                    $FIG_Config::fig );
# Line 104  Line 124 
124                                                          # data file directory                                                          # data file directory
125                         xmlFileName  => "$dbd_dir/SproutDBD.xml",                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
126                                                          # database definition file name                                                          # database definition file name
127                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",                         userData     => "$FIG_Config::sproutUser/$FIG_Config::sproutPass",
128                                                          # user name and password                                                          # user name and password
129                         port         => $FIG_Config::dbport,                         port         => $FIG_Config::sproutPort,
130                                                          # database connection port                                                          # database connection port
131                         sock         => $FIG_Config::dbsock,                         sock         => $FIG_Config::sproutSock,
132                         host         => $FIG_Config::dbhost,                         host         => $FIG_Config::sprout_host,
133                         maxSegmentLength => 4500,        # maximum feature segment length                         maxSegmentLength => 4500,        # maximum feature segment length
134                         maxSequenceLength => 8000,       # maximum contig sequence length                         maxSequenceLength => 8000,       # maximum contig sequence length
135                         noDBOpen     => 0,               # 1 to suppress the database open                         noDBOpen     => 0,               # 1 to suppress the database open
136                           demandDriven => 0,               # 1 for forward-only queries
137                        }, $options);                        }, $options);
138      # Get the data directory.      # Get the data directory.
139      my $dataDir = $optionTable->{dataDir};      my $dataDir = $optionTable->{dataDir};
# Line 122  Line 143 
143      # Connect to the database.      # Connect to the database.
144      my $dbh;      my $dbh;
145      if (! $optionTable->{noDBOpen}) {      if (! $optionTable->{noDBOpen}) {
146            Trace("Connect data: host = $optionTable->{host}, port = $optionTable->{port}.") if T(3);
147          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
148                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
149      }      }
150      # Create the ERDB object.      # Create the ERDB object.
151      my $xmlFileName = "$optionTable->{xmlFileName}";      my $xmlFileName = "$optionTable->{xmlFileName}";
152      my $retVal = ERDB::new($class, $dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName, %$optionTable);
153      # Add the option table and XML file name.      # Add the option table and XML file name.
154      $retVal->{_options} = $optionTable;      $retVal->{_options} = $optionTable;
155      $retVal->{_xmlName} = $xmlFileName;      $retVal->{_xmlName} = $xmlFileName;
156      # Set up space for the group file data.      # Set up space for the group file data.
157      $retVal->{groupHash} = undef;      $retVal->{groupHash} = undef;
158        # Set up space for the genome hash. We use this to identify NMPDR genomes
159        # and remember genome data.
160        $retVal->{genomeHash} = {};
161        $retVal->{genomeHashFilled} = 0;
162        # Remember the data directory name.
163        $retVal->{dataDir} = $dataDir;
164      # Return it.      # Return it.
165      return $retVal;      return $retVal;
166  }  }
167    
168    =head3 ca
169    
170        my $ca = $sprout->ca():;
171    
172    Return the [[CustomAttributesPm]] object for retrieving object
173    properties.
174    
175    =cut
176    
177    sub ca {
178        # Get the parameters.
179        my ($self) = @_;
180        # Do we already have an attribute object?
181        my $retVal = $self->{_ca};
182        if (! defined $retVal) {
183            # No, create one. How we do it depends on the configuration.
184            if ($FIG_Config::attrURL) {
185                Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);
186                $retVal = RemoteCustomAttributes->new($FIG_Config::attrURL);
187            } elsif ($FIG_Config::attrDbName) {
188                Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);
189                my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));
190                $retVal = CustomAttributes->new(user => $user);
191            }
192            # Save it for next time.
193            $self->{_ca} = $retVal;
194        }
195        # Return the result.
196        return $retVal;
197    }
198    
199    =head3 CoreGenomes
200    
201        my @genomes = $sprout->CoreGenomes($scope);
202    
203    Return the IDs of NMPDR genomes in the specified scope.
204    
205    =over 4
206    
207    =item scope
208    
209    Scope of the desired genomes. C<core> covers the original core genomes,
210    C<nmpdr> covers all genomes in NMPDR groups, and C<all> covers all
211    genomes in the system.
212    
213    =item RETURN
214    
215    Returns a list of the IDs for the genomes in the specified scope.
216    
217    =back
218    
219    =cut
220    
221    sub CoreGenomes {
222        # Get the parameters.
223        my ($self, $scope) = @_;
224        # Declare the return variable.
225        my @retVal = ();
226        # If we want all genomes, then this is easy.
227        if ($scope eq 'all') {
228            @retVal = $self->Genomes();
229        } else {
230            # Here we're dealing with groups. Get the hash of all the
231            # genome groups.
232            my %groups = $self->GetGroups();
233            # Loop through the groups, keeping the ones that we want.
234            for my $group (keys %groups) {
235                # Decide if we want to keep this group.
236                my $keepGroup = 0;
237                if ($scope eq 'nmpdr') {
238                    # NMPDR mode: keep all groups.
239                    $keepGroup = 1;
240                } elsif ($scope eq 'core') {
241                    # CORE mode. Only keep real core groups.
242                    if (grep { $group =~ /$_/ } @{$FIG_Config::realCoreGroups}) {
243                        $keepGroup = 1;
244                    }
245                }
246                # Add this group if we're keeping it.
247                if ($keepGroup) {
248                    push @retVal, @{$groups{$group}};
249                }
250            }
251        }
252        # Return the result.
253        return @retVal;
254    }
255    
256    =head3 SuperGroup
257    
258        my $superGroup = $sprout->SuperGroup($groupName);
259    
260    Return the name of the super-group containing the specified NMPDR genome
261    group. If no appropriate super-group can be found, an error will be
262    thrown.
263    
264    =over 4
265    
266    =item groupName
267    
268    Name of the group whose super-group is desired.
269    
270    =item RETURN
271    
272    Returns the name of the super-group containing the incoming group.
273    
274    =back
275    
276    =cut
277    
278    sub SuperGroup {
279        # Get the parameters.
280        my ($self, $groupName) = @_;
281        # Declare the return variable.
282        my $retVal;
283        # Get the group hash.
284        my %groupHash = $self->CheckGroupFile();
285        # Find the super-group genus.
286        $groupName =~ /([A-Z]\w+)/;
287        my $nameThing = $1;
288        # See if it's directly in the group hash.
289        if (exists $groupHash{$nameThing}) {
290            # Yes, then it's our result.
291            $retVal = $nameThing;
292        } else {
293            # No, so we have to search.
294            for my $superGroup (keys %groupHash) {
295                # Get this super-group's item list.
296                my $list = $groupHash{$superGroup}->{contents};
297                # Search it.
298                if (grep { $_->[0] eq $nameThing } @{$list}) {
299                    $retVal = $superGroup;
300                }
301            }
302            # Make sure we found something.
303            if (! $retVal) {
304                Confess("No super-group found for \"$groupName\".");
305            }
306        }
307        # Return the result.
308        return $retVal;
309    }
310    
311  =head3 MaxSegment  =head3 MaxSegment
312    
313  C<< my $length = $sprout->MaxSegment(); >>      my $length = $sprout->MaxSegment();
314    
315  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
316  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 156  Line 327 
327    
328  =head3 MaxSequence  =head3 MaxSequence
329    
330  C<< my $length = $sprout->MaxSequence(); >>      my $length = $sprout->MaxSequence();
331    
332  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
333  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 171  Line 342 
342    
343  =head3 Load  =head3 Load
344    
345  C<< $sprout->Load($rebuild); >>;      $sprout->Load($rebuild);;
346    
347  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.
348    
# Line 183  Line 354 
354  The files are loaded based on the presumption that each line of the file is a record in the  The files are loaded based on the presumption that each line of the file is a record in the
355  relation, and the individual fields are delimited by tabs. Tab and new-line characters inside  relation, and the individual fields are delimited by tabs. Tab and new-line characters inside
356  fields must be represented by the escape sequences C<\t> and C<\n>, respectively. The fields must  fields must be represented by the escape sequences C<\t> and C<\n>, respectively. The fields must
357  be presented in the order given in the relation tables produced by the L</ShowMetaData> method.  be presented in the order given in the relation tables produced by the database documentation.
358    
359  =over 4  =over 4
360    
# Line 211  Line 382 
382    
383  =head3 LoadUpdate  =head3 LoadUpdate
384    
385  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>      my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList);
386    
387  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
388  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 257  Line 428 
428              Trace("No load file found for $tableName in $dataDir.") if T(0);              Trace("No load file found for $tableName in $dataDir.") if T(0);
429          } else {          } else {
430              # Attempt to load this table.              # Attempt to load this table.
431              my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);              my $result = $self->LoadTable($fileName, $tableName, truncate => $truncateFlag);
432              # Accumulate the resulting statistics.              # Accumulate the resulting statistics.
433              $retVal->Accumulate($result);              $retVal->Accumulate($result);
434          }          }
# Line 268  Line 439 
439    
440  =head3 GenomeCounts  =head3 GenomeCounts
441    
442  C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>      my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete);
443    
444  Count the number of genomes in each domain. If I<$complete> is TRUE, only complete  Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
445  genomes will be included in the counts.  genomes will be included in the counts.
# Line 313  Line 484 
484    
485  =head3 ContigCount  =head3 ContigCount
486    
487  C<< my $count = $sprout->ContigCount($genomeID); >>      my $count = $sprout->ContigCount($genomeID);
488    
489  Return the number of contigs for the specified genome ID.  Return the number of contigs for the specified genome ID.
490    
# Line 340  Line 511 
511      return $retVal;      return $retVal;
512  }  }
513    
514  =head3 GeneMenu  =head3 GenomeMenu
515    
516  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected); >>      my $html = $sprout->GenomeMenu(%options);
517    
518  Return an HTML select menu of genomes. Each genome will be an option in the menu,  Generate a genome selection control with the specified name and options.
519  and will be displayed by name with the ID and a contig count attached. The selection  This control is almost but not quite the same as the genome control in the
520  value will be the genome ID. The genomes will be sorted by genus/species name.  B<SearchHelper> class. Eventually, the two will be combined.
521    
522  =over 4  =over 4
523    
524  =item attributes  =item options
525    
526    Optional parameters for the control (see below).
527    
528    =item RETURN
529    
530    Returns the HTML for a genome selection control on a form (sometimes called a popup menu).
531    
532  Reference to a hash mapping attributes to values for the SELECT tag generated.  =back
533    
534  =item filterString  The valid options are as follows.
535    
536  A filter string for use in selecting the genomes. The filter string must conform  =over 4
 to the rules for the C<< ERDB->Get >> method.  
537    
538  =item params  =item name
539    
540  Reference to a list of values to be substituted in for the parameter marks in  Name to give this control for use in passing it to the form. The default is C<myGenomeControl>.
541  the filter string.  Terrible things will happen if you have two controls with the same name on the same page.
542    
543  =item selected (optional)  =item filter
544    
545  ID of the genome to be initially selected.  If specified, a filter for the list of genomes to display. The filter should be in the form of a
546    list reference, a string, or a hash reference. If it is a list reference, the first element
547    of the list should be the filter string, and the remaining elements the filter parameters. If it is a
548    string, it will be split into a list at each included tab. If it is a hash reference, it should be
549    a hash that maps genomes which should be included to a TRUE value.
550    
551  =item fast (optional)  =item multiSelect
552    
553  If specified and TRUE, the contig counts will be omitted to improve performance.  If TRUE, then the user can select multiple genomes. If FALSE, the user can only select one genome.
554    
555  =item RETURN  =item size
556    
557  Returns an HTML select menu with the specified genomes as selectable options.  Number of rows to display in the control. The default is C<10>
558    
559    =item id
560    
561    ID to give this control. The default is the value of the C<name> option. Nothing will work correctly
562    unless this ID is unique.
563    
564    =item selected
565    
566    A comma-delimited list of selected genomes, or a reference to a list of selected genomes. The
567    default is none.
568    
569    =item class
570    
571    If specified, a style class to assign to the genome control.
572    
573  =back  =back
574    
575  =cut  =cut
576    
577  sub GeneMenu {  sub GenomeMenu {
578      # Get the parameters.      # Get the parameters.
579      my ($self, $attributes, $filterString, $params, $selected, $fast) = @_;      my ($self, %options) = @_;
580      my $slowMode = ! $fast;      # Get the control's name and ID.
581      # Default to nothing selected. This prevents an execution warning if "$selected"      my $menuName = $options{name} || $options{id} || 'myGenomeControl';
582      # is undefined.      my $menuID = $options{id} || $menuName;
583      $selected = "" unless defined $selected;      Trace("Genome menu name = $menuName with ID $menuID.") if T(3);
584      Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3);      # Compute the IDs for the status display.
585      # Start the menu.      my $divID = "${menuID}_status";
586      my $retVal = "<select " .      my $urlID = "${menuID}_url";
587          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .      # Compute the code to show selected genomes in the status area.
588          ">\n";      my $showSelect = "showSelected('$menuID', '$divID', '$urlID', $FIG_Config::genome_control_cap)";
589      # Get the genomes.      # Check for single-select or multi-select.
590      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',      my $multiSelect = $options{multiSelect} || 0;
591                                                                       'Genome(genus)',      # Get the style data.
592                                                                       'Genome(species)',      my $class = $options{class} || '';
593                                                                       'Genome(unique-characterization)']);      # Get the list of pre-selected items.
594      # Sort them by name.      my $selections = $options{selected} || [];
595      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;      if (ref $selections ne 'ARRAY') {
596      # Loop through the genomes, creating the option tags.          $selections = [ split /\s*,\s*/, $selections ];
597      for my $genomeData (@sorted) {      }
598          # Get the data for this genome.      my %selected = map { $_ => 1 } @{$selections};
599          my ($genomeID, $genus, $species, $strain) = @{$genomeData};      # Extract the filter information. The default is no filtering. It can be passed as a tab-delimited
600          # Get the contig count.      # string, a hash reference, or a list reference.
601          my $contigInfo = "";      my ($filterHash, $filterString);
602          if ($slowMode) {      my $filterParms = $options{filter} || "";
603              my $count = $self->ContigCount($genomeID);      if (ref $filterParms eq 'HASH') {
604              my $counting = ($count == 1 ? "contig" : "contigs");          $filterHash = $filterParms;
605              $contigInfo = "[$count $counting]";          $filterParms = [];
606          }          $filterString = "";
607          # Find out if we're selected.      } else {
608          my $selectOption = ($selected eq $genomeID ? " selected" : "");          if (! ref $filterParms) {
609          # Build the option tag.              $filterParms = [split /\t|\\t/, $filterParms];
610          $retVal .= "<option value=\"$genomeID\"$selectOption>$genus $species $strain ($genomeID)$contigInfo</option>\n";          }
611            $filterString = shift @{$filterParms};
612        }
613        # Check for possible subsystem filtering. If there is one, we will tack the
614        # relationship onto the object name list.
615        my @objectNames = qw(Genome);
616        if ($filterString =~ /ParticipatesIn\(/) {
617            push @objectNames, 'ParticipatesIn';
618        }
619        # Get a list of all the genomes in group order. In fact, we only need them ordered
620        # by name (genus,species,strain), but putting primary-group in front enables us to
621        # take advantage of an existing index.
622        my @genomeList = $self->GetAll(\@objectNames, "$filterString ORDER BY Genome(primary-group), Genome(genus), Genome(species), Genome(unique-characterization)",
623                                       $filterParms,
624                                       [qw(Genome(primary-group) Genome(id) Genome(genus) Genome(species) Genome(unique-characterization) Genome(taxonomy) Genome(contigs))]);
625        # Apply the hash filter (if any).
626        if (defined $filterHash) {
627            @genomeList = grep { $filterHash->{$_->[1]} } @genomeList;
628        }
629        # Create a hash to organize the genomes by group. Each group will contain a list of
630        # 2-tuples, the first element being the genome ID and the second being the genome
631        # name.
632        my %gHash = ();
633        for my $genome (@genomeList) {
634            # Get the genome data.
635            my ($group, $genomeID, $genus, $species, $strain, $taxonomy, $contigs) = @{$genome};
636            # Compute its name. This is the genus, species, strain (if any), and the contig count.
637            my $name = "$genus $species ";
638            $name .= "$strain " if $strain;
639            my $contigCount = ($contigs == 1 ? "" : ", $contigs contigs");
640            # Now we get the domain. The domain tells us the display style of the organism.
641            my ($domain) = split /\s*;\s*/, $taxonomy, 2;
642            # Now compute the display group. This is normally the primary group, but if the
643            # organism is supporting, we blank it out.
644            my $displayGroup = ($group eq $FIG_Config::otherGroup ? "" : $group);
645            # Push the genome into the group's list. Note that we use the real group
646            # name for the hash key here, not the display group name.
647            push @{$gHash{$group}}, [$genomeID, $name, $contigCount, $domain];
648        }
649        # We are almost ready to unroll the menu out of the group hash. The final step is to separate
650        # the supporting genomes by domain. First, we extract the NMPDR groups and sort them. They
651        # are sorted by the first capitalized word. Groups with "other" are sorted after groups
652        # that aren't "other". At some point, we will want to make this less complicated.
653        my %sortGroups = map { $_ =~ /(other)?(.*)([A-Z].+)/; "$3$1$2" => $_ }
654                             grep { $_ ne $FIG_Config::otherGroup } keys %gHash;
655        my @groups = map { $sortGroups{$_} } sort keys %sortGroups;
656        # Remember the number of NMPDR groups.
657        my $nmpdrGroupCount = scalar @groups;
658        # Are there any supporting genomes?
659        if (exists $gHash{$FIG_Config::otherGroup}) {
660            # Loop through the supporting genomes, classifying them by domain. We'll also keep a list
661            # of the domains found.
662            my @otherGenomes = @{$gHash{$FIG_Config::otherGroup}};
663            my @domains = ();
664            for my $genomeData (@otherGenomes) {
665                my ($genomeID, $name, $contigCount, $domain) = @{$genomeData};
666                if (exists $gHash{$domain}) {
667                    push @{$gHash{$domain}}, $genomeData;
668                } else {
669                    $gHash{$domain} = [$genomeData];
670                    push @domains, $domain;
671                }
672            }
673            # Add the domain groups at the end of the main group list. The main group list will now
674            # contain all the categories we need to display the genomes.
675            push @groups, sort @domains;
676            # Delete the supporting group.
677            delete $gHash{$FIG_Config::otherGroup};
678        }
679        # Now it gets complicated. We need a way to mark all the NMPDR genomes. We take advantage
680        # of the fact they come first in the list. We'll accumulate a count of the NMPDR genomes
681        # and use that to make the selections.
682        my $nmpdrCount = 0;
683        # Create the type counters.
684        my $groupCount = 1;
685        # Get the number of rows to display.
686        my $rows = $options{size} || 10;
687        # If we're multi-row, create an onChange event.
688        my $onChangeTag = ( $rows > 1 ? " onChange=\"$showSelect;\" onFocus=\"$showSelect;\"" : "" );
689        # Set up the multiple-select flag.
690        my $multipleTag = ($multiSelect ? " multiple" : "" );
691        # Set up the style class.
692        my $classTag = ($class ? " $class" : "" );
693        # Create the SELECT tag and stuff it into the output array.
694        my @lines = qq(<SELECT name="$menuName" id="$menuID" class="genomeSelect $class" $onChangeTag$multipleTag$classTag size="$rows">);
695        # Loop through the groups.
696        for my $group (@groups) {
697            # Get the genomes in the group.
698            for my $genome (@{$gHash{$group}}) {
699                # If this is an NMPDR organism, we add an extra style and count it.
700                my $nmpdrStyle = "";
701                if ($nmpdrGroupCount > 0) {
702                    $nmpdrCount++;
703                    $nmpdrStyle = " Core";
704                }
705                # Get the organism ID, name, contig count, and domain.
706                my ($genomeID, $name, $contigCount, $domain) = @{$genome};
707                # See if we're pre-selected.
708                my $selectTag = ($selected{$genomeID} ? " SELECTED" : "");
709                # Compute the display name.
710                my $nameString = "$name ($genomeID$contigCount)";
711                # Generate the option tag.
712                my $optionTag = "<OPTION class=\"$domain$nmpdrStyle\" title=\"$group\" value=\"$genomeID\"$selectTag>$nameString</OPTION>";
713                push @lines, "    $optionTag";
714            }
715            # Record this group in the nmpdrGroup count. When that gets to 0, we've finished the NMPDR
716            # groups.
717            $nmpdrGroupCount--;
718      }      }
719      # Close the SELECT tag.      # Close the SELECT tag.
720      $retVal .= "</select>\n";      push @lines, "</SELECT>";
721        if ($rows > 1) {
722            # We're in a non-compact mode, so we need to add some selection helpers. First is
723            # the search box. This allows the user to type text and change which genomes are
724            # displayed. For multiple-select mode, we include a button that selects the displayed
725            # genes. For single-select mode, we use a plain label instead.
726            my $searchThingName = "${menuID}_SearchThing";
727            my $searchThingLabel = "Type to narrow selection";
728            my $searchThingButton = "";
729            my $goHint = "";
730            if ($multiSelect) {
731                $searchThingButton = qq(<INPUT type="button" name="MacroSearch" class="button" value="Go" onClick="selectShowing('$menuID', '$searchThingName'); $showSelect;" />);
732                $goHint = " Click <strong>Go</strong> to select them.";
733            }
734            push @lines, "<br />$searchThingLabel&nbsp;" .
735                         qq(<INPUT type="text" id="$searchThingName" name="$searchThingName" class="genomeSearchThing" onKeyup="showTyped('$menuID', '$searchThingName');" />) .
736                         $searchThingButton .
737                         Hint("GenomeControl", "Type a genome ID or part of an organism name to filter the genomes displayed.$goHint") . "<br />";
738            # For multi-select mode, we also have buttons to set and clear selections.
739            if ($multiSelect) {
740                push @lines, qq(<INPUT type="button" name="ClearAll" class="bigButton genomeButton" value="Clear All" onClick="clearAll(getElementById('$menuID')); $showSelect" />);
741                push @lines, qq(<INPUT type="button" name="SelectAll" class="bigButton genomeButton" value="Select All" onClick="selectAll(getElementById('$menuID')); $showSelect" />);
742                push @lines, qq(<INPUT type="button" name="NMPDROnly" class="bigButton genomeButton" value="Select NMPDR" onClick="selectSome(getElementById('$menuID'), $nmpdrCount, true); $showSelect;" />);
743            }
744            # Add a hidden field we can use to generate organism page hyperlinks.
745            push @lines, qq(<INPUT type="hidden" id="$urlID" value="$FIG_Config::cgi_url/wiki/rest.cgi/NmpdrPlugin/SeedViewer?page=Organism;organism=" />);
746            # Add the status display. This tells the user what's selected no matter where the list is scrolled.
747            push @lines, qq(<DIV id="$divID" class="Panel"></DIV>);
748        }
749        # Assemble all the lines into a string.
750        my $retVal = join("\n", @lines, "");
751        # Return the result.
752        return $retVal;
753    }
754    
755    
756    =head3 Stem
757    
758        my $stem = $sprout->Stem($word);
759    
760    Return the stem of the specified word, or C<undef> if the word is not
761    stemmable. Note that even if the word is stemmable, the stem may be
762    the same as the original word.
763    
764    =over 4
765    
766    =item word
767    
768    Word to convert into a stem.
769    
770    =item RETURN
771    
772    Returns a stem of the word (which may be the word itself), or C<undef> if
773    the word is not stemmable.
774    
775    =back
776    
777    =cut
778    
779    sub Stem {
780        # Get the parameters.
781        my ($self, $word) = @_;
782        # Get the stemmer object.
783        my $stemmer = $self->{stemmer};
784        if (! defined $stemmer) {
785            # We don't have one pre-built, so we build and save it now.
786            $stemmer = BioWords->new(exceptions => "$FIG_Config::sproutData/Exceptions.txt",
787                                     stops => "$FIG_Config::sproutData/StopWords.txt",
788                                     cache => 0);
789            $self->{stemmer} = $stemmer;
790        }
791        # Try to stem the word.
792        my $retVal = $stemmer->Process($word);
793      # Return the result.      # Return the result.
794      return $retVal;      return $retVal;
795  }  }
796    
797    
798  =head3 Build  =head3 Build
799    
800  C<< $sprout->Build(); >>      $sprout->Build();
801    
802  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.
803  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 440  Line 814 
814    
815  =head3 Genomes  =head3 Genomes
816    
817  C<< my @genomes = $sprout->Genomes(); >>      my @genomes = $sprout->Genomes();
818    
819  Return a list of all the genome IDs.  Return a list of all the genome IDs.
820    
# Line 457  Line 831 
831    
832  =head3 GenusSpecies  =head3 GenusSpecies
833    
834  C<< my $infoString = $sprout->GenusSpecies($genomeID); >>      my $infoString = $sprout->GenusSpecies($genomeID);
835    
836  Return the genus, species, and unique characterization for a genome.  Return the genus, species, and unique characterization for a genome.
837    
# Line 479  Line 853 
853  sub GenusSpecies {  sub GenusSpecies {
854      # Get the parameters.      # Get the parameters.
855      my ($self, $genomeID) = @_;      my ($self, $genomeID) = @_;
856      # Get the data for the specified genome.      # Declare the return value.
857      my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',      my $retVal;
858                                                                'Genome(unique-characterization)']);      # Get the genome data.
859      # Format the result and return it.      my $genomeData = $self->_GenomeData($genomeID);
860      my $retVal = join(' ', @values);      # Only proceed if we found the genome.
861        if (defined $genomeData) {
862            $retVal = $genomeData->PrimaryValue('Genome(scientific-name)');
863        }
864        # Return it.
865      return $retVal;      return $retVal;
866  }  }
867    
868  =head3 FeaturesOf  =head3 FeaturesOf
869    
870  C<< my @features = $sprout->FeaturesOf($genomeID, $ftype); >>      my @features = $sprout->FeaturesOf($genomeID, $ftype);
871    
872  Return a list of the features relevant to a specified genome.  Return a list of the features relevant to a specified genome.
873    
# Line 534  Line 912 
912    
913  =head3 FeatureLocation  =head3 FeatureLocation
914    
915  C<< my @locations = $sprout->FeatureLocation($featureID); >>      my @locations = $sprout->FeatureLocation($featureID);
916    
917  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
918  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 558  Line 936 
936  =item RETURN  =item RETURN
937    
938  Returns a list of the feature's contig segments. The locations are returned as a list in a list  Returns a list of the feature's contig segments. The locations are returned as a list in a list
939  context and as a comma-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context. An empty list means the feature
940    wasn't found.
941    
942  =back  =back
943    
944  =cut  =cut
945  #: Return Type @;  
 #: Return Type $;  
946  sub FeatureLocation {  sub FeatureLocation {
947      # Get the parameters.      # Get the parameters.
948      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
949      # Create a query for the feature locations.      # Declare the return variable.
     my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",  
                            [$featureID]);  
     # Create the return list.  
950      my @retVal = ();      my @retVal = ();
951      # Set up the variables used to determine if we have adjacent segments. This initial setup will      # Get the feature record.
952      # not match anything.      my $object = $self->GetEntity('Feature', $featureID);
953      my ($prevContig, $prevBeg, $prevDir, $prevLen) = ("", 0, "0", 0);      # Only proceed if we found it.
954      # Loop through the query results, creating location specifiers.      if (defined $object) {
955      while (my $location = $query->Fetch()) {          # Get the location string.
956          # Get the location parameters.          my $locString = $object->PrimaryValue('Feature(location-string)');
957          my ($contigID, $beg, $dir, $len) = $location->Values(['IsLocatedIn(to-link)',          # Create the return list.
958              'IsLocatedIn(beg)', 'IsLocatedIn(dir)', 'IsLocatedIn(len)']);          @retVal = split /\s*,\s*/, $locString;
         # Check to see if we are adjacent to the previous segment.  
         if ($prevContig eq $contigID && $dir eq $prevDir) {  
             # Here the new segment is in the same direction on the same contig. Insure the  
             # new segment's beginning is next to the old segment's end.  
             if ($dir eq "-" && $beg + $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";  
959      }      }
960      # Return the list in the format indicated by the context.      # Return the list in the format indicated by the context.
961      return (wantarray ? @retVal : join(',', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
# Line 613  Line 963 
963    
964  =head3 ParseLocation  =head3 ParseLocation
965    
966  C<< my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location); >>      my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location);
967    
968  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
969  length.  length.
# Line 632  Line 982 
982  =back  =back
983    
984  =cut  =cut
985  #: Return Type @;  
986  sub ParseLocation {  sub ParseLocation {
987      # 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
988      # the first parameter.      # the first parameter.
# Line 659  Line 1009 
1009    
1010  =head3 PointLocation  =head3 PointLocation
1011    
1012  C<< my $found = Sprout::PointLocation($location, $point); >>      my $found = Sprout::PointLocation($location, $point);
1013    
1014  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
1015  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 688  Line 1038 
1038  =back  =back
1039    
1040  =cut  =cut
1041  #: Return Type $;  
1042  sub PointLocation {  sub PointLocation {
1043      # 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
1044      # the first parameter.      # the first parameter.
# Line 711  Line 1061 
1061    
1062  =head3 DNASeq  =head3 DNASeq
1063    
1064  C<< my $sequence = $sprout->DNASeq(\@locationList); >>      my $sequence = $sprout->DNASeq(\@locationList);
1065    
1066  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
1067  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,
# Line 795  Line 1145 
1145    
1146  =head3 AllContigs  =head3 AllContigs
1147    
1148  C<< my @idList = $sprout->AllContigs($genomeID); >>      my @idList = $sprout->AllContigs($genomeID);
1149    
1150  Return a list of all the contigs for a genome.  Return a list of all the contigs for a genome.
1151    
# Line 825  Line 1175 
1175    
1176  =head3 GenomeLength  =head3 GenomeLength
1177    
1178  C<< my $length = $sprout->GenomeLength($genomeID); >>      my $length = $sprout->GenomeLength($genomeID);
1179    
1180  Return the length of the specified genome in base pairs.  Return the length of the specified genome in base pairs.
1181    
# Line 849  Line 1199 
1199      my ($self, $genomeID) = @_;      my ($self, $genomeID) = @_;
1200      # Declare the return variable.      # Declare the return variable.
1201      my $retVal = 0;      my $retVal = 0;
1202      # Get the genome's contig sequence lengths.      # Get the genome data.
1203      my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',      my $genomeData = $self->_GenomeData($genomeID);
1204                         [$genomeID], 'IsMadeUpOf(len)');      # Only proceed if it exists.
1205      # Sum the lengths.      if (defined $genomeData) {
1206      map { $retVal += $_ } @lens;          $retVal = $genomeData->PrimaryValue('Genome(dna-size)');
1207        }
1208      # Return the result.      # Return the result.
1209      return $retVal;      return $retVal;
1210  }  }
1211    
1212  =head3 FeatureCount  =head3 FeatureCount
1213    
1214  C<< my $count = $sprout->FeatureCount($genomeID, $type); >>      my $count = $sprout->FeatureCount($genomeID, $type);
1215    
1216  Return the number of features of the specified type in the specified genome.  Return the number of features of the specified type in the specified genome.
1217    
# Line 895  Line 1246 
1246    
1247  =head3 GenomeAssignments  =head3 GenomeAssignments
1248    
1249  C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>      my $fidHash = $sprout->GenomeAssignments($genomeID);
1250    
1251  Return a list of a genome's assigned features. The return hash will contain each  Return a list of a genome's assigned features. The return hash will contain each
1252  assigned feature of the genome mapped to the text of its most recent functional  assigned feature of the genome mapped to the text of its most recent functional
# Line 938  Line 1289 
1289    
1290  =head3 ContigLength  =head3 ContigLength
1291    
1292  C<< my $length = $sprout->ContigLength($contigID); >>      my $length = $sprout->ContigLength($contigID);
1293    
1294  Compute the length of a contig.  Compute the length of a contig.
1295    
# Line 977  Line 1328 
1328    
1329  =head3 ClusterPEGs  =head3 ClusterPEGs
1330    
1331  C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>      my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs);
1332    
1333  Cluster the PEGs in a list according to the cluster coding scheme of the specified  Cluster the PEGs in a list according to the cluster coding scheme of the specified
1334  subsystem. In order for this to work properly, the subsystem object must have  subsystem. In order for this to work properly, the subsystem object must have
1335  been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.  been used recently to retrieve the PEGs using the B<get_pegs_from_cell> or
1336  This causes the cluster numbers to be pulled into the subsystem's color hash.  B<get_row> methods. This causes the cluster numbers to be pulled into the
1337  If a PEG is not found in the color hash, it will not appear in the output  subsystem's color hash. If a PEG is not found in the color hash, it will not
1338  sequence.  appear in the output sequence.
1339    
1340  =over 4  =over 4
1341    
# Line 1025  Line 1376 
1376    
1377  =head3 GenesInRegion  =head3 GenesInRegion
1378    
1379  C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>      my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop);
1380    
1381  List the features which overlap a specified region in a contig.  List the features which overlap a specified region in a contig.
1382    
# Line 1054  Line 1405 
1405  =back  =back
1406    
1407  =cut  =cut
1408  #: Return Type @@;  
1409  sub GenesInRegion {  sub GenesInRegion {
1410      # Get the parameters.      # Get the parameters.
1411      my ($self, $contigID, $start, $stop) = @_;      my ($self, $contigID, $start, $stop) = @_;
1412      # Get the maximum segment length.      # Get the maximum segment length.
1413      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 = ();  
1414      # Prime the values we'll use for the returned beginning and end.      # Prime the values we'll use for the returned beginning and end.
1415      my @initialMinMax = ($self->ContigLength($contigID), 0);      my @initialMinMax = ($self->ContigLength($contigID), 0);
1416      my ($min, $max) = @initialMinMax;      my ($min, $max) = @initialMinMax;
1417      # Create a table of parameters for each query. Each query looks for features travelling in      # Get the overlapping features.
1418        my @featureObjects = $self->GeneDataInRegion($contigID, $start, $stop);
1419        # We'l use this hash to help us track the feature IDs and sort them. The key is the
1420        # feature ID and the value is a [$left,$right] pair indicating the maximum extent
1421        # of the feature's locations.
1422        my %featureMap = ();
1423        # Loop through them to do the begin/end analysis.
1424        for my $featureObject (@featureObjects) {
1425            # Get the feature's location string. This may contain multiple actual locations.
1426            my ($locations, $fid) = $featureObject->Values([qw(Feature(location-string) Feature(id))]);
1427            my @locationSegments = split /\s*,\s*/, $locations;
1428            # Loop through the locations.
1429            for my $locationSegment (@locationSegments) {
1430                # Construct an object for the location.
1431                my $locationObject = BasicLocation->new($locationSegment);
1432                # Merge the current segment's begin and end into the min and max.
1433                my ($left, $right) = ($locationObject->Left, $locationObject->Right);
1434                my ($beg, $end);
1435                if (exists $featureMap{$fid}) {
1436                    ($beg, $end) = @{$featureMap{$fid}};
1437                    $beg = $left if $left < $beg;
1438                    $end = $right if $right > $end;
1439                } else {
1440                    ($beg, $end) = ($left, $right);
1441                }
1442                $min = $beg if $beg < $min;
1443                $max = $end if $end > $max;
1444                # Store the feature's new extent back into the hash table.
1445                $featureMap{$fid} = [$beg, $end];
1446            }
1447        }
1448        # Now we must compute the list of the IDs for the features found. We start with a list
1449        # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1450        # but the result of the sort will be the same.)
1451        my @list = map { [$featureMap{$_}->[0] + $featureMap{$_}->[1], $_] } keys %featureMap;
1452        # Now we sort by midpoint and yank out the feature IDs.
1453        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1454        # Return it along with the min and max.
1455        return (\@retVal, $min, $max);
1456    }
1457    
1458    =head3 GeneDataInRegion
1459    
1460        my @featureList = $sprout->GenesInRegion($contigID, $start, $stop);
1461    
1462    List the features which overlap a specified region in a contig.
1463    
1464    =over 4
1465    
1466    =item contigID
1467    
1468    ID of the contig containing the region of interest.
1469    
1470    =item start
1471    
1472    Offset of the first residue in the region of interest.
1473    
1474    =item stop
1475    
1476    Offset of the last residue in the region of interest.
1477    
1478    =item RETURN
1479    
1480    Returns a list of B<ERDBObjects> for the desired features. Each object will
1481    contain a B<Feature> record.
1482    
1483    =back
1484    
1485    =cut
1486    
1487    sub GeneDataInRegion {
1488        # Get the parameters.
1489        my ($self, $contigID, $start, $stop) = @_;
1490        # Get the maximum segment length.
1491        my $maximumSegmentLength = $self->MaxSegment;
1492        # Create a hash to receive the feature list. We use a hash so that we can eliminate
1493        # duplicates easily. The hash key will be the feature ID. The value will be the feature's
1494        # ERDBObject from the query.
1495        my %featuresFound = ();
1496        # Create a table of parameters for the queries. Each query looks for features travelling in
1497      # 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,
1498      # 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
1499      # 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 1077  Line 1502 
1502      # Loop through the query parameters.      # Loop through the query parameters.
1503      for my $parms (values %queryParms) {      for my $parms (values %queryParms) {
1504          # Create the query.          # Create the query.
1505          my $query = $self->Get(['IsLocatedIn'],          my $query = $self->Get([qw(Feature IsLocatedIn)],
1506              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
1507              $parms);              $parms);
1508          # Loop through the feature segments found.          # Loop through the feature segments found.
1509          while (my $segment = $query->Fetch) {          while (my $segment = $query->Fetch) {
1510              # Get the data about this segment.              # Get the data about this segment.
1511              my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',              my ($featureID, $contig, $dir, $beg, $len) = $segment->Values([qw(IsLocatedIn(from-link)
1512                  'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);                  IsLocatedIn(to-link) IsLocatedIn(dir) IsLocatedIn(beg) IsLocatedIn(len))]);
1513              # 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
1514              # 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
1515              # 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
1516              # length.              # length.
1517              my ($found, $end) = (0, 0);              my $loc = BasicLocation->new($contig, $beg, $dir, $len);
1518              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;  
                 }  
             }  
1519              if ($found) {              if ($found) {
1520                  # Here we need to record the feature and update the minima and maxima. First,                  # Save this feature in the result list.
1521                  # get the current entry for the specified feature.                  $featuresFound{$featureID} = $segment;
                 my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :  
                                      @initialMinMax);  
                 # Merge the current segment's begin and end into the feature begin and end and the  
                 # global min and max.  
                 if ($beg < $loc1) {  
                     $loc1 = $beg;  
                     $min = $beg if $beg < $min;  
                 }  
                 if ($end > $loc2) {  
                     $loc2 = $end;  
                     $max = $end if $end > $max;  
                 }  
                 # Store the entry back into the hash table.  
                 $featuresFound{$featureID} = [$loc1, $loc2];  
1522              }              }
1523          }          }
1524      }      }
1525      # Now we must compute the list of the IDs for the features found. We start with a list      # Return the ERDB objects for the features found.
1526      # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,      return values %featuresFound;
     # but the result of the sort will be the same.)  
     my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;  
     # Now we sort by midpoint and yank out the feature IDs.  
     my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;  
     # Return it along with the min and max.  
     return (\@retVal, $min, $max);  
1527  }  }
1528    
1529  =head3 FType  =head3 FType
1530    
1531  C<< my $ftype = $sprout->FType($featureID); >>      my $ftype = $sprout->FType($featureID);
1532    
1533  Return the type of a feature.  Return the type of a feature.
1534    
# Line 1167  Line 1558 
1558    
1559  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1560    
1561  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>      my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag);
1562    
1563  Return the annotations of a feature.  Return the annotations of a feature.
1564    
# Line 1230  Line 1621 
1621    
1622  =head3 AllFunctionsOf  =head3 AllFunctionsOf
1623    
1624  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>      my %functions = $sprout->AllFunctionsOf($featureID);
1625    
1626  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
1627  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 1285  Line 1676 
1676    
1677  =head3 FunctionOf  =head3 FunctionOf
1678    
1679  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>      my $functionText = $sprout->FunctionOf($featureID, $userID);
1680    
1681  Return the most recently-determined functional assignment of a particular feature.  Return the most recently-determined functional assignment of a particular feature.
1682    
# Line 1298  Line 1689 
1689  the specified user and FIG are considered trusted. If the user ID is omitted, only FIG  the specified user and FIG are considered trusted. If the user ID is omitted, only FIG
1690  is trusted.  is trusted.
1691    
1692  If the feature is B<not> identified by a FIG ID, then the functional assignment  If the feature is B<not> identified by a FIG ID, then we search the aliases for it.
1693  information is taken from the B<ExternalAliasFunc> table. If the table does  If no matching alias is found, we return an undefined value.
 not contain an entry for the feature, an undefined value is returned.  
1694    
1695  =over 4  =over 4
1696    
# Line 1326  Line 1716 
1716      my ($self, $featureID, $userID) = @_;      my ($self, $featureID, $userID) = @_;
1717      # Declare the return value.      # Declare the return value.
1718      my $retVal;      my $retVal;
1719      # Determine the ID type.      # Find a FIG ID for this feature.
1720      if ($featureID =~ m/^fig\|/) {      my ($fid) = $self->FeaturesByAlias($featureID);
1721        # Only proceed if we have an ID.
1722        if ($fid) {
1723          # Here we have a FIG feature ID.          # Here we have a FIG feature ID.
1724          if (!$userID) {          if (!$userID) {
1725              # Use the primary assignment.              # Use the primary assignment.
1726              ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']);              ($retVal) = $self->GetEntityValues('Feature', $fid, ['Feature(assignment)']);
1727          } else {          } else {
1728              # We must build the list of trusted users.              # We must build the list of trusted users.
1729              my %trusteeTable = ();              my %trusteeTable = ();
# Line 1357  Line 1749 
1749              # 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.
1750              my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],              my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1751                                     "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                     "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1752                                     [$featureID]);                                     [$fid]);
1753              my $timeSelected = 0;              my $timeSelected = 0;
1754              # Loop until we run out of annotations.              # Loop until we run out of annotations.
1755              while (my $annotation = $query->Fetch()) {              while (my $annotation = $query->Fetch()) {
# Line 1377  Line 1769 
1769                  }                  }
1770              }              }
1771          }          }
     } else {  
         # Here we have a non-FIG feature ID. In this case the user ID does not  
         # matter. We simply get the information from the External Alias Function  
         # table.  
         ($retVal) = $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']);  
1772      }      }
1773      # Return the assignment found.      # Return the assignment found.
1774      return $retVal;      return $retVal;
# Line 1389  Line 1776 
1776    
1777  =head3 FunctionsOf  =head3 FunctionsOf
1778    
1779  C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>      my @functionList = $sprout->FunctionOf($featureID, $userID);
1780    
1781  Return the functional assignments of a particular feature.  Return the functional assignments of a particular feature.
1782    
# Line 1400  Line 1787 
1787  annotation itself because it's a text field; however, this is not a big problem because  annotation itself because it's a text field; however, this is not a big problem because
1788  most features only have a small number of annotations.  most features only have a small number of annotations.
1789    
 If the feature is B<not> identified by a FIG ID, then the functional assignment  
 information is taken from the B<ExternalAliasFunc> table. If the table does  
 not contain an entry for the feature, an empty list is returned.  
   
1790  =over 4  =over 4
1791    
1792  =item featureID  =item featureID
# Line 1424  Line 1807 
1807      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1808      # Declare the return value.      # Declare the return value.
1809      my @retVal = ();      my @retVal = ();
1810      # Determine the ID type.      # Convert to a FIG ID.
1811      if ($featureID =~ m/^fig\|/) {      my ($fid) = $self->FeaturesByAlias($featureID);
1812        # Only proceed if we found one.
1813        if ($fid) {
1814          # Here we have a FIG feature ID. We must build the list of trusted          # Here we have a FIG feature ID. We must build the list of trusted
1815          # users.          # users.
1816          my %trusteeTable = ();          my %trusteeTable = ();
1817          # 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.
1818          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1819                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1820                                 [$featureID]);                                 [$fid]);
1821          my $timeSelected = 0;          my $timeSelected = 0;
1822          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1823          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
# Line 1447  Line 1832 
1832                  push @retVal, [$actualUser, $function];                  push @retVal, [$actualUser, $function];
1833              }              }
1834          }          }
     } else {  
         # Here we have a non-FIG feature ID. In this case the user ID does not  
         # matter. We simply get the information from the External Alias Function  
         # table.  
         my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,  
                                                  ['ExternalAliasFunc(func)']);  
         push @retVal, map { ['master', $_] } @assignments;  
1835      }      }
1836      # Return the assignments found.      # Return the assignments found.
1837      return @retVal;      return @retVal;
# Line 1461  Line 1839 
1839    
1840  =head3 BBHList  =head3 BBHList
1841    
1842  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>      my $bbhHash = $sprout->BBHList($genomeID, \@featureList);
1843    
1844  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
1845  on a specified target genome.  on a specified target genome.
# Line 1493  Line 1871 
1871      # Loop through the incoming features.      # Loop through the incoming features.
1872      for my $featureID (@{$featureList}) {      for my $featureID (@{$featureList}) {
1873          # Ask the server for the feature's best hit.          # Ask the server for the feature's best hit.
1874          my @bbhData = FIGRules::BBHData($featureID);          my $bbhData = FIGRules::BBHData($featureID);
1875          # Peel off the BBHs found.          # Peel off the BBHs found.
1876          my @found = ();          my @found = ();
1877          for my $bbh (@bbhData) {          for my $bbh (@$bbhData) {
1878              my $fid = $bbh->[0];              my $fid = $bbh->[0];
1879              my $bbGenome = $self->GenomeOf($fid);              my $bbGenome = $self->GenomeOf($fid);
1880              if ($bbGenome eq $genomeID) {              if ($bbGenome eq $genomeID) {
# Line 1511  Line 1889 
1889    
1890  =head3 SimList  =head3 SimList
1891    
1892  C<< my %similarities = $sprout->SimList($featureID, $count); >>      my %similarities = $sprout->SimList($featureID, $count);
1893    
1894  Return a list of the similarities to the specified feature.  Return a list of the similarities to the specified feature.
1895    
# Line 1535  Line 1913 
1913      # Get the parameters.      # Get the parameters.
1914      my ($self, $featureID, $count) = @_;      my ($self, $featureID, $count) = @_;
1915      # Ask for the best hits.      # Ask for the best hits.
1916      my @lists = FIGRules::BBHData($featureID);      my $lists = FIGRules::BBHData($featureID);
1917      # Create the return value.      # Create the return value.
1918      my %retVal = ();      my %retVal = ();
1919      for my $tuple (@lists) {      for my $tuple (@$lists) {
1920          $retVal{$tuple->[0]} = $tuple->[1];          $retVal{$tuple->[0]} = $tuple->[1];
1921      }      }
1922      # Return the result.      # Return the result.
# Line 1547  Line 1925 
1925    
1926  =head3 IsComplete  =head3 IsComplete
1927    
1928  C<< my $flag = $sprout->IsComplete($genomeID); >>      my $flag = $sprout->IsComplete($genomeID);
1929    
1930  Return TRUE if the specified genome is complete, else FALSE.  Return TRUE if the specified genome is complete, else FALSE.
1931    
# Line 1572  Line 1950 
1950      # Declare the return variable.      # Declare the return variable.
1951      my $retVal;      my $retVal;
1952      # Get the genome's data.      # Get the genome's data.
1953      my $genomeData = $self->GetEntity('Genome', $genomeID);      my $genomeData = $self->_GenomeData($genomeID);
1954      if ($genomeData) {      # Only proceed if it exists.
1955        if (defined $genomeData) {
1956          # The genome exists, so get the completeness flag.          # The genome exists, so get the completeness flag.
1957          ($retVal) = $genomeData->Value('Genome(complete)');          $retVal = $genomeData->PrimaryValue('Genome(complete)');
1958      }      }
1959      # Return the result.      # Return the result.
1960      return $retVal;      return $retVal;
# Line 1583  Line 1962 
1962    
1963  =head3 FeatureAliases  =head3 FeatureAliases
1964    
1965  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>      my @aliasList = $sprout->FeatureAliases($featureID);
1966    
1967  Return a list of the aliases for a specified feature.  Return a list of the aliases for a specified feature.
1968    
# Line 1606  Line 1985 
1985      # Get the parameters.      # Get the parameters.
1986      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1987      # Get the desired feature's aliases      # Get the desired feature's aliases
1988      my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);      my @retVal = $self->GetFlat(['IsAliasOf'], "IsAliasOf(to-link) = ?", [$featureID], 'IsAliasOf(from-link)');
1989      # Return the result.      # Return the result.
1990      return @retVal;      return @retVal;
1991  }  }
1992    
1993  =head3 GenomeOf  =head3 GenomeOf
1994    
1995  C<< my $genomeID = $sprout->GenomeOf($featureID); >>      my $genomeID = $sprout->GenomeOf($featureID);
1996    
1997  Return the genome that contains a specified feature or contig.  Return the genome that contains a specified feature or contig.
1998    
# Line 1635  Line 2014 
2014  sub GenomeOf {  sub GenomeOf {
2015      # Get the parameters.      # Get the parameters.
2016      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
     # Create a query to find the genome associated with the incoming ID.  
     my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ? OR HasContig(to-link) = ?",  
                            [$featureID, $featureID]);  
2017      # Declare the return value.      # Declare the return value.
2018      my $retVal;      my $retVal;
2019      # Get the genome ID.      # Parse the genome ID from the feature ID.
2020      if (my $relationship = $query->Fetch()) {      if ($featureID =~ /^fig\|(\d+\.\d+)/) {
2021          ($retVal) = $relationship->Value('HasContig(from-link)');          $retVal = $1;
2022        } else {
2023            # Find the feature by alias.
2024            my ($realFeatureID) = $self->FeaturesByAlias($featureID);
2025            if ($realFeatureID && $realFeatureID =~ /^fig\|(\d+\.\d+)/) {
2026                $retVal = $1;
2027            }
2028      }      }
2029      # Return the value found.      # Return the value found.
2030      return $retVal;      return $retVal;
# Line 1650  Line 2032 
2032    
2033  =head3 CoupledFeatures  =head3 CoupledFeatures
2034    
2035  C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >>      my %coupleHash = $sprout->CoupledFeatures($featureID);
2036    
2037  Return the features functionally coupled with a specified feature. Features are considered  Return the features functionally coupled with a specified feature. Features are considered
2038  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 1672  Line 2054 
2054  sub CoupledFeatures {  sub CoupledFeatures {
2055      # Get the parameters.      # Get the parameters.
2056      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2057        # Ask the coupling server for the data.
2058      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
2059      # Create a query to retrieve the functionally-coupled features.      my @rawPairs = FIGRules::NetCouplingData('coupled_to', id1 => $featureID);
2060      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      Trace(scalar(@rawPairs) . " couplings returned.") if T(coupling => 3);
2061                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);      # Form them into a hash.
     # This value will be set to TRUE if we find at least one coupled feature.  
     my $found = 0;  
     # Create the return hash.  
2062      my %retVal = ();      my %retVal = ();
2063      # Retrieve the relationship records and store them in the hash.      for my $pair (@rawPairs) {
2064      while (my $clustering = $query->Fetch()) {          # Get the feature ID and score.
2065          # Get the ID and score of the coupling.          my ($featureID2, $score) = @{$pair};
2066          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          # Only proceed if the feature is in NMPDR.
2067                                                          'Coupling(score)']);          if ($self->_CheckFeature($featureID2)) {
2068          Trace("$featureID coupled with score $score to ID $couplingID.") if T(coupling => 4);              $retVal{$featureID2} = $score;
         # Get the other feature that participates in the coupling.  
         my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],  
                                            "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",  
                                            [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');  
         Trace("$couplingID target feature is $otherFeatureID.") if T(coupling => 4);  
         # Attach the other feature's score to its ID.  
         $retVal{$otherFeatureID} = $score;  
         $found = 1;  
2069      }      }
     # Functional coupling is reflexive. If we found at least one coupled feature, we must add  
     # the incoming feature as well.  
     if ($found) {  
         $retVal{$featureID} = 9999;  
2070      }      }
2071      # Return the hash.      # Return the hash.
2072      return %retVal;      return %retVal;
# Line 1706  Line 2074 
2074    
2075  =head3 CouplingEvidence  =head3 CouplingEvidence
2076    
2077  C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>      my @evidence = $sprout->CouplingEvidence($peg1, $peg2);
2078    
2079  Return the evidence for a functional coupling.  Return the evidence for a functional coupling.
2080    
# Line 1754  Line 2122 
2122      my ($self, $peg1, $peg2) = @_;      my ($self, $peg1, $peg2) = @_;
2123      # Declare the return variable.      # Declare the return variable.
2124      my @retVal = ();      my @retVal = ();
2125      # Our first task is to find out the nature of the coupling: whether or not      # Get the coupling and evidence data.
2126      # it exists, its score, and whether the features are stored in the same      my @rawData = FIGRules::NetCouplingData('coupling_evidence', id1 => $peg1, id2 => $peg2);
2127      # order as the ones coming in.      # Loop through the raw data, saving the ones that are in NMPDR genomes.
2128      my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);      for my $rawTuple (@rawData) {
2129      # Only proceed if a coupling exists.          if ($self->_CheckFeature($rawTuple->[0]) && $self->_CheckFeature($rawTuple->[1])) {
2130      if ($couplingID) {              push @retVal, $rawTuple;
         # 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);  
2131      }      }
     # Return the result.  
     return @retVal;  
 }  
   
 =head3 GetCoupling  
   
 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.  
   
 =over 4  
   
 =item peg1  
   
 ID of the feature of interest.  
   
 =item peg2  
   
 ID of the potentially coupled feature.  
   
 =item RETURN  
   
 Returns a three-element list. The first element contains the database ID of  
 the coupling. The second element is FALSE if the coupling is stored in the  
 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>.  
   
 =back  
   
 =cut  
 #: Return Type $%@;  
 sub GetCoupling {  
     # Get the parameters.  
     my ($self, $peg1, $peg2) = @_;  
     # Declare the return values. We'll start with the coupling ID and undefine the  
     # flag and score until we have more information.  
     my ($retVal, $inverted, $score) = ($self->CouplingID($peg1, $peg2), undef, undef);  
     # Find the coupling data.  
     my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],  
                                  "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",  
                                  [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);  
     # Check to see if we found anything.  
     if (!@pegs) {  
         Trace("No coupling found.") if T(Coupling => 4);  
         # No coupling, so undefine the return value.  
         $retVal = undef;  
     } else {  
         # We have a coupling! Get the score and check for inversion.  
         $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);  
2132      }      }
2133      # Return the result.      # Return the result.
2134      return ($retVal, $inverted, $score);      return @retVal;
2135  }  }
2136    
2137  =head3 GetSynonymGroup  =head3 GetSynonymGroup
2138    
2139  C<< my $id = $sprout->GetSynonymGroup($fid); >>      my $id = $sprout->GetSynonymGroup($fid);
2140    
2141  Return the synonym group name for the specified feature.  Return the synonym group name for the specified feature.
2142    
# Line 1885  Line 2175 
2175    
2176  =head3 GetBoundaries  =head3 GetBoundaries
2177    
2178  C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>      my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList);
2179    
2180  Determine the begin and end boundaries for the locations in a list. All of the  Determine the begin and end boundaries for the locations in a list. All of the
2181  locations must belong to the same contig and have mostly the same direction in  locations must belong to the same contig and have mostly the same direction in
# Line 1947  Line 2237 
2237      return ($contig, $beg, $end);      return ($contig, $beg, $end);
2238  }  }
2239    
 =head3 CouplingID  
   
 C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >>  
   
 Return the coupling ID for a pair of feature IDs.  
   
 The coupling ID is currently computed by joining the feature IDs in  
 sorted order with a space. Client modules (that is, modules which  
 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")>.  
   
 =over 4  
   
 =item peg1  
   
 First feature of interest.  
   
 =item peg2  
   
 Second feature of interest.  
   
 =item RETURN  
   
 Returns the ID that would be used to represent a functional coupling of  
 the two specified PEGs.  
   
 =back  
   
 =cut  
 #: Return Type $;  
 sub CouplingID {  
     my ($self, @pegs) = @_;  
     return $self->DigestKey(join " ", sort @pegs);  
 }  
   
2240  =head3 ReadFasta  =head3 ReadFasta
2241    
2242  C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>      my %sequenceData = Sprout::ReadFasta($fileName, $prefix);
2243    
2244  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
2245  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 2054  Line 2305 
2305    
2306  =head3 FormatLocations  =head3 FormatLocations
2307    
2308  C<< my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat); >>      my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat);
2309    
2310  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
2311  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 2119  Line 2370 
2370    
2371  =head3 DumpData  =head3 DumpData
2372    
2373  C<< $sprout->DumpData(); >>      $sprout->DumpData();
2374    
2375  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.
2376    
# Line 2136  Line 2387 
2387    
2388  =head3 XMLFileName  =head3 XMLFileName
2389    
2390  C<< my $fileName = $sprout->XMLFileName(); >>      my $fileName = $sprout->XMLFileName();
2391    
2392  Return the name of this database's XML definition file.  Return the name of this database's XML definition file.
2393    
# Line 2147  Line 2398 
2398      return $self->{_xmlName};      return $self->{_xmlName};
2399  }  }
2400    
2401  =head3 Insert  =head3 GetGenomeNameData
2402    
2403  C<< $sprout->Insert($objectType, \%fieldHash); >>      my ($genus, $species, $strain) = $sprout->GenomeNameData($genomeID);
2404    
2405  Insert an entity or relationship instance into the database. The entity or relationship of interest  Return the genus, species, and unique characterization for a genome. This
2406  is defined by a type name and then a hash of field names to values. Field values in the primary  is similar to L</GenusSpecies>, with the exception that it returns the
2407    values in three seperate fields.
2408    
2409    =over 4
2410    
2411    =item genomeID
2412    
2413    ID of the genome whose name data is desired.
2414    
2415    =item RETURN
2416    
2417    Returns a three-element list, consisting of the genus, species, and strain
2418    of the specified genome. If the genome is not found, an error occurs.
2419    
2420    =back
2421    
2422    =cut
2423    
2424    sub GetGenomeNameData {
2425        # Get the parameters.
2426        my ($self, $genomeID) = @_;
2427        # Declare the return variables.
2428        my ($genus, $species, $strain);
2429        # Get the genome's data.
2430        my $genomeData = $self->_GenomeData($genomeID);
2431        # Only proceed if the genome exists.
2432        if (defined $genomeData) {
2433            # Get the desired values.
2434            ($genus, $species, $strain) = $genomeData->Values(['Genome(genus)',
2435                                                               'Genome(species)',
2436                                                               'Genome(unique-characterization)']);
2437        } else {
2438            # Throw an error because they were not found.
2439            Confess("Genome $genomeID not found in database.");
2440        }
2441        # Return the results.
2442        return ($genus, $species, $strain);
2443    }
2444    
2445    =head3 GetGenomeByNameData
2446    
2447        my @genomes = $sprout->GetGenomeByNameData($genus, $species, $strain);
2448    
2449    Return a list of the IDs of the genomes with the specified genus,
2450    species, and strain. In almost every case, there will be either zero or
2451    one IDs returned; however, two or more IDs could be returned if there are
2452    multiple versions of the genome in the database.
2453    
2454    =over 4
2455    
2456    =item genus
2457    
2458    Genus of the desired genome.
2459    
2460    =item species
2461    
2462    Species of the desired genome.
2463    
2464    =item strain
2465    
2466    Strain (unique characterization) of the desired genome. This may be an empty
2467    string, in which case it is presumed that the desired genome has no strain
2468    specified.
2469    
2470    =item RETURN
2471    
2472    Returns a list of the IDs of the genomes having the specified genus, species, and
2473    strain.
2474    
2475    =back
2476    
2477    =cut
2478    
2479    sub GetGenomeByNameData {
2480        # Get the parameters.
2481        my ($self, $genus, $species, $strain) = @_;
2482        # Try to find the genomes.
2483        my @retVal = $self->GetFlat(['Genome'], "Genome(genus) = ? AND Genome(species) = ? AND Genome(unique-characterization) = ?",
2484                                    [$genus, $species, $strain], 'Genome(id)');
2485        # Return the result.
2486        return @retVal;
2487    }
2488    
2489    =head3 Insert
2490    
2491        $sprout->Insert($objectType, \%fieldHash);
2492    
2493    Insert an entity or relationship instance into the database. The entity or relationship of interest
2494    is defined by a type name and then a hash of field names to values. Field values in the primary
2495  relation are represented by scalars. (Note that for relationships, the primary relation is  relation are represented by scalars. (Note that for relationships, the primary relation is
2496  the B<only> relation.) Field values for the other relations comprising the entity are always  the B<only> relation.) Field values for the other relations comprising the entity are always
2497  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
2498  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>.
2499    
2500  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']});
2501    
2502  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
2503  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>.
2504    
2505  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'});
2506    
2507  =over 4  =over 4
2508    
# Line 2188  Line 2527 
2527    
2528  =head3 Annotate  =head3 Annotate
2529    
2530  C<< my $ok = $sprout->Annotate($fid, $timestamp, $user, $text); >>      my $ok = $sprout->Annotate($fid, $timestamp, $user, $text);
2531    
2532  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
2533  specified feature and user.  specified feature and user.
# Line 2242  Line 2581 
2581    
2582  =head3 AssignFunction  =head3 AssignFunction
2583    
2584  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>      my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser);
2585    
2586  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
2587  format is described in L</ParseAssignment>.  format is described in L</ParseAssignment>.
# Line 2302  Line 2641 
2641    
2642  =head3 FeaturesByAlias  =head3 FeaturesByAlias
2643    
2644  C<< my @features = $sprout->FeaturesByAlias($alias); >>      my @features = $sprout->FeaturesByAlias($alias);
2645    
2646  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
2647  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 2336  Line 2675 
2675          push @retVal, $mappedAlias;          push @retVal, $mappedAlias;
2676      } else {      } else {
2677          # 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.
2678          @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');          @retVal = $self->GetFlat(['IsAliasOf'], 'IsAliasOf(from-link) = ?', [$mappedAlias], 'IsAliasOf(to-link)');
2679      }      }
2680      # Return the result.      # Return the result.
2681      return @retVal;      return @retVal;
# Line 2344  Line 2683 
2683    
2684  =head3 FeatureTranslation  =head3 FeatureTranslation
2685    
2686  C<< my $translation = $sprout->FeatureTranslation($featureID); >>      my $translation = $sprout->FeatureTranslation($featureID);
2687    
2688  Return the translation of a feature.  Return the translation of a feature.
2689    
# Line 2372  Line 2711 
2711    
2712  =head3 Taxonomy  =head3 Taxonomy
2713    
2714  C<< my @taxonomyList = $sprout->Taxonomy($genome); >>      my @taxonomyList = $sprout->Taxonomy($genome);
2715    
2716  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
2717  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>,
2718  or C<Eukaryote>) to sub-species. For example,  or C<Eukaryote>) to sub-species. For example,
2719    
2720  C<< (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12) >>      (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12)
2721    
2722  =over 4  =over 4
2723    
# Line 2397  Line 2736 
2736  sub Taxonomy {  sub Taxonomy {
2737      # Get the parameters.      # Get the parameters.
2738      my ($self, $genome) = @_;      my ($self, $genome) = @_;
     # Find the specified genome's taxonomy string.  
     my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);  
2739      # Declare the return variable.      # Declare the return variable.
2740      my @retVal = ();      my @retVal = ();
2741      # If we found the genome, return its taxonomy string.      # Get the genome data.
2742      if ($list) {      my $genomeData = $self->_GenomeData($genome);
2743          @retVal = split /\s*;\s*/, $list;      # Only proceed if it exists.
2744        if (defined $genomeData) {
2745            # Create the taxonomy from the taxonomy string.
2746            @retVal = split /\s*;\s*/, $genomeData->PrimaryValue('Genome(taxonomy)');
2747      } else {      } else {
2748            # Genome doesn't exist, so emit a warning.
2749          Trace("Genome \"$genome\" does not have a taxonomy in the database.\n") if T(0);          Trace("Genome \"$genome\" does not have a taxonomy in the database.\n") if T(0);
2750      }      }
2751      # Return the value found.      # Return the value found.
# Line 2413  Line 2754 
2754    
2755  =head3 CrudeDistance  =head3 CrudeDistance
2756    
2757  C<< my $distance = $sprout->CrudeDistance($genome1, $genome2); >>      my $distance = $sprout->CrudeDistance($genome1, $genome2);
2758    
2759  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
2760  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 2449  Line 2790 
2790      }      }
2791      my @taxA = $self->Taxonomy($genomeA);      my @taxA = $self->Taxonomy($genomeA);
2792      my @taxB = $self->Taxonomy($genomeB);      my @taxB = $self->Taxonomy($genomeB);
2793      # Initialize the distance to 1. We'll reduce it each time we find a match between the      # Compute the distance.
2794      # taxonomies.      my $retVal = FIGRules::CrudeDistanceFormula(\@taxA, \@taxB);
     my $retVal = 1.0;  
     # Initialize the subtraction amount. This amount determines the distance reduction caused  
     # by a mismatch at the current level.  
     my $v = 0.5;  
     # Loop through the taxonomies.  
     for (my $i = 0; ($i < @taxA) && ($i < @taxB) && ($taxA[$i] eq $taxB[$i]); $i++) {  
         $retVal -= $v;  
         $v /= 2;  
     }  
2795      return $retVal;      return $retVal;
2796  }  }
2797    
2798  =head3 RoleName  =head3 RoleName
2799    
2800  C<< my $roleName = $sprout->RoleName($roleID); >>      my $roleName = $sprout->RoleName($roleID);
2801    
2802  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
2803  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 2499  Line 2831 
2831    
2832  =head3 RoleDiagrams  =head3 RoleDiagrams
2833    
2834  C<< my @diagrams = $sprout->RoleDiagrams($roleID); >>      my @diagrams = $sprout->RoleDiagrams($roleID);
2835    
2836  Return a list of the diagrams containing a specified functional role.  Return a list of the diagrams containing a specified functional role.
2837    
# Line 2527  Line 2859 
2859      return @retVal;      return @retVal;
2860  }  }
2861    
 =head3 GetProperties  
   
 C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>  
   
 Return a list of the properties with the specified characteristics.  
   
 Properties are arbitrary key-value pairs associated with a feature. (At some point they  
 will also be associated with genomes.) A property value is represented by a 4-tuple of  
 the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter  
   
 =over 4  
   
 =item fid  
   
 ID of the feature possessing the property.  
   
 =item key  
   
 Name or key of the property.  
   
 =item value  
   
 Value of the property.  
   
 =item url  
   
 URL of the document that indicated the property should have this particular value, or an  
 empty string if no such document exists.  
   
 =back  
   
 The parameters act as a filter for the desired data. Any non-null parameter will  
 automatically match all the tuples returned. So, specifying just the I<$fid> will  
 return all the properties of the specified feature; similarly, specifying the I<$key>  
 and I<$value> parameters will return all the features having the specified property  
 value.  
   
 A single property key can have many values, representing different ideas about the  
 feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is  
 virulent, and another may declare that it is not virulent. A query about the virulence of  
 C<fig|83333.1.peg.10> would be coded as  
   
     my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');  
   
 Here the I<$value> and I<$url> fields are left blank, indicating that those fields are  
 not to be filtered. The tuples returned would be  
   
     ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')  
     ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')  
   
 =cut  
 #: Return Type @@;  
 sub GetProperties {  
     # Get the parameters.  
     my ($self, @parms) = @_;  
     # Declare the return variable.  
     my @retVal = ();  
     # 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;  
     }  
     # Return the result.  
     return @retVal;  
 }  
   
2862  =head3 FeatureProperties  =head3 FeatureProperties
2863    
2864  C<< my @properties = $sprout->FeatureProperties($featureID); >>      my @properties = $sprout->FeatureProperties($featureID);
2865    
2866  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
2867  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
2868  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
2869  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
2870  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.  
2871    
2872  =over 4  =over 4
2873    
# Line 2630  Line 2877 
2877    
2878  =item RETURN  =item RETURN
2879    
2880  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.  
2881    
2882  =back  =back
2883    
# Line 2641  Line 2887 
2887      # Get the parameters.      # Get the parameters.
2888      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2889      # Get the properties.      # Get the properties.
2890      my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],      my @attributes = $self->ca->GetAttributes($featureID);
2891                              ['Property(property-name)', 'Property(property-value)',      # Strip the feature ID off each tuple.
2892                               'HasProperty(evidence)']);      my @retVal = ();
2893        for my $attributeRow (@attributes) {
2894            shift @{$attributeRow};
2895            push @retVal, $attributeRow;
2896        }
2897      # Return the resulting list.      # Return the resulting list.
2898      return @retVal;      return @retVal;
2899  }  }
2900    
2901  =head3 DiagramName  =head3 DiagramName
2902    
2903  C<< my $diagramName = $sprout->DiagramName($diagramID); >>      my $diagramName = $sprout->DiagramName($diagramID);
2904    
2905  Return the descriptive name of a diagram.  Return the descriptive name of a diagram.
2906    
# Line 2678  Line 2928 
2928    
2929  =head3 PropertyID  =head3 PropertyID
2930    
2931  C<< my $id = $sprout->PropertyID($propName, $propValue); >>      my $id = $sprout->PropertyID($propName, $propValue);
2932    
2933  Return the ID of the specified property name and value pair, if the  Return the ID of the specified property name and value pair, if the
2934  pair exists.  pair exists. Only a small subset of the FIG attributes are stored as
2935    Sprout properties, mostly for use in search optimization.
2936    
2937  =over 4  =over 4
2938    
# Line 2714  Line 2965 
2965    
2966  =head3 MergedAnnotations  =head3 MergedAnnotations
2967    
2968  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>      my @annotationList = $sprout->MergedAnnotations(\@list);
2969    
2970  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
2971  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 2763  Line 3014 
3014    
3015  =head3 RoleNeighbors  =head3 RoleNeighbors
3016    
3017  C<< my @roleList = $sprout->RoleNeighbors($roleID); >>      my @roleList = $sprout->RoleNeighbors($roleID);
3018    
3019  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
3020  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 2806  Line 3057 
3057    
3058  =head3 FeatureLinks  =head3 FeatureLinks
3059    
3060  C<< my @links = $sprout->FeatureLinks($featureID); >>      my @links = $sprout->FeatureLinks($featureID);
3061    
3062  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
3063  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 2837  Line 3088 
3088    
3089  =head3 SubsystemsOf  =head3 SubsystemsOf
3090    
3091  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>      my %subsystems = $sprout->SubsystemsOf($featureID);
3092    
3093  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
3094  to the roles the feature performs.  to the roles the feature performs.
# Line 2885  Line 3136 
3136    
3137  =head3 SubsystemList  =head3 SubsystemList
3138    
3139  C<< my @subsystems = $sprout->SubsystemList($featureID); >>      my @subsystems = $sprout->SubsystemList($featureID);
3140    
3141  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
3142  feature participates. Unlike L</SubsystemsOf>, this method only returns the  feature participates. Unlike L</SubsystemsOf>, this method only returns the
# Line 2908  Line 3159 
3159  sub SubsystemList {  sub SubsystemList {
3160      # Get the parameters.      # Get the parameters.
3161      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
3162      # Get the list of names.      # Get the list of names. We do a join to the Subsystem table because we have missing subsystems in
3163      my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?",      # the Sprout database!
3164        my @retVal = $self->GetFlat(['HasRoleInSubsystem', 'Subsystem'], "HasRoleInSubsystem(from-link) = ?",
3165                                  [$featureID], 'HasRoleInSubsystem(to-link)');                                  [$featureID], 'HasRoleInSubsystem(to-link)');
3166      # Return the result, sorted.      # Return the result, sorted.
3167      return sort @retVal;      return sort @retVal;
# Line 2917  Line 3169 
3169    
3170  =head3 GenomeSubsystemData  =head3 GenomeSubsystemData
3171    
3172  C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>      my %featureData = $sprout->GenomeSubsystemData($genomeID);
3173    
3174  Return a hash mapping genome features to their subsystem roles.  Return a hash mapping genome features to their subsystem roles.
3175    
# Line 2942  Line 3194 
3194      # Declare the return variable.      # Declare the return variable.
3195      my %retVal = ();      my %retVal = ();
3196      # Get a list of the genome features that participate in subsystems. For each      # Get a list of the genome features that participate in subsystems. For each
3197      # feature we get its spreadsheet cells and the corresponding roles.      # feature we get its subsystem ID and the corresponding roles.
3198      my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],      my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf', 'HasSSCell'],
3199                               "HasFeature(from-link) = ?", [$genomeID],                               "HasFeature(from-link) = ?", [$genomeID],
3200                               ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);                                   ['HasFeature(to-link)', 'IsRoleOf(from-link)',  'HasSSCell(from-link)']);
3201      # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems      # Now we get a list of valid subsystems. These are the subsystems connected to the genome with
3202      # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the      # a non-negative variant code.
3203      # list. We use it at the beginning to get all the spreadsheet cells for the genome and      my %subs = map { $_ => 1 } $self->GetFlat(['ParticipatesIn'],
3204      # again at the end to filter out participation in subsystems with a negative variant code.                                                  "ParticipatesIn(from-link) = ? AND ParticipatesIn(variant-code) >= 0",
3205      my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],                                                  [$genomeID], 'ParticipatesIn(to-link)');
3206                                   "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?",      # We loop through @roleData to build the hash.
                                  [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']);  
     # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features.  
     # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We  
     # link these two lists together to create the result. First, we want a hash mapping  
     # spreadsheet cells to subsystem names.  
     my %subHash = map { $_->[0] => $_->[1] } @cellData;  
     # We loop through @cellData to build the hash.  
3207      for my $roleEntry (@roleData) {      for my $roleEntry (@roleData) {
3208          # Get the data for this feature and cell.          # Get the data for this feature and cell.
3209          my ($fid, $cellID, $role) = @{$roleEntry};          my ($fid, $role, $subsys) = @{$roleEntry};
3210          # Check for a subsystem name.          Trace("Subsystem for $fid is $subsys.") if T(4);
3211          my $subsys = $subHash{$cellID};          # Check the subsystem;
3212          if ($subsys) {          if ($subs{$subsys}) {
3213                Trace("Subsystem found.") if T(4);
3214              # Insure this feature has an entry in the return hash.              # Insure this feature has an entry in the return hash.
3215              if (! exists $retVal{$fid}) { $retVal{$fid} = []; }              if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
3216              # Merge in this new data.              # Merge in this new data.
# Line 2977  Line 3223 
3223    
3224  =head3 RelatedFeatures  =head3 RelatedFeatures
3225    
3226  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>      my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID);
3227    
3228  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
3229  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 3010  Line 3256 
3256      # Get the parameters.      # Get the parameters.
3257      my ($self, $featureID, $function, $userID) = @_;      my ($self, $featureID, $function, $userID) = @_;
3258      # 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.
3259      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);      my $bbhData = FIGRules::BBHData($featureID);
3260        my @bbhFeatures = map { $_->[0] } @$bbhData;
3261      # 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
3262      # functional assignment.      # functional assignment.
3263      my @retVal = ();      my @retVal = ();
# Line 3028  Line 3275 
3275    
3276  =head3 TaxonomySort  =head3 TaxonomySort
3277    
3278  C<< my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs); >>      my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs);
3279    
3280  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
3281  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 3063  Line 3310 
3310          my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",          my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
3311                                          [$fid], 'Genome(taxonomy)');                                          [$fid], 'Genome(taxonomy)');
3312          # Add this feature to the hash buffer.          # Add this feature to the hash buffer.
3313          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);          push @{$hashBuffer{$taxonomy}}, $fid;
3314      }      }
3315      # Sort the keys and get the elements.      # Sort the keys and get the elements.
3316      my @retVal = ();      my @retVal = ();
# Line 3076  Line 3323 
3323    
3324  =head3 Protein  =head3 Protein
3325    
3326  C<< my $protein = Sprout::Protein($sequence, $table); >>      my $protein = Sprout::Protein($sequence, $table);
3327    
3328  Translate a DNA sequence into a protein sequence.  Translate a DNA sequence into a protein sequence.
3329    
# Line 3162  Line 3409 
3409    
3410  =head3 LoadInfo  =head3 LoadInfo
3411    
3412  C<< my ($dirName, @relNames) = $sprout->LoadInfo(); >>      my ($dirName, @relNames) = $sprout->LoadInfo();
3413    
3414  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
3415  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 3181  Line 3428 
3428      return @retVal;      return @retVal;
3429  }  }
3430    
3431    =head3 BBHMatrix
3432    
3433        my $bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets);
3434    
3435    Find all the bidirectional best hits for the features of a genome in a
3436    specified list of target genomes. The return value will be a hash mapping
3437    features in the original genome to their bidirectional best hits in the
3438    target genomes.
3439    
3440    =over 4
3441    
3442    =item genomeID
3443    
3444    ID of the genome whose features are to be examined for bidirectional best hits.
3445    
3446    =item cutoff
3447    
3448    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3449    
3450    =item targets
3451    
3452    List of target genomes. Only pairs originating in the original
3453    genome and landing in one of the target genomes will be returned.
3454    
3455    =item RETURN
3456    
3457    Returns a reference to a hash mapping each feature in the original genome
3458    to a sub-hash mapping its BBH pegs in the target genomes to their scores.
3459    
3460    =back
3461    
3462    =cut
3463    
3464    sub BBHMatrix {
3465        # Get the parameters.
3466        my ($self, $genomeID, $cutoff, @targets) = @_;
3467        # Declare the return variable.
3468        my %retVal = ();
3469        # Ask for the BBHs.
3470        my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets);
3471        Trace("Retrieved " . scalar(@bbhList) . " BBH results.") if T(3);
3472        # We now have a set of 4-tuples that we need to convert into a hash of hashes.
3473        for my $bbhData (@bbhList) {
3474            my ($peg1, $peg2, $score) = @{$bbhData};
3475            if (! exists $retVal{$peg1}) {
3476                $retVal{$peg1} = { $peg2 => $score };
3477            } else {
3478                $retVal{$peg1}->{$peg2} = $score;
3479            }
3480        }
3481        # Return the result.
3482        return \%retVal;
3483    }
3484    
3485    
3486    =head3 SimMatrix
3487    
3488        my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets);
3489    
3490    Find all the similarities for the features of a genome in a
3491    specified list of target genomes. The return value will be a hash mapping
3492    features in the original genome to their similarites in the
3493    target genomes.
3494    
3495    =over 4
3496    
3497    =item genomeID
3498    
3499    ID of the genome whose features are to be examined for similarities.
3500    
3501    =item cutoff
3502    
3503    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3504    
3505    =item targets
3506    
3507    List of target genomes. Only pairs originating in the original
3508    genome and landing in one of the target genomes will be returned.
3509    
3510    =item RETURN
3511    
3512    Returns a hash mapping each feature in the original genome to a hash mapping its
3513    similar pegs in the target genomes to their scores.
3514    
3515    =back
3516    
3517    =cut
3518    
3519    sub SimMatrix {
3520        # Get the parameters.
3521        my ($self, $genomeID, $cutoff, @targets) = @_;
3522        # Declare the return variable.
3523        my %retVal = ();
3524        # Get the list of features in the source organism.
3525        my @fids = $self->FeaturesOf($genomeID);
3526        # Ask for the sims. We only want similarities to fig features.
3527        my $simList = FIGRules::GetNetworkSims($self, \@fids, {}, 1000, $cutoff, "fig");
3528        if (! defined $simList) {
3529            Confess("Unable to retrieve similarities from server.");
3530        } else {
3531            Trace("Processing sims.") if T(3);
3532            # We now have a set of sims that we need to convert into a hash of hashes. First, we
3533            # Create a hash for the target genomes.
3534            my %targetHash = map { $_ => 1 } @targets;
3535            for my $simData (@{$simList}) {
3536                # Get the PEGs and the score.
3537                my ($peg1, $peg2, $score) = ($simData->id1, $simData->id2, $simData->psc);
3538                # Insure the second ID is in the target list.
3539                my ($genome2) = FIGRules::ParseFeatureID($peg2);
3540                if (exists $targetHash{$genome2}) {
3541                    # Here it is. Now we need to add it to the return hash. How we do that depends
3542                    # on whether or not $peg1 is new to us.
3543                    if (! exists $retVal{$peg1}) {
3544                        $retVal{$peg1} = { $peg2 => $score };
3545                    } else {
3546                        $retVal{$peg1}->{$peg2} = $score;
3547                    }
3548                }
3549            }
3550        }
3551        # Return the result.
3552        return %retVal;
3553    }
3554    
3555    
3556  =head3 LowBBHs  =head3 LowBBHs
3557    
3558  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>      my %bbhMap = $sprout->LowBBHs($featureID, $cutoff);
3559    
3560  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
3561  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 3213  Line 3585 
3585      # Create the return hash.      # Create the return hash.
3586      my %retVal = ();      my %retVal = ();
3587      # Query for the desired BBHs.      # Query for the desired BBHs.
3588      my @bbhList = FIGRules::BBHData($featureID, $cutoff);      my $bbhList = FIGRules::BBHData($featureID, $cutoff);
3589      # Form the results into the return hash.      # Form the results into the return hash.
3590      for my $pair (@bbhList) {      for my $pair (@$bbhList) {
3591          my $fid = $pair->[0];          my $fid = $pair->[0];
3592          if ($self->Exists('Feature', $fid)) {          if ($self->Exists('Feature', $fid)) {
3593              $retVal{$fid} = $pair->[1];              $retVal{$fid} = $pair->[1];
# Line 3227  Line 3599 
3599    
3600  =head3 Sims  =head3 Sims
3601    
3602  C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>      my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters);
3603    
3604  Get a list of similarities for a specified feature. Similarity information is not kept in the  Get a list of similarities for a specified feature. Similarity information is not kept in the
3605  Sprout database; rather, they are retrieved from a network server. The similarities are  Sprout database; rather, they are retrieved from a network server. The similarities are
# Line 3237  Line 3609 
3609  Similarities can be either raw or expanded. The raw similarities are basic  Similarities can be either raw or expanded. The raw similarities are basic
3610  hits between features with similar DNA. Expanding a raw similarity drags in any  hits between features with similar DNA. Expanding a raw similarity drags in any
3611  features considered substantially identical. So, for example, if features B<A1>,  features considered substantially identical. So, for example, if features B<A1>,
3612  B<A2>, and B<A3> are all substatially identical to B<A>, then a raw similarity  B<A2>, and B<A3> are all substantially identical to B<A>, then a raw similarity
3613  B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.  B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3614    
3615  =over 4  =over 4
3616    
3617  =item fid  =item fid
3618    
3619  ID of the feature whose similarities are desired.  ID of the feature whose similarities are desired, or reference to a list of IDs
3620    of features whose similarities are desired.
3621    
3622  =item maxN  =item maxN
3623    
# Line 3292  Line 3665 
3665    
3666  =head3 IsAllGenomes  =head3 IsAllGenomes
3667    
3668  C<< my $flag = $sprout->IsAllGenomes(\@list, \@checkList); >>      my $flag = $sprout->IsAllGenomes(\@list, \@checkList);
3669    
3670  Return TRUE if all genomes in the second list are represented in the first list at  Return TRUE if all genomes in the second list are represented in the first list at
3671  least one. Otherwise, return FALSE. If the second list is omitted, the first list is  least one. Otherwise, return FALSE. If the second list is omitted, the first list is
# Line 3341  Line 3714 
3714    
3715  =head3 GetGroups  =head3 GetGroups
3716    
3717  C<< my %groups = $sprout->GetGroups(\@groupList); >>      my %groups = $sprout->GetGroups(\@groupList);
3718    
3719  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.
3720  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 3373  Line 3746 
3746                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3747          # Loop through the genomes found.          # Loop through the genomes found.
3748          for my $genome (@genomes) {          for my $genome (@genomes) {
3749              # Pop this genome's ID off the current list.              # Get the genome ID and group, and add this genome to the group's list.
3750              my @groups = @{$genome};              my ($genomeID, $group) = @{$genome};
3751              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);  
             }  
3752          }          }
3753      }      }
3754      # Return the hash we just built.      # Return the hash we just built.
# Line 3389  Line 3757 
3757    
3758  =head3 MyGenomes  =head3 MyGenomes
3759    
3760  C<< my @genomes = Sprout::MyGenomes($dataDir); >>      my @genomes = Sprout::MyGenomes($dataDir);
3761    
3762  Return a list of the genomes to be included in the Sprout.  Return a list of the genomes to be included in the Sprout.
3763    
# Line 3421  Line 3789 
3789    
3790  =head3 LoadFileName  =head3 LoadFileName
3791    
3792  C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>      my $fileName = Sprout::LoadFileName($dataDir, $tableName);
3793    
3794  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
3795  directory.  directory.
# Line 3462  Line 3830 
3830    
3831  =head3 DeleteGenome  =head3 DeleteGenome
3832    
3833  C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>      my $stats = $sprout->DeleteGenome($genomeID, $testFlag);
3834    
3835  Delete a genome from the database.  Delete a genome from the database.
3836    
# Line 3488  Line 3856 
3856      # Get the parameters.      # Get the parameters.
3857      my ($self, $genomeID, $testFlag) = @_;      my ($self, $genomeID, $testFlag) = @_;
3858      # Perform the delete for the genome's features.      # Perform the delete for the genome's features.
3859      my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);      my $retVal = $self->Delete('Feature', "fig|$genomeID.%", testMode => $testFlag);
3860      # Perform the delete for the primary genome data.      # Perform the delete for the primary genome data.
3861      my $stats = $self->Delete('Genome', $genomeID, $testFlag);      my $stats = $self->Delete('Genome', $genomeID, testMode => $testFlag);
3862      $retVal->Accumulate($stats);      $retVal->Accumulate($stats);
3863      # Return the result.      # Return the result.
3864      return $retVal;      return $retVal;
# Line 3498  Line 3866 
3866    
3867  =head3 Fix  =head3 Fix
3868    
3869  C<< my %fixedHash = Sprout::Fix(%groupHash); >>      my %fixedHash = $sprout->Fix(%groupHash);
3870    
3871  Prepare a genome group hash (like that returned by L</GetGroups> for processing.  Prepare a genome group hash (like that returned by L</GetGroups>) for processing.
3872  Groups with the same primary name will be combined. The primary name is the  The groups will be combined into the appropriate super-groups.
 first capitalized word in the group name.  
3873    
3874  =over 4  =over 4
3875    
# Line 3520  Line 3887 
3887    
3888  sub Fix {  sub Fix {
3889      # Get the parameters.      # Get the parameters.
3890      my (%groupHash) = @_;      my ($self, %groupHash) = @_;
3891      # Create the result hash.      # Create the result hash.
3892      my %retVal = ();      my %retVal = ();
3893      # Copy over the genomes.      # Copy over the genomes.
3894      for my $groupID (keys %groupHash) {      for my $groupID (keys %groupHash) {
3895          # Make a safety copy of the group ID.          # Get the super-group name.
3896          my $realGroupID = $groupID;          my $realGroupID = $self->SuperGroup($groupID);
3897          # Yank the primary name.          # Append this group's genomes into the result hash
3898          if ($groupID =~ /([A-Z]\w+)/) {          # using the super-group name.
3899              $realGroupID = $1;          push @{$retVal{$realGroupID}}, @{$groupHash{$groupID}};
         }  
         # Append this group's genomes into the result hash.  
         Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}});  
3900      }      }
3901      # Return the result hash.      # Return the result hash.
3902      return %retVal;      return %retVal;
# Line 3540  Line 3904 
3904    
3905  =head3 GroupPageName  =head3 GroupPageName
3906    
3907  C<< my $name = $sprout->GroupPageName($group); >>      my $name = $sprout->GroupPageName($group);
3908    
3909  Return the name of the page for the specified NMPDR group.  Return the name of the page for the specified NMPDR group.
3910    
# Line 3562  Line 3926 
3926  sub GroupPageName {  sub GroupPageName {
3927      # Get the parameters.      # Get the parameters.
3928      my ($self, $group) = @_;      my ($self, $group) = @_;
     # Declare the return variable.  
     my $retVal;  
3929      # Check for the group file data.      # Check for the group file data.
3930      if (! defined $self->{groupHash}) {      my %superTable = $self->CheckGroupFile();
         # Read the group file.  
         my %groupData = Sprout::ReadGroupFile($self->{_options}->{dataDir} . "/groups.tbl");  
         # Store it in our object.  
         $self->{groupHash} = \%groupData;  
     }  
3931      # Compute the real group name.      # Compute the real group name.
3932      my $realGroup = $group;      my $realGroup = $self->SuperGroup($group);
3933      if ($group =~ /([A-Z]\w+)/) {      # Get the associated page name.
3934          $realGroup = $1;      my $retVal = "../content/$superTable{$realGroup}->{page}";
     }  
     # Return the page name.  
     $retVal = "../content/" . $self->{groupHash}->{$realGroup}->[1];  
3935      # Return the result.      # Return the result.
3936      return $retVal;      return $retVal;
3937  }  }
3938    
 =head3 ReadGroupFile  
3939    
3940  C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >>  =head3 AddProperty
3941    
3942        $sprout->AddProperty($featureID, $key, @values);
3943    
3944  Read in the data from the specified group file. The group file contains information  Add a new attribute value (Property) to a feature.
 about each of the NMPDR groups.  
3945    
3946  =over 4  =over 4
3947    
3948  =item name  =item peg
3949    
3950  Name of the group.  ID of the feature to which the attribute is to be added.
3951    
3952  =item page  =item key
3953    
3954  Name of the group's page on the web site (e.g. C<campy.php> for  Name of the attribute (key).
 Campylobacter)  
3955    
3956  =item genus  =item values
3957    
3958  Genus of the group  Values of the attribute.
3959    
3960  =item species  =back
3961    
3962  Species of the group, or an empty string if the group is for an entire  =cut
3963  genus. If the group contains more than one species, the species names  #: Return Type ;
3964  should be separated by commas.  sub AddProperty {
3965        # Get the parameters.
3966        my ($self, $featureID, $key, @values) = @_;
3967        # Add the property using the attached attributes object.
3968        $self->ca->AddAttribute($featureID, $key, @values);
3969    }
3970    
3971  =back  =head3 CheckGroupFile
3972    
3973  The parameters to this method are as follows      my %groupData = $sprout->CheckGroupFile();
3974    
3975    Get the group file hash. The group file hash describes the relationship
3976    between a group and the super-group to which it belongs for purposes of
3977    display. The super-group name is computed from the first capitalized word
3978    in the actual group name. For each super-group, the group file contains
3979    the page name and a list of the species expected to be in the group.
3980    Each species is specified by a genus and a species name. A species name
3981    of C<0> implies an entire genus.
3982    
3983    This method returns a hash from super-group names to a hash reference. Each
3984    resulting hash reference contains the following fields.
3985    
3986  =over 4  =over 4
3987    
3988  =item groupFile  =item page
3989    
3990  Name of the file containing the group data.  The super-group's web page in the NMPDR.
3991    
3992  =item RETURN  =item contents
3993    
3994  Returns a hash keyed on group name. The value of each hash  A list of 2-tuples, each containing a genus name followed by a species name
3995    (or 0, indicating all species). This list indicates which organisms belong
3996    in the super-group.
3997    
3998  =back  =back
3999    
4000  =cut  =cut
4001    
4002  sub ReadGroupFile {  sub CheckGroupFile {
4003      # Get the parameters.      # Get the parameters.
4004      my ($groupFileName) = @_;      my ($self) = @_;
4005      # Declare the return variable.      # Check to see if we already have this hash.
4006      my %retVal;      if (! defined $self->{groupHash}) {
4007            # We don't, so we need to read it in.
4008            my %groupHash;
4009      # Read the group file.      # Read the group file.
4010      my @groupLines = Tracer::GetFile($groupFileName);          my @groupLines = Tracer::GetFile("$FIG_Config::sproutData/groups.tbl");
4011            # Loop through the list of sort-of groups.
4012      for my $groupLine (@groupLines) {      for my $groupLine (@groupLines) {
4013          my ($name, $page, $genus, $species) = split(/\t/, $groupLine);              my ($name, $page, @contents) = split /\t/, $groupLine;
4014          $retVal{$name} = [$page, $genus, $species];              $groupHash{$name} = { page => $page,
4015                                      contents => [ map { [ split /\s*,\s*/, $_ ] } @contents ]
4016                                    };
4017            }
4018            # Save the hash.
4019            $self->{groupHash} = \%groupHash;
4020      }      }
4021      # Return the result.      # Return the result.
4022      return %retVal;      return %{$self->{groupHash}};
4023  }  }
4024    
4025  =head3 AddProperty  =head2 Virtual Methods
4026    
4027  C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>  =head3 CleanKeywords
4028    
4029  Add a new attribute value (Property) to a feature. In the SEED system, attributes can      my $cleanedString = $sprout->CleanKeywords($searchExpression);
4030  be added to almost any object. In Sprout, they can only be added to features. In  
4031  Sprout, attributes are implemented using I<properties>. A property represents a key/value  Clean up a search expression or keyword list. This involves converting the periods
4032  pair. If the particular key/value pair coming in is not already in the database, a new  in EC numbers to underscores, converting non-leading minus signs to underscores,
4033  B<Property> record is created to hold it.  a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
4034    characters. In addition, any extra spaces are removed.
4035    
4036  =over 4  =over 4
4037    
4038  =item peg  =item searchExpression
4039    
4040  ID of the feature to which the attribute is to be replied.  Search expression or keyword list to clean. Note that a search expression may
4041    contain boolean operators which need to be preserved. This includes leading
4042    minus signs.
4043    
4044  =item key  =item RETURN
4045    
4046  Name of the attribute (key).  Cleaned expression or keyword list.
4047    
4048  =item value  =back
4049    
4050    =cut
4051    
4052  Value of the attribute.  sub CleanKeywords {
4053        # Get the parameters.
4054        my ($self, $searchExpression) = @_;
4055        # Get the stemmer.
4056        my $stemmer = $self->GetStemmer();
4057        # Convert the search expression using the stemmer.
4058        my $retVal = $stemmer->PrepareSearchExpression($searchExpression);
4059        Trace("Cleaned keyword list for \"$searchExpression\" is \"$retVal\".") if T(3);
4060        # Return the result.
4061        return $retVal;
4062    }
4063    
4064  =item url  =head3 GetSourceObject
4065    
4066  URL or text citation from which the property was obtained.      my $source = $erdb->GetSourceObject();
4067    
4068  =back  Return the object to be used in creating load files for this database.
4069    
4070  =cut  =cut
4071  #: Return Type ;  
4072  sub AddProperty {  sub GetSourceObject {
4073      # Get the parameters.      # Get the parameters.
4074      my ($self, $featureID, $key, $value, $url) = @_;      my ($self) = @_;
4075      # Declare the variable to hold the desired property ID.      # Check to see if we already have a source object.
4076      my $propID;      my $retVal = $self->{_fig};
4077      # Attempt to find a property record for this key/value pair.      if (! defined $retVal) {
4078      my @properties = $self->GetFlat(['Property'],          # No, so create one.
4079                                     "Property(property-name) = ? AND Property(property-value) = ?",          require FIG;
4080                                     [$key, $value], 'Property(id)');          $retVal = FIG->new();
     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 });  
4081      }      }
4082      # Now we connect the incoming feature to the property.      # Return the object.
4083      $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });      return $retVal;
4084  }  }
4085    
4086  =head2 Virtual Methods  =head3 SectionList
4087    
4088  =head3 CleanKeywords      my @sections = $erdb->SectionList();
4089    
4090  C<< my $cleanedString = $sprout->CleanKeywords($searchExpression); >>  Return a list of the names for the different data sections used when loading this database.
4091    The default is a single string, in which case there is only one section representing the
4092    entire database.
4093    
4094  Clean up a search expression or keyword list. This involves converting the periods  =cut
4095  in EC numbers to underscores, converting non-leading minus signs to underscores,  
4096  a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic  sub SectionList {
4097  characters. In addition, any extra spaces are removed.      # Get the parameters.
4098        my ($self, $source) = @_;
4099        # Ask the BaseSproutLoader for a section list.
4100        require BaseSproutLoader;
4101        my @retVal = BaseSproutLoader::GetSectionList($self);
4102        # Return the list.
4103        return @retVal;
4104    }
4105    
4106    =head3 Loader
4107    
4108        my $groupLoader = $erdb->Loader($groupName, $options);
4109    
4110    Return an [[ERDBLoadGroupPm]] object for the specified load group. This method is used
4111    by [[ERDBGeneratorPl]] to create the load group objects. If you are not using
4112    [[ERDBGeneratorPl]], you don't need to override this method.
4113    
4114  =over 4  =over 4
4115    
4116  =item searchExpression  =item groupName
4117    
4118  Search expression or keyword list to clean. Note that a search expression may  Name of the load group whose object is to be returned. The group name is
4119  contain boolean operators which need to be preserved. This includes leading  guaranteed to be a single word with only the first letter capitalized.
4120  minus signs.  
4121    =item options
4122    
4123    Reference to a hash of command-line options.
4124    
4125  =item RETURN  =item RETURN
4126    
4127  Cleaned expression or keyword list.  Returns an [[ERDBLoadGroupPm]] object that can be used to process the specified load group
4128    for this database.
4129    
4130  =back  =back
4131    
4132  =cut  =cut
4133    
4134  sub CleanKeywords {  sub Loader {
4135      # Get the parameters.      # Get the parameters.
4136      my ($self, $searchExpression) = @_;      my ($self, $groupName, $options) = @_;
4137      # Perform the standard cleanup.      # Compute the loader name.
4138      my $retVal = $self->ERDB::CleanKeywords($searchExpression);      my $loaderClass = "${groupName}SproutLoader";
4139      # Fix the periods in EC and TC numbers.      # Pull in its definition.
4140      $retVal =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g;      require "$loaderClass.pm";
4141      # Fix non-trailing periods.      # Create an object for it.
4142      $retVal =~ s/\.(\w)/_$1/g;      my $retVal = eval("$loaderClass->new(\$self, \$options)");
4143      # Fix non-leading minus signs.      # Insure it worked.
4144      $retVal =~ s/(\w)[\-]/$1_/g;      Confess("Could not create $loaderClass object: $@") if $@;
4145      # Fix the vertical bars and colons      # Return it to the caller.
     $retVal =~ s/(\w)[|:](\w)/$1'$2/g;  
     # Return the result.  
4146      return $retVal;      return $retVal;
4147  }  }
4148    
4149    
4150    =head3 LoadGroupList
4151    
4152        my @groups = $erdb->LoadGroupList();
4153    
4154    Returns a list of the names for this database's load groups. This method is used
4155    by [[ERDBGeneratorPl]] when the user wishes to load all table groups. The default
4156    is a single group called 'All' that loads everything.
4157    
4158    =cut
4159    
4160    sub LoadGroupList {
4161        # Return the list.
4162        return qw(Genome Subsystem Annotation Property Source Reaction Synonym Feature Drug);
4163    }
4164    
4165    =head3 LoadDirectory
4166    
4167        my $dirName = $erdb->LoadDirectory();
4168    
4169    Return the name of the directory in which load files are kept. The default is
4170    the FIG temporary directory, which is a really bad choice, but it's always there.
4171    
4172    =cut
4173    
4174    sub LoadDirectory {
4175        # Get the parameters.
4176        my ($self) = @_;
4177        # Return the directory name.
4178        return $self->{dataDir};
4179    }
4180    
4181  =head2 Internal Utility Methods  =head2 Internal Utility Methods
4182    
4183    =head3 GetStemmer
4184    
4185        my $stermmer = $sprout->GetStemmer();
4186    
4187    Return the stemmer object for this database.
4188    
4189    =cut
4190    
4191    sub GetStemmer {
4192        # Get the parameters.
4193        my ($self) = @_;
4194        # Declare the return variable.
4195        my $retVal = $self->{stemmer};
4196        if (! defined $retVal) {
4197            # We don't have one pre-built, so we build and save it now.
4198            $retVal = BioWords->new(exceptions => "$FIG_Config::sproutData/Exceptions.txt",
4199                                     stops => "$FIG_Config::sproutData/StopWords.txt",
4200                                     cache => 0);
4201            $self->{stemmer} = $retVal;
4202        }
4203        # Return the result.
4204        return $retVal;
4205    }
4206    
4207  =head3 ParseAssignment  =head3 ParseAssignment
4208    
4209  Parse annotation text to determine whether or not it is a functional assignment. If it is,  Parse annotation text to determine whether or not it is a functional assignment. If it is,
# Line 3754  Line 4212 
4212    
4213  A functional assignment is always of the form  A functional assignment is always of the form
4214    
4215      C<set >I<YYYY>C< function to\n>I<ZZZZZ>      set YYYY function to
4216        ZZZZ
4217    
4218  where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,  where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
4219  the user and the assigning user (from MadeAnnotation) will be the same, but that is  the user and the assigning user (from MadeAnnotation) will be the same, but that is
# Line 3807  Line 4266 
4266      return @retVal;      return @retVal;
4267  }  }
4268    
4269    =head3 _CheckFeature
4270    
4271        my $flag = $sprout->_CheckFeature($fid);
4272    
4273    Return TRUE if the specified FID is probably an NMPDR feature ID, else FALSE.
4274    
4275    =over 4
4276    
4277    =item fid
4278    
4279    Feature ID to check.
4280    
4281    =item RETURN
4282    
4283    Returns TRUE if the FID is for one of the NMPDR genomes, else FALSE.
4284    
4285    =back
4286    
4287    =cut
4288    
4289    sub _CheckFeature {
4290        # Get the parameters.
4291        my ($self, $fid) = @_;
4292        # Insure we have a genome hash.
4293        my $genomes = $self->_GenomeHash();
4294        # Get the feature's genome ID.
4295        my ($genomeID) = FIGRules::ParseFeatureID($fid);
4296        # Return an indicator of whether or not the genome ID is in the hash.
4297        return ($self->{genomeHash}->{$genomeID} ? 1 : 0);
4298    }
4299    
4300  =head3 FriendlyTimestamp  =head3 FriendlyTimestamp
4301    
4302  Convert a time number to a user-friendly time stamp for display.  Convert a time number to a user-friendly time stamp for display.
# Line 3834  Line 4324 
4324  }  }
4325    
4326    
4327    =head3 Hint
4328    
4329        my $htmlText = SearchHelper::Hint($wikiPage, $hintText);
4330    
4331    Return the HTML for a small question mark that displays the specified hint text when it is clicked.
4332    This HTML can be put in forms to provide a useful hinting mechanism.
4333    
4334    =over 4
4335    
4336    =item wikiPage
4337    
4338    Name of the wiki page to be popped up when the hint mark is clicked.
4339    
4340    =item hintText
4341    
4342    Text to display for the hint. It is raw html, but may not contain any double quotes.
4343    
4344    =item RETURN
4345    
4346    Returns the html for the hint facility. The resulting html shows a small button-like thing that
4347    uses the standard FIG popup technology.
4348    
4349    =back
4350    
4351    =cut
4352    
4353    sub Hint {
4354        # Get the parameters.
4355        my ($wikiPage, $hintText) = @_;
4356        # Escape the single quotes in the hint text.
4357        my $quotedText = $hintText;
4358        $quotedText =~ s/'/\\'/g;
4359        # Convert the wiki page name to a URL.
4360        my $wikiURL = join("", map { ucfirst $_ } split /\s+/, $wikiPage);
4361        $wikiURL = "$FIG_Config::cgi_url/wiki/view.cgi/FIG/$wikiURL";
4362        # Compute the mouseover script.
4363        my $mouseOver = "doTooltip(this, '$quotedText')";
4364        # Create the html.
4365        my $retVal = "&nbsp;<a href=\"$wikiURL\"><img src=\"$FIG_Config::cgi_url/Html/button-h.png\" class=\"helpicon\" onmouseover=\"$mouseOver\"/></a>";
4366        # Return it.
4367        return $retVal;
4368    }
4369    
4370    =head3 _GenomeHash
4371    
4372        my $gHash = $sprout->_GenomeHash();
4373    
4374    Return a hash mapping all NMPDR genome IDs to [[ERDBObjectPm]] genome objects.
4375    
4376    =cut
4377    
4378    sub _GenomeHash {
4379        # Get the parameters.
4380        my ($self) = @_;
4381        # Do we already have a filled hash?
4382        if (! $self->{genomeHashFilled}) {
4383            # No, create it.
4384            my %gHash = map { $_->PrimaryValue('id') => $_ } $self->GetList("Genome", "", []);
4385            $self->{genomeHash} = \%gHash;
4386            # Denote we have it.
4387            $self->{genomeHashFilled} = 1;
4388        }
4389        # Return the hash.
4390        return $self->{genomeHash};
4391    }
4392    
4393    =head3 _GenomeData
4394    
4395        my $genomeData = $sprout->_GenomeData($genomeID);
4396    
4397    Return an [[ERDBObjectPm]] object for the specified genome, or an undefined
4398    value if the genome does not exist.
4399    
4400    =over 4
4401    
4402    =item genomeID
4403    
4404    ID of the desired genome.
4405    
4406    =item RETURN
4407    
4408    Returns either an [[ERDBObjectPm]] containing the genome, or an undefined value.
4409    If the genome exists, it will have been read into the genome cache.
4410    
4411    =back
4412    
4413    =cut
4414    
4415    sub _GenomeData {
4416        # Get the parameters.
4417        my ($self, $genomeID) = @_;
4418        # Are we in the genome hash?
4419        if (! exists $self->{genomeHash}->{$genomeID} && ! $self->{genomeHashFilled}) {
4420            # The genome isn't in the hash, and the hash is not complete, so we try to
4421            # read it.
4422            $self->{genomeHash}->{$genomeID} = $self->GetEntity(Genome => $genomeID);
4423        }
4424        # Return the result.
4425        return $self->{genomeHash}->{$genomeID};
4426    }
4427    
4428    =head3 _CacheGenome
4429    
4430        $sprout->_CacheGenome($genomeID, $genomeData);
4431    
4432    Store the specified genome object in the genome cache if it is already there.
4433    
4434    =over 4
4435    
4436    =item genomeID
4437    
4438    ID of the genome to store in the cache.
4439    
4440    =item genomeData
4441    
4442    An [[ERDBObjectPm]] containing at least the data for the specified genome.
4443    Note that the Genome may not be the primary object in it, so a fully-qualified
4444    field name has to be used to retrieve data from it.
4445    
4446    =back
4447    
4448    =cut
4449    
4450    sub _CacheGenome {
4451        # Get the parameters.
4452        my ($self, $genomeID, $genomeData) = @_;
4453        # Only proceed if we don't already have the genome.
4454        if (! exists $self->{genomeHash}->{$genomeID}) {
4455            $self->{genomeHash}->{$genomeID} = $genomeData;
4456        }
4457    }
4458    
4459  1;  1;

Legend:
Removed from v.1.94  
changed lines
  Added in v.1.124

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3