[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.65, Sun Jun 18 07:20:33 2006 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;
     use Carp;  
5      use DBKernel;      use DBKernel;
6      use XML::Simple;      use XML::Simple;
7      use DBQuery;      use ERDBQuery;
8      use DBObject;      use ERDBObject;
9      use Tracer;      use Tracer;
10      use FIGRules;      use FIGRules;
11        use FidCheck;
12      use Stats;      use Stats;
13      use POSIX qw(strftime);      use POSIX qw(strftime);
14        use BasicLocation;
15        use CustomAttributes;
16        use RemoteCustomAttributes;
17        use CGI 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 27  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 78  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.
111        my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
112                                                      $FIG_Config::fig );
113      # Compute the options. We do this by starting with a table of defaults and overwriting with      # Compute the options. We do this by starting with a table of defaults and overwriting with
114      # the incoming data.      # the incoming data.
115      my $optionTable = Tracer::GetOptions({      my $optionTable = Tracer::GetOptions({
# Line 98  Line 117 
117                                                          # database type                                                          # database type
118                         dataDir      => $FIG_Config::sproutData,                         dataDir      => $FIG_Config::sproutData,
119                                                          # data file directory                                                          # data file directory
120                         xmlFileName  => "$FIG_Config::fig/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::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 117  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}, undef, $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.
152        $retVal->{groupHash} = undef;
153        # 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.      # Return it.
160      return $retVal;      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) {
180                Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);
181                $retVal = RemoteCustomAttributes->new($FIG_Config::attrURL);
182            } elsif ($FIG_Config::attrDbName) {
183                Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);
184                my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));
185                $retVal = CustomAttributes->new(user => $user);
186            }
187            # 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;
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 149  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 164  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 176  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 204  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 250  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 261  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 306  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 333  Line 502 
502      return $retVal;      return $retVal;
503  }  }
504    
505  =head3 GeneMenu  =head3 GenomeMenu
506    
507  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params); >>      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  Reference to a hash mapping attributes to values for the SELECT tag generated.  =item RETURN
520    
521  =item filterString  Returns the HTML for a genome selection control on a form (sometimes called a popup menu).
522    
523  A filter string for use in selecting the genomes. The filter string must conform  =back
 to the rules for the C<< ERDB->Get >> method.  
524    
525  =item params  The valid options are as follows.
526    
527  Reference to a list of values to be substituted in for the parameter marks in  =over 4
 the filter string.  
528    
529  =item RETURN  =item name
530    
531    Name to give this control for use in passing it to the form. The default is C<myGenomeControl>.
532    Terrible things will happen if you have two controls with the same name on the same page.
533    
534    =item filter
535    
536    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 multiSelect
543    
544  Returns an HTML select menu with the specified genomes as selectable options.  If TRUE, then the user can select multiple genomes. If FALSE, the user can only select one genome.
545    
546    =item size
547    
548    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) = @_;      my ($self, %options) = @_;
571      # Start the menu.      # Get the control's name and ID.
572      my $retVal = "<select " .      my $menuName = $options{name} || $options{id} || 'myGenomeControl';
573          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .      my $menuID = $options{id} || $menuName;
574          ">\n";      Trace("Genome menu name = $menuName with ID $menuID.") if T(3);
575      # Get the genomes.      # Compute the IDs for the status display.
576      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',      my $divID = "${menuID}_status";
577                                                                       'Genome(genus)',      my $urlID = "${menuID}_url";
578                                                                       'Genome(species)']);      # Compute the code to show selected genomes in the status area.
579      # Sort them by name.      my $showSelect = "showSelected('$menuID', '$divID', '$urlID', $FIG_Config::genome_control_cap)";
580      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;      # Check for single-select or multi-select.
581      # Loop through the genomes, creating the option tags.      my $multiSelect = $options{multiSelect} || 0;
582      for my $genomeData (@sorted) {      # Get the style data.
583          # Get the data for this genome.      my $class = $options{class} || '';
584          my ($genomeID, $genus, $species) = @{$genomeData};      # Get the list of pre-selected items.
585          # Get the contig count.      my $selections = $options{selected} || [];
586          my $count = $self->ContigCount($genomeID);      if (ref $selections ne 'ARRAY') {
587          my $counting = ($count == 1 ? "contig" : "contigs");          $selections = [ split /\s*,\s*/, $selections ];
588          # Build the option tag.      }
589          $retVal .= "<option value=\"$genomeID\">$genus $species ($genomeID) [$count $counting]</option>\n";      my %selected = map { $_ => 1 } @{$selections};
590        # Extract the filter information. The default is no filtering. It can be passed as a tab-delimited
591        # string, a hash reference, or a list reference.
592        my ($filterHash, $filterString);
593        my $filterParms = $options{filter} || "";
594        if (ref $filterParms eq 'HASH') {
595            $filterHash = $filterParms;
596            $filterParms = [];
597            $filterString = "";
598        } else {
599            if (! ref $filterParms) {
600                $filterParms = [split /\t|\\t/, $filterParms];
601            }
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 412  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 429  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 451  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 506  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 530  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 585  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 604  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 627  Line 1018 
1018      return ($contigID, $start, $dir, $len);      return ($contigID, $start, $dir, $len);
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 658  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 681  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 765  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 795  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 819  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    
1230  =over 4  =over 4
1231    
1232  =genomeID  =item genomeID
1233    
1234  ID of the genome whose feature count is desired.  ID of the genome whose feature count is desired.
1235    
# Line 865  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 891  Line 1284 
1284      my ($self, $genomeID) = @_;      my ($self, $genomeID) = @_;
1285      # Declare the return variable.      # Declare the return variable.
1286      my $retVal = {};      my $retVal = {};
1287      # Query the genome's features and annotations. We'll put the oldest annotations      # Query the genome's features.
1288      # first so that the last assignment to go into the hash will be the correct one.      my $query = $self->Get(['HasFeature', 'Feature'], "HasFeature(from-link) = ?",
     my $query = $self->Get(['HasFeature', 'IsTargetOfAnnotation', 'Annotation'],  
                            "HasFeature(from-link) = ? ORDER BY Annotation(time)",  
1289                             [$genomeID]);                             [$genomeID]);
1290      # Loop through the annotations.      # Loop through the features.
1291      while (my $data = $query->Fetch) {      while (my $data = $query->Fetch) {
1292          # Get the feature ID and annotation text.          # Get the feature ID and assignment.
1293          my ($fid, $annotation) = $data->Values(['HasFeature(from-link)',          my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']);
1294                                                  'Annotation(annotation)']);          if ($assignment) {
         # Check to see if this is an assignment. Note that the user really  
         # doesn't matter to us, other than we use it to determine whether or  
         # not this is an assignment.  
         my ($user, $assignment) = $self->_ParseAssignment('fig', $annotation);  
         if ($user) {  
             # Here it's an assignment. We put it in the return hash, overwriting  
             # any older assignment that might be present.  
1295              $retVal->{$fid} = $assignment;              $retVal->{$fid} = $assignment;
1296          }          }
1297      }      }
# Line 917  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 956  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 1004  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 1033  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 1056  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;  
                 }  
                 # Store the entry back into the hash table.  
                 $featuresFound{$featureID} = [$loc1, $loc2];  
1534              }              }
1535          }          }
1536      }      }
1537      # Now we must compute the list of the IDs for the features found. We start with a list      # Return the ERDB objects for the features found.
1538      # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,      return values %featuresFound;
     # but the result of the sort will be the same.)  
     my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;  
     # Now we sort by midpoint and yank out the feature IDs.  
     my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;  
     # Return it along with the min and max.  
     return (\@retVal, $min, $max);  
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 1146  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 1209  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 1264  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    
1695  The functional assignment is handled differently depending on the type of feature. If  The functional assignment is handled differently depending on the type of feature. If
1696  the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional  the feature is identified by a FIG ID (begins with the string C<fig|>), then the functional
1697  assignment is a type of annotation. The format of an assignment is described in  assignment is taken from the B<Feature> or C<Annotation> table, depending.
 L</ParseAssignment>. Its worth noting that we cannot filter on the content of the  
 annotation itself because it's a text field; however, this is not a big problem because  
 most features only have a small number of annotations.  
