[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.99, Fri Apr 27 22:21:46 2007 UTC revision 1.128, Tue Jun 30 19:53:01 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;
5      use DBKernel;      use DBKernel;
6      use XML::Simple;      use XML::Simple;
7      use DBQuery;      use ERDBQuery;
8      use ERDBObject;      use ERDBObject;
9      use Tracer;      use Tracer;
10      use FIGRules;      use FIGRules;
# Line 17  Line 14 
14      use BasicLocation;      use BasicLocation;
15      use CustomAttributes;      use CustomAttributes;
16      use RemoteCustomAttributes;      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 29  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(%parms)
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 incoming parameter hash has the following permissible
52  database.  members (others will be ignored without error.
53    
54  =over 4  =over 4
55    
56    =item DBD
57    
58    Name of the XML file containing the database definition (default C<SproutDBD.xml> in
59    the DBD directory).
60    
61  =item dbName  =item dbName
62    
63  Name of the database.  Name of the database. If omitted, the default Sprout database name is used.
64    
65  =item options  =item options
66    
67  Table of options.  Sub-hash of special options.
68    
69  * B<dbType> type of database (currently C<mysql> for MySQL and C<pg> for PostgreSQL) (default C<mysql>)  * B<dbType> type of database (currently C<mysql> for MySQL and C<pg> for PostgreSQL) (default C<mysql>)
70    
71  * B<dataDir> directory containing the database definition file and the flat files used to load the data (default C<Data>)  * B<dataDir> directory containing the database definition file and the flat files used to load the data (default C<Data>)
72    
 * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)  
   
73  * B<userData> user name and password, delimited by a slash (default same as SEED)  * B<userData> user name and password, delimited by a slash (default same as SEED)
74    
75  * B<port> connection port (default C<0>)  * B<port> connection port (default C<0>)
# Line 80  Line 82 
82    
83  * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE  * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
84    
85    * B<host> name of the database host
86    
87  =back  =back
88    
89  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
90  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
91  F</usr/fig/SproutData>.  F</usr/fig/SproutData>.
92    
93  C<< my $sprout = Sprout->new('Sprout', { userData =>; 'fig/admin', dataDir => '/usr/fig/SproutData' }); >>      my $sprout = Sprout->new(dbName => 'Sprout', options => { userData => 'fig/admin', dataDir => '/usr/fig/SproutData' });
94    
95    The odd constructor signature is a result of Sprout's status as the first ERDB database,
96    and the need to make it compatible with the needs of its younger siblings.
97    
98  =cut  =cut
99    
100  sub new {  sub new {
101      # Get the parameters.      # Get the parameters.
102      my ($class, $dbName, $options) = @_;      my ($class, %parms) = @_;
103        # Look for an options hash.
104        my $options = $parms{options} || {};
105        # Plug in the DBD and name parameters.
106        if ($parms{DBD}) {
107            $options->{xmlFileName} = $parms{DBD};
108        }
109        my $dbName = $parms{dbName} || $FIG_Config::sproutDB;
110      # Compute the DBD directory.      # Compute the DBD directory.
111      my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :      my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
112                                                    $FIG_Config::fig );                                                    $FIG_Config::fig );
# Line 105  Line 119 
119                                                          # data file directory                                                          # data file directory
120                         xmlFileName  => "$dbd_dir/SproutDBD.xml",                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
121                                                          # database definition file name                                                          # database definition file name
122                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",                         userData     => "$FIG_Config::sproutUser/$FIG_Config::sproutPass",
123                                                          # user name and password                                                          # user name and password
124                         port         => $FIG_Config::dbport,                         port         => $FIG_Config::sproutPort,
125                                                          # database connection port                                                          # database connection port
126                         sock         => $FIG_Config::dbsock,                         sock         => $FIG_Config::sproutSock,
127                         host         => $FIG_Config::dbhost,                         host         => $FIG_Config::sprout_host,
128                         maxSegmentLength => 4500,        # maximum feature segment length                         maxSegmentLength => 4500,        # maximum feature segment length
129                         maxSequenceLength => 8000,       # maximum contig sequence length                         maxSequenceLength => 8000,       # maximum contig sequence length
130                         noDBOpen     => 0,               # 1 to suppress the database open                         noDBOpen     => 0,               # 1 to suppress the database open
131                           demandDriven => 0,               # 1 for forward-only queries
132                        }, $options);                        }, $options);
133      # Get the data directory.      # Get the data directory.
134      my $dataDir = $optionTable->{dataDir};      my $dataDir = $optionTable->{dataDir};
# Line 123  Line 138 
138      # Connect to the database.      # Connect to the database.
139      my $dbh;      my $dbh;
140      if (! $optionTable->{noDBOpen}) {      if (! $optionTable->{noDBOpen}) {
141            Trace("Connect data: host = $optionTable->{host}, port = $optionTable->{port}.") if T(3);
142          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
143                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
144      }      }
145      # Create the ERDB object.      # Create the ERDB object.
146      my $xmlFileName = "$optionTable->{xmlFileName}";      my $xmlFileName = "$optionTable->{xmlFileName}";
147      my $retVal = ERDB::new($class, $dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName, %$optionTable);
148      # Add the option table and XML file name.      # Add the option table and XML file name.
149      $retVal->{_options} = $optionTable;      $retVal->{_options} = $optionTable;
150      $retVal->{_xmlName} = $xmlFileName;      $retVal->{_xmlName} = $xmlFileName;
151      # Set up space for the group file data.      # Set up space for the group file data.
152      $retVal->{groupHash} = undef;      $retVal->{groupHash} = undef;
153      # Connect to the attributes.      # Set up space for the genome hash. We use this to identify NMPDR genomes
154        # and remember genome data.
155        $retVal->{genomeHash} = {};
156        $retVal->{genomeHashFilled} = 0;
157        # Remember the data directory name.
158        $retVal->{dataDir} = $dataDir;
159        # Return it.
160        return $retVal;
161    }
162    
163    =head3 ca
164    
165        my $ca = $sprout->ca():;
166    
167    Return the [[CustomAttributesPm]] object for retrieving object
168    properties.
169    
170    =cut
171    
172    sub ca {
173        # Get the parameters.
174        my ($self) = @_;
175        # Do we already have an attribute object?
176        my $retVal = $self->{_ca};
177        if (! defined $retVal) {
178            # No, create one. How we do it depends on the configuration.
179      if ($FIG_Config::attrURL) {      if ($FIG_Config::attrURL) {
180          Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);          Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);
181          $retVal->{_ca} = RemoteCustomAttributes->new($FIG_Config::attrURL);              $retVal = RemoteCustomAttributes->new($FIG_Config::attrURL);
182      } elsif ($FIG_Config::attrDbName) {      } elsif ($FIG_Config::attrDbName) {
183          Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);          Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);
184          my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));          my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));
185          $retVal->{_ca} = CustomAttributes->new(user => $user);              $retVal = CustomAttributes->new(user => $user);
186      }      }
187      # Return it.          # Save it for next time.
188            $self->{_ca} = $retVal;
189        }
190        # Return the result.
191        return $retVal;
192    }
193    
194    =head3 CoreGenomes
195    
196        my @genomes = $sprout->CoreGenomes($scope);
197    
198    Return the IDs of NMPDR genomes in the specified scope.
199    
200    =over 4
201    
202    =item scope
203    
204    Scope of the desired genomes. C<core> covers the original core genomes,
205    C<nmpdr> covers all genomes in NMPDR groups, and C<all> covers all
206    genomes in the system.
207    
208    =item RETURN
209    
210    Returns a list of the IDs for the genomes in the specified scope.
211    
212    =back
213    
214    =cut
215    
216    sub CoreGenomes {
217        # Get the parameters.
218        my ($self, $scope) = @_;
219        # Declare the return variable.
220        my @retVal = ();
221        # If we want all genomes, then this is easy.
222        if ($scope eq 'all') {
223            @retVal = $self->Genomes();
224        } else {
225            # Here we're dealing with groups. Get the hash of all the
226            # genome groups.
227            my %groups = $self->GetGroups();
228            # Loop through the groups, keeping the ones that we want.
229            for my $group (keys %groups) {
230                # Decide if we want to keep this group.
231                my $keepGroup = 0;
232                if ($scope eq 'nmpdr') {
233                    # NMPDR mode: keep all groups.
234                    $keepGroup = 1;
235                } elsif ($scope eq 'core') {
236                    # CORE mode. Only keep real core groups.
237                    if (grep { $group =~ /$_/ } @{$FIG_Config::realCoreGroups}) {
238                        $keepGroup = 1;
239                    }
240                }
241                # Add this group if we're keeping it.
242                if ($keepGroup) {
243                    push @retVal, @{$groups{$group}};
244                }
245            }
246        }
247        # Return the result.
248        return @retVal;
249    }
250    
251    =head3 SuperGroup
252    
253        my $superGroup = $sprout->SuperGroup($groupName);
254    
255    Return the name of the super-group containing the specified NMPDR genome
256    group. If no appropriate super-group can be found, an error will be
257    thrown.
258    
259    =over 4
260    
261    =item groupName
262    
263    Name of the group whose super-group is desired.
264    
265    =item RETURN
266    
267    Returns the name of the super-group containing the incoming group.
268    
269    =back
270    
271    =cut
272    
273    sub SuperGroup {
274        # Get the parameters.
275        my ($self, $groupName) = @_;
276        # Declare the return variable.
277        my $retVal;
278        # Get the group hash.
279        my %groupHash = $self->CheckGroupFile();
280        # Find the super-group genus.
281        $groupName =~ /([A-Z]\w+)/;
282        my $nameThing = $1;
283        # See if it's directly in the group hash.
284        if (exists $groupHash{$nameThing}) {
285            # Yes, then it's our result.
286            $retVal = $nameThing;
287        } else {
288            # No, so we have to search.
289            for my $superGroup (keys %groupHash) {
290                # Get this super-group's item list.
291                my $list = $groupHash{$superGroup}->{contents};
292                # Search it.
293                if (grep { $_->[0] eq $nameThing } @{$list}) {
294                    $retVal = $superGroup;
295                }
296            }
297        }
298        # Return the result.
299      return $retVal;      return $retVal;
300  }  }
301    
302  =head3 MaxSegment  =head3 MaxSegment
303    
304  C<< my $length = $sprout->MaxSegment(); >>      my $length = $sprout->MaxSegment();
305    
306  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
307  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 166  Line 318 
318    
319  =head3 MaxSequence  =head3 MaxSequence
320    
321  C<< my $length = $sprout->MaxSequence(); >>      my $length = $sprout->MaxSequence();
322    
323  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
324  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 181  Line 333 
333    
334  =head3 Load  =head3 Load
335    
336  C<< $sprout->Load($rebuild); >>;      $sprout->Load($rebuild);;
337    
338  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.
339    
# Line 193  Line 345 
345  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
346  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
347  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
348  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.
349    
350  =over 4  =over 4
351    
# Line 221  Line 373 
373    
374  =head3 LoadUpdate  =head3 LoadUpdate
375    
376  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>      my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList);
377    
378  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
379  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 267  Line 419 
419              Trace("No load file found for $tableName in $dataDir.") if T(0);              Trace("No load file found for $tableName in $dataDir.") if T(0);
420          } else {          } else {
421              # Attempt to load this table.              # Attempt to load this table.
422              my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);              my $result = $self->LoadTable($fileName, $tableName, truncate => $truncateFlag);
423              # Accumulate the resulting statistics.              # Accumulate the resulting statistics.
424              $retVal->Accumulate($result);              $retVal->Accumulate($result);
425          }          }
# Line 278  Line 430 
430    
431  =head3 GenomeCounts  =head3 GenomeCounts
432    
433  C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>      my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete);
434    
435  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
436  genomes will be included in the counts.  genomes will be included in the counts.
# Line 323  Line 475 
475    
476  =head3 ContigCount  =head3 ContigCount
477    
478  C<< my $count = $sprout->ContigCount($genomeID); >>      my $count = $sprout->ContigCount($genomeID);
479    
480  Return the number of contigs for the specified genome ID.  Return the number of contigs for the specified genome ID.
481    
# Line 350  Line 502 
502      return $retVal;      return $retVal;
503  }  }
504    
505  =head3 GeneMenu  =head3 GenomeMenu
506    
507  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected); >>      my $html = $sprout->GenomeMenu(%options);
508    
509  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.
510  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
511  value will be the genome ID. The genomes will be sorted by genus/species name.  B<SearchHelper> class. Eventually, the two will be combined.
512    
513  =over 4  =over 4
514    
515  =item attributes  =item options
516    
517    Optional parameters for the control (see below).
518    
519    =item RETURN
520    
521    Returns the HTML for a genome selection control on a form (sometimes called a popup menu).
522    
523  Reference to a hash mapping attributes to values for the SELECT tag generated.  =back
524    
525  =item filterString  The valid options are as follows.
526    
527  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.  
528    
529  =item params  =item name
530    
531  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>.
532  the filter string.  Terrible things will happen if you have two controls with the same name on the same page.
533    
534  =item selected (optional)  =item filter
535    
536  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
537    list reference, a string, or a hash reference. If it is a list reference, the first element
538    of the list should be the filter string, and the remaining elements the filter parameters. If it is a
539    string, it will be split into a list at each included tab. If it is a hash reference, it should be
540    a hash that maps genomes which should be included to a TRUE value.
541    
542  =item fast (optional)  =item multiSelect
543    
544  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.
545    
546  =item RETURN  =item size
547    
548  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>
549    
550    =item id
551    
552    ID to give this control. The default is the value of the C<name> option. Nothing will work correctly
553    unless this ID is unique.
554    
555    =item selected
556    
557    A comma-delimited list of selected genomes, or a reference to a list of selected genomes. The
558    default is none.
559    
560    =item class
561    
562    If specified, a style class to assign to the genome control.
563    
564  =back  =back
565    
566  =cut  =cut
567    
568  sub GeneMenu {  sub GenomeMenu {
569      # Get the parameters.      # Get the parameters.
570      my ($self, $attributes, $filterString, $params, $selected, $fast) = @_;      my ($self, %options) = @_;
571      my $slowMode = ! $fast;      # Get the control's name and ID.
572      # Default to nothing selected. This prevents an execution warning if "$selected"      my $menuName = $options{name} || $options{id} || 'myGenomeControl';
573      # is undefined.      my $menuID = $options{id} || $menuName;
574      $selected = "" unless defined $selected;      Trace("Genome menu name = $menuName with ID $menuID.") if T(3);
575      Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3);      # Compute the IDs for the status display.
576      # Start the menu.      my $divID = "${menuID}_status";
577      my $retVal = "<select " .      my $urlID = "${menuID}_url";
578          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .      # Compute the code to show selected genomes in the status area.
579          ">\n";      my $showSelect = "showSelected('$menuID', '$divID', '$urlID', $FIG_Config::genome_control_cap)";
580      # Get the genomes.      # Check for single-select or multi-select.
581      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',      my $multiSelect = $options{multiSelect} || 0;
582                                                                       'Genome(genus)',      # Get the style data.
583                                                                       'Genome(species)',      my $class = $options{class} || '';
584                                                                       'Genome(unique-characterization)']);      # Get the list of pre-selected items.
585      # Sort them by name.      my $selections = $options{selected} || [];
586      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;      if (ref $selections ne 'ARRAY') {
587      # Loop through the genomes, creating the option tags.          $selections = [ split /\s*,\s*/, $selections ];
588      for my $genomeData (@sorted) {      }
589          # Get the data for this genome.      my %selected = map { $_ => 1 } @{$selections};
590          my ($genomeID, $genus, $species, $strain) = @{$genomeData};      # Extract the filter information. The default is no filtering. It can be passed as a tab-delimited
591          # Get the contig count.      # string, a hash reference, or a list reference.
592          my $contigInfo = "";      my ($filterHash, $filterString);
593          if ($slowMode) {      my $filterParms = $options{filter} || "";
594              my $count = $self->ContigCount($genomeID);      if (ref $filterParms eq 'HASH') {
595              my $counting = ($count == 1 ? "contig" : "contigs");          $filterHash = $filterParms;
596              $contigInfo = "[$count $counting]";          $filterParms = [];
597          }          $filterString = "";
598          # Find out if we're selected.      } else {
599          my $selectOption = ($selected eq $genomeID ? " selected" : "");          if (! ref $filterParms) {
600          # Build the option tag.              $filterParms = [split /\t|\\t/, $filterParms];
601          $retVal .= "<option value=\"$genomeID\"$selectOption>$genus $species $strain ($genomeID)$contigInfo</option>\n";          }
602            $filterString = shift @{$filterParms};
603        }
604        # Check for possible subsystem filtering. If there is one, we will tack the
605        # relationship onto the object name list.
606        my @objectNames = qw(Genome);
607        if ($filterString =~ /ParticipatesIn\(/) {
608            push @objectNames, 'ParticipatesIn';
609        }
610        # Get a list of all the genomes in group order. In fact, we only need them ordered
611        # by name (genus,species,strain), but putting primary-group in front enables us to
612        # take advantage of an existing index.
613        my @genomeList = $self->GetAll(\@objectNames, "$filterString ORDER BY Genome(primary-group), Genome(genus), Genome(species), Genome(unique-characterization)",
614                                       $filterParms,
615                                       [qw(Genome(primary-group) Genome(id) Genome(genus) Genome(species) Genome(unique-characterization) Genome(taxonomy) Genome(contigs))]);
616        # Apply the hash filter (if any).
617        if (defined $filterHash) {
618            @genomeList = grep { $filterHash->{$_->[1]} } @genomeList;
619        }
620        # Create a hash to organize the genomes by group. Each group will contain a list of
621        # 2-tuples, the first element being the genome ID and the second being the genome
622        # name.
623        my %gHash = ();
624        for my $genome (@genomeList) {
625            # Get the genome data.
626            my ($group, $genomeID, $genus, $species, $strain, $taxonomy, $contigs) = @{$genome};
627            # Compute its name. This is the genus, species, strain (if any), and the contig count.
628            my $name = "$genus $species ";
629            $name .= "$strain " if $strain;
630            my $contigCount = ($contigs == 1 ? "" : ", $contigs contigs");
631            # Now we get the domain. The domain tells us the display style of the organism.
632            my ($domain) = split /\s*;\s*/, $taxonomy, 2;
633            # Now compute the display group. This is normally the primary group, but if the
634            # organism is supporting, we blank it out.
635            my $displayGroup = ($group eq $FIG_Config::otherGroup ? "" : $group);
636            # Push the genome into the group's list. Note that we use the real group
637            # name for the hash key here, not the display group name.
638            push @{$gHash{$group}}, [$genomeID, $name, $contigCount, $domain];
639        }
640        # We are almost ready to unroll the menu out of the group hash. The final step is to separate
641        # the supporting genomes by domain. First, we extract the NMPDR groups and sort them. They
642        # are sorted by the first capitalized word. Groups with "other" are sorted after groups
643        # that aren't "other". At some point, we will want to make this less complicated.
644        my %sortGroups = map { $_ =~ /(other)?(.*)([A-Z].+)/; "$3$1$2" => $_ }
645                             grep { $_ ne $FIG_Config::otherGroup } keys %gHash;
646        my @groups = map { $sortGroups{$_} } sort keys %sortGroups;
647        # Remember the number of NMPDR groups.
648        my $nmpdrGroupCount = scalar @groups;
649        # Are there any supporting genomes?
650        if (exists $gHash{$FIG_Config::otherGroup}) {
651            # Loop through the supporting genomes, classifying them by domain. We'll also keep a list
652            # of the domains found.
653            my @otherGenomes = @{$gHash{$FIG_Config::otherGroup}};
654            my @domains = ();
655            for my $genomeData (@otherGenomes) {
656                my ($genomeID, $name, $contigCount, $domain) = @{$genomeData};
657                if (exists $gHash{$domain}) {
658                    push @{$gHash{$domain}}, $genomeData;
659                } else {
660                    $gHash{$domain} = [$genomeData];
661                    push @domains, $domain;
662                }
663            }
664            # Add the domain groups at the end of the main group list. The main group list will now
665            # contain all the categories we need to display the genomes.
666            push @groups, sort @domains;
667            # Delete the supporting group.
668            delete $gHash{$FIG_Config::otherGroup};
669        }
670        # Now it gets complicated. We need a way to mark all the NMPDR genomes. We take advantage
671        # of the fact they come first in the list. We'll accumulate a count of the NMPDR genomes
672        # and use that to make the selections.
673        my $nmpdrCount = 0;
674        # Create the type counters.
675        my $groupCount = 1;
676        # Get the number of rows to display.
677        my $rows = $options{size} || 10;
678        # If we're multi-row, create an onChange event.
679        my $onChangeTag = ( $rows > 1 ? " onChange=\"$showSelect;\" onFocus=\"$showSelect;\"" : "" );
680        # Set up the multiple-select flag.
681        my $multipleTag = ($multiSelect ? " multiple" : "" );
682        # Set up the style class.
683        my $classTag = ($class ? " $class" : "" );
684        # Create the SELECT tag and stuff it into the output array.
685        my @lines = qq(<SELECT name="$menuName" id="$menuID" class="genomeSelect $class" $onChangeTag$multipleTag$classTag size="$rows">);
686        # Loop through the groups.
687        for my $group (@groups) {
688            # Get the genomes in the group.
689            for my $genome (@{$gHash{$group}}) {
690                # If this is an NMPDR organism, we add an extra style and count it.
691                my $nmpdrStyle = "";
692                if ($nmpdrGroupCount > 0) {
693                    $nmpdrCount++;
694                    $nmpdrStyle = " Core";
695                }
696                # Get the organism ID, name, contig count, and domain.
697                my ($genomeID, $name, $contigCount, $domain) = @{$genome};
698                # See if we're pre-selected.
699                my $selectTag = ($selected{$genomeID} ? " SELECTED" : "");
700                # Compute the display name.
701                my $nameString = "$name ($genomeID$contigCount)";
702                # Generate the option tag.
703                my $optionTag = "<OPTION class=\"$domain$nmpdrStyle\" title=\"$group\" value=\"$genomeID\"$selectTag>$nameString</OPTION>";
704                push @lines, "    $optionTag";
705            }
706            # Record this group in the nmpdrGroup count. When that gets to 0, we've finished the NMPDR
707            # groups.
708            $nmpdrGroupCount--;
709      }      }
710      # Close the SELECT tag.      # Close the SELECT tag.
711      $retVal .= "</select>\n";      push @lines, "</SELECT>";
712        if ($rows > 1) {
713            # We're in a non-compact mode, so we need to add some selection helpers. First is
714            # the search box. This allows the user to type text and change which genomes are
715            # displayed. For multiple-select mode, we include a button that selects the displayed
716            # genes. For single-select mode, we use a plain label instead.
717            my $searchThingName = "${menuID}_SearchThing";
718            my $searchThingLabel = "Type to narrow selection";
719            my $searchThingButton = "";
720            if ($multiSelect) {
721                $searchThingButton = qq(<INPUT type="button" name="MacroSearch" class="button" value="Go" onClick="selectShowing('$menuID', '$searchThingName'); $showSelect;" />);
722            }
723            push @lines, "<br />$searchThingLabel&nbsp;" .
724                         qq(<INPUT type="text" id="$searchThingName" name="$searchThingName" class="genomeSearchThing" onKeyup="showTyped('$menuID', '$searchThingName');" />) .
725                         $searchThingButton .
726                         Hint("GenomeControl", 28) . "<br />";
727            # For multi-select mode, we also have buttons to set and clear selections.
728            if ($multiSelect) {
729                push @lines, qq(<INPUT type="button" name="ClearAll" class="bigButton genomeButton" value="Clear All" onClick="clearAll(getElementById('$menuID')); $showSelect" />);
730                push @lines, qq(<INPUT type="button" name="SelectAll" class="bigButton genomeButton" value="Select All" onClick="selectAll(getElementById('$menuID')); $showSelect" />);
731                push @lines, qq(<INPUT type="button" name="NMPDROnly" class="bigButton genomeButton" value="Select NMPDR" onClick="selectSome(getElementById('$menuID'), $nmpdrCount, true); $showSelect;" />);
732            }
733            # Add a hidden field we can use to generate organism page hyperlinks.
734            push @lines, qq(<INPUT type="hidden" id="$urlID" value="$FIG_Config::cgi_url/wiki/rest.cgi/NmpdrPlugin/SeedViewer?page=Organism;organism=" />);
735            # Add the status display. This tells the user what's selected no matter where the list is scrolled.
736            push @lines, qq(<DIV id="$divID" class="Panel"></DIV>);
737        }
738        # Assemble all the lines into a string.
739        my $retVal = join("\n", @lines, "");
740        # Return the result.
741        return $retVal;
742    }
743    
744    =head3 Cleanup
745    
746        $sprout->Cleanup();
747    
748    Release the internal cache structures to free up memory.
749    
750    =cut
751    
752    sub Cleanup {
753        # Get the parameters.
754        my ($self) = @_;
755        # Delete the stemmer.
756        delete $self->{stemmer};
757        # Delete the attribute database.
758        delete $self->{_ca};
759        # Delete the group hash.
760        delete $self->{groupHash};
761        # Is there a FIG object?
762        if (defined $self->{fig}) {
763            # Yes, clear its subsystem cache.
764            $self->{fig}->clear_subsystem_cache();
765        }
766    }
767    
768    
769    =head3 Stem
770    
771        my $stem = $sprout->Stem($word);
772    
773    Return the stem of the specified word, or C<undef> if the word is not
774    stemmable. Note that even if the word is stemmable, the stem may be
775    the same as the original word.
776    
777    =over 4
778    
779    =item word
780    
781    Word to convert into a stem.
782    
783    =item RETURN
784    
785    Returns a stem of the word (which may be the word itself), or C<undef> if
786    the word is not stemmable.
787    
788    =back
789    
790    =cut
791    
792    sub Stem {
793        # Get the parameters.
794        my ($self, $word) = @_;
795        # Get the stemmer object.
796        my $stemmer = $self->{stemmer};
797        if (! defined $stemmer) {
798            # We don't have one pre-built, so we build and save it now.
799            $stemmer = BioWords->new(exceptions => "$FIG_Config::sproutData/Exceptions.txt",
800                                     stops => "$FIG_Config::sproutData/StopWords.txt",
801                                     cache => 0);
802            $self->{stemmer} = $stemmer;
803        }
804        # Try to stem the word.
805        my $retVal = $stemmer->Process($word);
806      # Return the result.      # Return the result.
807      return $retVal;      return $retVal;
808  }  }
809    
810    
811  =head3 Build  =head3 Build
812    
813  C<< $sprout->Build(); >>      $sprout->Build();
814    
815  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.
816  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 450  Line 827 
827    
828  =head3 Genomes  =head3 Genomes
829    
830  C<< my @genomes = $sprout->Genomes(); >>      my @genomes = $sprout->Genomes();
831    
832  Return a list of all the genome IDs.  Return a list of all the genome IDs.
833    
# Line 467  Line 844 
844    
845  =head3 GenusSpecies  =head3 GenusSpecies
846    
847  C<< my $infoString = $sprout->GenusSpecies($genomeID); >>      my $infoString = $sprout->GenusSpecies($genomeID);
848    
849  Return the genus, species, and unique characterization for a genome.  Return the genus, species, and unique characterization for a genome.
850    
# Line 489  Line 866 
866  sub GenusSpecies {  sub GenusSpecies {
867      # Get the parameters.      # Get the parameters.
868      my ($self, $genomeID) = @_;      my ($self, $genomeID) = @_;
869      # Get the data for the specified genome.      # Declare the return value.
870      my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',      my $retVal;
871                                                                'Genome(unique-characterization)']);      # Get the genome data.
872      # Format the result and return it.      my $genomeData = $self->_GenomeData($genomeID);
873      my $retVal = join(' ', @values);      # Only proceed if we found the genome.
874        if (defined $genomeData) {
875            $retVal = $genomeData->PrimaryValue('Genome(scientific-name)');
876        }
877        # Return it.
878      return $retVal;      return $retVal;
879  }  }
880    
881  =head3 FeaturesOf  =head3 FeaturesOf
882    
883  C<< my @features = $sprout->FeaturesOf($genomeID, $ftype); >>      my @features = $sprout->FeaturesOf($genomeID, $ftype);
884    
885  Return a list of the features relevant to a specified genome.  Return a list of the features relevant to a specified genome.
886    
# Line 544  Line 925 
925    
926  =head3 FeatureLocation  =head3 FeatureLocation
927    
928  C<< my @locations = $sprout->FeatureLocation($featureID); >>      my @locations = $sprout->FeatureLocation($featureID);
929    
930  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
931  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 568  Line 949 
949  =item RETURN  =item RETURN
950    
951  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
952  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
953    wasn't found.
954    
955  =back  =back
956    
957  =cut  =cut
958  #: Return Type @;  
 #: Return Type $;  