1698    
1699  Each user has an associated list of trusted users. The assignment returned will be the most  Each user has an associated list of trusted users. The assignment returned will be the most
1700  recent one by at least one of the trusted users. If no trusted user list is available, then  recent one by at least one of the trusted users. If no trusted user list is available, then
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 1292  Line 1712 
1712    
1713  =item userID (optional)  =item userID (optional)
1714    
1715  ID of the user whose function determination is desired. If omitted, only the latest  ID of the user whose function determination is desired. If omitted, the primary
1716  C<FIG> assignment will be returned.  functional assignment in the B<Feature> table will be returned.
1717    
1718  =item RETURN  =item RETURN
1719    
# Line 1308  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          # Here we have a FIG feature ID. We must build the list of trusted      # Only proceed if we have an ID.
1734          # users.      if ($fid) {
1735            # Here we have a FIG feature ID.
1736            if (!$userID) {
1737                # Use the primary assignment.
1738                ($retVal) = $self->GetEntityValues('Feature', $fid, ['Feature(assignment)']);
1739            } else {
1740                # We must build the list of trusted users.
1741          my %trusteeTable = ();          my %trusteeTable = ();
1742          # Check the user ID.          # Check the user ID.
1743          if (!$userID) {          if (!$userID) {
# Line 1335  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 1354  Line 1780 
1780                  }                  }
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 1366  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 1377  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 1401  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 1424  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 1438  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 1469  Line 1882 
1882      my %retVal = ();      my %retVal = ();
1883      # Loop through the incoming features.      # Loop through the incoming features.
1884      for my $featureID (@{$featureList}) {      for my $featureID (@{$featureList}) {
1885          # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1886          my $query = $self->Get(['IsBidirectionalBestHitOf'],          my $bbhData = FIGRules::BBHData($featureID);
                                "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",  
                                [$featureID, $genomeID]);  
1887          # Peel off the BBHs found.          # Peel off the BBHs found.
1888          my @found = ();          my @found = ();
1889          while (my $bbh = $query->Fetch) {          for my $bbh (@$bbhData) {
1890              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');              my $fid = $bbh->[0];
1891                my $bbGenome = $self->GenomeOf($fid);
1892                if ($bbGenome eq $genomeID) {
1893                    push @found, $fid;
1894                }
1895          }          }
1896          $retVal{$featureID} = \@found;          $retVal{$featureID} = \@found;
1897      }      }
# Line 1486  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    
1908  Sprout does not support real similarities, so this method just returns the bidirectional  This method just returns the bidirectional best hits for performance reasons.
 best hits.  
1909    
1910  =over 4  =over 4
1911    
# Line 1511  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 = $self->GetAll(['IsBidirectionalBestHitOf'],      my $lists = FIGRules::BBHData($featureID);
                               "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",  
                               [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],  
                               $count);  
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.
1935      return %retVal;      return %retVal;
1936  }  }
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 1553  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 1564  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 1587  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 1616  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 1631  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 1653  Line 2066 
2066  sub CoupledFeatures {  sub CoupledFeatures {
2067      # Get the parameters.      # Get the parameters.
2068      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2069      # Create a query to retrieve the functionally-coupled features.      # Ask the coupling server for the data.
2070      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
2071                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);      my @rawPairs = FIGRules::NetCouplingData('coupled_to', id1 => $featureID);
2072      # This value will be set to TRUE if we find at least one coupled feature.      Trace(scalar(@rawPairs) . " couplings returned.") if T(coupling => 3);
2073      my $found = 0;      # Form them into a hash.
     # 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          # Get the other feature that participates in the coupling.              $retVal{$featureID2} = $score;
         my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],  
                                            "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",  
                                            [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');  
         # 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 1684  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 1732  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;
2143          # 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);  
2144      }      }
2145      # Return the result.      # Return the result.
2146      return @retVal;      return @retVal;
2147  }  }
2148    
2149  =head3 GetCoupling  =head3 GetSynonymGroup
   
 C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>  
   
 Return the coupling (if any) for the specified pair of PEGs. If a coupling  
 exists, we return the coupling ID along with an indicator of whether the  
 coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.  
 In the second case, we say the coupling is I<inverted>. The importance of an  
 inverted coupling is that the PEGs in the evidence will appear in reverse order.  
2150    
2151  =over 4      my $id = $sprout->GetSynonymGroup($fid);
2152    
2153  =item peg1  Return the synonym group name for the specified feature.
2154    
2155  ID of the feature of interest.  =over 4
2156    
2157  =item peg2  =item fid
2158    
2159  ID of the potentially coupled feature.  ID of the feature whose synonym group is desired.
2160    
2161  =item RETURN  =item RETURN
2162    
2163  Returns a three-element list. The first element contains the database ID of  The name of the synonym group to which the feature belongs. If the feature does
2164  the coupling. The second element is FALSE if the coupling is stored in the  not belong to a synonym group, the feature ID itself is returned.
 database in the caller specified order and TRUE if it is stored in the  
 inverted order. The third element is the coupling's score. If the coupling  
 does not exist, all three list elements will be C<undef>.  
2165    
2166  =back  =back
2167    
2168  =cut  =cut
2169  #: Return Type $%@;  
2170  sub GetCoupling {  sub GetSynonymGroup {
2171      # Get the parameters.      # Get the parameters.
2172      my ($self, $peg1, $peg2) = @_;      my ($self, $fid) = @_;
2173      # Declare the return values. We'll start with the coupling ID and undefine the      # Declare the return variable.
2174      # flag and score until we have more information.      my $retVal;
2175      my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);      # Find the synonym group.
2176      # Find the coupling data.      my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
2177      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],                                     [$fid], 'IsSynonymGroupFor(from-link)');
                                  "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",  
                                  [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);  
2178      # Check to see if we found anything.      # Check to see if we found anything.
2179      if (!@pegs) {      if (@groups) {
2180          Trace("No coupling found.") if T(Coupling => 4);          $retVal = $groups[0];
         # No coupling, so undefine the return value.  
         $retVal = undef;  
2181      } else {      } else {
2182          # We have a coupling! Get the score and check for inversion.          $retVal = $fid;
         $score = $pegs[0]->[1];  
         my $firstFound = $pegs[0]->[0];  
         $inverted = ($firstFound ne $peg1);  
         Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);  
2183      }      }
2184      # Return the result.      # Return the result.
2185      return ($retVal, $inverted, $score);      return $retVal;
2186  }  }
2187    
2188  =head3 CouplingID  =head3 GetBoundaries
   
 C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>  
2189    
2190  Return the coupling ID for a pair of feature IDs.      my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList);
2191    
2192  The coupling ID is currently computed by joining the feature IDs in  Determine the begin and end boundaries for the locations in a list. All of the
2193  sorted order with a space. Client modules (that is, modules which  locations must belong to the same contig and have mostly the same direction in
2194  use Sprout) should not, however, count on this always being the  order for this method to produce a meaningful result. The resulting
2195  case. This method provides a way for abstracting the concept of a  begin/end pair will contain all of the bases in any of the locations.
 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")>.  
2196    
2197  =over 4  =over 4
2198    
2199  =item peg1  =item locList
   
 First feature of interest.  
2200    
2201  =item peg2  List of locations to process.
   
 Second feature of interest.  
2202    
2203  =item RETURN  =item RETURN
2204    
2205  Returns the ID that would be used to represent a functional coupling of  Returns a 3-tuple consisting of the contig ID, the beginning boundary,
2206  the two specified PEGs.  and the ending boundary. The beginning boundary will be left of the
2207    end for mostly-forward locations and right of the end for mostly-backward
2208    locations.
2209    
2210  =back  =back
2211    
2212  =cut  =cut
2213  #: Return Type $;  
2214  sub CouplingID {  sub GetBoundaries {
2215      return join " ", sort @_;      # Get the parameters.
2216  }      my ($self, @locList) = @_;
2217        # Set up the counters used to determine the most popular direction.
2218        my %counts = ( '+' => 0, '-' => 0 );
2219        # Get the last location and parse it.
2220        my $locObject = BasicLocation->new(pop @locList);
2221        # Prime the loop with its data.
2222        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
2223        # Count its direction.
2224        $counts{$locObject->Dir}++;
2225        # Loop through the remaining locations. Note that in most situations, this loop
2226        # will not iterate at all, because most of the time we will be dealing with a
2227        # singleton list.
2228        for my $loc (@locList) {
2229            # Create a location object.
2230            my $locObject = BasicLocation->new($loc);
2231            # Count the direction.
2232            $counts{$locObject->Dir}++;
2233            # Get the left end and the right end.
2234            my $left = $locObject->Left;
2235            my $right = $locObject->Right;
2236            # Merge them into the return variables.
2237            if ($left < $beg) {
2238                $beg = $left;
2239            }
2240            if ($right > $end) {
2241                $end = $right;
2242            }
2243        }
2244        # If the most common direction is reverse, flip the begin and end markers.
2245        if ($counts{'-'} > $counts{'+'}) {
2246            ($beg, $end) = ($end, $beg);
2247        }
2248        # Return the result.
2249        return ($contig, $beg, $end);
2250    }
2251    
2252  =head3 ReadFasta  =head3 ReadFasta
2253    
2254  C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>      my %sequenceData = Sprout::ReadFasta($fileName, $prefix);
2255    
2256  Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by  Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by
2257  one or more lines of data. The first line begins with a > character and contains an ID.  one or more lines of data. The first line begins with a > character and contains an ID.
# Line 1928  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 1993  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 2010  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 2021  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 2032  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 2062  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 2116  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 2176  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 2210  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;
2694  }  }
2695    
 =head3 Exists  
   
 C<< my $found = $sprout->Exists($entityName, $entityID); >>  
   
 Return TRUE if an entity exists, else FALSE.  
   
 =over 4  
   
 =item entityName  
   
 Name of the entity type (e.g. C<Feature>) relevant to the existence check.  
   
 =item entityID  
   
 ID of the entity instance whose existence is to be checked.  
   
 =item RETURN  
   
 Returns TRUE if the entity instance exists, else FALSE.  
   
 =back  
   
 =cut  
 #: Return Type $;  
 sub Exists {  
     # Get the parameters.  
     my ($self, $entityName, $entityID) = @_;  
     # Check for the entity instance.  
     Trace("Checking existence of $entityName with ID=$entityID.") if T(4);  
     my $testInstance = $self->GetEntity($entityName, $entityID);  
     # Return an existence indicator.  
     my $retVal = ($testInstance ? 1 : 0);  
     return $retVal;  
 }  
   
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 2281  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 2306  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 2322  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 2358  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 2408  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 2436  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 arbitrary key-value pairs associated with a feature. (At some point they  
 will also be associated with genomes.) A property value is represented by a 4-tuple of  
 the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter  
   
 =over 4  
   
 =item fid  
   
 ID of the feature possessing the property.  
   
 =item key  
   
 Name or key of the property.  
   
 =item value  
   
 Value of the property.  
   
 =item url  
   
 URL of the document that indicated the property should have this particular value, or an  
 empty string if no such document exists.  
   
 =back  
   
 The parameters act as a filter for the desired data. Any non-null parameter will  
 automatically match all the tuples returned. So, specifying just the I<$fid> will  
 return all the properties of the specified feature; similarly, specifying the I<$key>  
 and I<$value> parameters will return all the features having the specified property  
 value.  
   
 A single property key can have many values, representing different ideas about the  
 feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is  
 virulent, and another may declare that it is not virulent. A query about the virulence of  
 C<fig|83333.1.peg.10> would be coded as  
   
     my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');  
   
 Here the I<$value> and I<$url> fields are left blank, indicating that those fields are  
 not to be filtered. The tuples returned would be  
   
     ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')  
     ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')  
   
 =cut  
 #: Return Type @@;  
 sub GetProperties {  
     # Get the parameters.  
     my ($self, @parms) = @_;  
     # Declare the return variable.  
     my @retVal = ();  
     # Now we need to create a WHERE clause that will get us the data we want. First,  
     # we create a list of the columns containing the data for each parameter.  
     my @colNames = ('HasProperty(from-link)', 'Property(property-name)',  
                     'Property(property-value)', 'HasProperty(evidence)');  
     # Now we build the WHERE clause and the list of parameter values.  
     my @where = ();  
     my @values = ();  
     for (my $i = 0; $i <= $#colNames; $i++) {  
         my $parm = $parms[$i];  
         if (defined $parm && ($parm ne '')) {  
             push @where, "$colNames[$i] = ?";  
             push @values, $parm;  
         }  
     }  
     # Format the WHERE clause.  
     my $filter = (@values > 0 ? (join " AND ", @where) : undef);  
     # Ask for all the propertie values with the desired characteristics.  
     my $query = $self->Get(['HasProperty', 'Property'], $filter, \@values);  
     while (my $valueObject = $query->Fetch()) {  
         my @tuple = $valueObject->Values(\@colNames);  
         push @retVal, \@tuple;  
     }  
     # Return the result.  
     return @retVal;  
 }  
   
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
2880  that a feature is essential to the survival of the organism or that it has benign influence  that a feature is essential to the survival of the organism or that it has benign influence
2881  on the activities of a pathogen. Each property is returned as a triple of the form  on the activities of a pathogen. Each property is returned as a triple of the form
2882  C<($key,$value,$url)>, where C<$key> is the property name, C<$value> is its value (commonly  C<($key,@values)>, where C<$key> is the property name and  C<@values> are its values.
 a 1 or a 0, but possibly a string or a floating-point value), and C<$url> is a string describing  
 the web address or citation in which the property's value for the feature was identified.  