959  sub FeatureLocation {  sub FeatureLocation {
960      # Get the parameters.      # Get the parameters.
961      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
962      # 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.  
963      my @retVal = ();      my @retVal = ();
964      # Set up the variables used to determine if we have adjacent segments. This initial setup will      # Get the feature record.
965      # not match anything.      my $object = $self->GetEntity('Feature', $featureID);
966      my ($prevContig, $prevBeg, $prevDir, $prevLen) = ("", 0, "0", 0);      # Only proceed if we found it.
967      # Loop through the query results, creating location specifiers.      if (defined $object) {
968      while (my $location = $query->Fetch()) {          # Get the location string.
969          # Get the location parameters.          my $locString = $object->PrimaryValue('Feature(location-string)');
970          my ($contigID, $beg, $dir, $len) = $location->Values(['IsLocatedIn(to-link)',          # Create the return list.
971              '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";  
972      }      }
973      # Return the list in the format indicated by the context.      # Return the list in the format indicated by the context.
974      return (wantarray ? @retVal : join(',', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
# Line 623  Line 976 
976    
977  =head3 ParseLocation  =head3 ParseLocation
978    
979  C<< my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location); >>      my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location);
980    
981  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
982  length.  length.
# Line 642  Line 995 
995  =back  =back
996    
997  =cut  =cut
998  #: Return Type @;  
999  sub ParseLocation {  sub ParseLocation {
1000      # 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
1001      # the first parameter.      # the first parameter.
# Line 666  Line 1019 
1019  }  }
1020    
1021    
   
1022  =head3 PointLocation  =head3 PointLocation
1023    
1024  C<< my $found = Sprout::PointLocation($location, $point); >>      my $found = Sprout::PointLocation($location, $point);
1025    
1026  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
1027  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 698  Line 1050 
1050  =back  =back
1051    
1052  =cut  =cut
1053  #: Return Type $;  
1054  sub PointLocation {  sub PointLocation {
1055      # 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
1056      # the first parameter.      # the first parameter.
# Line 721  Line 1073 
1073    
1074  =head3 DNASeq  =head3 DNASeq
1075    
1076  C<< my $sequence = $sprout->DNASeq(\@locationList); >>      my $sequence = $sprout->DNASeq(\@locationList);
1077    
1078  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
1079  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 805  Line 1157 
1157    
1158  =head3 AllContigs  =head3 AllContigs
1159    
1160  C<< my @idList = $sprout->AllContigs($genomeID); >>      my @idList = $sprout->AllContigs($genomeID);
1161    
1162  Return a list of all the contigs for a genome.  Return a list of all the contigs for a genome.
1163    
# Line 835  Line 1187 
1187    
1188  =head3 GenomeLength  =head3 GenomeLength
1189    
1190  C<< my $length = $sprout->GenomeLength($genomeID); >>      my $length = $sprout->GenomeLength($genomeID);
1191    
1192  Return the length of the specified genome in base pairs.  Return the length of the specified genome in base pairs.
1193    
# Line 859  Line 1211 
1211      my ($self, $genomeID) = @_;      my ($self, $genomeID) = @_;
1212      # Declare the return variable.      # Declare the return variable.
1213      my $retVal = 0;      my $retVal = 0;
1214      # Get the genome's contig sequence lengths.      # Get the genome data.
1215      my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',      my $genomeData = $self->_GenomeData($genomeID);
1216                         [$genomeID], 'IsMadeUpOf(len)');      # Only proceed if it exists.
1217      # Sum the lengths.      if (defined $genomeData) {
1218      map { $retVal += $_ } @lens;          $retVal = $genomeData->PrimaryValue('Genome(dna-size)');
1219        }
1220      # Return the result.      # Return the result.
1221      return $retVal;      return $retVal;
1222  }  }
1223    
1224  =head3 FeatureCount  =head3 FeatureCount
1225    
1226  C<< my $count = $sprout->FeatureCount($genomeID, $type); >>      my $count = $sprout->FeatureCount($genomeID, $type);
1227    
1228  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.
1229    
# Line 905  Line 1258 
1258    
1259  =head3 GenomeAssignments  =head3 GenomeAssignments
1260    
1261  C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>      my $fidHash = $sprout->GenomeAssignments($genomeID);
1262    
1263  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
1264  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 948  Line 1301 
1301    
1302  =head3 ContigLength  =head3 ContigLength
1303    
1304  C<< my $length = $sprout->ContigLength($contigID); >>      my $length = $sprout->ContigLength($contigID);
1305    
1306  Compute the length of a contig.  Compute the length of a contig.
1307    
# Line 987  Line 1340 
1340    
1341  =head3 ClusterPEGs  =head3 ClusterPEGs
1342    
1343  C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>      my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs);
1344    
1345  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
1346  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
1347  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
1348  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
1349  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
1350  sequence.  appear in the output sequence.
1351    
1352  =over 4  =over 4
1353    
# Line 1035  Line 1388 
1388    
1389  =head3 GenesInRegion  =head3 GenesInRegion
1390    
1391  C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>      my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop);
1392    
1393  List the features which overlap a specified region in a contig.  List the features which overlap a specified region in a contig.
1394    
# Line 1064  Line 1417 
1417  =back  =back
1418    
1419  =cut  =cut
1420  #: Return Type @@;  
1421  sub GenesInRegion {  sub GenesInRegion {
1422      # Get the parameters.      # Get the parameters.
1423      my ($self, $contigID, $start, $stop) = @_;      my ($self, $contigID, $start, $stop) = @_;
1424      # Get the maximum segment length.      # Get the maximum segment length.
1425      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 = ();  
1426      # Prime the values we'll use for the returned beginning and end.      # Prime the values we'll use for the returned beginning and end.
1427      my @initialMinMax = ($self->ContigLength($contigID), 0);      my @initialMinMax = ($self->ContigLength($contigID), 0);
1428      my ($min, $max) = @initialMinMax;      my ($min, $max) = @initialMinMax;
1429      # Create a table of parameters for each query. Each query looks for features travelling in      # Get the overlapping features.
1430        my @featureObjects = $self->GeneDataInRegion($contigID, $start, $stop);
1431        # We'l use this hash to help us track the feature IDs and sort them. The key is the
1432        # feature ID and the value is a [$left,$right] pair indicating the maximum extent
1433        # of the feature's locations.
1434        my %featureMap = ();
1435        # Loop through them to do the begin/end analysis.
1436        for my $featureObject (@featureObjects) {
1437            # Get the feature's location string. This may contain multiple actual locations.
1438            my ($locations, $fid) = $featureObject->Values([qw(Feature(location-string) Feature(id))]);
1439            my @locationSegments = split /\s*,\s*/, $locations;
1440            # Loop through the locations.
1441            for my $locationSegment (@locationSegments) {
1442                # Construct an object for the location.
1443                my $locationObject = BasicLocation->new($locationSegment);
1444                # Merge the current segment's begin and end into the min and max.
1445                my ($left, $right) = ($locationObject->Left, $locationObject->Right);
1446                my ($beg, $end);
1447                if (exists $featureMap{$fid}) {
1448                    ($beg, $end) = @{$featureMap{$fid}};
1449                    $beg = $left if $left < $beg;
1450                    $end = $right if $right > $end;
1451                } else {
1452                    ($beg, $end) = ($left, $right);
1453                }
1454                $min = $beg if $beg < $min;
1455                $max = $end if $end > $max;
1456                # Store the feature's new extent back into the hash table.
1457                $featureMap{$fid} = [$beg, $end];
1458            }
1459        }
1460        # Now we must compute the list of the IDs for the features found. We start with a list
1461        # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1462        # but the result of the sort will be the same.)
1463        my @list = map { [$featureMap{$_}->[0] + $featureMap{$_}->[1], $_] } keys %featureMap;
1464        # Now we sort by midpoint and yank out the feature IDs.
1465        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1466        # Return it along with the min and max.
1467        return (\@retVal, $min, $max);
1468    }
1469    
1470    =head3 GeneDataInRegion
1471    
1472        my @featureList = $sprout->GenesInRegion($contigID, $start, $stop);
1473    
1474    List the features which overlap a specified region in a contig.
1475    
1476    =over 4
1477    
1478    =item contigID
1479    
1480    ID of the contig containing the region of interest.
1481    
1482    =item start
1483    
1484    Offset of the first residue in the region of interest.
1485    
1486    =item stop
1487    
1488    Offset of the last residue in the region of interest.
1489    
1490    =item RETURN
1491    
1492    Returns a list of B<ERDBObjects> for the desired features. Each object will
1493    contain a B<Feature> record.
1494    
1495    =back
1496    
1497    =cut
1498    
1499    sub GeneDataInRegion {
1500        # Get the parameters.
1501        my ($self, $contigID, $start, $stop) = @_;
1502        # Get the maximum segment length.
1503        my $maximumSegmentLength = $self->MaxSegment;
1504        # Create a hash to receive the feature list. We use a hash so that we can eliminate
1505        # duplicates easily. The hash key will be the feature ID. The value will be the feature's
1506        # ERDBObject from the query.
1507        my %featuresFound = ();
1508        # Create a table of parameters for the queries. Each query looks for features travelling in
1509      # 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,
1510      # 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
1511      # 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 1087  Line 1514 
1514      # Loop through the query parameters.      # Loop through the query parameters.
1515      for my $parms (values %queryParms) {      for my $parms (values %queryParms) {
1516          # Create the query.          # Create the query.
1517          my $query = $self->Get(['IsLocatedIn'],          my $query = $self->Get([qw(Feature IsLocatedIn)],
1518              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
1519              $parms);              $parms);
1520          # Loop through the feature segments found.          # Loop through the feature segments found.
1521          while (my $segment = $query->Fetch) {          while (my $segment = $query->Fetch) {
1522              # Get the data about this segment.              # Get the data about this segment.
1523              my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',              my ($featureID, $contig, $dir, $beg, $len) = $segment->Values([qw(IsLocatedIn(from-link)
1524                  'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);                  IsLocatedIn(to-link) IsLocatedIn(dir) IsLocatedIn(beg) IsLocatedIn(len))]);
1525              # 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
1526              # 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
1527              # 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
1528              # length.              # length.
1529              my ($found, $end) = (0, 0);              my $loc = BasicLocation->new($contig, $beg, $dir, $len);
1530              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;  
                 }  
             }  
1531              if ($found) {              if ($found) {
1532                  # Here we need to record the feature and update the minima and maxima. First,                  # Save this feature in the result list.
1533                  # 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;  
1534                  }                  }
                 # Store the entry back into the hash table.  
                 $featuresFound{$featureID} = [$loc1, $loc2];  
1535              }              }
1536          }          }
1537      }      # Return the ERDB objects for the features found.
1538      # Now we must compute the list of the IDs for the features found. We start with a list      return values %featuresFound;
     # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,  
     # but the result of the sort will be the same.)  
     my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;  
     # Now we sort by midpoint and yank out the feature IDs.  
     my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;  
     # Return it along with the min and max.  
     return (\@retVal, $min, $max);  
1539  }  }
1540    
1541  =head3 FType  =head3 FType
1542    
1543  C<< my $ftype = $sprout->FType($featureID); >>      my $ftype = $sprout->FType($featureID);
1544    
1545  Return the type of a feature.  Return the type of a feature.
1546    
# Line 1177  Line 1570 
1570    
1571  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1572    
1573  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>      my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag);
1574    
1575  Return the annotations of a feature.  Return the annotations of a feature.
1576    
# Line 1240  Line 1633 
1633    
1634  =head3 AllFunctionsOf  =head3 AllFunctionsOf
1635    
1636  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>      my %functions = $sprout->AllFunctionsOf($featureID);
1637    
1638  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
1639  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 1295  Line 1688 
1688    
1689  =head3 FunctionOf  =head3 FunctionOf
1690    
1691  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>      my $functionText = $sprout->FunctionOf($featureID, $userID);
1692    
1693  Return the most recently-determined functional assignment of a particular feature.  Return the most recently-determined functional assignment of a particular feature.
1694    
# Line 1308  Line 1701 
1701  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
1702  is trusted.  is trusted.
1703    
1704  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.
1705  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.  
1706    
1707  =over 4  =over 4
1708    
# Line 1336  Line 1728 
1728      my ($self, $featureID, $userID) = @_;      my ($self, $featureID, $userID) = @_;
1729      # Declare the return value.      # Declare the return value.
1730      my $retVal;      my $retVal;
1731      # Determine the ID type.      # Find a FIG ID for this feature.
1732      if ($featureID =~ m/^fig\|/) {      my ($fid) = $self->FeaturesByAlias($featureID);
1733        # Only proceed if we have an ID.
1734        if ($fid) {
1735          # Here we have a FIG feature ID.          # Here we have a FIG feature ID.
1736          if (!$userID) {          if (!$userID) {
1737              # Use the primary assignment.              # Use the primary assignment.
1738              ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']);              ($retVal) = $self->GetEntityValues('Feature', $fid, ['Feature(assignment)']);
1739          } else {          } else {
1740              # We must build the list of trusted users.              # We must build the list of trusted users.
1741              my %trusteeTable = ();              my %trusteeTable = ();
# Line 1367  Line 1761 
1761              # 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.
1762              my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],              my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1763                                     "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                     "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1764                                     [$featureID]);                                     [$fid]);
1765              my $timeSelected = 0;              my $timeSelected = 0;
1766              # Loop until we run out of annotations.              # Loop until we run out of annotations.
1767              while (my $annotation = $query->Fetch()) {              while (my $annotation = $query->Fetch()) {
# Line 1387  Line 1781 
1781                  }                  }
1782              }              }
1783          }          }
     } 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)']);  