2883    
2884  =over 4  =over 4
2885    
# Line 2539  Line 2889 
2889    
2890  =item RETURN  =item RETURN
2891    
2892  Returns a list of triples, each triple containing the property name, its value, and a URL or  Returns a list of tuples, each tuple containing the property name and its values.
 citation.  
2893    
2894  =back  =back
2895    
# Line 2550  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 @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],      my @attributes = $self->ca->GetAttributes($featureID);
2903                              ['Property(property-name)', 'Property(property-value)',      # Strip the feature ID off each tuple.
2904                               'HasProperty(evidence)']);      my @retVal = ();
2905        for my $attributeRow (@attributes) {
2906            shift @{$attributeRow};
2907            push @retVal, $attributeRow;
2908        }
2909      # Return the resulting list.      # Return the resulting list.
2910      return @retVal;      return @retVal;
2911  }  }
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 2585  Line 2938 
2938      return $retVal;      return $retVal;
2939  }  }
2940    
2941    =head3 PropertyID
2942    
2943        my $id = $sprout->PropertyID($propName, $propValue);
2944    
2945    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
2947    Sprout properties, mostly for use in search optimization.
2948    
2949    =over 4
2950    
2951    =item propName
2952    
2953    Name of the desired property.
2954    
2955    =item propValue
2956    
2957    Value expected for the desired property.
2958    
2959    =item RETURN
2960    
2961    Returns the ID of the name/value pair, or C<undef> if the pair does not exist.
2962    
2963    =back
2964    
2965    =cut
2966    
2967    sub PropertyID {
2968        # Get the parameters.
2969        my ($self, $propName, $propValue) = @_;
2970        # Try to find the ID.
2971        my ($retVal) = $self->GetFlat(['Property'],
2972                                      "Property(property-name) = ? AND Property(property-value) = ?",
2973                                      [$propName, $propValue], 'Property(id)');
2974        # Return the result.
2975        return $retVal;
2976    }
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 2636  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 2679  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 2710  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 2758  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 2781  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(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",      # the Sprout database!
3176                                  [$featureID], 'HasSSCell(from-link)');      my @retVal = $self->GetFlat(['HasRoleInSubsystem', 'Subsystem'], "HasRoleInSubsystem(from-link) = ?",
3177      # Return the result.                                  [$featureID], 'HasRoleInSubsystem(to-link)');
3178      return @retVal;      # Return the result, sorted.
3179        return sort @retVal;
3180  }  }
3181    
3182    =head3 GenomeSubsystemData
3183    
3184        my %featureData = $sprout->GenomeSubsystemData($genomeID);
3185    
3186    Return a hash mapping genome features to their subsystem roles.
3187    
3188    =over 4
3189    
3190    =item genomeID
3191    
3192    ID of the genome whose subsystem feature map is desired.
3193    
3194    =item RETURN
3195    
3196    Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb
3197    2-tuple contains a subsystem name followed by a role ID.
3198    
3199    =back
3200    
3201    =cut
3202    
3203    sub GenomeSubsystemData {
3204        # Get the parameters.
3205        my ($self, $genomeID) = @_;
3206        # Declare the return variable.
3207        my %retVal = ();
3208        # Get a list of the genome features that participate in subsystems. For each
3209        # feature we get its subsystem ID and the corresponding roles.
3210        my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf', 'HasSSCell'],
3211                                     "HasFeature(from-link) = ?", [$genomeID],
3212                                     ['HasFeature(to-link)', 'IsRoleOf(from-link)',  'HasSSCell(from-link)']);
3213        # Now we get a list of valid subsystems. These are the subsystems connected to the genome with
3214        # a non-negative variant code.
3215        my %subs = map { $_ => 1 } $self->GetFlat(['ParticipatesIn'],
3216                                                    "ParticipatesIn(from-link) = ? AND ParticipatesIn(variant-code) >= 0",
3217                                                    [$genomeID], 'ParticipatesIn(to-link)');
3218        # We loop through @roleData to build the hash.
3219        for my $roleEntry (@roleData) {
3220            # Get the data for this feature and cell.
3221            my ($fid, $role, $subsys) = @{$roleEntry};
3222            Trace("Subsystem for $fid is $subsys.") if T(4);
3223            # Check the subsystem;
3224            if ($subs{$subsys}) {
3225                Trace("Subsystem found.") if T(4);
3226                # Insure this feature has an entry in the return hash.
3227                if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
3228                # Merge in this new data.
3229                push @{$retVal{$fid}}, [$subsys, $role];
3230            }
3231        }
3232        # Return the result.
3233        return %retVal;
3234    }
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 2825  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 = $self->GetFlat(['IsBidirectionalBestHitOf'],      my $bbhData = FIGRules::BBHData($featureID);
3272                                       "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],      my @bbhFeatures = map { $_->[0] } @$bbhData;
                                      'IsBidirectionalBestHitOf(to-link)');  
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 2845  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 2880  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 2893  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 2963  Line 3405 
3405      # Loop through the input triples.      # Loop through the input triples.
3406      my $n = length $sequence;      my $n = length $sequence;
3407      for (my $i = 0; $i < $n; $i += 3) {      for (my $i = 0; $i < $n; $i += 3) {
3408          # Get the current triple from the sequence.          # Get the current triple from the sequence. Note we convert to
3409          my $triple = substr($sequence, $i, 3);          # upper case to insure a match.
3410            my $triple = uc substr($sequence, $i, 3);
3411          # Translate it using the table.          # Translate it using the table.
3412          my $protein = "X";          my $protein = "X";
3413          if (exists $table->{$triple}) { $protein = $table->{$triple}; }          if (exists $table->{$triple}) { $protein = $table->{$triple}; }
# Line 2978  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 2997  Line 3440 
3440      return @retVal;      return @retVal;
3441  }  }
3442    
3443  =head3 LowBBHs  =head3 BBHMatrix
3444    
3445  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>      my $bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets);
3446    
3447  Return the bidirectional best hits of a feature whose score is no greater than a  Find all the bidirectional best hits for the features of a genome in a
3448  specified cutoff value. A higher cutoff value will allow inclusion of hits with  specified list of target genomes. The return value will be a hash mapping
3449  a greater score. The value returned is a map of feature IDs to scores.  features in the original genome to their bidirectional best hits in the
3450    target genomes.
3451    
3452  =over 4  =over 4
3453    
3454  =item featureID  =item genomeID
3455    
3456  ID of the feature whose best hits are desired.  ID of the genome whose features are to be examined for bidirectional best hits.
3457    
3458  =item cutoff  =item cutoff
3459    
3460  Maximum permissible score for inclusion in the results.  A cutoff value. Only hits with a score lower than the cutoff will be returned.
3461    
3462    =item targets
3463    
3464    List of target genomes. Only pairs originating in the original
3465    genome and landing in one of the target genomes will be returned.
3466    
3467  =item RETURN  =item RETURN
3468    
3469  Returns a hash mapping feature IDs to scores.  Returns a reference to a hash mapping each feature in the original genome
3470    to a sub-hash mapping its BBH pegs in the target genomes to their scores.
3471    
3472  =back  =back
3473    
3474  =cut  =cut
3475  #: Return Type %;  
3476  sub LowBBHs {  sub BBHMatrix {
3477      # Get the parsameters.      # Get the parameters.
3478      my ($self, $featureID, $cutoff) = @_;      my ($self, $genomeID, $cutoff, @targets) = @_;
3479      # Create the return hash.      # Declare the return variable.
3480      my %retVal = ();      my %retVal = ();
3481      # Create a query to get the desired BBHs.      # Ask for the BBHs.
3482      my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets);
3483                                  'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',      Trace("Retrieved " . scalar(@bbhList) . " BBH results.") if T(3);
3484                                  [$cutoff, $featureID],      # We now have a set of 4-tuples that we need to convert into a hash of hashes.
3485                                  ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);      for my $bbhData (@bbhList) {
3486      # Form the results into the return hash.          my ($peg1, $peg2, $score) = @{$bbhData};
3487      for my $pair (@bbhList) {          if (! exists $retVal{$peg1}) {
3488          $retVal{$pair->[0]} = $pair->[1];              $retVal{$peg1} = { $peg2 => $score };
3489            } else {
3490                $retVal{$peg1}->{$peg2} = $score;
3491            }
3492      }      }
3493      # Return the result.      # Return the result.
3494      return %retVal;      return \%retVal;
3495  }  }
3496    
 =head3 GetGroups  