1784      }      }
1785      # Return the assignment found.      # Return the assignment found.
1786      return $retVal;      return $retVal;
# Line 1399  Line 1788 
1788    
1789  =head3 FunctionsOf  =head3 FunctionsOf
1790    
1791  C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>      my @functionList = $sprout->FunctionOf($featureID, $userID);
1792    
1793  Return the functional assignments of a particular feature.  Return the functional assignments of a particular feature.
1794    
# Line 1410  Line 1799 
1799  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
1800  most features only have a small number of annotations.  most features only have a small number of annotations.
1801    
 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.  
   
1802  =over 4  =over 4
1803    
1804  =item featureID  =item featureID
# Line 1434  Line 1819 
1819      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1820      # Declare the return value.      # Declare the return value.
1821      my @retVal = ();      my @retVal = ();
1822      # Determine the ID type.      # Convert to a FIG ID.
1823      if ($featureID =~ m/^fig\|/) {      my ($fid) = $self->FeaturesByAlias($featureID);
1824        # Only proceed if we found one.
1825        if ($fid) {
1826          # 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
1827          # users.          # users.
1828          my %trusteeTable = ();          my %trusteeTable = ();
1829          # 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.
1830          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1831                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1832                                 [$featureID]);                                 [$fid]);
1833          my $timeSelected = 0;          my $timeSelected = 0;
1834          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1835          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
# Line 1457  Line 1844 
1844                  push @retVal, [$actualUser, $function];                  push @retVal, [$actualUser, $function];
1845              }              }
1846          }          }
     } 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;  
1847      }      }
1848      # Return the assignments found.      # Return the assignments found.
1849      return @retVal;      return @retVal;
# Line 1471  Line 1851 
1851    
1852  =head3 BBHList  =head3 BBHList
1853    
1854  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>      my $bbhHash = $sprout->BBHList($genomeID, \@featureList);
1855    
1856  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
1857  on a specified target genome.  on a specified target genome.
# Line 1503  Line 1883 
1883      # Loop through the incoming features.      # Loop through the incoming features.
1884      for my $featureID (@{$featureList}) {      for my $featureID (@{$featureList}) {
1885          # Ask the server for the feature's best hit.          # Ask the server for the feature's best hit.
1886          my @bbhData = FIGRules::BBHData($featureID);          my $bbhData = FIGRules::BBHData($featureID);
1887          # Peel off the BBHs found.          # Peel off the BBHs found.
1888          my @found = ();          my @found = ();
1889          for my $bbh (@bbhData) {          for my $bbh (@$bbhData) {
1890              my $fid = $bbh->[0];              my $fid = $bbh->[0];
1891              my $bbGenome = $self->GenomeOf($fid);              my $bbGenome = $self->GenomeOf($fid);
1892              if ($bbGenome eq $genomeID) {              if ($bbGenome eq $genomeID) {
# Line 1521  Line 1901 
1901    
1902  =head3 SimList  =head3 SimList
1903    
1904  C<< my %similarities = $sprout->SimList($featureID, $count); >>      my %similarities = $sprout->SimList($featureID, $count);
1905    
1906  Return a list of the similarities to the specified feature.  Return a list of the similarities to the specified feature.
1907    
# Line 1545  Line 1925 
1925      # Get the parameters.      # Get the parameters.
1926      my ($self, $featureID, $count) = @_;      my ($self, $featureID, $count) = @_;
1927      # Ask for the best hits.      # Ask for the best hits.
1928      my @lists = FIGRules::BBHData($featureID);      my $lists = FIGRules::BBHData($featureID);
1929      # Create the return value.      # Create the return value.
1930      my %retVal = ();      my %retVal = ();
1931      for my $tuple (@lists) {      for my $tuple (@$lists) {
1932          $retVal{$tuple->[0]} = $tuple->[1];          $retVal{$tuple->[0]} = $tuple->[1];
1933      }      }
1934      # Return the result.      # Return the result.
# Line 1557  Line 1937 
1937    
1938  =head3 IsComplete  =head3 IsComplete
1939    
1940  C<< my $flag = $sprout->IsComplete($genomeID); >>      my $flag = $sprout->IsComplete($genomeID);
1941    
1942  Return TRUE if the specified genome is complete, else FALSE.  Return TRUE if the specified genome is complete, else FALSE.
1943    
# Line 1582  Line 1962 
1962      # Declare the return variable.      # Declare the return variable.
1963      my $retVal;      my $retVal;
1964      # Get the genome's data.      # Get the genome's data.
1965      my $genomeData = $self->GetEntity('Genome', $genomeID);      my $genomeData = $self->_GenomeData($genomeID);
1966      if ($genomeData) {      # Only proceed if it exists.
1967        if (defined $genomeData) {
1968          # The genome exists, so get the completeness flag.          # The genome exists, so get the completeness flag.
1969          ($retVal) = $genomeData->Value('Genome(complete)');          $retVal = $genomeData->PrimaryValue('Genome(complete)');
1970      }      }
1971      # Return the result.      # Return the result.
1972      return $retVal;      return $retVal;
# Line 1593  Line 1974 
1974    
1975  =head3 FeatureAliases  =head3 FeatureAliases
1976    
1977  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>      my @aliasList = $sprout->FeatureAliases($featureID);
1978    
1979  Return a list of the aliases for a specified feature.  Return a list of the aliases for a specified feature.
1980    
# Line 1616  Line 1997 
1997      # Get the parameters.      # Get the parameters.
1998      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1999      # Get the desired feature's aliases      # Get the desired feature's aliases
2000      my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);      my @retVal = $self->GetFlat(['IsAliasOf'], "IsAliasOf(to-link) = ?", [$featureID], 'IsAliasOf(from-link)');
2001      # Return the result.      # Return the result.
2002      return @retVal;      return @retVal;
2003  }  }
2004    
2005  =head3 GenomeOf  =head3 GenomeOf
2006    
2007  C<< my $genomeID = $sprout->GenomeOf($featureID); >>      my $genomeID = $sprout->GenomeOf($featureID);
2008    
2009  Return the genome that contains a specified feature or contig.  Return the genome that contains a specified feature or contig.
2010    
# Line 1645  Line 2026 
2026  sub GenomeOf {  sub GenomeOf {
2027      # Get the parameters.      # Get the parameters.
2028      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]);  
2029      # Declare the return value.      # Declare the return value.
2030      my $retVal;      my $retVal;
2031      # Get the genome ID.      # Parse the genome ID from the feature ID.
2032      if (my $relationship = $query->Fetch()) {      if ($featureID =~ /^fig\|(\d+\.\d+)/) {
2033          ($retVal) = $relationship->Value('HasContig(from-link)');          $retVal = $1;
2034        } else {
2035            # Find the feature by alias.
2036            my ($realFeatureID) = $self->FeaturesByAlias($featureID);
2037            if ($realFeatureID && $realFeatureID =~ /^fig\|(\d+\.\d+)/) {
2038                $retVal = $1;
2039            }
2040      }      }
2041      # Return the value found.      # Return the value found.
2042      return $retVal;      return $retVal;
# Line 1660  Line 2044 
2044    
2045  =head3 CoupledFeatures  =head3 CoupledFeatures
2046    
2047  C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >>      my %coupleHash = $sprout->CoupledFeatures($featureID);
2048    
2049  Return the features functionally coupled with a specified feature. Features are considered  Return the features functionally coupled with a specified feature. Features are considered
2050  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 1682  Line 2066 
2066  sub CoupledFeatures {  sub CoupledFeatures {
2067      # Get the parameters.      # Get the parameters.
2068      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2069        # Ask the coupling server for the data.
2070      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
2071      # Create a query to retrieve the functionally-coupled features.      my @rawPairs = FIGRules::NetCouplingData('coupled_to', id1 => $featureID);
2072      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      Trace(scalar(@rawPairs) . " couplings returned.") if T(coupling => 3);
2073                             "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.  
2074      my %retVal = ();      my %retVal = ();
2075      # Retrieve the relationship records and store them in the hash.      for my $pair (@rawPairs) {
2076      while (my $clustering = $query->Fetch()) {          # Get the feature ID and score.
2077          # Get the ID and score of the coupling.          my ($featureID2, $score) = @{$pair};
2078          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          # Only proceed if the feature is in NMPDR.
2079                                                          'Coupling(score)']);          if ($self->_CheckFeature($featureID2)) {
2080          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;  
2081      }      }
     # 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;  
2082      }      }
2083      # Return the hash.      # Return the hash.
2084      return %retVal;      return %retVal;
# Line 1716  Line 2086 
2086    
2087  =head3 CouplingEvidence  =head3 CouplingEvidence
2088    
2089  C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>      my @evidence = $sprout->CouplingEvidence($peg1, $peg2);
2090    
2091  Return the evidence for a functional coupling.  Return the evidence for a functional coupling.
2092    
# Line 1764  Line 2134 
2134      my ($self, $peg1, $peg2) = @_;      my ($self, $peg1, $peg2) = @_;
2135      # Declare the return variable.      # Declare the return variable.
2136      my @retVal = ();      my @retVal = ();
2137      # Our first task is to find out the nature of the coupling: whether or not      # Get the coupling and evidence data.
2138      # it exists, its score, and whether the features are stored in the same      my @rawData = FIGRules::NetCouplingData('coupling_evidence', id1 => $peg1, id2 => $peg2);
2139      # order as the ones coming in.      # Loop through the raw data, saving the ones that are in NMPDR genomes.
2140      my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);      for my $rawTuple (@rawData) {
2141      # Only proceed if a coupling exists.          if ($self->_CheckFeature($rawTuple->[0]) && $self->_CheckFeature($rawTuple->[1])) {
2142      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);  
     }  
     # Return the result.  
     return @retVal;  
2143  }  }
   
 =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);  
2144      }      }
2145      # Return the result.      # Return the result.
2146      return ($retVal, $inverted, $score);      return @retVal;
2147  }  }
2148    
2149  =head3 GetSynonymGroup  =head3 GetSynonymGroup
2150    
2151  C<< my $id = $sprout->GetSynonymGroup($fid); >>      my $id = $sprout->GetSynonymGroup($fid);
2152    
2153  Return the synonym group name for the specified feature.  Return the synonym group name for the specified feature.
2154    
# Line 1895  Line 2187 
2187    
2188  =head3 GetBoundaries  =head3 GetBoundaries
2189    
2190  C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>      my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList);
2191    
2192  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
2193  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 1957  Line 2249 
2249      return ($contig, $beg, $end);      return ($contig, $beg, $end);
2250  }  }
2251    
2252  =head3 CouplingID  =head3 ReadFasta
   
 C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >>  
2253    
2254  Return the coupling ID for a pair of feature IDs.      my %sequenceData = Sprout::ReadFasta($fileName, $prefix);
2255    
2256  The coupling ID is currently computed by joining the feature IDs in  Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by
2257  sorted order with a space. Client modules (that is, modules which  one or more lines of data. The first line begins with a > character and contains an ID.
2258  use Sprout) should not, however, count on this always being the  The remaining lines contain the sequence data in order.
 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")>.  
2259    
2260  =over 4  =over 4
2261    
2262  =item peg1  =item fileName
2263    
2264  First feature of interest.  Name of the FASTA file.
2265    
2266  =item peg2  =item prefix (optional)
2267    
2268  Second feature of interest.  Prefix to be put in front of each ID found.
2269    
2270  =item RETURN  =item RETURN
2271    
2272  Returns the ID that would be used to represent a functional coupling of  Returns a hash that maps each ID to its sequence.
 the two specified PEGs.  
   
 =back  
   
 =cut  
 #: Return Type $;  
 sub CouplingID {  
     my ($self, @pegs) = @_;  
     return $self->DigestKey(join " ", sort @pegs);  
 }  
   
 =head3 ReadFasta  
   
 C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>  
   
 Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by  
 one or more lines of data. The first line begins with a > character and contains an ID.  
 The remaining lines contain the sequence data in order.  
   
 =over 4  
   
 =item fileName  
   
 Name of the FASTA file.  
   
 =item prefix (optional)  
   
 Prefix to be put in front of each ID found.  
   
 =item RETURN  
   
 Returns a hash that maps each ID to its sequence.  
2273    
2274  =back  =back
2275    
# Line 2064  Line 2317 
2317    
2318  =head3 FormatLocations  =head3 FormatLocations
2319    
2320  C<< my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat); >>      my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat);
2321    
2322  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
2323  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 2129  Line 2382 
2382    
2383  =head3 DumpData  =head3 DumpData
2384    
2385  C<< $sprout->DumpData(); >>      $sprout->DumpData();
2386    
2387  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.
2388    
# Line 2146  Line 2399 
2399    
2400  =head3 XMLFileName  =head3 XMLFileName
2401    
2402  C<< my $fileName = $sprout->XMLFileName(); >>      my $fileName = $sprout->XMLFileName();
2403    
2404  Return the name of this database's XML definition file.  Return the name of this database's XML definition file.
2405    
# Line 2157  Line 2410 
2410      return $self->{_xmlName};      return $self->{_xmlName};
2411  }  }
2412    
2413    =head3 GetGenomeNameData
2414    
2415        my ($genus, $species, $strain) = $sprout->GenomeNameData($genomeID);
2416    
2417    Return the genus, species, and unique characterization for a genome. This
2418    is similar to L</GenusSpecies>, with the exception that it returns the
2419    values in three seperate fields.
2420    
2421    =over 4
2422    
2423    =item genomeID
2424    
2425    ID of the genome whose name data is desired.
2426    
2427    =item RETURN
2428    
2429    Returns a three-element list, consisting of the genus, species, and strain
2430    of the specified genome. If the genome is not found, an error occurs.
2431    
2432    =back
2433    
2434    =cut
2435    
2436    sub GetGenomeNameData {
2437        # Get the parameters.
2438        my ($self, $genomeID) = @_;
2439        # Declare the return variables.
2440        my ($genus, $species, $strain);
2441        # Get the genome's data.
2442        my $genomeData = $self->_GenomeData($genomeID);
2443        # Only proceed if the genome exists.
2444        if (defined $genomeData) {
2445            # Get the desired values.
2446            ($genus, $species, $strain) = $genomeData->Values(['Genome(genus)',
2447                                                               'Genome(species)',
2448                                                               'Genome(unique-characterization)']);
2449        } else {
2450            # Throw an error because they were not found.
2451            Confess("Genome $genomeID not found in database.");
2452        }
2453        # Return the results.
2454        return ($genus, $species, $strain);
2455    }
2456    
2457    =head3 GetGenomeByNameData
2458    
2459        my @genomes = $sprout->GetGenomeByNameData($genus, $species, $strain);
2460    
2461    Return a list of the IDs of the genomes with the specified genus,
2462    species, and strain. In almost every case, there will be either zero or
2463    one IDs returned; however, two or more IDs could be returned if there are
2464    multiple versions of the genome in the database.
2465    
2466    =over 4
2467    
2468    =item genus
2469    
2470    Genus of the desired genome.
2471    
2472    =item species
2473    
2474    Species of the desired genome.
2475    
2476    =item strain
2477    
2478    Strain (unique characterization) of the desired genome. This may be an empty
2479    string, in which case it is presumed that the desired genome has no strain
2480    specified.
2481    
2482    =item RETURN
2483    
2484    Returns a list of the IDs of the genomes having the specified genus, species, and
2485    strain.
2486    
2487    =back
2488    
2489    =cut
2490    
2491    sub GetGenomeByNameData {
2492        # Get the parameters.
2493        my ($self, $genus, $species, $strain) = @_;
2494        # Try to find the genomes.
2495        my @retVal = $self->GetFlat(['Genome'], "Genome(genus) = ? AND Genome(species) = ? AND Genome(unique-characterization) = ?",
2496                                    [$genus, $species, $strain], 'Genome(id)');
2497        # Return the result.
2498        return @retVal;
2499    }
2500    
2501  =head3 Insert  =head3 Insert
2502    
2503  C<< $sprout->Insert($objectType, \%fieldHash); >>      $sprout->Insert($objectType, \%fieldHash);
2504    
2505  Insert an entity or relationship instance into the database. The entity or relationship of interest  Insert an entity or relationship instance into the database. The entity or relationship of interest
2506  is defined by a type name and then a hash of field names to values. Field values in the primary  is defined by a type name and then a hash of field names to values. Field values in the primary
# Line 2168  Line 2509 
2509  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
2510  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>.
2511    
2512  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']});
2513    
2514  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
2515  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>.
2516    
2517  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'});
2518    
2519  =over 4  =over 4
2520    
# Line 2198  Line 2539 
2539    
2540  =head3 Annotate  =head3 Annotate
2541    
2542  C<< my $ok = $sprout->Annotate($fid, $timestamp, $user, $text); >>      my $ok = $sprout->Annotate($fid, $timestamp, $user, $text);
2543    
2544  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
2545  specified feature and user.  specified feature and user.
# Line 2252  Line 2593 
2593    
2594  =head3 AssignFunction  =head3 AssignFunction
2595    
2596  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>      my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser);
2597    
2598  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
2599  format is described in L</ParseAssignment>.  format is described in L</ParseAssignment>.
# Line 2312  Line 2653 
2653    
2654  =head3 FeaturesByAlias  =head3 FeaturesByAlias
2655    
2656  C<< my @features = $sprout->FeaturesByAlias($alias); >>      my @features = $sprout->FeaturesByAlias($alias);
2657    
2658  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
2659  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 2346  Line 2687 
2687          push @retVal, $mappedAlias;          push @retVal, $mappedAlias;
2688      } else {      } else {
2689          # 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.
2690          @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');          @retVal = $self->GetFlat(['IsAliasOf'], 'IsAliasOf(from-link) = ?', [$mappedAlias], 'IsAliasOf(to-link)');
2691      }      }
2692      # Return the result.      # Return the result.
2693      return @retVal;      return @retVal;
# Line 2354  Line 2695 
2695    
2696  =head3 FeatureTranslation  =head3 FeatureTranslation
2697    
2698  C<< my $translation = $sprout->FeatureTranslation($featureID); >>      my $translation = $sprout->FeatureTranslation($featureID);
2699    
2700  Return the translation of a feature.  Return the translation of a feature.
2701    
# Line 2382  Line 2723 
2723    
2724  =head3 Taxonomy  =head3 Taxonomy
2725    
2726  C<< my @taxonomyList = $sprout->Taxonomy($genome); >>      my @taxonomyList = $sprout->Taxonomy($genome);
2727    
2728  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
2729  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>,
2730  or C<Eukaryote>) to sub-species. For example,  or C<Eukaryote>) to sub-species. For example,
2731    
2732  C<< (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12) >>      (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12)
2733    
2734  =over 4  =over 4
2735    
# Line 2407  Line 2748 
2748  sub Taxonomy {  sub Taxonomy {
2749      # Get the parameters.      # Get the parameters.
2750      my ($self, $genome) = @_;      my ($self, $genome) = @_;
     # Find the specified genome's taxonomy string.  
     my ($list) = $self->GetEntityValues('Genome', $genome, ['Genome(taxonomy)']);  
2751      # Declare the return variable.      # Declare the return variable.
2752      my @retVal = ();      my @retVal = ();
2753      # If we found the genome, return its taxonomy string.      # Get the genome data.
2754      if ($list) {      my $genomeData = $self->_GenomeData($genome);
2755          @retVal = split /\s*;\s*/, $list;      # Only proceed if it exists.
2756        if (defined $genomeData) {
2757            # Create the taxonomy from the taxonomy string.
2758            @retVal = split /\s*;\s*/, $genomeData->PrimaryValue('Genome(taxonomy)');
2759      } else {      } else {
2760            # Genome doesn't exist, so emit a warning.
2761          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);
2762      }      }
2763      # Return the value found.      # Return the value found.
# Line 2423  Line 2766 
2766    
2767  =head3 CrudeDistance  =head3 CrudeDistance
2768    
2769  C<< my $distance = $sprout->CrudeDistance($genome1, $genome2); >>      my $distance = $sprout->CrudeDistance($genome1, $genome2);
2770    
2771  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
2772  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 2459  Line 2802 
2802      }      }
2803      my @taxA = $self->Taxonomy($genomeA);      my @taxA = $self->Taxonomy($genomeA);
2804      my @taxB = $self->Taxonomy($genomeB);      my @taxB = $self->Taxonomy($genomeB);
2805      # Initialize the distance to 1. We'll reduce it each time we find a match between the      # Compute the distance.
2806      # 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;  
     }  