3497    
3498  C<< my %groups = $sprout->GetGroups(\@groupList); >>  =head3 SimMatrix
3499    
3500  Return a hash mapping each group to the IDs of the genomes in the group.      my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets);
3501  A list of groups may be specified, in which case only those groups will be  
3502  shown. Alternatively, if no parameter is supplied, all groups will be  Find all the similarities for the features of a genome in a
3503  included. Genomes that are not in any group are omitted.  specified list of target genomes. The return value will be a hash mapping
3504    features in the original genome to their similarites in the
3505    target genomes.
3506    
3507    =over 4
3508    
3509    =item genomeID
3510    
3511    ID of the genome whose features are to be examined for similarities.
3512    
3513    =item cutoff
3514    
3515    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3516    
3517    =item targets
3518    
3519    List of target genomes. Only pairs originating in the original
3520    genome and landing in one of the target genomes will be returned.
3521    
3522    =item RETURN
3523    
3524    Returns a hash mapping each feature in the original genome to a hash mapping its
3525    similar pegs in the target genomes to their scores.
3526    
3527    =back
3528    
3529  =cut  =cut
3530  #: Return Type %@;  
3531  sub GetGroups {  sub SimMatrix {
3532      # Get the parameters.      # Get the parameters.
3533      my ($self, $groupList) = @_;      my ($self, $genomeID, $cutoff, @targets) = @_;
3534      # Declare the return value.      # Declare the return variable.
3535      my %retVal = ();      my %retVal = ();
3536      # Determine whether we are getting all the groups or just some.      # Get the list of features in the source organism.
3537      if (defined $groupList) {      my @fids = $self->FeaturesOf($genomeID);
3538          # Here we have a group list. Loop through them individually,      # Ask for the sims. We only want similarities to fig features.
3539          # getting a list of the relevant genomes.      my $simList = FIGRules::GetNetworkSims($self, \@fids, {}, 1000, $cutoff, "fig");
3540          for my $group (@{$groupList}) {      if (! defined $simList) {
3541              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",          Confess("Unable to retrieve similarities from server.");
                 [$group], "Genome(id)");  
             $retVal{$group} = \@genomeIDs;  
         }  
3542      } else {      } else {
3543          # Here we need all of the groups. In this case, we run through all          Trace("Processing sims.") if T(3);
3544          # of the genome records, putting each one found into the appropriate          # We now have a set of sims that we need to convert into a hash of hashes. First, we
3545          # group. Note that we use a filter clause to insure that only genomes          # Create a hash for the target genomes.
3546          # in groups are included in the return set.          my %targetHash = map { $_ => 1 } @targets;
3547          my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],          for my $simData (@{$simList}) {
3548                                      ['Genome(id)', 'Genome(group-name)']);              # Get the PEGs and the score.
3549          # Loop through the genomes found.              my ($peg1, $peg2, $score) = ($simData->id1, $simData->id2, $simData->psc);
3550          for my $genome (@genomes) {              # Insure the second ID is in the target list.
3551              # Pop this genome's ID off the current list.              my ($genome2) = FIGRules::ParseFeatureID($peg2);
3552              my @groups = @{$genome};              if (exists $targetHash{$genome2}) {
3553              my $genomeID = shift @groups;                  # Here it is. Now we need to add it to the return hash. How we do that depends
3554              # Loop through the groups, adding the genome ID to each group's                  # on whether or not $peg1 is new to us.
3555              # list.                  if (! exists $retVal{$peg1}) {
3556              for my $group (@groups) {                      $retVal{$peg1} = { $peg2 => $score };
3557                  Tracer::AddToListMap(\%retVal, $group, $genomeID);                  } else {
3558                        $retVal{$peg1}->{$peg2} = $score;
3559              }              }
3560          }          }
3561      }      }
3562      # Return the hash we just built.      }
3563        # Return the result.
3564      return %retVal;      return %retVal;
3565  }  }
3566    
 =head3 MyGenomes  