2807      return $retVal;      return $retVal;
2808  }  }
2809    
2810  =head3 RoleName  =head3 RoleName
2811    
2812  C<< my $roleName = $sprout->RoleName($roleID); >>      my $roleName = $sprout->RoleName($roleID);
2813    
2814  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
2815  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 2509  Line 2843 
2843    
2844  =head3 RoleDiagrams  =head3 RoleDiagrams
2845    
2846  C<< my @diagrams = $sprout->RoleDiagrams($roleID); >>      my @diagrams = $sprout->RoleDiagrams($roleID);
2847    
2848  Return a list of the diagrams containing a specified functional role.  Return a list of the diagrams containing a specified functional role.
2849    
# Line 2537  Line 2871 
2871      return @retVal;      return @retVal;
2872  }  }
2873    
 =head3 GetProperties  
   
 C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>  
   
 Return a list of the properties with the specified characteristics.  
   
 Properties are the Sprout analog of the FIG attributes. The call is  
 passed directly to the CustomAttributes or RemoteCustomAttributes object  
 contained in this object.  
   
 This method returns a series of tuples that match the specified criteria. Each tuple  
 will contain an object ID, a key, and one or more values. The parameters to this  
 method therefore correspond structurally to the values expected in each tuple. In  
 addition, you can ask for a generic search by suffixing a percent sign (C<%>) to any  
 of the parameters. So, for example,  
   
     my @attributeList = $sprout->GetProperties('fig|100226.1.peg.1004', 'structure%', 1, 2);  
   
 would return something like  
   
     ['fig}100226.1.peg.1004', 'structure', 1, 2]  
     ['fig}100226.1.peg.1004', 'structure1', 1, 2]  
     ['fig}100226.1.peg.1004', 'structure2', 1, 2]  
     ['fig}100226.1.peg.1004', 'structureA', 1, 2]  
   
 Use of C<undef> in any position acts as a wild card (all values). You can also specify  
 a list reference in the ID column. Thus,  
   
     my @attributeList = $sprout->GetProperties(['100226.1', 'fig|100226.1.%'], 'PUBMED');  
   
 would get the PUBMED attribute data for Streptomyces coelicolor A3(2) and all its  
 features.  
   
 In addition to values in multiple sections, a single attribute key can have multiple  
 values, so even  
   
     my @attributeList = $sprout->GetProperties($peg, 'virulent');  
   
 which has no wildcard in the key or the object ID, may return multiple tuples.  
   
 =over 4  
   
 =item objectID  
   
 ID of object whose attributes are desired. If the attributes are desired for multiple  
 objects, this parameter can be specified as a list reference. If the attributes are  
 desired for all objects, specify C<undef> or an empty string. Finally, you can specify  
 attributes for a range of object IDs by putting a percent sign (C<%>) at the end.  
   
 =item key  
   
 Attribute key name. A value of C<undef> or an empty string will match all  
 attribute keys. If the values are desired for multiple keys, this parameter can be  
 specified as a list reference. Finally, you can specify attributes for a range of  
 keys by putting a percent sign (C<%>) at the end.  
   
 =item values  
   
 List of the desired attribute values, section by section. If C<undef>  
 or an empty string is specified, all values in that section will match. A  
 generic match can be requested by placing a percent sign (C<%>) at the end.  
 In that case, all values that match up to and not including the percent sign  
 will match. You may also specify a regular expression enclosed  
 in slashes. All values that match the regular expression will be returned. For  
 performance reasons, only values have this extra capability.  
   
 =item RETURN  
   
 Returns a list of tuples. The first element in the tuple is an object ID, the  
 second is an attribute key, and the remaining elements are the sections of  
 the attribute value. All of the tuples will match the criteria set forth in  
 the parameter list.  
   
 =back  
   
 =cut  
   
 sub GetProperties {  
     # Get the parameters.  
     my ($self, @parms) = @_;  
     # Declare the return variable.  
     my @retVal = $self->{_ca}->GetAttributes(@parms);  
     # Return the result.  
     return @retVal;  
 }  
   
2874  =head3 FeatureProperties  =head3 FeatureProperties
2875    
2876  C<< my @properties = $sprout->FeatureProperties($featureID); >>      my @properties = $sprout->FeatureProperties($featureID);
2877    
2878  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
2879  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
# Line 2651  Line 2899 
2899      # Get the parameters.      # Get the parameters.
2900      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2901      # Get the properties.      # Get the properties.
2902      my @attributes = $self->{_ca}->GetAttributes($featureID);      my @attributes = $self->ca->GetAttributes($featureID);
2903      # Strip the feature ID off each tuple.      # Strip the feature ID off each tuple.
2904      my @retVal = ();      my @retVal = ();
2905      for my $attributeRow (@attributes) {      for my $attributeRow (@attributes) {
# Line 2664  Line 2912 
2912    
2913  =head3 DiagramName  =head3 DiagramName
2914    
2915  C<< my $diagramName = $sprout->DiagramName($diagramID); >>      my $diagramName = $sprout->DiagramName($diagramID);
2916    
2917  Return the descriptive name of a diagram.  Return the descriptive name of a diagram.
2918    
# Line 2692  Line 2940 
2940    
2941  =head3 PropertyID  =head3 PropertyID
2942    
2943  C<< my $id = $sprout->PropertyID($propName, $propValue); >>      my $id = $sprout->PropertyID($propName, $propValue);
2944    
2945  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
2946  pair exists. Only a small subset of the FIG attributes are stored as  pair exists. Only a small subset of the FIG attributes are stored as
# Line 2729  Line 2977 
2977    
2978  =head3 MergedAnnotations  =head3 MergedAnnotations
2979    
2980  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>      my @annotationList = $sprout->MergedAnnotations(\@list);
2981    
2982  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
2983  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 2778  Line 3026 
3026    
3027  =head3 RoleNeighbors  =head3 RoleNeighbors
3028    
3029  C<< my @roleList = $sprout->RoleNeighbors($roleID); >>      my @roleList = $sprout->RoleNeighbors($roleID);
3030    
3031  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
3032  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 2821  Line 3069 
3069    
3070  =head3 FeatureLinks  =head3 FeatureLinks
3071    
3072  C<< my @links = $sprout->FeatureLinks($featureID); >>      my @links = $sprout->FeatureLinks($featureID);
3073    
3074  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
3075  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 2852  Line 3100 
3100    
3101  =head3 SubsystemsOf  =head3 SubsystemsOf
3102    
3103  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>      my %subsystems = $sprout->SubsystemsOf($featureID);
3104    
3105  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
3106  to the roles the feature performs.  to the roles the feature performs.
# Line 2900  Line 3148 
3148    
3149  =head3 SubsystemList  =head3 SubsystemList
3150    
3151  C<< my @subsystems = $sprout->SubsystemList($featureID); >>      my @subsystems = $sprout->SubsystemList($featureID);
3152    
3153  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
3154  feature participates. Unlike L</SubsystemsOf>, this method only returns the  feature participates. Unlike L</SubsystemsOf>, this method only returns the
# Line 2923  Line 3171 
3171  sub SubsystemList {  sub SubsystemList {
3172      # Get the parameters.      # Get the parameters.
3173      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
3174      # Get the list of names.      # Get the list of names. We do a join to the Subsystem table because we have missing subsystems in
3175      my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?",      # the Sprout database!
3176        my @retVal = $self->GetFlat(['HasRoleInSubsystem', 'Subsystem'], "HasRoleInSubsystem(from-link) = ?",
3177                                  [$featureID], 'HasRoleInSubsystem(to-link)');                                  [$featureID], 'HasRoleInSubsystem(to-link)');
3178      # Return the result, sorted.      # Return the result, sorted.
3179      return sort @retVal;      return sort @retVal;
# Line 2932  Line 3181 
3181    
3182  =head3 GenomeSubsystemData  =head3 GenomeSubsystemData
3183    
3184  C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>      my %featureData = $sprout->GenomeSubsystemData($genomeID);
3185    
3186  Return a hash mapping genome features to their subsystem roles.  Return a hash mapping genome features to their subsystem roles.
3187    
# Line 2957  Line 3206 
3206      # Declare the return variable.      # Declare the return variable.
3207      my %retVal = ();      my %retVal = ();
3208      # 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
3209      # feature we get its spreadsheet cells and the corresponding roles.      # feature we get its subsystem ID and the corresponding roles.
3210      my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],      my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf', 'HasSSCell'],
3211                               "HasFeature(from-link) = ?", [$genomeID],                               "HasFeature(from-link) = ?", [$genomeID],
3212                               ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);                                   ['HasFeature(to-link)', 'IsRoleOf(from-link)',  'HasSSCell(from-link)']);
3213      # 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
3214      # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the      # a non-negative variant code.
3215      # list. We use it at the beginning to get all the spreadsheet cells for the genome and      my %subs = map { $_ => 1 } $self->GetFlat(['ParticipatesIn'],
3216      # again at the end to filter out participation in subsystems with a negative variant code.                                                  "ParticipatesIn(from-link) = ? AND ParticipatesIn(variant-code) >= 0",
3217      my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],                                                  [$genomeID], 'ParticipatesIn(to-link)');
3218                                   "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.  
3219      for my $roleEntry (@roleData) {      for my $roleEntry (@roleData) {
3220          # Get the data for this feature and cell.          # Get the data for this feature and cell.
3221          my ($fid, $cellID, $role) = @{$roleEntry};          my ($fid, $role, $subsys) = @{$roleEntry};
3222          # Check for a subsystem name.          Trace("Subsystem for $fid is $subsys.") if T(4);
3223          my $subsys = $subHash{$cellID};          # Check the subsystem;
3224          if ($subsys) {          if ($subs{$subsys}) {
3225                Trace("Subsystem found.") if T(4);
3226              # Insure this feature has an entry in the return hash.              # Insure this feature has an entry in the return hash.
3227              if (! exists $retVal{$fid}) { $retVal{$fid} = []; }              if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
3228              # Merge in this new data.              # Merge in this new data.
# Line 2992  Line 3235 
3235    
3236  =head3 RelatedFeatures  =head3 RelatedFeatures
3237    
3238  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>      my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID);
3239    
3240  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
3241  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 3025  Line 3268 
3268      # Get the parameters.      # Get the parameters.
3269      my ($self, $featureID, $function, $userID) = @_;      my ($self, $featureID, $function, $userID) = @_;
3270      # 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.
3271      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);      my $bbhData = FIGRules::BBHData($featureID);
3272        my @bbhFeatures = map { $_->[0] } @$bbhData;
3273      # 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
3274      # functional assignment.      # functional assignment.
3275      my @retVal = ();      my @retVal = ();
# Line 3043  Line 3287 
3287    
3288  =head3 TaxonomySort  =head3 TaxonomySort
3289    
3290  C<< my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs); >>      my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs);
3291    
3292  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
3293  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 3078  Line 3322 
3322          my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",          my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
3323                                          [$fid], 'Genome(taxonomy)');                                          [$fid], 'Genome(taxonomy)');
3324          # Add this feature to the hash buffer.          # Add this feature to the hash buffer.
3325          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);          push @{$hashBuffer{$taxonomy}}, $fid;
3326      }      }
3327      # Sort the keys and get the elements.      # Sort the keys and get the elements.
3328      my @retVal = ();      my @retVal = ();
# Line 3091  Line 3335 
3335    
3336  =head3 Protein  =head3 Protein
3337    
3338  C<< my $protein = Sprout::Protein($sequence, $table); >>      my $protein = Sprout::Protein($sequence, $table);
3339    
3340  Translate a DNA sequence into a protein sequence.  Translate a DNA sequence into a protein sequence.
3341    
# Line 3177  Line 3421 
3421    
3422  =head3 LoadInfo  =head3 LoadInfo
3423    
3424  C<< my ($dirName, @relNames) = $sprout->LoadInfo(); >>      my ($dirName, @relNames) = $sprout->LoadInfo();
3425    
3426  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
3427  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 3198  Line 3442 
3442    
3443  =head3 BBHMatrix  =head3 BBHMatrix
3444    
3445  C<< my %bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets); >>      my $bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets);
3446    
3447  Find all the bidirectional best hits for the features of a genome in a  Find all the bidirectional best hits for the features of a genome in a
3448  specified list of target genomes. The return value will be a hash mapping  specified list of target genomes. The return value will be a hash mapping
# Line 3222  Line 3466 
3466    
3467  =item RETURN  =item RETURN
3468    
3469  Returns a hash mapping each feature in the original genome to a hash mapping its  Returns a reference to a hash mapping each feature in the original genome
3470  BBH pegs in the target genomes to their scores.  to a sub-hash mapping its BBH pegs in the target genomes to their scores.
3471    
3472  =back  =back
3473    
# Line 3236  Line 3480 
3480      my %retVal = ();      my %retVal = ();
3481      # Ask for the BBHs.      # Ask for the BBHs.
3482      my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets);      my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets);
3483        Trace("Retrieved " . scalar(@bbhList) . " BBH results.") if T(3);
3484      # We now have a set of 4-tuples that we need to convert into a hash of hashes.      # We now have a set of 4-tuples that we need to convert into a hash of hashes.
3485      for my $bbhData (@bbhList) {      for my $bbhData (@bbhList) {
3486          my ($peg1, $peg2, $score) = @{$bbhData};          my ($peg1, $peg2, $score) = @{$bbhData};
# Line 3246  Line 3491 
3491          }          }
3492      }      }
3493      # Return the result.      # Return the result.
3494      return %retVal;      return \%retVal;
3495  }  }
3496    
3497    
3498  =head3 SimMatrix  =head3 SimMatrix
3499    
3500  C<< my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets); >>      my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets);
3501    
3502  Find all the similarities for the features of a genome in a  Find all the similarities for the features of a genome in a
3503  specified list of target genomes. The return value will be a hash mapping  specified list of target genomes. The return value will be a hash mapping
# Line 3322  Line 3567 
3567    
3568  =head3 LowBBHs  =head3 LowBBHs
3569    
3570  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>      my %bbhMap = $sprout->LowBBHs($featureID, $cutoff);
3571    
3572  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
3573  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 3352  Line 3597 
3597      # Create the return hash.      # Create the return hash.
3598      my %retVal = ();      my %retVal = ();
3599      # Query for the desired BBHs.      # Query for the desired BBHs.
3600      my @bbhList = FIGRules::BBHData($featureID, $cutoff);      my $bbhList = FIGRules::BBHData($featureID, $cutoff);
3601      # Form the results into the return hash.      # Form the results into the return hash.
3602      for my $pair (@bbhList) {      for my $pair (@$bbhList) {
3603          my $fid = $pair->[0];          my $fid = $pair->[0];
3604          if ($self->Exists('Feature', $fid)) {          if ($self->Exists('Feature', $fid)) {
3605              $retVal{$fid} = $pair->[1];              $retVal{$fid} = $pair->[1];
# Line 3366  Line 3611 
3611    
3612  =head3 Sims  =head3 Sims
3613    
3614  C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>      my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters);
3615    
3616  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
3617  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 3383  Line 3628 
3628    
3629  =item fid  =item fid
3630    
3631  ID of the feature whose similarities are desired.  ID of the feature whose similarities are desired, or reference to a list of IDs
3632    of features whose similarities are desired.
3633    
3634  =item maxN  =item maxN
3635    
# Line 3431  Line 3677 
3677    
3678  =head3 IsAllGenomes  =head3 IsAllGenomes
3679    
3680  C<< my $flag = $sprout->IsAllGenomes(\@list, \@checkList); >>      my $flag = $sprout->IsAllGenomes(\@list, \@checkList);
3681    
3682  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
3683  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 3480  Line 3726 
3726    
3727  =head3 GetGroups  =head3 GetGroups
3728    
3729  C<< my %groups = $sprout->GetGroups(\@groupList); >>      my %groups = $sprout->GetGroups(\@groupList);
3730    
3731  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.
3732  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 3512  Line 3758 
3758                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3759          # Loop through the genomes found.          # Loop through the genomes found.
3760          for my $genome (@genomes) {          for my $genome (@genomes) {
3761              # Pop this genome's ID off the current list.              # Get the genome ID and group, and add this genome to the group's list.
3762              my @groups = @{$genome};              my ($genomeID, $group) = @{$genome};
3763              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);  
             }  
3764          }          }
3765      }      }
3766      # Return the hash we just built.      # Return the hash we just built.
# Line 3528  Line 3769 
3769    
3770  =head3 MyGenomes  =head3 MyGenomes
3771    
3772  C<< my @genomes = Sprout::MyGenomes($dataDir); >>      my @genomes = Sprout::MyGenomes($dataDir);
3773    
3774  Return a list of the genomes to be included in the Sprout.  Return a list of the genomes to be included in the Sprout.
3775    
# Line 3560  Line 3801 
3801    
3802  =head3 LoadFileName  =head3 LoadFileName
3803    
3804  C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>      my $fileName = Sprout::LoadFileName($dataDir, $tableName);
3805    
3806  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
3807  directory.  directory.
# Line 3601  Line 3842 
3842    
3843  =head3 DeleteGenome  =head3 DeleteGenome
3844    
3845  C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>      my $stats = $sprout->DeleteGenome($genomeID, $testFlag);
3846    
3847  Delete a genome from the database.  Delete a genome from the database.
3848    
# Line 3637  Line 3878 
3878    
3879  =head3 Fix  =head3 Fix
3880    
3881  C<< my %fixedHash = Sprout::Fix(%groupHash); >>      my %fixedHash = $sprout->Fix(%groupHash);
3882    
3883  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.
3884  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.  
3885    
3886  =over 4  =over 4
3887    
# Line 3659  Line 3899 
3899    
3900  sub Fix {  sub Fix {
3901      # Get the parameters.      # Get the parameters.
3902      my (%groupHash) = @_;      my ($self, %groupHash) = @_;
3903      # Create the result hash.      # Create the result hash.
3904      my %retVal = ();      my %retVal = ();
3905      # Copy over the genomes.      # Copy over the genomes.
3906      for my $groupID (keys %groupHash) {      for my $groupID (keys %groupHash) {
3907          # Make a safety copy of the group ID.          # Get the super-group name.
3908          my $realGroupID = $groupID;          my $realGroupID = $self->SuperGroup($groupID);
3909          # Yank the primary name.          # Append this group's genomes into the result hash
3910          if ($groupID =~ /([A-Z]\w+)/) {          # using the super-group name.
3911              $realGroupID = $1;          push @{$retVal{$realGroupID}}, @{$groupHash{$groupID}};
         }  
         # Append this group's genomes into the result hash.  
         Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}});  
3912      }      }
3913      # Return the result hash.      # Return the result hash.
3914      return %retVal;      return %retVal;
# Line 3679  Line 3916 
3916    
3917  =head3 GroupPageName  =head3 GroupPageName
3918    
3919  C<< my $name = $sprout->GroupPageName($group); >>      my $name = $sprout->GroupPageName($group);
3920    
3921  Return the name of the page for the specified NMPDR group.  Return the name of the page for the specified NMPDR group.
3922    
# Line 3701  Line 3938 
3938  sub GroupPageName {  sub GroupPageName {
3939      # Get the parameters.      # Get the parameters.
3940      my ($self, $group) = @_;      my ($self, $group) = @_;
     # Declare the return variable.  
     my $retVal;  
3941      # Check for the group file data.      # Check for the group file data.
3942      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;  
     }  
3943      # Compute the real group name.      # Compute the real group name.
3944      my $realGroup = $group;      my $realGroup = $self->SuperGroup($group);
3945      if ($group =~ /([A-Z]\w+)/) {      # Get the associated page name.
3946          $realGroup = $1;      my $retVal = "../content/$superTable{$realGroup}->{page}";
     }  
     # Return the page name.  
     $retVal = "../content/" . $self->{groupHash}->{$realGroup}->[1];  
3947      # Return the result.      # Return the result.
3948      return $retVal;      return $retVal;
3949  }  }
3950    
 =head3 ReadGroupFile  
3951    
3952  C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >>  =head3 AddProperty
3953    
3954  Read in the data from the specified group file. The group file contains information      $sprout->AddProperty($featureID, $key, @values);
3955  about each of the NMPDR groups.  
3956    Add a new attribute value (Property) to a feature.
3957    
3958  =over 4  =over 4
3959    
3960  =item name  =item peg
3961    
3962  Name of the group.  ID of the feature to which the attribute is to be added.
3963    
3964  =item page  =item key
3965    
3966  Name of the group's page on the web site (e.g. C<campy.php> for  Name of the attribute (key).
 Campylobacter)  
3967    
3968  =item genus  =item values
3969    
3970  Genus of the group  Values of the attribute.
3971    
3972  =item species  =back
3973    
3974    =cut
3975    #: Return Type ;
3976    sub AddProperty {
3977        # Get the parameters.
3978        my ($self, $featureID, $key, @values) = @_;
3979        # Add the property using the attached attributes object.
3980        $self->ca->AddAttribute($featureID, $key, @values);
3981    }
3982    
3983  Species of the group, or an empty string if the group is for an entire  =head3 CheckGroupFile
 genus. If the group contains more than one species, the species names  
 should be separated by commas.  
3984    
3985  =back      my %groupData = $sprout->CheckGroupFile();
3986    
3987    Get the group file hash. The group file hash describes the relationship
3988    between a group and the super-group to which it belongs for purposes of
3989    display. The super-group name is computed from the first capitalized word
3990    in the actual group name. For each super-group, the group file contains
3991    the page name and a list of the species expected to be in the group.
3992    Each species is specified by a genus and a species name. A species name
3993    of C<0> implies an entire genus.
3994    
3995  The parameters to this method are as follows  This method returns a hash from super-group names to a hash reference. Each
3996    resulting hash reference contains the following fields.
3997    
3998  =over 4  =over 4
3999    
4000  =item groupFile  =item specials
4001    
4002  Name of the file containing the group data.  Reference to a hash whose keys are the names of special species.
4003    
4004  =item RETURN  =item contents
4005    
4006  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
4007    (or 0, indicating all species). This list indicates which organisms belong
4008    in the super-group.
4009    
4010  =back  =back
4011    
4012  =cut  =cut
4013    
4014  sub ReadGroupFile {  sub CheckGroupFile {
4015      # Get the parameters.      # Get the parameters.
4016      my ($groupFileName) = @_;      my ($self) = @_;
4017      # Declare the return variable.      # Check to see if we already have this hash.
4018      my %retVal;      if (! defined $self->{groupHash}) {
4019            # We don't, so we need to read it in.
4020            my %groupHash;
4021      # Read the group file.      # Read the group file.
4022      my @groupLines = Tracer::GetFile($groupFileName);          my @groupLines = Tracer::GetFile("$FIG_Config::sproutData/groups.tbl");
4023            # Loop through the list of sort-of groups.
4024      for my $groupLine (@groupLines) {      for my $groupLine (@groupLines) {
4025          my ($name, $page, $genus, $species) = split(/\t/, $groupLine);              my ($name, $specials, @contents) = split /\t/, $groupLine;
4026          $retVal{$name} = [$page, $genus, $species];              $groupHash{$name} = { specials => { map { $_ => 1 } split /\s*,\s*/, $specials },
4027                                      contents => [ map { [ split /\s*,\s*/, $_ ] } @contents ]
4028                                    };
4029            }
4030            # Save the hash.
4031            $self->{groupHash} = \%groupHash;
4032      }      }
4033      # Return the result.      # Return the result.
4034      return %retVal;      return %{$self->{groupHash}};
4035  }  }
4036    
4037  =head3 AddProperty  =head2 Virtual Methods
4038    
4039  C<< my  = $sprout->AddProperty($featureID, $key, @values); >>  =head3 CleanKeywords
4040    
4041  Add a new attribute value (Property) to a feature.      my $cleanedString = $sprout->CleanKeywords($searchExpression);
4042    
4043    Clean up a search expression or keyword list. This involves converting the periods
4044    in EC numbers to underscores, converting non-leading minus signs to underscores,
4045    a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
4046    characters. In addition, any extra spaces are removed.
4047    
4048  =over 4  =over 4
4049    
4050  =item peg  =item searchExpression
4051    
4052  ID of the feature to which the attribute is to be added.  Search expression or keyword list to clean. Note that a search expression may
4053    contain boolean operators which need to be preserved. This includes leading
4054    minus signs.
4055    
4056  =item key  =item RETURN
4057    
4058  Name of the attribute (key).  Cleaned expression or keyword list.
4059    
4060  =item values  =back
4061    
4062  Values of the attribute.  =cut
4063    
4064  =back  sub CleanKeywords {
4065        # Get the parameters.
4066        my ($self, $searchExpression) = @_;
4067        # Get the stemmer.
4068        my $stemmer = $self->GetStemmer();
4069        # Convert the search expression using the stemmer.
4070        my $retVal = $stemmer->PrepareSearchExpression($searchExpression);
4071        Trace("Cleaned keyword list for \"$searchExpression\" is \"$retVal\".") if T(3);
4072        # Return the result.
4073        return $retVal;
4074    }
4075    
4076    =head3 GetSourceObject
4077    
4078        my $source = $erdb->GetSourceObject();
4079    
4080    Return the object to be used in creating load files for this database.
4081    
4082  =cut  =cut
4083  #: Return Type ;  
4084  sub AddProperty {  sub GetSourceObject {
4085      # Get the parameters.      # Get the parameters.
4086      my ($self, $featureID, $key, @values) = @_;      my ($self) = @_;
4087      # Add the property using the attached attributes object.      # Do we already have one?
4088      $self->{_ca}->AddAttribute($featureID, $key, @values);      my $retVal = $self->{fig};
4089        if (! defined $retVal) {
4090            # Create the object.
4091            require FIG;
4092            $retVal = FIG->new();
4093            Trace("FIG source object created for process $$.") if T(ERDBLoadGroup => 3);
4094            # Set up retries to prevent the lost-connection error when harvesting
4095            # the feature data.
4096            my $dbh = $retVal->db_handle();
4097            $dbh->set_retries(5);
4098            # Save it for other times.
4099            $self->{fig} = $retVal;
4100        }
4101        # Return the object.
4102        return $retVal;
4103  }  }
4104    
4105  =head2 Virtual Methods  =head3 SectionList
4106    
4107  =head3 CleanKeywords      my @sections = $erdb->SectionList($fig);
4108    
4109  C<< my $cleanedString = $sprout->CleanKeywords($searchExpression); >>  Return a list of the names for the different data sections used when loading this database.
4110    The default is a single string, in which case there is only one section representing the
4111    entire database.
4112    
4113  Clean up a search expression or keyword list. This involves converting the periods  =cut
4114  in EC numbers to underscores, converting non-leading minus signs to underscores,  
4115  a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic  sub SectionList {
4116  characters. In addition, any extra spaces are removed.      # Get the parameters.
4117        my ($self, $source) = @_;
4118        # Ask the BaseSproutLoader for a section list.
4119        require BaseSproutLoader;
4120        my @retVal = BaseSproutLoader::GetSectionList($self, $source);
4121        # Return the list.
4122        return @retVal;
4123    }
4124    
4125    =head3 Loader
4126    
4127        my $groupLoader = $erdb->Loader($groupName, $options);
4128    
4129    Return an [[ERDBLoadGroupPm]] object for the specified load group. This method is used
4130    by L<ERDBGenerator.pl> to create the load group objects. If you are not using
4131    L<ERDBGenerator.pl>, you don't need to override this method.
4132    
4133  =over 4  =over 4
4134    
4135  =item searchExpression  =item groupName
4136    
4137  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
4138  contain boolean operators which need to be preserved. This includes leading  guaranteed to be a single word with only the first letter capitalized.
4139  minus signs.  
4140    =item options
4141    
4142    Reference to a hash of command-line options.
4143    
4144  =item RETURN  =item RETURN
4145    
4146  Cleaned expression or keyword list.  Returns an [[ERDBLoadGroupPm]] object that can be used to process the specified load group
4147    for this database.
4148    
4149  =back  =back
4150    
4151  =cut  =cut
4152    
4153  sub CleanKeywords {  sub Loader {
4154      # Get the parameters.      # Get the parameters.
4155      my ($self, $searchExpression) = @_;      my ($self, $groupName, $options) = @_;
4156      # Perform the standard cleanup.      # Compute the loader name.
4157      my $retVal = $self->ERDB::CleanKeywords($searchExpression);      my $loaderClass = "${groupName}SproutLoader";
4158      # Fix the periods in EC and TC numbers.      # Pull in its definition.
4159      $retVal =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g;      require "$loaderClass.pm";
4160      # Fix non-trailing periods.      # Create an object for it.
4161      $retVal =~ s/\.(\w)/_$1/g;      my $retVal = eval("$loaderClass->new(\$self, \$options)");
4162      # Fix non-leading minus signs.      # Insure it worked.
4163      $retVal =~ s/(\w)[\-]/$1_/g;      Confess("Could not create $loaderClass object: $@") if $@;
4164      # Fix the vertical bars and colons      # Return it to the caller.
     $retVal =~ s/(\w)[|:](\w)/$1'$2/g;  
     # Return the result.  
4165      return $retVal;      return $retVal;
4166  }  }
4167    
4168    
4169    =head3 LoadGroupList
4170    
4171        my @groups = $erdb->LoadGroupList();
4172    
4173    Returns a list of the names for this database's load groups. This method is used
4174    by L<ERDBGenerator.pl> when the user wishes to load all table groups. The default
4175    is a single group called 'All' that loads everything.
4176    
4177    =cut
4178    
4179    sub LoadGroupList {
4180        # Return the list.
4181        return qw(Feature Subsystem Genome Annotation Property Source Reaction Synonym Drug);
4182    }
4183    
4184    =head3 LoadDirectory
4185    
4186        my $dirName = $erdb->LoadDirectory();
4187    
4188    Return the name of the directory in which load files are kept. The default is
4189    the FIG temporary directory, which is a really bad choice, but it's always there.
4190    
4191    =cut
4192    
4193    sub LoadDirectory {
4194        # Get the parameters.
4195        my ($self) = @_;
4196        # Return the directory name.
4197        return $self->{dataDir};
4198    }
4199    
4200  =head2 Internal Utility Methods  =head2 Internal Utility Methods
4201    
4202    =head3 GetStemmer
4203    
4204        my $stermmer = $sprout->GetStemmer();
4205    
4206    Return the stemmer object for this database.
4207    
4208    =cut
4209    
4210    sub GetStemmer {
4211        # Get the parameters.
4212        my ($self) = @_;
4213        # Declare the return variable.
4214        my $retVal = $self->{stemmer};
4215        if (! defined $retVal) {
4216            # We don't have one pre-built, so we build and save it now.
4217            $retVal = BioWords->new(exceptions => "$FIG_Config::sproutData/Exceptions.txt",
4218                                     stops => "$FIG_Config::sproutData/StopWords.txt",
4219                                     cache => 0);
4220            $self->{stemmer} = $retVal;
4221        }
4222        # Return the result.
4223        return $retVal;
4224    }
4225    
4226  =head3 ParseAssignment  =head3 ParseAssignment
4227    
4228  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 3867  Line 4231 
4231    
4232  A functional assignment is always of the form  A functional assignment is always of the form
4233    
4234      C<set >I<YYYY>C< function to\n>I<ZZZZZ>      set YYYY function to
4235        ZZZZ
4236    
4237  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,
4238  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 3920  Line 4285 
4285      return @retVal;      return @retVal;
4286  }  }
4287    
4288    =head3 _CheckFeature
4289    
4290        my $flag = $sprout->_CheckFeature($fid);
4291    
4292    Return TRUE if the specified FID is probably an NMPDR feature ID, else FALSE.
4293    
4294    =over 4
4295    
4296    =item fid
4297    
4298    Feature ID to check.
4299    
4300    =item RETURN
4301    
4302    Returns TRUE if the FID is for one of the NMPDR genomes, else FALSE.
4303    
4304    =back
4305    
4306    =cut
4307    
4308    sub _CheckFeature {
4309        # Get the parameters.
4310        my ($self, $fid) = @_;
4311        # Insure we have a genome hash.
4312        my $genomes = $self->_GenomeHash();
4313        # Get the feature's genome ID.
4314        my ($genomeID) = FIGRules::ParseFeatureID($fid);
4315        # Return an indicator of whether or not the genome ID is in the hash.
4316        return ($self->{genomeHash}->{$genomeID} ? 1 : 0);
4317    }
4318    
4319  =head3 FriendlyTimestamp  =head3 FriendlyTimestamp
4320    
4321  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 3947  Line 4343 
4343  }  }
4344    
4345    
4346    =head3 Hint
4347    
4348        my $htmlText = Sprout::Hint($wikiPage, $hintID);
4349    
4350    Return the HTML for a help link that displays the specified hint text when it is clicked.
4351    This HTML can be put in forms to provide a useful hinting mechanism.
4352    
4353    =over 4
4354    
4355    =item wikiPage
4356    
4357    Name of the wiki page to be popped up when the hint mark is clicked.
4358    
4359    =item hintID
4360    
4361    ID of the text to display for the hint. This should correspond to a tip number
4362    in the Wiki.
4363    
4364    =item RETURN
4365    
4366    Returns the html for the hint facility. The resulting html shows the word "help" and
4367    uses the standard FIG popup technology.
4368    
4369    =back
4370    
4371    =cut
4372    
4373    sub Hint {
4374        # Get the parameters.
4375        my ($wikiPage, $hintID) = @_;
4376        # Declare the return variable.
4377        my $retVal;
4378        # Convert the wiki page name to a URL.
4379        my $wikiURL;
4380        if ($wikiPage =~ m#/#) {
4381            # Here it's a URL of some sort.
4382            $wikiURL = $wikiPage;
4383        } else {
4384            # Here it's a wiki page.
4385            my $page = join("", map { ucfirst $_ } split /\s+/, $wikiPage);
4386            if ($page =~ /^(.+?)\.(.+)$/) {
4387                $page = "$1/$2";
4388            } else {
4389                $page = "FIG/$page";
4390            }
4391            $wikiURL = "$FIG_Config::cgi_url/wiki/view.cgi/$page";
4392        }
4393        # Is there hint text?
4394        if (! $hintID) {
4395            # No. Create a new-page hint.
4396            $retVal = qq(&nbsp;<a class="hint" onclick="doPagePopup(this, '$wikiURL')">(help)</a>);
4397        } else {
4398            # With hint text, we create a popup window hint. We need to compute the hint URL.
4399            my $tipURL = "$FIG_Config::cgi_url/wiki/view.cgi/FIG/TWikiCustomTip" .
4400                Tracer::Pad($hintID, 3, 1, "0");
4401            # Create a hint pop-up link.
4402            $retVal = qq(&nbsp;<a class="hint" onclick="doHintPopup(this, '$wikiURL', '$tipURL')">(help)</a>);
4403        }
4404        # Return the HTML.
4405        return $retVal;
4406    }
4407    
4408    =head3 _GenomeHash
4409    
4410        my $gHash = $sprout->_GenomeHash();
4411    
4412    Return a hash mapping all NMPDR genome IDs to [[ERDBObjectPm]] genome objects.
4413    
4414    =cut
4415    
4416    sub _GenomeHash {
4417        # Get the parameters.
4418        my ($self) = @_;
4419        # Do we already have a filled hash?
4420        if (! $self->{genomeHashFilled}) {
4421            # No, create it.
4422            my %gHash = map { $_->PrimaryValue('id') => $_ } $self->GetList("Genome", "", []);
4423            $self->{genomeHash} = \%gHash;
4424            # Denote we have it.
4425            $self->{genomeHashFilled} = 1;
4426        }
4427        # Return the hash.
4428        return $self->{genomeHash};
4429    }
4430    
4431    =head3 _GenomeData
4432    
4433        my $genomeData = $sprout->_GenomeData($genomeID);
4434    
4435    Return an [[ERDBObjectPm]] object for the specified genome, or an undefined
4436    value if the genome does not exist.
4437    
4438    =over 4
4439    
4440    =item genomeID
4441    
4442    ID of the desired genome.
4443    
4444    =item RETURN
4445    
4446    Returns either an [[ERDBObjectPm]] containing the genome, or an undefined value.
4447    If the genome exists, it will have been read into the genome cache.
4448    
4449    =back
4450    
4451    =cut
4452    
4453    sub _GenomeData {
4454        # Get the parameters.
4455        my ($self, $genomeID) = @_;
4456        # Are we in the genome hash?
4457        if (! exists $self->{genomeHash}->{$genomeID} && ! $self->{genomeHashFilled}) {
4458            # The genome isn't in the hash, and the hash is not complete, so we try to
4459            # read it.
4460            $self->{genomeHash}->{$genomeID} = $self->GetEntity(Genome => $genomeID);
4461        }
4462        # Return the result.
4463        return $self->{genomeHash}->{$genomeID};
4464    }
4465    
4466    =head3 _CacheGenome
4467    
4468        $sprout->_CacheGenome($genomeID, $genomeData);
4469    
4470    Store the specified genome object in the genome cache if it is already there.
4471    
4472    =over 4
4473    
4474    =item genomeID
4475    
4476    ID of the genome to store in the cache.
4477    
4478    =item genomeData
4479    
4480    An [[ERDBObjectPm]] containing at least the data for the specified genome.
4481    Note that the Genome may not be the primary object in it, so a fully-qualified
4482    field name has to be used to retrieve data from it.
4483    
4484    =back
4485    
4486    =cut
4487    
4488    sub _CacheGenome {
4489        # Get the parameters.
4490        my ($self, $genomeID, $genomeData) = @_;
4491        # Only proceed if we don't already have the genome.
4492        if (! exists $self->{genomeHash}->{$genomeID}) {
4493            $self->{genomeHash}->{$genomeID} = $genomeData;
4494        }
4495    }
4496    
4497  1;  1;

Legend:
Removed from v.1.99  
changed lines
  Added in v.1.128

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3