3567    
3568  C<< my @genomes = Sprout::MyGenomes($dataDir); >>  =head3 LowBBHs
3569    
3570  Return a list of the genomes to be included in the Sprout.      my %bbhMap = $sprout->LowBBHs($featureID, $cutoff);
3571    
3572  This method is provided for use during the Sprout load. It presumes the Genome load file has  Return the bidirectional best hits of a feature whose score is no greater than a
3573  already been created. (It will be in the Sprout data directory and called either C<Genome>  specified cutoff value. A higher cutoff value will allow inclusion of hits with
3574  or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome  a greater score. The value returned is a map of feature IDs to scores.
 IDs.  
3575    
3576  =over 4  =over 4
3577    
3578  =item dataDir  =item featureID
3579    
3580  Directory containing the Sprout load files.  ID of the feature whose best hits are desired.
3581    
3582    =item cutoff
3583    
3584    Maximum permissible score for inclusion in the results.
3585    
3586    =item RETURN
3587    
3588    Returns a hash mapping feature IDs to scores.
3589    
3590  =back  =back
3591    
3592  =cut  =cut
3593  #: Return Type @;  #: Return Type %;
3594  sub MyGenomes {  sub LowBBHs {
3595      # Get the parameters.      # Get the parsameters.
3596      my ($dataDir) = @_;      my ($self, $featureID, $cutoff) = @_;
3597      # Compute the genome file name.      # Create the return hash.
3598      my $genomeFileName = LoadFileName($dataDir, "Genome");      my %retVal = ();
3599      # Extract the genome IDs from the files.      # Query for the desired BBHs.
3600      my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);      my $bbhList = FIGRules::BBHData($featureID, $cutoff);
3601        # Form the results into the return hash.
3602        for my $pair (@$bbhList) {
3603            my $fid = $pair->[0];
3604            if ($self->Exists('Feature', $fid)) {
3605                $retVal{$fid} = $pair->[1];
3606            }
3607        }
3608        # Return the result.
3609        return %retVal;
3610    }
3611    
3612    =head3 Sims
3613    
3614        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
3617    Sprout database; rather, they are retrieved from a network server. The similarities are
3618    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3619    so that its elements can be accessed by name.
3620    
3621    Similarities can be either raw or expanded. The raw similarities are basic
3622    hits between features with similar DNA. Expanding a raw similarity drags in any
3623    features considered substantially identical. So, for example, if features B<A1>,
3624    B<A2>, and B<A3> are all substantially identical to B<A>, then a raw similarity
3625    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3626    
3627    =over 4
3628    
3629    =item fid
3630    
3631    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
3635    
3636    Maximum number of similarities to return.
3637    
3638    =item maxP
3639    
3640    Minumum allowable similarity score.
3641    
3642    =item select
3643    
3644    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3645    means only similarities to FIG features are returned; C<all> means all expanded
3646    similarities are returned; and C<figx> means similarities are expanded until the
3647    number of FIG features equals the maximum.
3648    
3649    =item max_expand
3650    
3651    The maximum number of features to expand.
3652    
3653    =item filters
3654    
3655    Reference to a hash containing filter information, or a subroutine that can be
3656    used to filter the sims.
3657    
3658    =item RETURN
3659    
3660    Returns a reference to a list of similarity objects, or C<undef> if an error
3661    occurred.
3662    
3663    =back
3664    
3665    =cut
3666    
3667    sub Sims {
3668        # Get the parameters.
3669        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3670        # Create the shim object to test for deleted FIDs.
3671        my $shim = FidCheck->new($self);
3672        # Ask the network for sims.
3673        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3674        # Return the result.
3675        return $retVal;
3676    }
3677    
3678    =head3 IsAllGenomes
3679    
3680        my $flag = $sprout->IsAllGenomes(\@list, \@checkList);
3681    
3682    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
3684    compared to a list of all the genomes.
3685    
3686    =over 4
3687    
3688    =item list
3689    
3690    Reference to the list to be compared to the second list.
3691    
3692    =item checkList (optional)
3693    
3694    Reference to the comparison target list. Every genome ID in this list must occur at
3695    least once in the first list. If this parameter is omitted, a list of all the genomes
3696    is used.
3697    
3698    =item RETURN
3699    
3700    Returns TRUE if every item in the second list appears at least once in the
3701    first list, else FALSE.
3702    
3703    =back
3704    
3705    =cut
3706    
3707    sub IsAllGenomes {
3708        # Get the parameters.
3709        my ($self, $list, $checkList) = @_;
3710        # Supply the checklist if it was omitted.
3711        $checkList = [$self->Genomes()] if ! defined($checkList);
3712        # Create a hash of the original list.
3713        my %testList = map { $_ => 1 } @{$list};
3714        # Declare the return variable. We assume that the representation
3715        # is complete and stop at the first failure.
3716        my $retVal = 1;
3717        my $n = scalar @{$checkList};
3718        for (my $i = 0; $retVal && $i < $n; $i++) {
3719            if (! $testList{$checkList->[$i]}) {
3720                $retVal = 0;
3721            }
3722        }
3723        # Return the result.
3724        return $retVal;
3725    }
3726    
3727    =head3 GetGroups
3728    
3729        my %groups = $sprout->GetGroups(\@groupList);
3730    
3731    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
3733    shown. Alternatively, if no parameter is supplied, all groups will be
3734    included. Genomes that are not in any group are omitted.
3735    
3736    =cut
3737    #: Return Type %@;
3738    sub GetGroups {
3739        # Get the parameters.
3740        my ($self, $groupList) = @_;
3741        # Declare the return value.
3742        my %retVal = ();
3743        # Determine whether we are getting all the groups or just some.
3744        if (defined $groupList) {
3745            # Here we have a group list. Loop through them individually,
3746            # getting a list of the relevant genomes.
3747            for my $group (@{$groupList}) {
3748                my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3749                    [$group], "Genome(id)");
3750                $retVal{$group} = \@genomeIDs;
3751            }
3752        } else {
3753            # Here we need all of the groups. In this case, we run through all
3754            # of the genome records, putting each one found into the appropriate
3755            # group. Note that we use a filter clause to insure that only genomes
3756            # in real NMPDR groups are included in the return set.
3757            my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3758                                        [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3759            # Loop through the genomes found.
3760            for my $genome (@genomes) {
3761                # Get the genome ID and group, and add this genome to the group's list.
3762                my ($genomeID, $group) = @{$genome};
3763                push @{$retVal{$group}}, $genomeID;
3764            }
3765        }
3766        # Return the hash we just built.
3767        return %retVal;
3768    }
3769    
3770    =head3 MyGenomes
3771    
3772        my @genomes = Sprout::MyGenomes($dataDir);
3773    
3774    Return a list of the genomes to be included in the Sprout.
3775    
3776    This method is provided for use during the Sprout load. It presumes the Genome load file has
3777    already been created. (It will be in the Sprout data directory and called either C<Genome>
3778    or C<Genome.dtx>.) Essentially, it reads in the Genome load file and strips out the genome
3779    IDs.
3780    
3781    =over 4
3782    
3783    =item dataDir
3784    
3785    Directory containing the Sprout load files.
3786    
3787    =back
3788    
3789    =cut
3790    #: Return Type @;
3791    sub MyGenomes {
3792        # Get the parameters.
3793        my ($dataDir) = @_;
3794        # Compute the genome file name.
3795        my $genomeFileName = LoadFileName($dataDir, "Genome");
3796        # Extract the genome IDs from the files.
3797        my @retVal = map { $_ =~ /^(\S+)/; $1 } Tracer::GetFile($genomeFileName);
3798      # Return the result.      # Return the result.
3799      return @retVal;      return @retVal;
3800  }  }
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 3164  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 3190  Line 3868 
3868      # Get the parameters.      # Get the parameters.
3869      my ($self, $genomeID, $testFlag) = @_;      my ($self, $genomeID, $testFlag) = @_;
3870      # Perform the delete for the genome's features.      # Perform the delete for the genome's features.
3871      my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);      my $retVal = $self->Delete('Feature', "fig|$genomeID.%", testMode => $testFlag);
3872      # Perform the delete for the primary genome data.      # Perform the delete for the primary genome data.
3873      my $stats = $self->Delete('Genome', $genomeID, $testFlag);      my $stats = $self->Delete('Genome', $genomeID, testMode => $testFlag);
3874      $retVal->Accumulate($stats);      $retVal->Accumulate($stats);
3875      # Return the result.      # Return the result.
3876      return $retVal;      return $retVal;
3877  }  }
3878    
3879    =head3 Fix
3880    
3881        my %fixedHash = $sprout->Fix(%groupHash);
3882    
3883    Prepare a genome group hash (like that returned by L</GetGroups>) for processing.
3884    The groups will be combined into the appropriate super-groups.
3885    
3886    =over 4
3887    
3888    =item groupHash
3889    
3890    Hash to be fixed up.
3891    
3892    =item RETURN
3893    
3894    Returns a fixed-up version of the hash.
3895    
3896    =back
3897    
3898    =cut
3899    
3900    sub Fix {
3901        # Get the parameters.
3902        my ($self, %groupHash) = @_;
3903        # Create the result hash.
3904        my %retVal = ();
3905        # Copy over the genomes.
3906        for my $groupID (keys %groupHash) {
3907            # Get the super-group name.
3908            my $realGroupID = $self->SuperGroup($groupID);
3909            # Append this group's genomes into the result hash
3910            # using the super-group name.
3911            push @{$retVal{$realGroupID}}, @{$groupHash{$groupID}};
3912        }
3913        # Return the result hash.
3914        return %retVal;
3915    }
3916    
3917    =head3 GroupPageName
3918    
3919        my $name = $sprout->GroupPageName($group);
3920    
3921    Return the name of the page for the specified NMPDR group.
3922    
3923    =over 4
3924    
3925    =item group
3926    
3927    Name of the relevant group.
3928    
3929    =item RETURN
3930    
3931    Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3932    memory it will be read in.
3933    
3934    =back
3935    
3936    =cut
3937    
3938    sub GroupPageName {
3939        # Get the parameters.
3940        my ($self, $group) = @_;
3941        # Check for the group file data.
3942        my %superTable = $self->CheckGroupFile();
3943        # Compute the real group name.
3944        my $realGroup = $self->SuperGroup($group);
3945        # Get the associated page name.
3946        my $retVal = "../content/$superTable{$realGroup}->{page}";
3947        # Return the result.
3948        return $retVal;
3949    }
3950    
3951    
3952    =head3 AddProperty
3953    
3954        $sprout->AddProperty($featureID, $key, @values);
3955    
3956    Add a new attribute value (Property) to a feature.
3957    
3958    =over 4
3959    
3960    =item peg
3961    
3962    ID of the feature to which the attribute is to be added.
3963    
3964    =item key
3965    
3966    Name of the attribute (key).
3967    
3968    =item values
3969    
3970    Values of the attribute.
3971    
3972    =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    =head3 CheckGroupFile
3984    
3985        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    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
3999    
4000    =item specials
4001    
4002    Reference to a hash whose keys are the names of special species.
4003    
4004    =item contents
4005    
4006    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
4011    
4012    =cut
4013    
4014    sub CheckGroupFile {
4015        # Get the parameters.
4016        my ($self) = @_;
4017        # Check to see if we already have this hash.
4018        if (! defined $self->{groupHash}) {
4019            # We don't, so we need to read it in.
4020            my %groupHash;
4021            # Read the group file.
4022            my @groupLines = Tracer::GetFile("$FIG_Config::sproutData/groups.tbl");
4023            # Loop through the list of sort-of groups.
4024            for my $groupLine (@groupLines) {
4025                my ($name, $specials, @contents) = split /\t/, $groupLine;
4026                $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.
4034        return %{$self->{groupHash}};
4035    }
4036    
4037    =head2 Virtual Methods
4038    
4039    =head3 CleanKeywords
4040    
4041        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
4049    
4050    =item searchExpression
4051    
4052    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 RETURN
4057    
4058    Cleaned expression or keyword list.
4059    
4060    =back
4061    
4062    =cut
4063    
4064    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
4083    
4084    sub GetSourceObject {
4085        # Get the parameters.
4086        my ($self) = @_;
4087        # Do we already have one?
4088        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    =head3 SectionList
4106    
4107        my @sections = $erdb->SectionList($fig);
4108    
4109    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    =cut
4114    
4115    sub SectionList {
4116        # 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
4134    
4135    =item groupName
4136    
4137    Name of the load group whose object is to be returned. The group name is
4138    guaranteed to be a single word with only the first letter capitalized.
4139    
4140    =item options
4141    
4142    Reference to a hash of command-line options.
4143    
4144    =item RETURN
4145    
4146    Returns an [[ERDBLoadGroupPm]] object that can be used to process the specified load group
4147    for this database.
4148    
4149    =back
4150    
4151    =cut
4152    
4153    sub Loader {
4154        # Get the parameters.
4155        my ($self, $groupName, $options) = @_;
4156        # Compute the loader name.
4157        my $loaderClass = "${groupName}SproutLoader";
4158        # Pull in its definition.
4159        require "$loaderClass.pm";
4160        # Create an object for it.
4161        my $retVal = eval("$loaderClass->new(\$self, \$options)");
4162        # Insure it worked.
4163        Confess("Could not create $loaderClass object: $@") if $@;
4164        # Return it to the caller.
4165        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 3208  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 3254  Line 4278 
4278      }      }
4279      # If we have an assignment, we need to clean the function text. There may be      # If we have an assignment, we need to clean the function text. There may be
4280      # extra junk at the end added as a note from the user.      # extra junk at the end added as a note from the user.
4281      if (@retVal) {      if (defined( $retVal[1] )) {
4282          $retVal[1] =~ s/(\t\S)?\s*$//;          $retVal[1] =~ s/(\t\S)?\s*$//;
4283      }      }
4284      # Return the result list.      # Return the result list.
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 3287  Line 4342 
4342      return $retVal;      return $retVal;
4343  }  }
4344    
 =head3 AddProperty  
4345    
4346  C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>  =head3 Hint
4347    
4348        my $htmlText = Sprout::Hint($wikiPage, $hintID);
4349    
4350  Add a new attribute value (Property) to a feature. In the SEED system, attributes can  Return the HTML for a help link that displays the specified hint text when it is clicked.
4351  be added to almost any object. In Sprout, they can only be added to features. In  This HTML can be put in forms to provide a useful hinting mechanism.
 Sprout, attributes are implemented using I<properties>. A property represents a key/value  
 pair. If the particular key/value pair coming in is not already in the database, a new  
 B<Property> record is created to hold it.  
4352    
4353  =over 4  =over 4
4354    
4355  =item peg  =item wikiPage
4356    
4357  ID of the feature to which the attribute is to be replied.  Name of the wiki page to be popped up when the hint mark is clicked.
4358    
4359  =item key  =item hintID
4360    
4361  Name of the attribute (key).  ID of the text to display for the hint. This should correspond to a tip number
4362    in the Wiki.
4363    
4364  =item value  =item RETURN
4365    
4366  Value of the attribute.  Returns the html for the hint facility. The resulting html shows the word "help" and
4367    uses the standard FIG popup technology.
4368    
4369  =item url  =back
4370    
4371  URL or text citation from which the property was obtained.  =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  =back
4450    
4451  =cut  =cut
4452  #: Return Type ;  
4453  sub AddProperty {  sub _GenomeData {
4454      # Get the parameters.      # Get the parameters.
4455      my ($self, $featureID, $key, $value, $url) = @_;      my ($self, $genomeID) = @_;
4456      # Declare the variable to hold the desired property ID.      # Are we in the genome hash?
4457      my $propID;      if (! exists $self->{genomeHash}->{$genomeID} && ! $self->{genomeHashFilled}) {
4458      # Attempt to find a property record for this key/value pair.          # The genome isn't in the hash, and the hash is not complete, so we try to
4459      my @properties = $self->GetFlat(['Property'],          # read it.
4460                                     "Property(property-name) = ? AND Property(property-value) = ?",          $self->{genomeHash}->{$genomeID} = $self->GetEntity(Genome => $genomeID);
                                    [$key, $value], 'Property(id)');  
     if (@properties) {  
         # Here the property is already in the database. We save its ID.  
         $propID = $properties[0];  
         # Here the property value does not exist. We need to generate an ID. It will be set  
         # to a number one greater than the maximum value in the database. This call to  
         # GetAll will stop after one record.  
         my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],  
                                         1);  
         $propID = $maxProperty[0]->[0] + 1;  
         # Insert the new property value.  
         $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });  
4461      }      }
4462      # Now we connect the incoming feature to the property.      # Return the result.
4463      $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });      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.65  
changed lines
  Added in v.1.128

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3