[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.96, Wed Dec 6 03:37:26 2006 UTC revision 1.119, Tue Sep 30 15:23:55 2008 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 DBQuery;
8      use DBObject;      use ERDBObject;
9      use Tracer;      use Tracer;
10      use FIGRules;      use FIGRules;
11      use FidCheck;      use FidCheck;
12      use Stats;      use Stats;
13      use POSIX qw(strftime);      use POSIX qw(strftime);
14      use BasicLocation;      use BasicLocation;
15        use CustomAttributes;
16        use RemoteCustomAttributes;
17        use CGI;
18        use WikiTools;
19        use BioWords;
20        use base qw(ERDB);
21    
22  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
23    
# Line 28  Line 30 
30  on the constructor. For example, the following invocation specifies a PostgreSQL database named I<GenDB>  on the constructor. For example, the following invocation specifies a PostgreSQL database named I<GenDB>
31  whose definition and data files are in a co-directory named F<Data>.  whose definition and data files are in a co-directory named F<Data>.
32    
33  C<< my $sprout = Sprout->new('GenDB', { dbType => 'pg', dataDir => '../Data', xmlFileName => '../Data/SproutDBD.xml' }); >>      my $sprout = Sprout->new('GenDB', { dbType => 'pg', dataDir => '../Data', xmlFileName => '../Data/SproutDBD.xml' });
34    
35  Once you have a sprout object, you may use it to re-create the database, load the tables from  Once you have a sprout object, you may use it to re-create the database, load the tables from
36  tab-delimited flat files and perform queries. Several special methods are provided for common  tab-delimited flat files and perform queries. Several special methods are provided for common
37  query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and  query tasks. For example, L</Genomes> lists the IDs of all the genomes in the database and
38  L</dna_seq> returns the DNA sequence for a specified genome location.  L</DNASeq> returns the DNA sequence for a specified genome location.
39    
40  The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.  The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.
41    
# Line 45  Line 47 
47    
48  =head3 new  =head3 new
49    
50  C<< my $sprout = Sprout->new($dbName, \%options); >>      my $sprout = Sprout->new($dbName, \%options);
51    
52  This is the constructor for a sprout object. It connects to the database and loads the  This is the constructor for a sprout object. It connects to the database and loads the
53  database definition into memory. The positional first parameter specifies the name of the  database definition into memory. The positional first parameter specifies the name of the
# Line 55  Line 57 
57    
58  =item dbName  =item dbName
59    
60  Name of the database.  Name of the database. If omitted, the default Sprout database name is used.
61    
62  =item options  =item options
63    
# Line 79  Line 81 
81    
82  * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE  * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
83    
84    * B<host> name of the database host
85    
86  =back  =back
87    
88  For example, the following constructor call specifies a database named I<Sprout> and a user name of  For example, the following constructor call specifies a database named I<Sprout> and a user name of
89  I<fig> with a password of I<admin>. The database load files are in the directory  I<fig> with a password of I<admin>. The database load files are in the directory
90  F</usr/fig/SproutData>.  F</usr/fig/SproutData>.
91    
92  C<< my $sprout = Sprout->new('Sprout', { userData =>; 'fig/admin', dataDir => '/usr/fig/SproutData' }); >>      my $sprout = Sprout->new('Sprout', { userData => 'fig/admin', dataDir => '/usr/fig/SproutData' });
93    
94  =cut  =cut
95    
96  sub new {  sub new {
97      # Get the parameters.      # Get the parameters.
98      my ($class, $dbName, $options) = @_;      my ($class, $dbName, $options) = @_;
99        # Default the database name if it is missing.
100        if (! defined $dbName) {
101            $dbName = $FIG_Config::sproutDB;
102        } elsif (ref $dbName eq 'HASH') {
103            $options = $dbName;
104            $dbName = $FIG_Config::sproutDB;
105        }
106      # Compute the DBD directory.      # Compute the DBD directory.
107      my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :      my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
108                                                    $FIG_Config::fig );                                                    $FIG_Config::fig );
# Line 104  Line 115 
115                                                          # data file directory                                                          # data file directory
116                         xmlFileName  => "$dbd_dir/SproutDBD.xml",                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
117                                                          # database definition file name                                                          # database definition file name
118                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",                         userData     => "$FIG_Config::sproutUser/$FIG_Config::sproutPass",
119                                                          # user name and password                                                          # user name and password
120                         port         => $FIG_Config::dbport,                         port         => $FIG_Config::sproutPort,
121                                                          # database connection port                                                          # database connection port
122                         sock         => $FIG_Config::dbsock,                         sock         => $FIG_Config::sproutSock,
123                         host         => $FIG_Config::dbhost,                         host         => $FIG_Config::sprout_host,
124                         maxSegmentLength => 4500,        # maximum feature segment length                         maxSegmentLength => 4500,        # maximum feature segment length
125                         maxSequenceLength => 8000,       # maximum contig sequence length                         maxSequenceLength => 8000,       # maximum contig sequence length
126                         noDBOpen     => 0,               # 1 to suppress the database open                         noDBOpen     => 0,               # 1 to suppress the database open
# Line 122  Line 133 
133      # Connect to the database.      # Connect to the database.
134      my $dbh;      my $dbh;
135      if (! $optionTable->{noDBOpen}) {      if (! $optionTable->{noDBOpen}) {
136            Trace("Connect data: host = $optionTable->{host}, port = $optionTable->{port}.") if T(3);
137          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
138                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
139      }      }
# Line 133  Line 145 
145      $retVal->{_xmlName} = $xmlFileName;      $retVal->{_xmlName} = $xmlFileName;
146      # Set up space for the group file data.      # Set up space for the group file data.
147      $retVal->{groupHash} = undef;      $retVal->{groupHash} = undef;
148        # Set up space for the genome hash. We use this to identify NMPDR genomes.
149        $retVal->{genomeHash} = undef;
150        # Remember the data directory name.
151        $retVal->{dataDir} = $dataDir;
152        # Connect to the attributes.
153        if ($FIG_Config::attrURL) {
154            Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);
155            $retVal->{_ca} = RemoteCustomAttributes->new($FIG_Config::attrURL);
156        } elsif ($FIG_Config::attrDbName) {
157            Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);
158            my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));
159            $retVal->{_ca} = CustomAttributes->new(user => $user);
160        }
161      # Return it.      # Return it.
162      return $retVal;      return $retVal;
163  }  }
164    
165    =head3 CoreGenomes
166    
167        my @genomes = $sprout->CoreGenomes($scope);
168    
169    Return the IDs of NMPDR genomes in the specified scope.
170    
171    =over 4
172    
173    =item scope
174    
175    Scope of the desired genomes. C<core> covers the original core genomes,
176    C<nmpdr> covers all genomes in NMPDR groups, and C<all> covers all
177    genomes in the system.
178    
179    =item RETURN
180    
181    Returns a list of the IDs for the genomes in the specified scope.
182    
183    =back
184    
185    =cut
186    
187    sub CoreGenomes {
188        # Get the parameters.
189        my ($self, $scope) = @_;
190        # Declare the return variable.
191        my @retVal = ();
192        # If we want all genomes, then this is easy.
193        if ($scope eq 'all') {
194            @retVal = $self->Genomes();
195        } else {
196            # Here we're dealing with groups. Get the hash of all the
197            # genome groups.
198            my %groups = $self->GetGroups();
199            # Loop through the groups, keeping the ones that we want.
200            for my $group (keys %groups) {
201                # Decide if we want to keep this group.
202                my $keepGroup = 0;
203                if ($scope eq 'nmpdr') {
204                    # NMPDR mode: keep all groups.
205                    $keepGroup = 1;
206                } elsif ($scope eq 'core') {
207                    # CORE mode. Only keep real core groups.
208                    if (grep { $group =~ /$_/ } @{$FIG_Config::realCoreGroups}) {
209                        $keepGroup = 1;
210                    }
211                }
212                # Add this group if we're keeping it.
213                if ($keepGroup) {
214                    push @retVal, @{$groups{$group}};
215                }
216            }
217        }
218        # Return the result.
219        return @retVal;
220    }
221    
222    =head3 SuperGroup
223    
224        my $superGroup = $sprout->SuperGroup($groupName);
225    
226    Return the name of the super-group containing the specified NMPDR genome
227    group. If no appropriate super-group can be found, an error will be
228    thrown.
229    
230    =over 4
231    
232    =item groupName
233    
234    Name of the group whose super-group is desired.
235    
236    =item RETURN
237    
238    Returns the name of the super-group containing the incoming group.
239    
240    =back
241    
242    =cut
243    
244    sub SuperGroup {
245        # Get the parameters.
246        my ($self, $groupName) = @_;
247        # Declare the return variable.
248        my $retVal;
249        # Get the group hash.
250        my %groupHash = $self->CheckGroupFile();
251        # Find the super-group genus.
252        $groupName =~ /([A-Z]\w+)/;
253        my $nameThing = $1;
254        # See if it's directly in the group hash.
255        if (exists $groupHash{$nameThing}) {
256            # Yes, then it's our result.
257            $retVal = $nameThing;
258        } else {
259            # No, so we have to search.
260            for my $superGroup (keys %groupHash) {
261                # Get this super-group's item list.
262                my $list = $groupHash{$superGroup}->{contents};
263                # Search it.
264                if (grep { $_->[0] eq $nameThing } @{$list}) {
265                    $retVal = $superGroup;
266                }
267            }
268            # Make sure we found something.
269            if (! $retVal) {
270                Confess("No super-group found for \"$groupName\".");
271            }
272        }
273        # Return the result.
274        return $retVal;
275    }
276    
277  =head3 MaxSegment  =head3 MaxSegment
278    
279  C<< my $length = $sprout->MaxSegment(); >>      my $length = $sprout->MaxSegment();
280    
281  This method returns the maximum permissible length of a feature segment. The length is important  This method returns the maximum permissible length of a feature segment. The length is important
282  because it enables us to make reasonable guesses at how to find features inside a particular  because it enables us to make reasonable guesses at how to find features inside a particular
# Line 156  Line 293 
293    
294  =head3 MaxSequence  =head3 MaxSequence
295    
296  C<< my $length = $sprout->MaxSequence(); >>      my $length = $sprout->MaxSequence();
297    
298  This method returns the maximum permissible length of a contig sequence. A contig is broken  This method returns the maximum permissible length of a contig sequence. A contig is broken
299  into sequences in order to save memory resources. In particular, when manipulating features,  into sequences in order to save memory resources. In particular, when manipulating features,
# Line 171  Line 308 
308    
309  =head3 Load  =head3 Load
310    
311  C<< $sprout->Load($rebuild); >>;      $sprout->Load($rebuild);;
312    
313  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.
314    
# Line 211  Line 348 
348    
349  =head3 LoadUpdate  =head3 LoadUpdate
350    
351  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>      my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList);
352    
353  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
354  or two tables without reloading the whole database. For each table, there must be a corresponding  or two tables without reloading the whole database. For each table, there must be a corresponding
# Line 257  Line 394 
394              Trace("No load file found for $tableName in $dataDir.") if T(0);              Trace("No load file found for $tableName in $dataDir.") if T(0);
395          } else {          } else {
396              # Attempt to load this table.              # Attempt to load this table.
397              my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);              my $result = $self->LoadTable($fileName, $tableName, truncate => $truncateFlag);
398              # Accumulate the resulting statistics.              # Accumulate the resulting statistics.
399              $retVal->Accumulate($result);              $retVal->Accumulate($result);
400          }          }
# Line 268  Line 405 
405    
406  =head3 GenomeCounts  =head3 GenomeCounts
407    
408  C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>      my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete);
409    
410  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
411  genomes will be included in the counts.  genomes will be included in the counts.
# Line 313  Line 450 
450    
451  =head3 ContigCount  =head3 ContigCount
452    
453  C<< my $count = $sprout->ContigCount($genomeID); >>      my $count = $sprout->ContigCount($genomeID);
454    
455  Return the number of contigs for the specified genome ID.  Return the number of contigs for the specified genome ID.
456    
# Line 340  Line 477 
477      return $retVal;      return $retVal;
478  }  }
479    
480  =head3 GeneMenu  =head3 GenomeMenu
481    
482        my $html = $sprout->GenomeMenu(%options);
483    
484    Generate a genome selection control with the specified name and options.
485    This control is almost but not quite the same as the genome control in the
486    B<SearchHelper> class. Eventually, the two will be combined.
487    
488    =over 4
489    
490    =item options
491    
492    Optional parameters for the control (see below).
493    
494    =item RETURN
495    
496    Returns the HTML for a genome selection control on a form (sometimes called a popup menu).
497    
498  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected); >>  =back
499    
500  Return an HTML select menu of genomes. Each genome will be an option in the menu,  The valid options are as follows.
 and will be displayed by name with the ID and a contig count attached. The selection  
 value will be the genome ID. The genomes will be sorted by genus/species name.  
501    
502  =over 4  =over 4
503    
504  =item attributes  =item name
505    
506    Name to give this control for use in passing it to the form. The default is C<myGenomeControl>.
507    Terrible things will happen if you have two controls with the same name on the same page.
508    
509    =item filter
510    
511    If specified, a filter for the list of genomes to display. The filter should be in the form of a
512    list reference. The first element of the list should be the filter string, and the remaining elements
513    the filter parameters.
514    
515    =item multiSelect
516    
517    If TRUE, then the user can select multiple genomes. If FALSE, the user can only select one genome.
518    
519    =item size
520    
521    Number of rows to display in the control. The default is C<10>
522    
523    =item id
524    
525    ID to give this control. The default is the value of the C<name> option. Nothing will work correctly
526    unless this ID is unique.
527    
528    =item selected
529    
530    A comma-delimited list of selected genomes, or a reference to a list of selected genomes. The
531    default is none.
532    
533    =item class
534    
535    If specified, a style class to assign to the genome control.
536    
537    =back
538    
539  Reference to a hash mapping attributes to values for the SELECT tag generated.  =cut
540    
541  =item filterString  sub GenomeMenu {
542        # Get the parameters.
543        my ($self, %options) = @_;
544        # Get the control's name and ID.
545        my $menuName = $options{name} || $options{id} || 'myGenomeControl';
546        my $menuID = $options{id} || $menuName;
547        Trace("Genome menu name = $menuName with ID $menuID.") if T(3);
548        # Compute the IDs for the status display.
549        my $divID = "${menuID}_status";
550        my $urlID = "${menuID}_url";
551        # Compute the code to show selected genomes in the status area.
552        my $showSelect = "showSelected('$menuID', '$divID', '$urlID', 1000)";
553        # Check for single-select or multi-select.
554        my $multiSelect = $options{multiSelect} || 0;
555        # Get the style data.
556        my $class = $options{class} || '';
557        # Get the list of pre-selected items.
558        my $selections = $options{selected} || [];
559        if (ref $selections ne 'ARRAY') {
560            $selections = [ split /\s*,\s*/, $selections ];
561        }
562        my %selected = map { $_ => 1 } @{$selections};
563        # Extract the filter information. The default is no filtering. It can be passed as a tab-delimited
564        # string or a list reference.
565        my $filterParms = $options{filter} || "";
566        if (! ref $filterParms) {
567            $filterParms = [split /\t|\\t/, $filterParms];
568        }
569        my $filterString = shift @{$filterParms};
570        # Get a list of all the genomes in group order. In fact, we only need them ordered
571        # by name (genus,species,strain), but putting primary-group in front enables us to
572        # take advantage of an existing index.
573        my @genomeList = $self->GetAll(['Genome'], "$filterString ORDER BY Genome(primary-group), Genome(genus), Genome(species), Genome(unique-characterization)",
574                                       $filterParms,
575                                       [qw(Genome(primary-group) Genome(id) Genome(genus) Genome(species) Genome(unique-characterization) Genome(taxonomy) Genome(contigs))]);
576        # Create a hash to organize the genomes by group. Each group will contain a list of
577        # 2-tuples, the first element being the genome ID and the second being the genome
578        # name.
579        my %gHash = ();
580        for my $genome (@genomeList) {
581            # Get the genome data.
582            my ($group, $genomeID, $genus, $species, $strain, $taxonomy, $contigs) = @{$genome};
583            # Compute its name. This is the genus, species, strain (if any), and the contig count.
584            my $name = "$genus $species ";
585            $name .= "$strain " if $strain;
586            my $contigCount = ($contigs == 1 ? "" : ", $contigs contigs");
587            # Now we get the domain. The domain tells us the display style of the organism.
588            my ($domain) = split /\s*;\s*/, $taxonomy, 2;
589            # Now compute the display group. This is normally the primary group, but if the
590            # organism is supporting, we blank it out.
591            my $displayGroup = ($group eq $FIG_Config::otherGroup ? "" : $group);
592            # Push the genome into the group's list. Note that we use the real group
593            # name for the hash key here, not the display group name.
594            push @{$gHash{$group}}, [$genomeID, $name, $contigCount, $domain];
595        }
596        # We are almost ready to unroll the menu out of the group hash. The final step is to separate
597        # the supporting genomes by domain. First, we extract the NMPDR groups and sort them. They
598        # are sorted by the first capitalized word. Groups with "other" are sorted after groups
599        # that aren't "other". At some point, we will want to make this less complicated.
600        my %sortGroups = map { $_ =~ /(other)?(.*)([A-Z].+)/; "$3$1$2" => $_ }
601                             grep { $_ ne $FIG_Config::otherGroup } keys %gHash;
602        my @groups = map { $sortGroups{$_} } sort keys %sortGroups;
603        # Remember the number of NMPDR groups.
604        my $nmpdrGroupCount = scalar @groups;
605        # Loop through the supporting genomes, classifying them by domain. We'll also keep a list
606        # of the domains found.
607        my @otherGenomes = @{$gHash{$FIG_Config::otherGroup}};
608        my @domains = ();
609        for my $genomeData (@otherGenomes) {
610            my ($genomeID, $name, $contigCount, $domain) = @{$genomeData};
611            if (exists $gHash{$domain}) {
612                push @{$gHash{$domain}}, $genomeData;
613            } else {
614                $gHash{$domain} = [$genomeData];
615                push @domains, $domain;
616            }
617        }
618        # Add the domain groups at the end of the main group list. The main group list will now
619        # contain all the categories we need to display the genomes.
620        push @groups, sort @domains;
621        # Delete the supporting group.
622        delete $gHash{$FIG_Config::otherGroup};
623        # Now it gets complicated. We need a way to mark all the NMPDR genomes. We take advantage
624        # of the fact they come first in the list. We'll accumulate a count of the NMPDR genomes
625        # and use that to make the selections.
626        my $nmpdrCount = 0;
627        # Create the type counters.
628        my $groupCount = 1;
629        # Get the number of rows to display.
630        my $rows = $options{size} || 10;
631        # If we're multi-row, create an onChange event.
632        my $onChangeTag = ( $rows > 1 ? " onChange=\"$showSelect;\" onFocus=\"$showSelect;\"" : "" );
633        # Set up the multiple-select flag.
634        my $multipleTag = ($multiSelect ? " multiple" : "" );
635        # Set up the style class.
636        my $classTag = ($class ? " class=\"$class\"" : "" );
637        # Create the SELECT tag and stuff it into the output array.
638        my @lines = ("<SELECT name=\"$menuName\" id=\"$menuID\" $onChangeTag$multipleTag$classTag size=\"$rows\">");
639        # Loop through the groups.
640        for my $group (@groups) {
641            # Get the genomes in the group.
642            for my $genome (@{$gHash{$group}}) {
643                # If this is an NMPDR organism, we add an extra style and count it.
644                my $nmpdrStyle = "";
645                if ($nmpdrGroupCount > 0) {
646                    $nmpdrCount++;
647                    $nmpdrStyle = " Core";
648                }
649                # Get the organism ID, name, contig count, and domain.
650                my ($genomeID, $name, $contigCount, $domain) = @{$genome};
651                # See if we're pre-selected.
652                my $selectTag = ($selected{$genomeID} ? " SELECTED" : "");
653                # Compute the display name.
654                my $nameString = "$name ($genomeID$contigCount)";
655                # Generate the option tag.
656                my $optionTag = "<OPTION class=\"$domain$nmpdrStyle\" title=\"$group\" value=\"$genomeID\"$selectTag>$nameString</OPTION>";
657                push @lines, "    $optionTag";
658            }
659            # Record this group in the nmpdrGroup count. When that gets to 0, we've finished the NMPDR
660            # groups.
661            $nmpdrGroupCount--;
662        }
663        # Close the SELECT tag.
664        push @lines, "</SELECT>";
665        if ($rows > 1) {
666            # We're in a non-compact mode, so we need to add some selection helpers. First is
667            # the search box. This allows the user to type text and change which genomes are
668            # displayed. For multiple-select mode, we include a button that selects the displayed
669            # genes. For single-select mode, we use a plain label instead.
670            my $searchThingName = "${menuID}_SearchThing";
671            my $searchThingLabel = ($multiSelect ? "<INPUT type=\"button\" name=\"MacroSearch\" class=\"button\" value=\"Select genomes containing\" onClick=\"selectShowing('$menuID', '$searchThingName'); $showSelect;\" />"
672                                                 : "Show genomes containing");
673            push @lines, "<br />$searchThingLabel&nbsp;" .
674                         "<INPUT type=\"text\" id=\"$searchThingName\" name=\"$searchThingName\" size=\"30\" onKeyup=\"showTyped('$menuID', '$searchThingName');\" />" .
675                         Hint("GenomeControl", "Type here to filter the genomes displayed.") . "<br />";
676            # For multi-select mode, we also have buttons to set and clear selections.
677            if ($multiSelect) {
678                push @lines, "<INPUT type=\"button\" name=\"ClearAll\" class=\"bigButton\"  value=\"Clear All\" onClick=\"clearAll('$menuID'); $showSelect\" />";
679                push @lines, "<INPUT type=\"button\" name=\"SelectAll\" class=\"bigButton\" value=\"Select All\" onClick=\"selectAll('$menuID'); $showSelect\" />";
680                push @lines, "<INPUT type=\"button\" name=\"NMPDROnly\" class=\"bigButton\"  value=\"Select NMPDR\" onClick=\"selectSome('$menuID', $nmpdrCount, true); $showSelect;\" />";
681            }
682            # Add a hidden field we can use to generate organism page hyperlinks.
683            push @lines, "<INPUT type=\"hidden\" id=\"$urlID\" value=\"$FIG_Config::cgi_url/wiki/rest.cgi/NmpdrPlugin/SeedViewer?page=Organism;organism=\" />";
684            # Add the status display. This tells the user what's selected no matter where the list is scrolled.
685            push @lines, "<DIV id=\"$divID\" class=\"Panel\"></DIV>";
686        }
687        # Assemble all the lines into a string.
688        my $retVal = join("\n", @lines, "");
689        # Return the result.
690        return $retVal;
691    }
692    
 A filter string for use in selecting the genomes. The filter string must conform  
 to the rules for the C<< ERDB->Get >> method.  
693    
694  =item params  =head3 Stem
695    
696  Reference to a list of values to be substituted in for the parameter marks in      my $stem = $sprout->Stem($word);
 the filter string.  
697    
698  =item selected (optional)  Return the stem of the specified word, or C<undef> if the word is not
699    stemmable. Note that even if the word is stemmable, the stem may be
700    the same as the original word.
701    
702  ID of the genome to be initially selected.  =over 4
703    
704  =item fast (optional)  =item word
705    
706  If specified and TRUE, the contig counts will be omitted to improve performance.  Word to convert into a stem.
707    
708  =item RETURN  =item RETURN
709    
710  Returns an HTML select menu with the specified genomes as selectable options.  Returns a stem of the word (which may be the word itself), or C<undef> if
711    the word is not stemmable.
712    
713  =back  =back
714    
715  =cut  =cut
716    
717  sub GeneMenu {  sub Stem {
718      # Get the parameters.      # Get the parameters.
719      my ($self, $attributes, $filterString, $params, $selected, $fast) = @_;      my ($self, $word) = @_;
720      my $slowMode = ! $fast;      # Get the stemmer object.
721      # Default to nothing selected. This prevents an execution warning if "$selected"      my $stemmer = $self->{stemmer};
722      # is undefined.      if (! defined $stemmer) {
723      $selected = "" unless defined $selected;          # We don't have one pre-built, so we build and save it now.
724      Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3);          $stemmer = BioWords->new(exceptions => "$FIG_Config::sproutData/Exceptions.txt",
725      # Start the menu.                                   stops => "$FIG_Config::sproutData/StopWords.txt",
726      my $retVal = "<select " .                                   cache => 0);
727          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .          $self->{stemmer} = $stemmer;
         ">\n";  
     # Get the genomes.  
     my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',  
                                                                      'Genome(genus)',  
                                                                      'Genome(species)',  
                                                                      'Genome(unique-characterization)']);  
     # Sort them by name.  
     my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;  
     # Loop through the genomes, creating the option tags.  
     for my $genomeData (@sorted) {  
         # Get the data for this genome.  
         my ($genomeID, $genus, $species, $strain) = @{$genomeData};  
         # Get the contig count.  
         my $contigInfo = "";  
         if ($slowMode) {  
             my $count = $self->ContigCount($genomeID);  
             my $counting = ($count == 1 ? "contig" : "contigs");  
             $contigInfo = "[$count $counting]";  
         }  
         # Find out if we're selected.  
         my $selectOption = ($selected eq $genomeID ? " selected" : "");  
         # Build the option tag.  
         $retVal .= "<option value=\"$genomeID\"$selectOption>$genus $species $strain ($genomeID)$contigInfo</option>\n";  
728      }      }
729      # Close the SELECT tag.      # Try to stem the word.
730      $retVal .= "</select>\n";      my $retVal = $stemmer->Process($word);
731      # Return the result.      # Return the result.
732      return $retVal;      return $retVal;
733  }  }
734    
735    
736  =head3 Build  =head3 Build
737    
738  C<< $sprout->Build(); >>      $sprout->Build();
739    
740  Build the database. The database will be cleared and the tables re-created from the metadata.  Build the database. The database will be cleared and the tables re-created from the metadata.
741  This method is useful when a database is brand new or when the database definition has  This method is useful when a database is brand new or when the database definition has
# Line 440  Line 752 
752    
753  =head3 Genomes  =head3 Genomes
754    
755  C<< my @genomes = $sprout->Genomes(); >>      my @genomes = $sprout->Genomes();
756    
757  Return a list of all the genome IDs.  Return a list of all the genome IDs.
758    
# Line 457  Line 769 
769    
770  =head3 GenusSpecies  =head3 GenusSpecies
771    
772  C<< my $infoString = $sprout->GenusSpecies($genomeID); >>      my $infoString = $sprout->GenusSpecies($genomeID);
773    
774  Return the genus, species, and unique characterization for a genome.  Return the genus, species, and unique characterization for a genome.
775    
# Line 489  Line 801 
801    
802  =head3 FeaturesOf  =head3 FeaturesOf
803    
804  C<< my @features = $sprout->FeaturesOf($genomeID, $ftype); >>      my @features = $sprout->FeaturesOf($genomeID, $ftype);
805    
806  Return a list of the features relevant to a specified genome.  Return a list of the features relevant to a specified genome.
807    
# Line 534  Line 846 
846    
847  =head3 FeatureLocation  =head3 FeatureLocation
848    
849  C<< my @locations = $sprout->FeatureLocation($featureID); >>      my @locations = $sprout->FeatureLocation($featureID);
850    
851  Return the location of a feature in its genome's contig segments. In a list context, this method  Return the location of a feature in its genome's contig segments. In a list context, this method
852  will return a list of the locations. In a scalar context, it will return the locations as a space-  will return a list of the locations. In a scalar context, it will return the locations as a space-
# Line 558  Line 870 
870  =item RETURN  =item RETURN
871    
872  Returns a list of the feature's contig segments. The locations are returned as a list in a list  Returns a list of the feature's contig segments. The locations are returned as a list in a list
873  context and as a comma-delimited string in a scalar context.  context and as a comma-delimited string in a scalar context. An empty list means the feature
874    wasn't found.
875    
876  =back  =back
877    
878  =cut  =cut
879  #: Return Type @;  
 #: Return Type $;  
880  sub FeatureLocation {  sub FeatureLocation {
881      # Get the parameters.      # Get the parameters.
882      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
883      # Create a query for the feature locations.      # Declare the return variable.
     my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",  
                            [$featureID]);  
     # Create the return list.  
884      my @retVal = ();      my @retVal = ();
885      # Set up the variables used to determine if we have adjacent segments. This initial setup will      # Get the feature record.
886      # not match anything.      my $object = $self->GetEntity('Feature', $featureID);
887      my ($prevContig, $prevBeg, $prevDir, $prevLen) = ("", 0, "0", 0);      # Only proceed if we found it.
888      # Loop through the query results, creating location specifiers.      if (defined $object) {
889      while (my $location = $query->Fetch()) {          # Get the location string.
890          # Get the location parameters.          my $locString = $object->PrimaryValue('Feature(location-string)');
891          my ($contigID, $beg, $dir, $len) = $location->Values(['IsLocatedIn(to-link)',          # Create the return list.
892              'IsLocatedIn(beg)', 'IsLocatedIn(dir)', 'IsLocatedIn(len)']);          @retVal = split /\s*,\s*/, $locString;
         # Check to see if we are adjacent to the previous segment.  
         if ($prevContig eq $contigID && $dir eq $prevDir) {  
             # Here the new segment is in the same direction on the same contig. Insure the  
             # new segment's beginning is next to the old segment's end.  
             if ($dir eq "-" && $beg + $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";  
893      }      }
894      # Return the list in the format indicated by the context.      # Return the list in the format indicated by the context.
895      return (wantarray ? @retVal : join(',', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
# Line 613  Line 897 
897    
898  =head3 ParseLocation  =head3 ParseLocation
899    
900  C<< my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location); >>      my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location);
901    
902  Split a location specifier into the contig ID, the starting point, the direction, and the  Split a location specifier into the contig ID, the starting point, the direction, and the
903  length.  length.
# Line 632  Line 916 
916  =back  =back
917    
918  =cut  =cut
919  #: Return Type @;  
920  sub ParseLocation {  sub ParseLocation {
921      # Get the parameter. Note that if we're called as an instance method, we ignore      # Get the parameter. Note that if we're called as an instance method, we ignore
922      # the first parameter.      # the first parameter.
# Line 659  Line 943 
943    
944  =head3 PointLocation  =head3 PointLocation
945    
946  C<< my $found = Sprout::PointLocation($location, $point); >>      my $found = Sprout::PointLocation($location, $point);
947    
948  Return the offset into the specified location of the specified point on the contig. If  Return the offset into the specified location of the specified point on the contig. If
949  the specified point is before the location, a negative value will be returned. If it is  the specified point is before the location, a negative value will be returned. If it is
# Line 688  Line 972 
972  =back  =back
973    
974  =cut  =cut
975  #: Return Type $;  
976  sub PointLocation {  sub PointLocation {
977      # Get the parameter. Note that if we're called as an instance method, we ignore      # Get the parameter. Note that if we're called as an instance method, we ignore
978      # the first parameter.      # the first parameter.
# Line 711  Line 995 
995    
996  =head3 DNASeq  =head3 DNASeq
997    
998  C<< my $sequence = $sprout->DNASeq(\@locationList); >>      my $sequence = $sprout->DNASeq(\@locationList);
999    
1000  This method returns the DNA sequence represented by a list of locations. The list of locations  This method returns the DNA sequence represented by a list of locations. The list of locations
1001  should be of the form returned by L</featureLocation> when in a list context. In other words,  should be of the form returned by L</featureLocation> when in a list context. In other words,
# Line 795  Line 1079 
1079    
1080  =head3 AllContigs  =head3 AllContigs
1081    
1082  C<< my @idList = $sprout->AllContigs($genomeID); >>      my @idList = $sprout->AllContigs($genomeID);
1083    
1084  Return a list of all the contigs for a genome.  Return a list of all the contigs for a genome.
1085    
# Line 825  Line 1109 
1109    
1110  =head3 GenomeLength  =head3 GenomeLength
1111    
1112  C<< my $length = $sprout->GenomeLength($genomeID); >>      my $length = $sprout->GenomeLength($genomeID);
1113    
1114  Return the length of the specified genome in base pairs.  Return the length of the specified genome in base pairs.
1115    
# Line 860  Line 1144 
1144    
1145  =head3 FeatureCount  =head3 FeatureCount
1146    
1147  C<< my $count = $sprout->FeatureCount($genomeID, $type); >>      my $count = $sprout->FeatureCount($genomeID, $type);
1148    
1149  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.
1150    
# Line 895  Line 1179 
1179    
1180  =head3 GenomeAssignments  =head3 GenomeAssignments
1181    
1182  C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>      my $fidHash = $sprout->GenomeAssignments($genomeID);
1183    
1184  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
1185  assigned feature of the genome mapped to the text of its most recent functional  assigned feature of the genome mapped to the text of its most recent functional
# Line 938  Line 1222 
1222    
1223  =head3 ContigLength  =head3 ContigLength
1224    
1225  C<< my $length = $sprout->ContigLength($contigID); >>      my $length = $sprout->ContigLength($contigID);
1226    
1227  Compute the length of a contig.  Compute the length of a contig.
1228    
# Line 977  Line 1261 
1261    
1262  =head3 ClusterPEGs  =head3 ClusterPEGs
1263    
1264  C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>      my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs);
1265    
1266  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
1267  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
1268  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
1269  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
1270  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
1271  sequence.  appear in the output sequence.
1272    
1273  =over 4  =over 4
1274    
# Line 1025  Line 1309 
1309    
1310  =head3 GenesInRegion  =head3 GenesInRegion
1311    
1312  C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>      my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop);
1313    
1314  List the features which overlap a specified region in a contig.  List the features which overlap a specified region in a contig.
1315    
# Line 1054  Line 1338 
1338  =back  =back
1339    
1340  =cut  =cut
1341  #: Return Type @@;  
1342  sub GenesInRegion {  sub GenesInRegion {
1343      # Get the parameters.      # Get the parameters.
1344      my ($self, $contigID, $start, $stop) = @_;      my ($self, $contigID, $start, $stop) = @_;
1345      # Get the maximum segment length.      # Get the maximum segment length.
1346      my $maximumSegmentLength = $self->MaxSegment;      my $maximumSegmentLength = $self->MaxSegment;
     # Create a hash to receive the feature list. We use a hash so that we can eliminate  
     # duplicates easily. The hash key will be the feature ID. The value will be a two-element  
     # containing the minimum and maximum offsets. We will use the offsets to sort the results  
     # when we're building the result set.  
     my %featuresFound = ();  
1347      # Prime the values we'll use for the returned beginning and end.      # Prime the values we'll use for the returned beginning and end.
1348      my @initialMinMax = ($self->ContigLength($contigID), 0);      my @initialMinMax = ($self->ContigLength($contigID), 0);
1349      my ($min, $max) = @initialMinMax;      my ($min, $max) = @initialMinMax;
1350      # Create a table of parameters for each query. Each query looks for features travelling in      # Get the overlapping features.
1351        my @featureObjects = $self->GeneDataInRegion($contigID, $start, $stop);
1352        # We'l use this hash to help us track the feature IDs and sort them. The key is the
1353        # feature ID and the value is a [$left,$right] pair indicating the maximum extent
1354        # of the feature's locations.
1355        my %featureMap = ();
1356        # Loop through them to do the begin/end analysis.
1357        for my $featureObject (@featureObjects) {
1358            # Get the feature's location string. This may contain multiple actual locations.
1359            my ($locations, $fid) = $featureObject->Values([qw(Feature(location-string) Feature(id))]);
1360            my @locationSegments = split /\s*,\s*/, $locations;
1361            # Loop through the locations.
1362            for my $locationSegment (@locationSegments) {
1363                # Construct an object for the location.
1364                my $locationObject = BasicLocation->new($locationSegment);
1365                # Merge the current segment's begin and end into the min and max.
1366                my ($left, $right) = ($locationObject->Left, $locationObject->Right);
1367                my ($beg, $end);
1368                if (exists $featureMap{$fid}) {
1369                    ($beg, $end) = @{$featureMap{$fid}};
1370                    $beg = $left if $left < $beg;
1371                    $end = $right if $right > $end;
1372                } else {
1373                    ($beg, $end) = ($left, $right);
1374                }
1375                $min = $beg if $beg < $min;
1376                $max = $end if $end > $max;
1377                # Store the feature's new extent back into the hash table.
1378                $featureMap{$fid} = [$beg, $end];
1379            }
1380        }
1381        # Now we must compute the list of the IDs for the features found. We start with a list
1382        # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1383        # but the result of the sort will be the same.)
1384        my @list = map { [$featureMap{$_}->[0] + $featureMap{$_}->[1], $_] } keys %featureMap;
1385        # Now we sort by midpoint and yank out the feature IDs.
1386        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1387        # Return it along with the min and max.
1388        return (\@retVal, $min, $max);
1389    }
1390    
1391    =head3 GeneDataInRegion
1392    
1393        my @featureList = $sprout->GenesInRegion($contigID, $start, $stop);
1394    
1395    List the features which overlap a specified region in a contig.
1396    
1397    =over 4
1398    
1399    =item contigID
1400    
1401    ID of the contig containing the region of interest.
1402    
1403    =item start
1404    
1405    Offset of the first residue in the region of interest.
1406    
1407    =item stop
1408    
1409    Offset of the last residue in the region of interest.
1410    
1411    =item RETURN
1412    
1413    Returns a list of B<ERDBObjects> for the desired features. Each object will
1414    contain a B<Feature> record.
1415    
1416    =back
1417    
1418    =cut
1419    
1420    sub GeneDataInRegion {
1421        # Get the parameters.
1422        my ($self, $contigID, $start, $stop) = @_;
1423        # Get the maximum segment length.
1424        my $maximumSegmentLength = $self->MaxSegment;
1425        # Create a hash to receive the feature list. We use a hash so that we can eliminate
1426        # duplicates easily. The hash key will be the feature ID. The value will be the feature's
1427        # ERDBObject from the query.
1428        my %featuresFound = ();
1429        # Create a table of parameters for the queries. Each query looks for features travelling in
1430      # a particular direction. The query parameters include the contig ID, the feature direction,      # a particular direction. The query parameters include the contig ID, the feature direction,
1431      # the lowest possible start position, and the highest possible start position. This works      # the lowest possible start position, and the highest possible start position. This works
1432      # because each feature segment length must be no greater than the maximum segment length.      # because each feature segment length must be no greater than the maximum segment length.
# Line 1077  Line 1435 
1435      # Loop through the query parameters.      # Loop through the query parameters.
1436      for my $parms (values %queryParms) {      for my $parms (values %queryParms) {
1437          # Create the query.          # Create the query.
1438          my $query = $self->Get(['IsLocatedIn'],          my $query = $self->Get([qw(Feature IsLocatedIn)],
1439              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
1440              $parms);              $parms);
1441          # Loop through the feature segments found.          # Loop through the feature segments found.
1442          while (my $segment = $query->Fetch) {          while (my $segment = $query->Fetch) {
1443              # Get the data about this segment.              # Get the data about this segment.
1444              my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',              my ($featureID, $contig, $dir, $beg, $len) = $segment->Values([qw(IsLocatedIn(from-link)
1445                  'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);                  IsLocatedIn(to-link) IsLocatedIn(dir) IsLocatedIn(beg) IsLocatedIn(len))]);
1446              # Determine if this feature actually overlaps the region. The query insures that              # Determine if this feature segment actually overlaps the region. The query insures that
1447              # this will be the case if the segment is the maximum length, so to fine-tune              # this will be the case if the segment is the maximum length, so to fine-tune
1448              # the results we insure that the inequality from the query holds using the actual              # the results we insure that the inequality from the query holds using the actual
1449              # length.              # length.
1450              my ($found, $end) = (0, 0);              my $loc = BasicLocation->new($contig, $beg, $dir, $len);
1451              if ($dir eq '+') {              my $found = $loc->Overlap($start, $stop);
                 $end = $beg + $len;  
                 if ($end >= $start) {  
                     # Denote we found a useful feature.  
                     $found = 1;  
                 }  
             } elsif ($dir eq '-') {  
                 # Note we switch things around so that the beginning is to the left of the  
                 # ending.  
                 ($beg, $end) = ($beg - $len, $beg);  
                 if ($beg <= $stop) {  
                     # Denote we found a useful feature.  
                     $found = 1;  
                 }  
             }  
1452              if ($found) {              if ($found) {
1453                  # Here we need to record the feature and update the minima and maxima. First,                  # Save this feature in the result list.
1454                  # get the current entry for the specified feature.                  $featuresFound{$featureID} = $segment;
                 my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :  
                                      @initialMinMax);  
                 # Merge the current segment's begin and end into the feature begin and end and the  
                 # global min and max.  
                 if ($beg < $loc1) {  
                     $loc1 = $beg;  
                     $min = $beg if $beg < $min;  
                 }  
                 if ($end > $loc2) {  
                     $loc2 = $end;  
                     $max = $end if $end > $max;  
                 }  
                 # Store the entry back into the hash table.  
                 $featuresFound{$featureID} = [$loc1, $loc2];  
1455              }              }
1456          }          }
1457      }      }
1458      # 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.
1459      # 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);  
1460  }  }
1461    
1462  =head3 FType  =head3 FType
1463    
1464  C<< my $ftype = $sprout->FType($featureID); >>      my $ftype = $sprout->FType($featureID);
1465    
1466  Return the type of a feature.  Return the type of a feature.
1467    
# Line 1167  Line 1491 
1491    
1492  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1493    
1494  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>      my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag);
1495    
1496  Return the annotations of a feature.  Return the annotations of a feature.
1497    
# Line 1230  Line 1554 
1554    
1555  =head3 AllFunctionsOf  =head3 AllFunctionsOf
1556    
1557  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>      my %functions = $sprout->AllFunctionsOf($featureID);
1558    
1559  Return all of the functional assignments for a particular feature. The data is returned as a  Return all of the functional assignments for a particular feature. The data is returned as a
1560  hash of functional assignments to user IDs. A functional assignment is a type of annotation,  hash of functional assignments to user IDs. A functional assignment is a type of annotation,
# Line 1285  Line 1609 
1609    
1610  =head3 FunctionOf  =head3 FunctionOf
1611    
1612  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>      my $functionText = $sprout->FunctionOf($featureID, $userID);
1613    
1614  Return the most recently-determined functional assignment of a particular feature.  Return the most recently-determined functional assignment of a particular feature.
1615    
# Line 1298  Line 1622 
1622  the specified user and FIG are considered trusted. If the user ID is omitted, only FIG  the specified user and FIG are considered trusted. If the user ID is omitted, only FIG
1623  is trusted.  is trusted.
1624    
1625  If the feature is B<not> identified by a FIG ID, then the functional assignment  If the feature is B<not> identified by a FIG ID, then we search the aliases for it.
1626  information is taken from the B<ExternalAliasFunc> table. If the table does  If no matching alias is found, we return an undefined value.
 not contain an entry for the feature, an undefined value is returned.  
1627    
1628  =over 4  =over 4
1629    
# Line 1326  Line 1649 
1649      my ($self, $featureID, $userID) = @_;      my ($self, $featureID, $userID) = @_;
1650      # Declare the return value.      # Declare the return value.
1651      my $retVal;      my $retVal;
1652      # Determine the ID type.      # Find a FIG ID for this feature.
1653      if ($featureID =~ m/^fig\|/) {      my ($fid) = $self->FeaturesByAlias($featureID);
1654        # Only proceed if we have an ID.
1655        if ($fid) {
1656          # Here we have a FIG feature ID.          # Here we have a FIG feature ID.
1657          if (!$userID) {          if (!$userID) {
1658              # Use the primary assignment.              # Use the primary assignment.
1659              ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']);              ($retVal) = $self->GetEntityValues('Feature', $fid, ['Feature(assignment)']);
1660          } else {          } else {
1661              # We must build the list of trusted users.              # We must build the list of trusted users.
1662              my %trusteeTable = ();              my %trusteeTable = ();
# Line 1357  Line 1682 
1682              # Build a query for all of the feature's annotations, sorted by date.              # Build a query for all of the feature's annotations, sorted by date.
1683              my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],              my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1684                                     "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                     "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1685                                     [$featureID]);                                     [$fid]);
1686              my $timeSelected = 0;              my $timeSelected = 0;
1687              # Loop until we run out of annotations.              # Loop until we run out of annotations.
1688              while (my $annotation = $query->Fetch()) {              while (my $annotation = $query->Fetch()) {
# Line 1377  Line 1702 
1702                  }                  }
1703              }              }
1704          }          }
     } else {  
         # Here we have a non-FIG feature ID. In this case the user ID does not  
         # matter. We simply get the information from the External Alias Function  
         # table.  
         ($retVal) = $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']);  
1705      }      }
1706      # Return the assignment found.      # Return the assignment found.
1707      return $retVal;      return $retVal;
# Line 1389  Line 1709 
1709    
1710  =head3 FunctionsOf  =head3 FunctionsOf
1711    
1712  C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>      my @functionList = $sprout->FunctionOf($featureID, $userID);
1713    
1714  Return the functional assignments of a particular feature.  Return the functional assignments of a particular feature.
1715    
# Line 1400  Line 1720 
1720  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
1721  most features only have a small number of annotations.  most features only have a small number of annotations.
1722    
 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.  
   
1723  =over 4  =over 4
1724    
1725  =item featureID  =item featureID
# Line 1424  Line 1740 
1740      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1741      # Declare the return value.      # Declare the return value.
1742      my @retVal = ();      my @retVal = ();
1743      # Determine the ID type.      # Convert to a FIG ID.
1744      if ($featureID =~ m/^fig\|/) {      my ($fid) = $self->FeaturesByAlias($featureID);
1745        # Only proceed if we found one.
1746        if ($fid) {
1747          # Here we have a FIG feature ID. We must build the list of trusted          # Here we have a FIG feature ID. We must build the list of trusted
1748          # users.          # users.
1749          my %trusteeTable = ();          my %trusteeTable = ();
1750          # 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.
1751          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1752                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1753                                 [$featureID]);                                 [$fid]);
1754          my $timeSelected = 0;          my $timeSelected = 0;
1755          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1756          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
# Line 1447  Line 1765 
1765                  push @retVal, [$actualUser, $function];                  push @retVal, [$actualUser, $function];
1766              }              }
1767          }          }
     } 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;  
1768      }      }
1769      # Return the assignments found.      # Return the assignments found.
1770      return @retVal;      return @retVal;
# Line 1461  Line 1772 
1772    
1773  =head3 BBHList  =head3 BBHList
1774    
1775  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>      my $bbhHash = $sprout->BBHList($genomeID, \@featureList);
1776    
1777  Return a hash mapping the features in a specified list to their bidirectional best hits  Return a hash mapping the features in a specified list to their bidirectional best hits
1778  on a specified target genome.  on a specified target genome.
# Line 1511  Line 1822 
1822    
1823  =head3 SimList  =head3 SimList
1824    
1825  C<< my %similarities = $sprout->SimList($featureID, $count); >>      my %similarities = $sprout->SimList($featureID, $count);
1826    
1827  Return a list of the similarities to the specified feature.  Return a list of the similarities to the specified feature.
1828    
# Line 1547  Line 1858 
1858    
1859  =head3 IsComplete  =head3 IsComplete
1860    
1861  C<< my $flag = $sprout->IsComplete($genomeID); >>      my $flag = $sprout->IsComplete($genomeID);
1862    
1863  Return TRUE if the specified genome is complete, else FALSE.  Return TRUE if the specified genome is complete, else FALSE.
1864    
# Line 1575  Line 1886 
1886      my $genomeData = $self->GetEntity('Genome', $genomeID);      my $genomeData = $self->GetEntity('Genome', $genomeID);
1887      if ($genomeData) {      if ($genomeData) {
1888          # The genome exists, so get the completeness flag.          # The genome exists, so get the completeness flag.
1889          ($retVal) = $genomeData->Value('Genome(complete)');          $retVal = $genomeData->PrimaryValue('Genome(complete)');
1890      }      }
1891      # Return the result.      # Return the result.
1892      return $retVal;      return $retVal;
# Line 1583  Line 1894 
1894    
1895  =head3 FeatureAliases  =head3 FeatureAliases
1896    
1897  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>      my @aliasList = $sprout->FeatureAliases($featureID);
1898    
1899  Return a list of the aliases for a specified feature.  Return a list of the aliases for a specified feature.
1900    
# Line 1606  Line 1917 
1917      # Get the parameters.      # Get the parameters.
1918      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1919      # Get the desired feature's aliases      # Get the desired feature's aliases
1920      my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);      my @retVal = $self->GetFlat(['IsAliasOf'], "IsAliasOf(to-link) = ?", [$featureID], 'IsAliasOf(from-link)');
1921      # Return the result.      # Return the result.
1922      return @retVal;      return @retVal;
1923  }  }
1924    
1925  =head3 GenomeOf  =head3 GenomeOf
1926    
1927  C<< my $genomeID = $sprout->GenomeOf($featureID); >>      my $genomeID = $sprout->GenomeOf($featureID);
1928    
1929  Return the genome that contains a specified feature or contig.  Return the genome that contains a specified feature or contig.
1930    
# Line 1635  Line 1946 
1946  sub GenomeOf {  sub GenomeOf {
1947      # Get the parameters.      # Get the parameters.
1948      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]);  
1949      # Declare the return value.      # Declare the return value.
1950      my $retVal;      my $retVal;
1951      # Get the genome ID.      # Parse the genome ID from the feature ID.
1952      if (my $relationship = $query->Fetch()) {      if ($featureID =~ /^fig\|(\d+\.\d+)/) {
1953          ($retVal) = $relationship->Value('HasContig(from-link)');          $retVal = $1;
1954        } else {
1955            # Find the feature by alias.
1956            my ($realFeatureID) = $self->FeaturesByAlias($featureID);
1957            if ($realFeatureID && $realFeatureID =~ /^fig\|(\d+\.\d+)/) {
1958                $retVal = $1;
1959            }
1960      }      }
1961      # Return the value found.      # Return the value found.
1962      return $retVal;      return $retVal;
# Line 1650  Line 1964 
1964    
1965  =head3 CoupledFeatures  =head3 CoupledFeatures
1966    
1967  C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >>      my %coupleHash = $sprout->CoupledFeatures($featureID);
1968    
1969  Return the features functionally coupled with a specified feature. Features are considered  Return the features functionally coupled with a specified feature. Features are considered
1970  functionally coupled if they tend to be clustered on the same chromosome.  functionally coupled if they tend to be clustered on the same chromosome.
# Line 1672  Line 1986 
1986  sub CoupledFeatures {  sub CoupledFeatures {
1987      # Get the parameters.      # Get the parameters.
1988      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1989        # Ask the coupling server for the data.
1990      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1991      # Create a query to retrieve the functionally-coupled features.      my @rawPairs = FIGRules::NetCouplingData('coupled_to', id1 => $featureID);
1992      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      Trace(scalar(@rawPairs) . " couplings returned.") if T(coupling => 3);
1993                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);      # Form them into a hash.
     # This value will be set to TRUE if we find at least one coupled feature.  
     my $found = 0;  
     # Create the return hash.  
1994      my %retVal = ();      my %retVal = ();
1995      # Retrieve the relationship records and store them in the hash.      for my $pair (@rawPairs) {
1996      while (my $clustering = $query->Fetch()) {          # Get the feature ID and score.
1997          # Get the ID and score of the coupling.          my ($featureID2, $score) = @{$pair};
1998          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          # Only proceed if the feature is in NMPDR.
1999                                                          'Coupling(score)']);          if ($self->_CheckFeature($featureID2)) {
2000          Trace("$featureID coupled with score $score to ID $couplingID.") if T(coupling => 4);              $retVal{$featureID2} = $score;
2001          # Get the other feature that participates in the coupling.          }
         my ($otherFeatureID) = $self->GetFlat(['ParticipatesInCoupling'],  
                                            "ParticipatesInCoupling(to-link) = ? AND ParticipatesInCoupling(from-link) <> ?",  
                                            [$couplingID, $featureID], 'ParticipatesInCoupling(from-link)');  
         Trace("$couplingID target feature is $otherFeatureID.") if T(coupling => 4);  
         # Attach the other feature's score to its ID.  
         $retVal{$otherFeatureID} = $score;  
         $found = 1;  
2002      }      }
2003      # Functional coupling is reflexive. If we found at least one coupled feature, we must add      # Functional coupling is reflexive. If we found at least one coupled feature, we must add
2004      # the incoming feature as well.      # the incoming feature as well.
2005      if ($found) {      if (keys %retVal) {
2006          $retVal{$featureID} = 9999;          $retVal{$featureID} = 9999;
2007      }      }
2008      # Return the hash.      # Return the hash.
# Line 1706  Line 2011 
2011    
2012  =head3 CouplingEvidence  =head3 CouplingEvidence
2013    
2014  C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>      my @evidence = $sprout->CouplingEvidence($peg1, $peg2);
2015    
2016  Return the evidence for a functional coupling.  Return the evidence for a functional coupling.
2017    
# Line 1754  Line 2059 
2059      my ($self, $peg1, $peg2) = @_;      my ($self, $peg1, $peg2) = @_;
2060      # Declare the return variable.      # Declare the return variable.
2061      my @retVal = ();      my @retVal = ();
2062      # Our first task is to find out the nature of the coupling: whether or not      # Get the coupling and evidence data.
2063      # it exists, its score, and whether the features are stored in the same      my @rawData = FIGRules::NetCouplingData('coupling_evidence', id1 => $peg1, id2 => $peg2);
2064      # order as the ones coming in.      # Loop through the raw data, saving the ones that are in NMPDR genomes.
2065      my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);      for my $rawTuple (@rawData) {
2066      # Only proceed if a coupling exists.          if ($self->_CheckFeature($rawTuple->[0]) && $self->_CheckFeature($rawTuple->[1])) {
2067      if ($couplingID) {              push @retVal, $rawTuple;
         # Determine the ordering to place on the evidence items. If we're  
         # inverted, we want to see feature 2 before feature 1 (descending); otherwise,  
         # we want feature 1 before feature 2 (normal).  
         Trace("Coupling evidence for ($peg1, $peg2) with inversion flag $inverted.") if T(Coupling => 4);  
         my $ordering = ($inverted ? "DESC" : "");  
         # Get the coupling evidence.  
         my @evidenceList = $self->GetAll(['IsEvidencedBy', 'PCH', 'UsesAsEvidence'],  
                                           "IsEvidencedBy(from-link) = ? ORDER BY PCH(id), UsesAsEvidence(pos) $ordering",  
                                           [$couplingID],  
                                           ['PCH(used)', 'UsesAsEvidence(to-link)']);  
         # Loop through the evidence items. Each piece of evidence is represented by two  
         # positions in the evidence list, one for each feature on the other side of the  
         # evidence link. If at some point we want to generalize to couplings with  
         # more than two positions, this section of code will need to be re-done.  
         while (@evidenceList > 0) {  
             my $peg1Data = shift @evidenceList;  
             my $peg2Data = shift @evidenceList;  
             Trace("Peg 1 is " . $peg1Data->[1] . " and Peg 2 is " . $peg2Data->[1] . ".") if T(Coupling => 4);  
             push @retVal, [$peg1Data->[1], $peg2Data->[1], $peg1Data->[0]];  
         }  
         Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);  
     }  
     # Return the result.  
     return @retVal;  
2068  }  }
   
 =head3 GetCoupling  
   
 C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>  
   
 Return the coupling (if any) for the specified pair of PEGs. If a coupling  
 exists, we return the coupling ID along with an indicator of whether the  
 coupling is stored as C<(>I<$peg1>C<, >I<$peg2>C<)> or C<(>I<$peg2>C<, >I<$peg1>C<)>.  
 In the second case, we say the coupling is I<inverted>. The importance of an  
 inverted coupling is that the PEGs in the evidence will appear in reverse order.  
   
 =over 4  
   
 =item peg1  
   
 ID of the feature of interest.  
   
 =item peg2  
   
 ID of the potentially coupled feature.  
   
 =item RETURN  
   
 Returns a three-element list. The first element contains the database ID of  
 the coupling. The second element is FALSE if the coupling is stored in the  
 database in the caller specified order and TRUE if it is stored in the  
 inverted order. The third element is the coupling's score. If the coupling  
 does not exist, all three list elements will be C<undef>.  
   
 =back  
   
 =cut  
 #: Return Type $%@;  
 sub GetCoupling {  
     # Get the parameters.  
     my ($self, $peg1, $peg2) = @_;  
     # Declare the return values. We'll start with the coupling ID and undefine the  
     # flag and score until we have more information.  
     my ($retVal, $inverted, $score) = ($self->CouplingID($peg1, $peg2), undef, undef);  
     # Find the coupling data.  
     my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],  
                                  "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",  
                                  [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);  
     # Check to see if we found anything.  
     if (!@pegs) {  
         Trace("No coupling found.") if T(Coupling => 4);  
         # No coupling, so undefine the return value.  
         $retVal = undef;  
     } else {  
         # We have a coupling! Get the score and check for inversion.  
         $score = $pegs[0]->[1];  
         my $firstFound = $pegs[0]->[0];  
         $inverted = ($firstFound ne $peg1);  
         Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);  
2069      }      }
2070      # Return the result.      # Return the result.
2071      return ($retVal, $inverted, $score);      return @retVal;
2072  }  }
2073    
2074  =head3 GetSynonymGroup  =head3 GetSynonymGroup
2075    
2076  C<< my $id = $sprout->GetSynonymGroup($fid); >>      my $id = $sprout->GetSynonymGroup($fid);
2077    
2078  Return the synonym group name for the specified feature.  Return the synonym group name for the specified feature.
2079    
# Line 1885  Line 2112 
2112    
2113  =head3 GetBoundaries  =head3 GetBoundaries
2114    
2115  C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>      my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList);
2116    
2117  Determine the begin and end boundaries for the locations in a list. All of the  Determine the begin and end boundaries for the locations in a list. All of the
2118  locations must belong to the same contig and have mostly the same direction in  locations must belong to the same contig and have mostly the same direction in
# Line 1947  Line 2174 
2174      return ($contig, $beg, $end);      return ($contig, $beg, $end);
2175  }  }
2176    
 =head3 CouplingID  
   
 C<< my $couplingID = $sprout->CouplingID($peg1, $peg2); >>  
   
 Return the coupling ID for a pair of feature IDs.  
   
 The coupling ID is currently computed by joining the feature IDs in  
 sorted order with a space. Client modules (that is, modules which  
 use Sprout) should not, however, count on this always being the  
 case. This method provides a way for abstracting the concept of a  
 coupling ID. All that we know for sure about it is that it can be  
 generated easily from the feature IDs and the order of the IDs  
 in the parameter list does not matter (i.e. C<CouplingID("a1", "b1")>  
 will have the same value as C<CouplingID("b1", "a1")>.  
   
 =over 4  
   
 =item peg1  
   
 First feature of interest.  
   
 =item peg2  
   
 Second feature of interest.  
   
 =item RETURN  
   
 Returns the ID that would be used to represent a functional coupling of  
 the two specified PEGs.  
   
 =back  
   
 =cut  
 #: Return Type $;  
 sub CouplingID {  
     my ($self, @pegs) = @_;  
     return $self->DigestKey(join " ", sort @pegs);  
 }  
   
2177  =head3 ReadFasta  =head3 ReadFasta
2178    
2179  C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>      my %sequenceData = Sprout::ReadFasta($fileName, $prefix);
2180    
2181  Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by  Read sequence data from a FASTA-format file. Each sequence in a FASTA file is represented by
2182  one or more lines of data. The first line begins with a > character and contains an ID.  one or more lines of data. The first line begins with a > character and contains an ID.
# Line 2054  Line 2242 
2242    
2243  =head3 FormatLocations  =head3 FormatLocations
2244    
2245  C<< my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat); >>      my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat);
2246    
2247  Insure that a list of feature locations is in the Sprout format. The Sprout feature location  Insure that a list of feature locations is in the Sprout format. The Sprout feature location
2248  format is I<contig>_I<beg*len> where I<*> is C<+> for a forward gene and C<-> for a backward  format is I<contig>_I<beg*len> where I<*> is C<+> for a forward gene and C<-> for a backward
# Line 2119  Line 2307 
2307    
2308  =head3 DumpData  =head3 DumpData
2309    
2310  C<< $sprout->DumpData(); >>      $sprout->DumpData();
2311    
2312  Dump all the tables to tab-delimited DTX files. The files will be stored in the data directory.  Dump all the tables to tab-delimited DTX files. The files will be stored in the data directory.
2313    
# Line 2136  Line 2324 
2324    
2325  =head3 XMLFileName  =head3 XMLFileName
2326    
2327  C<< my $fileName = $sprout->XMLFileName(); >>      my $fileName = $sprout->XMLFileName();
2328    
2329  Return the name of this database's XML definition file.  Return the name of this database's XML definition file.
2330    
# Line 2147  Line 2335 
2335      return $self->{_xmlName};      return $self->{_xmlName};
2336  }  }
2337    
2338  =head3 Insert  =head3 GetGenomeNameData
   
 C<< $sprout->Insert($objectType, \%fieldHash); >>  
   
 Insert an entity or relationship instance into the database. The entity or relationship of interest  
 is defined by a type name and then a hash of field names to values. Field values in the primary  
 relation are represented by scalars. (Note that for relationships, the primary relation is  
 the B<only> relation.) Field values for the other relations comprising the entity are always  
 list references. For example, the following line inserts an inactive PEG feature named  
 C<fig|188.1.peg.1> with aliases C<ZP_00210270.1> and C<gi|46206278>.  
   
 C<< $sprout->Insert('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >>  
2339    
2340  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and      my ($genus, $species, $strain) = $sprout->GenomeNameData($genomeID);
 property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.  
2341    
2342  C<< $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>  Return the genus, species, and unique characterization for a genome. This
2343    is similar to L</GenusSpecies>, with the exception that it returns the
2344    values in three seperate fields.
2345    
2346  =over 4  =over 4
2347    
2348  =item newObjectType  =item genomeID
2349    
2350  Type name of the entity or relationship to insert.  ID of the genome whose name data is desired.
2351    
2352  =item fieldHash  =item RETURN
2353    
2354  Hash of field names to values.  Returns a three-element list, consisting of the genus, species, and strain
2355    of the specified genome. If the genome is not found, an error occurs.
2356    
2357  =back  =back
2358    
2359  =cut  =cut
2360  #: Return Type ;  
2361  sub Insert {  sub GetGenomeNameData {
2362      # Get the parameters.      # Get the parameters.
2363      my ($self, $objectType, $fieldHash) = @_;      my ($self, $genomeID) = @_;
2364      # Call the underlying method.      # Get the desired values.
2365      $self->InsertObject($objectType, $fieldHash);      my ($genus, $species, $strain) = $self->GetEntityValues('Genome', $genomeID =>
2366                                                                [qw(Genome(genus) Genome(species) Genome(unique-characterization))]);
2367        # Throw an error if they were not found.
2368        if (! defined $genus) {
2369            Confess("Genome $genomeID not found in database.");
2370        }
2371        # Return the results.
2372        return ($genus, $species, $strain);
2373  }  }
2374    
2375  =head3 Annotate  =head3 GetGenomeByNameData
2376    
2377  C<< my $ok = $sprout->Annotate($fid, $timestamp, $user, $text); >>      my @genomes = $sprout->GetGenomeByNameData($genus, $species, $strain);
2378    
2379  Annotate a feature. This inserts an Annotation record into the database and links it to the  Return a list of the IDs of the genomes with the specified genus,
2380  specified feature and user.  species, and strain. In almost every case, there will be either zero or
2381    one IDs returned; however, two or more IDs could be returned if there are
2382    multiple versions of the genome in the database.
2383    
2384  =over 4  =over 4
2385    
2386  =item fid  =item genus
2387    
2388  ID of the feature to be annotated.  Genus of the desired genome.
2389    
2390  =item timestamp  =item species
2391    
2392  Numeric timestamp to apply to the annotation. This is concatenated to the feature ID to create the  Species of the desired genome.
 key.  
2393    
2394  =item user  =item strain
2395    
2396  ID of the user who is making the annotation.  Strain (unique characterization) of the desired genome. This may be an empty
2397    string, in which case it is presumed that the desired genome has no strain
2398    specified.
2399    
2400  =item text  =item RETURN
2401    
2402    Returns a list of the IDs of the genomes having the specified genus, species, and
2403    strain.
2404    
2405    =back
2406    
2407    =cut
2408    
2409    sub GetGenomeByNameData {
2410        # Get the parameters.
2411        my ($self, $genus, $species, $strain) = @_;
2412        # Try to find the genomes.
2413        my @retVal = $self->GetFlat(['Genome'], "Genome(genus) = ? AND Genome(species) = ? AND Genome(unique-characterization) = ?",
2414                                    [$genus, $species, $strain], 'Genome(id)');
2415        # Return the result.
2416        return @retVal;
2417    }
2418    
2419    =head3 Insert
2420    
2421        $sprout->Insert($objectType, \%fieldHash);
2422    
2423    Insert an entity or relationship instance into the database. The entity or relationship of interest
2424    is defined by a type name and then a hash of field names to values. Field values in the primary
2425    relation are represented by scalars. (Note that for relationships, the primary relation is
2426    the B<only> relation.) Field values for the other relations comprising the entity are always
2427    list references. For example, the following line inserts an inactive PEG feature named
2428    C<fig|188.1.peg.1> with aliases C<ZP_00210270.1> and C<gi|46206278>.
2429    
2430        $sprout->Insert('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']});
2431    
2432    The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
2433    property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
2434    
2435        $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'});
2436    
2437    =over 4
2438    
2439    =item newObjectType
2440    
2441    Type name of the entity or relationship to insert.
2442    
2443    =item fieldHash
2444    
2445    Hash of field names to values.
2446    
2447    =back
2448    
2449    =cut
2450    #: Return Type ;
2451    sub Insert {
2452        # Get the parameters.
2453        my ($self, $objectType, $fieldHash) = @_;
2454        # Call the underlying method.
2455        $self->InsertObject($objectType, $fieldHash);
2456    }
2457    
2458    =head3 Annotate
2459    
2460        my $ok = $sprout->Annotate($fid, $timestamp, $user, $text);
2461    
2462    Annotate a feature. This inserts an Annotation record into the database and links it to the
2463    specified feature and user.
2464    
2465    =over 4
2466    
2467    =item fid
2468    
2469    ID of the feature to be annotated.
2470    
2471    =item timestamp
2472    
2473    Numeric timestamp to apply to the annotation. This is concatenated to the feature ID to create the
2474    key.
2475    
2476    =item user
2477    
2478    ID of the user who is making the annotation.
2479    
2480    =item text
2481    
2482  Text of the annotation.  Text of the annotation.
2483    
# Line 2242  Line 2511 
2511    
2512  =head3 AssignFunction  =head3 AssignFunction
2513    
2514  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>      my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser);
2515    
2516  This method assigns a function to a feature. Functions are a special type of annotation. The general  This method assigns a function to a feature. Functions are a special type of annotation. The general
2517  format is described in L</ParseAssignment>.  format is described in L</ParseAssignment>.
# Line 2302  Line 2571 
2571    
2572  =head3 FeaturesByAlias  =head3 FeaturesByAlias
2573    
2574  C<< my @features = $sprout->FeaturesByAlias($alias); >>      my @features = $sprout->FeaturesByAlias($alias);
2575    
2576  Returns a list of features with the specified alias. The alias is parsed to determine  Returns a list of features with the specified alias. The alias is parsed to determine
2577  the type of the alias. A string of digits is a GenBack ID and a string of exactly 6  the type of the alias. A string of digits is a GenBack ID and a string of exactly 6
# Line 2336  Line 2605 
2605          push @retVal, $mappedAlias;          push @retVal, $mappedAlias;
2606      } else {      } else {
2607          # Here we have a non-FIG alias. Get the features with the normalized alias.          # Here we have a non-FIG alias. Get the features with the normalized alias.
2608          @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');          @retVal = $self->GetFlat(['IsAliasOf'], 'IsAliasOf(from-link) = ?', [$mappedAlias], 'IsAliasOf(to-link)');
2609      }      }
2610      # Return the result.      # Return the result.
2611      return @retVal;      return @retVal;
# Line 2344  Line 2613 
2613    
2614  =head3 FeatureTranslation  =head3 FeatureTranslation
2615    
2616  C<< my $translation = $sprout->FeatureTranslation($featureID); >>      my $translation = $sprout->FeatureTranslation($featureID);
2617    
2618  Return the translation of a feature.  Return the translation of a feature.
2619    
# Line 2372  Line 2641 
2641    
2642  =head3 Taxonomy  =head3 Taxonomy
2643    
2644  C<< my @taxonomyList = $sprout->Taxonomy($genome); >>      my @taxonomyList = $sprout->Taxonomy($genome);
2645    
2646  Return the taxonomy of the specified genome. This will be in the form of a list  Return the taxonomy of the specified genome. This will be in the form of a list
2647  containing the various classifications in order from domain (eg. C<Bacteria>, C<Archaea>,  containing the various classifications in order from domain (eg. C<Bacteria>, C<Archaea>,
2648  or C<Eukaryote>) to sub-species. For example,  or C<Eukaryote>) to sub-species. For example,
2649    
2650  C<< (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12) >>      (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12)
2651    
2652  =over 4  =over 4
2653    
# Line 2413  Line 2682 
2682    
2683  =head3 CrudeDistance  =head3 CrudeDistance
2684    
2685  C<< my $distance = $sprout->CrudeDistance($genome1, $genome2); >>      my $distance = $sprout->CrudeDistance($genome1, $genome2);
2686    
2687  Returns a crude estimate of the distance between two genomes. The distance is construed so  Returns a crude estimate of the distance between two genomes. The distance is construed so
2688  that it will be 0 for genomes with identical taxonomies and 1 for genomes from different domains.  that it will be 0 for genomes with identical taxonomies and 1 for genomes from different domains.
# Line 2465  Line 2734 
2734    
2735  =head3 RoleName  =head3 RoleName
2736    
2737  C<< my $roleName = $sprout->RoleName($roleID); >>      my $roleName = $sprout->RoleName($roleID);
2738    
2739  Return the descriptive name of the role with the specified ID. In general, a role  Return the descriptive name of the role with the specified ID. In general, a role
2740  will only have a descriptive name if it is coded as an EC number.  will only have a descriptive name if it is coded as an EC number.
# Line 2499  Line 2768 
2768    
2769  =head3 RoleDiagrams  =head3 RoleDiagrams
2770    
2771  C<< my @diagrams = $sprout->RoleDiagrams($roleID); >>      my @diagrams = $sprout->RoleDiagrams($roleID);
2772    
2773  Return a list of the diagrams containing a specified functional role.  Return a list of the diagrams containing a specified functional role.
2774    
# Line 2527  Line 2796 
2796      return @retVal;      return @retVal;
2797  }  }
2798    
 =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;  
 }  
   
2799  =head3 FeatureProperties  =head3 FeatureProperties
2800    
2801  C<< my @properties = $sprout->FeatureProperties($featureID); >>      my @properties = $sprout->FeatureProperties($featureID);
2802    
2803  Return a list of the properties for the specified feature. Properties are key-value pairs  Return a list of the properties for the specified feature. Properties are key-value pairs
2804  that specify special characteristics of the feature. For example, a property could indicate  that specify special characteristics of the feature. For example, a property could indicate
2805  that a feature is essential to the survival of the organism or that it has benign influence  that a feature is essential to the survival of the organism or that it has benign influence
2806  on the activities of a pathogen. Each property is returned as a triple of the form  on the activities of a pathogen. Each property is returned as a triple of the form
2807  C<($key,$value,$url)>, where C<$key> is the property name, C<$value> is its value (commonly  C<($key,@values)>, where C<$key> is the property name and  C<@values> are its values.
 a 1 or a 0, but possibly a string or a floating-point value), and C<$url> is a string describing  
 the web address or citation in which the property's value for the feature was identified.  
2808    
2809  =over 4  =over 4
2810    
# Line 2630  Line 2814 
2814    
2815  =item RETURN  =item RETURN
2816    
2817  Returns a list of triples, each triple containing the property name, its value, and a URL or  Returns a list of tuples, each tuple containing the property name and its values.
 citation.  
2818    
2819  =back  =back
2820    
# Line 2641  Line 2824 
2824      # Get the parameters.      # Get the parameters.
2825      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2826      # Get the properties.      # Get the properties.
2827      my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],      my @attributes = $self->{_ca}->GetAttributes($featureID);
2828                              ['Property(property-name)', 'Property(property-value)',      # Strip the feature ID off each tuple.
2829                               'HasProperty(evidence)']);      my @retVal = ();
2830        for my $attributeRow (@attributes) {
2831            shift @{$attributeRow};
2832            push @retVal, $attributeRow;
2833        }
2834      # Return the resulting list.      # Return the resulting list.
2835      return @retVal;      return @retVal;
2836  }  }
2837    
2838  =head3 DiagramName  =head3 DiagramName
2839    
2840  C<< my $diagramName = $sprout->DiagramName($diagramID); >>      my $diagramName = $sprout->DiagramName($diagramID);
2841    
2842  Return the descriptive name of a diagram.  Return the descriptive name of a diagram.
2843    
# Line 2678  Line 2865 
2865    
2866  =head3 PropertyID  =head3 PropertyID
2867    
2868  C<< my $id = $sprout->PropertyID($propName, $propValue); >>      my $id = $sprout->PropertyID($propName, $propValue);
2869    
2870  Return the ID of the specified property name and value pair, if the  Return the ID of the specified property name and value pair, if the
2871  pair exists.  pair exists. Only a small subset of the FIG attributes are stored as
2872    Sprout properties, mostly for use in search optimization.
2873    
2874  =over 4  =over 4
2875    
# Line 2714  Line 2902 
2902    
2903  =head3 MergedAnnotations  =head3 MergedAnnotations
2904    
2905  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>      my @annotationList = $sprout->MergedAnnotations(\@list);
2906    
2907  Returns a merged list of the annotations for the features in a list. Each annotation is  Returns a merged list of the annotations for the features in a list. Each annotation is
2908  represented by a 4-tuple of the form C<($fid, $timestamp, $userID, $annotation)>, where  represented by a 4-tuple of the form C<($fid, $timestamp, $userID, $annotation)>, where
# Line 2763  Line 2951 
2951    
2952  =head3 RoleNeighbors  =head3 RoleNeighbors
2953    
2954  C<< my @roleList = $sprout->RoleNeighbors($roleID); >>      my @roleList = $sprout->RoleNeighbors($roleID);
2955    
2956  Returns a list of the roles that occur in the same diagram as the specified role. Because  Returns a list of the roles that occur in the same diagram as the specified role. Because
2957  diagrams and roles are in a many-to-many relationship with each other, the list is  diagrams and roles are in a many-to-many relationship with each other, the list is
# Line 2806  Line 2994 
2994    
2995  =head3 FeatureLinks  =head3 FeatureLinks
2996    
2997  C<< my @links = $sprout->FeatureLinks($featureID); >>      my @links = $sprout->FeatureLinks($featureID);
2998    
2999  Return a list of the web hyperlinks associated with a feature. The web hyperlinks are  Return a list of the web hyperlinks associated with a feature. The web hyperlinks are
3000  to external websites describing either the feature itself or the organism containing it  to external websites describing either the feature itself or the organism containing it
# Line 2837  Line 3025 
3025    
3026  =head3 SubsystemsOf  =head3 SubsystemsOf
3027    
3028  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>      my %subsystems = $sprout->SubsystemsOf($featureID);
3029    
3030  Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped  Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped
3031  to the roles the feature performs.  to the roles the feature performs.
# Line 2885  Line 3073 
3073    
3074  =head3 SubsystemList  =head3 SubsystemList
3075    
3076  C<< my @subsystems = $sprout->SubsystemList($featureID); >>      my @subsystems = $sprout->SubsystemList($featureID);
3077    
3078  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
3079  feature participates. Unlike L</SubsystemsOf>, this method only returns the  feature participates. Unlike L</SubsystemsOf>, this method only returns the
# Line 2908  Line 3096 
3096  sub SubsystemList {  sub SubsystemList {
3097      # Get the parameters.      # Get the parameters.
3098      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
3099      # Get the list of names.      # Get the list of names. We do a join to the Subsystem table because we have missing subsystems in
3100      my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?",      # the Sprout database!
3101        my @retVal = $self->GetFlat(['HasRoleInSubsystem', 'Subsystem'], "HasRoleInSubsystem(from-link) = ?",
3102                                  [$featureID], 'HasRoleInSubsystem(to-link)');                                  [$featureID], 'HasRoleInSubsystem(to-link)');
3103      # Return the result, sorted.      # Return the result, sorted.
3104      return sort @retVal;      return sort @retVal;
# Line 2917  Line 3106 
3106    
3107  =head3 GenomeSubsystemData  =head3 GenomeSubsystemData
3108    
3109  C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>      my %featureData = $sprout->GenomeSubsystemData($genomeID);
3110    
3111  Return a hash mapping genome features to their subsystem roles.  Return a hash mapping genome features to their subsystem roles.
3112    
# Line 2942  Line 3131 
3131      # Declare the return variable.      # Declare the return variable.
3132      my %retVal = ();      my %retVal = ();
3133      # Get a list of the genome features that participate in subsystems. For each      # Get a list of the genome features that participate in subsystems. For each
3134      # feature we get its spreadsheet cells and the corresponding roles.      # feature we get its subsystem ID and the corresponding roles.
3135      my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],      my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf', 'HasSSCell'],
3136                               "HasFeature(from-link) = ?", [$genomeID],                               "HasFeature(from-link) = ?", [$genomeID],
3137                               ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);                                   ['HasFeature(to-link)', 'IsRoleOf(from-link)',  'HasSSCell(from-link)']);
3138      # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems      # Now we get a list of valid subsystems. These are the subsystems connected to the genome with
3139      # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the      # a non-negative variant code.
3140      # list. We use it at the beginning to get all the spreadsheet cells for the genome and      my %subs = map { $_ => 1 } $self->GetFlat(['ParticipatesIn'],
3141      # again at the end to filter out participation in subsystems with a negative variant code.                                                  "ParticipatesIn(from-link) = ? AND ParticipatesIn(variant-code) >= 0",
3142      my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],                                                  [$genomeID], 'ParticipatesIn(to-link)');
3143                                   "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?",      # We loop through @roleData to build the hash.
                                  [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']);  
     # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features.  
     # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We  
     # link these two lists together to create the result. First, we want a hash mapping  
     # spreadsheet cells to subsystem names.  
     my %subHash = map { $_->[0] => $_->[1] } @cellData;  
     # We loop through @cellData to build the hash.  
3144      for my $roleEntry (@roleData) {      for my $roleEntry (@roleData) {
3145          # Get the data for this feature and cell.          # Get the data for this feature and cell.
3146          my ($fid, $cellID, $role) = @{$roleEntry};          my ($fid, $role, $subsys) = @{$roleEntry};
3147          # Check for a subsystem name.          Trace("Subsystem for $fid is $subsys.") if T(4);
3148          my $subsys = $subHash{$cellID};          # Check the subsystem;
3149          if ($subsys) {          if ($subs{$subsys}) {
3150                Trace("Subsystem found.") if T(4);
3151              # Insure this feature has an entry in the return hash.              # Insure this feature has an entry in the return hash.
3152              if (! exists $retVal{$fid}) { $retVal{$fid} = []; }              if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
3153              # Merge in this new data.              # Merge in this new data.
# Line 2977  Line 3160 
3160    
3161  =head3 RelatedFeatures  =head3 RelatedFeatures
3162    
3163  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>      my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID);
3164    
3165  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
3166  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 3028  Line 3211 
3211    
3212  =head3 TaxonomySort  =head3 TaxonomySort
3213    
3214  C<< my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs); >>      my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs);
3215    
3216  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
3217  genome. This will cause genomes from similar organisms to float close to each other.  genome. This will cause genomes from similar organisms to float close to each other.
# Line 3063  Line 3246 
3246          my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",          my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
3247                                          [$fid], 'Genome(taxonomy)');                                          [$fid], 'Genome(taxonomy)');
3248          # Add this feature to the hash buffer.          # Add this feature to the hash buffer.
3249          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);          push @{$hashBuffer{$taxonomy}}, $fid;
3250      }      }
3251      # Sort the keys and get the elements.      # Sort the keys and get the elements.
3252      my @retVal = ();      my @retVal = ();
# Line 3076  Line 3259 
3259    
3260  =head3 Protein  =head3 Protein
3261    
3262  C<< my $protein = Sprout::Protein($sequence, $table); >>      my $protein = Sprout::Protein($sequence, $table);
3263    
3264  Translate a DNA sequence into a protein sequence.  Translate a DNA sequence into a protein sequence.
3265    
# Line 3162  Line 3345 
3345    
3346  =head3 LoadInfo  =head3 LoadInfo
3347    
3348  C<< my ($dirName, @relNames) = $sprout->LoadInfo(); >>      my ($dirName, @relNames) = $sprout->LoadInfo();
3349    
3350  Return the name of the directory from which data is to be loaded and a list of the relation  Return the name of the directory from which data is to be loaded and a list of the relation
3351  names. This information is useful when trying to analyze what needs to be put where in order  names. This information is useful when trying to analyze what needs to be put where in order
# Line 3183  Line 3366 
3366    
3367  =head3 BBHMatrix  =head3 BBHMatrix
3368    
3369  C<< my %bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets); >>      my %bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets);
3370    
3371  Find all the bidirectional best hits for the features of a genome in a  Find all the bidirectional best hits for the features of a genome in a
3372  specified list of target genomes. The return value will be a hash mapping  specified list of target genomes. The return value will be a hash mapping
# Line 3234  Line 3417 
3417      return %retVal;      return %retVal;
3418  }  }
3419    
3420    
3421    =head3 SimMatrix
3422    
3423        my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets);
3424    
3425    Find all the similarities for the features of a genome in a
3426    specified list of target genomes. The return value will be a hash mapping
3427    features in the original genome to their similarites in the
3428    target genomes.
3429    
3430    =over 4
3431    
3432    =item genomeID
3433    
3434    ID of the genome whose features are to be examined for similarities.
3435    
3436    =item cutoff
3437    
3438    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3439    
3440    =item targets
3441    
3442    List of target genomes. Only pairs originating in the original
3443    genome and landing in one of the target genomes will be returned.
3444    
3445    =item RETURN
3446    
3447    Returns a hash mapping each feature in the original genome to a hash mapping its
3448    similar pegs in the target genomes to their scores.
3449    
3450    =back
3451    
3452    =cut
3453    
3454    sub SimMatrix {
3455        # Get the parameters.
3456        my ($self, $genomeID, $cutoff, @targets) = @_;
3457        # Declare the return variable.
3458        my %retVal = ();
3459        # Get the list of features in the source organism.
3460        my @fids = $self->FeaturesOf($genomeID);
3461        # Ask for the sims. We only want similarities to fig features.
3462        my $simList = FIGRules::GetNetworkSims($self, \@fids, {}, 1000, $cutoff, "fig");
3463        if (! defined $simList) {
3464            Confess("Unable to retrieve similarities from server.");
3465        } else {
3466            Trace("Processing sims.") if T(3);
3467            # We now have a set of sims that we need to convert into a hash of hashes. First, we
3468            # Create a hash for the target genomes.
3469            my %targetHash = map { $_ => 1 } @targets;
3470            for my $simData (@{$simList}) {
3471                # Get the PEGs and the score.
3472                my ($peg1, $peg2, $score) = ($simData->id1, $simData->id2, $simData->psc);
3473                # Insure the second ID is in the target list.
3474                my ($genome2) = FIGRules::ParseFeatureID($peg2);
3475                if (exists $targetHash{$genome2}) {
3476                    # Here it is. Now we need to add it to the return hash. How we do that depends
3477                    # on whether or not $peg1 is new to us.
3478                    if (! exists $retVal{$peg1}) {
3479                        $retVal{$peg1} = { $peg2 => $score };
3480                    } else {
3481                        $retVal{$peg1}->{$peg2} = $score;
3482                    }
3483                }
3484            }
3485        }
3486        # Return the result.
3487        return %retVal;
3488    }
3489    
3490    
3491  =head3 LowBBHs  =head3 LowBBHs
3492    
3493  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>      my %bbhMap = $sprout->LowBBHs($featureID, $cutoff);
3494    
3495  Return the bidirectional best hits of a feature whose score is no greater than a  Return the bidirectional best hits of a feature whose score is no greater than a
3496  specified cutoff value. A higher cutoff value will allow inclusion of hits with  specified cutoff value. A higher cutoff value will allow inclusion of hits with
# Line 3280  Line 3534 
3534    
3535  =head3 Sims  =head3 Sims
3536    
3537  C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>      my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters);
3538    
3539  Get a list of similarities for a specified feature. Similarity information is not kept in the  Get a list of similarities for a specified feature. Similarity information is not kept in the
3540  Sprout database; rather, they are retrieved from a network server. The similarities are  Sprout database; rather, they are retrieved from a network server. The similarities are
# Line 3290  Line 3544 
3544  Similarities can be either raw or expanded. The raw similarities are basic  Similarities can be either raw or expanded. The raw similarities are basic
3545  hits between features with similar DNA. Expanding a raw similarity drags in any  hits between features with similar DNA. Expanding a raw similarity drags in any
3546  features considered substantially identical. So, for example, if features B<A1>,  features considered substantially identical. So, for example, if features B<A1>,
3547  B<A2>, and B<A3> are all substatially identical to B<A>, then a raw similarity  B<A2>, and B<A3> are all substantially identical to B<A>, then a raw similarity
3548  B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.  B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3549    
3550  =over 4  =over 4
3551    
3552  =item fid  =item fid
3553    
3554  ID of the feature whose similarities are desired.  ID of the feature whose similarities are desired, or reference to a list of IDs
3555    of features whose similarities are desired.
3556    
3557  =item maxN  =item maxN
3558    
# Line 3345  Line 3600 
3600    
3601  =head3 IsAllGenomes  =head3 IsAllGenomes
3602    
3603  C<< my $flag = $sprout->IsAllGenomes(\@list, \@checkList); >>      my $flag = $sprout->IsAllGenomes(\@list, \@checkList);
3604    
3605  Return TRUE if all genomes in the second list are represented in the first list at  Return TRUE if all genomes in the second list are represented in the first list at
3606  least one. Otherwise, return FALSE. If the second list is omitted, the first list is  least one. Otherwise, return FALSE. If the second list is omitted, the first list is
# Line 3394  Line 3649 
3649    
3650  =head3 GetGroups  =head3 GetGroups
3651    
3652  C<< my %groups = $sprout->GetGroups(\@groupList); >>      my %groups = $sprout->GetGroups(\@groupList);
3653    
3654  Return a hash mapping each group to the IDs of the genomes in the group.  Return a hash mapping each group to the IDs of the genomes in the group.
3655  A list of groups may be specified, in which case only those groups will be  A list of groups may be specified, in which case only those groups will be
# Line 3426  Line 3681 
3681                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3682          # Loop through the genomes found.          # Loop through the genomes found.
3683          for my $genome (@genomes) {          for my $genome (@genomes) {
3684              # Pop this genome's ID off the current list.              # Get the genome ID and group, and add this genome to the group's list.
3685              my @groups = @{$genome};              my ($genomeID, $group) = @{$genome};
3686              my $genomeID = shift @groups;              push @{$retVal{$group}}, $genomeID;
             # Loop through the groups, adding the genome ID to each group's  
             # list.  
             for my $group (@groups) {  
                 Tracer::AddToListMap(\%retVal, $group, $genomeID);  
             }  
3687          }          }
3688      }      }
3689      # Return the hash we just built.      # Return the hash we just built.
# Line 3442  Line 3692 
3692    
3693  =head3 MyGenomes  =head3 MyGenomes
3694    
3695  C<< my @genomes = Sprout::MyGenomes($dataDir); >>      my @genomes = Sprout::MyGenomes($dataDir);
3696    
3697  Return a list of the genomes to be included in the Sprout.  Return a list of the genomes to be included in the Sprout.
3698    
# Line 3474  Line 3724 
3724    
3725  =head3 LoadFileName  =head3 LoadFileName
3726    
3727  C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>      my $fileName = Sprout::LoadFileName($dataDir, $tableName);
3728    
3729  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
3730  directory.  directory.
# Line 3515  Line 3765 
3765    
3766  =head3 DeleteGenome  =head3 DeleteGenome
3767    
3768  C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>      my $stats = $sprout->DeleteGenome($genomeID, $testFlag);
3769    
3770  Delete a genome from the database.  Delete a genome from the database.
3771    
# Line 3551  Line 3801 
3801    
3802  =head3 Fix  =head3 Fix
3803    
3804  C<< my %fixedHash = Sprout::Fix(%groupHash); >>      my %fixedHash = $sprout->Fix(%groupHash);
3805    
3806  Prepare a genome group hash (like that returned by L</GetGroups> for processing.  Prepare a genome group hash (like that returned by L</GetGroups>) for processing.
3807  Groups with the same primary name will be combined. The primary name is the  The groups will be combined into the appropriate super-groups.
 first capitalized word in the group name.  
3808    
3809  =over 4  =over 4
3810    
# Line 3573  Line 3822 
3822    
3823  sub Fix {  sub Fix {
3824      # Get the parameters.      # Get the parameters.
3825      my (%groupHash) = @_;      my ($self, %groupHash) = @_;
3826      # Create the result hash.      # Create the result hash.
3827      my %retVal = ();      my %retVal = ();
3828      # Copy over the genomes.      # Copy over the genomes.
3829      for my $groupID (keys %groupHash) {      for my $groupID (keys %groupHash) {
3830          # Make a safety copy of the group ID.          # Get the super-group name.
3831          my $realGroupID = $groupID;          my $realGroupID = $self->SuperGroup($groupID);
3832          # Yank the primary name.          # Append this group's genomes into the result hash
3833          if ($groupID =~ /([A-Z]\w+)/) {          # using the super-group name.
3834              $realGroupID = $1;          push @{$retVal{$realGroupID}}, @{$groupHash{$groupID}};
         }  
         # Append this group's genomes into the result hash.  
         Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}});  
3835      }      }
3836      # Return the result hash.      # Return the result hash.
3837      return %retVal;      return %retVal;
# Line 3593  Line 3839 
3839    
3840  =head3 GroupPageName  =head3 GroupPageName
3841    
3842  C<< my $name = $sprout->GroupPageName($group); >>      my $name = $sprout->GroupPageName($group);
3843    
3844  Return the name of the page for the specified NMPDR group.  Return the name of the page for the specified NMPDR group.
3845    
# Line 3615  Line 3861 
3861  sub GroupPageName {  sub GroupPageName {
3862      # Get the parameters.      # Get the parameters.
3863      my ($self, $group) = @_;      my ($self, $group) = @_;
     # Declare the return variable.  
     my $retVal;  
3864      # Check for the group file data.      # Check for the group file data.
3865      if (! defined $self->{groupHash}) {      my %superTable = $self->CheckGroupFile();
         # Read the group file.  
         my %groupData = Sprout::ReadGroupFile($self->{_options}->{dataDir} . "/groups.tbl");  
         # Store it in our object.  
         $self->{groupHash} = \%groupData;  
     }  
3866      # Compute the real group name.      # Compute the real group name.
3867      my $realGroup = $group;      my $realGroup = $self->SuperGroup($group);
3868      if ($group =~ /([A-Z]\w+)/) {      # Get the associated page name.
3869          $realGroup = $1;      my $retVal = "../content/$superTable{$realGroup}->{page}";
     }  
     # Return the page name.  
     $retVal = "../content/" . $self->{groupHash}->{$realGroup}->[1];  
3870      # Return the result.      # Return the result.
3871      return $retVal;      return $retVal;
3872  }  }
3873    
 =head3 ReadGroupFile  
3874    
3875  C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >>  =head3 AddProperty
3876    
3877        $sprout->AddProperty($featureID, $key, @values);
3878    
3879  Read in the data from the specified group file. The group file contains information  Add a new attribute value (Property) to a feature.
 about each of the NMPDR groups.  
3880    
3881  =over 4  =over 4
3882    
3883  =item name  =item peg
3884    
3885  Name of the group.  ID of the feature to which the attribute is to be added.
3886    
3887  =item page  =item key
3888    
3889  Name of the group's page on the web site (e.g. C<campy.php> for  Name of the attribute (key).
 Campylobacter)  
3890    
3891  =item genus  =item values
3892    
3893  Genus of the group  Values of the attribute.
3894    
3895  =item species  =back
3896    
3897  Species of the group, or an empty string if the group is for an entire  =cut
3898  genus. If the group contains more than one species, the species names  #: Return Type ;
3899  should be separated by commas.  sub AddProperty {
3900        # Get the parameters.
3901        my ($self, $featureID, $key, @values) = @_;
3902        # Add the property using the attached attributes object.
3903        $self->{_ca}->AddAttribute($featureID, $key, @values);
3904    }
3905    
3906  =back  =head3 CheckGroupFile
3907    
3908        my %groupData = $sprout->CheckGroupFile();
3909    
3910    Get the group file hash. The group file hash describes the relationship
3911    between a group and the super-group to which it belongs for purposes of
3912    display. The super-group name is computed from the first capitalized word
3913    in the actual group name. For each super-group, the group file contains
3914    the page name and a list of the species expected to be in the group.
3915    Each species is specified by a genus and a species name. A species name
3916    of C<0> implies an entire genus.
3917    
3918  The parameters to this method are as follows  This method returns a hash from super-group names to a hash reference. Each
3919    resulting hash reference contains the following fields.
3920    
3921  =over 4  =over 4
3922    
3923  =item groupFile  =item page
3924    
3925  Name of the file containing the group data.  The super-group's web page in the NMPDR.
3926    
3927  =item RETURN  =item contents
3928    
3929  Returns a hash keyed on group name. The value of each hash  A list of 2-tuples, each containing a genus name followed by a species name
3930    (or 0, indicating all species). This list indicates which organisms belong
3931    in the super-group.
3932    
3933  =back  =back
3934    
3935  =cut  =cut
3936    
3937  sub ReadGroupFile {  sub CheckGroupFile {
3938      # Get the parameters.      # Get the parameters.
3939      my ($groupFileName) = @_;      my ($self) = @_;
3940      # Declare the return variable.      # Check to see if we already have this hash.
3941      my %retVal;      if (! defined $self->{groupHash}) {
3942            # We don't, so we need to read it in.
3943            my %groupHash;
3944      # Read the group file.      # Read the group file.
3945      my @groupLines = Tracer::GetFile($groupFileName);          my @groupLines = Tracer::GetFile("$FIG_Config::sproutData/groups.tbl");
3946            # Loop through the list of sort-of groups.
3947      for my $groupLine (@groupLines) {      for my $groupLine (@groupLines) {
3948          my ($name, $page, $genus, $species) = split(/\t/, $groupLine);              my ($name, $page, @contents) = split /\t/, $groupLine;
3949          $retVal{$name} = [$page, $genus, $species];              $groupHash{$name} = { page => $page,
3950                                      contents => [ map { [ split /\s*,\s*/, $_ ] } @contents ]
3951                                    };
3952            }
3953            # Save the hash.
3954            $self->{groupHash} = \%groupHash;
3955      }      }
3956      # Return the result.      # Return the result.
3957      return %retVal;      return %{$self->{groupHash}};
3958  }  }
3959    
3960  =head3 AddProperty  =head2 Virtual Methods
3961    
3962    =head3 CleanKeywords
3963    
3964  C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>      my $cleanedString = $sprout->CleanKeywords($searchExpression);
3965    
3966  Add a new attribute value (Property) to a feature. In the SEED system, attributes can  Clean up a search expression or keyword list. This involves converting the periods
3967  be added to almost any object. In Sprout, they can only be added to features. In  in EC numbers to underscores, converting non-leading minus signs to underscores,
3968  Sprout, attributes are implemented using I<properties>. A property represents a key/value  a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
3969  pair. If the particular key/value pair coming in is not already in the database, a new  characters. In addition, any extra spaces are removed.
 B<Property> record is created to hold it.  
3970    
3971  =over 4  =over 4
3972    
3973  =item peg  =item searchExpression
3974    
3975  ID of the feature to which the attribute is to be replied.  Search expression or keyword list to clean. Note that a search expression may
3976    contain boolean operators which need to be preserved. This includes leading
3977    minus signs.
3978    
3979  =item key  =item RETURN
3980    
3981  Name of the attribute (key).  Cleaned expression or keyword list.
3982    
3983    =back
3984    
3985    =cut
3986    
3987    sub CleanKeywords {
3988        # Get the parameters.
3989        my ($self, $searchExpression) = @_;
3990        # Get the stemmer.
3991        my $stemmer = $self->GetStemmer();
3992        # Convert the search expression using the stemmer.
3993        my $retVal = $stemmer->PrepareSearchExpression($searchExpression);
3994        Trace("Cleaned keyword list for \"$searchExpression\" is \"$retVal\".") if T(3);
3995        # Return the result.
3996        return $retVal;
3997    }
3998    
3999    =head3 GetSourceObject
4000    
4001        my $source = $erdb->GetSourceObject();
4002    
4003    Return the object to be used in creating load files for this database.
4004    
4005    =cut
4006    
4007    sub GetSourceObject {
4008        # Get access to the FIG code.
4009        require FIG;
4010        # Return a FIG object.
4011        return FIG->new();
4012    }
4013    
4014    =head3 SectionList
4015    
4016  =item value      my @sections = $erdb->SectionList($source);
4017    
4018  Value of the attribute.  Return a list of the names for the different data sections used when loading this database.
4019    The default is an empty string, in which case there is only one section representing the
4020    entire database.
4021    
4022  =item url  =over 4
4023    
4024    =item source
4025    
4026    Source object used to access the data from which the database is loaded. This is the
4027    same object returned by L</GetSourceObject>; however, we ask the caller to pass it
4028    in as a parameter so that we don't end up creating multiple copies of a potentially
4029    expensive data structure.
4030    
4031    =item RETURN
4032    
4033  URL or text citation from which the property was obtained.  Returns a list of section names.
4034    
4035  =back  =back
4036    
4037  =cut  =cut
4038  #: Return Type ;  
4039  sub AddProperty {  sub SectionList {
4040      # Get the parameters.      # Get the parameters.
4041      my ($self, $featureID, $key, $value, $url) = @_;      my ($self, $source) = @_;
4042      # Declare the variable to hold the desired property ID.      # Ask the BaseSproutLoader for a section list.
4043      my $propID;      require BaseSproutLoader;
4044      # Attempt to find a property record for this key/value pair.      my @retVal = BaseSproutLoader::GetSectionList($self, $source);
4045      my @properties = $self->GetFlat(['Property'],      # Return the list.
4046                                     "Property(property-name) = ? AND Property(property-value) = ?",      return @retVal;
                                    [$key, $value], 'Property(id)');  
     if (@properties) {  
         # Here the property is already in the database. We save its ID.  
         $propID = $properties[0];  
         # Here the property value does not exist. We need to generate an ID. It will be set  
         # to a number one greater than the maximum value in the database. This call to  
         # GetAll will stop after one record.  
         my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],  
                                         1);  
         $propID = $maxProperty[0]->[0] + 1;  
         # Insert the new property value.  
         $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });  
     }  
     # Now we connect the incoming feature to the property.  
     $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });  
4047  }  }
4048    
4049  =head2 Virtual Methods  =head3 Loader
4050    
4051  =head3 CleanKeywords      my $groupLoader = $erdb->Loader($groupName, $source, $options);
4052    
4053  C<< my $cleanedString = $sprout->CleanKeywords($searchExpression); >>  Return an [[ERDBLoadGroupPm]] object for the specified load group. This method is used
4054    by [[ERDBGeneratorPl]] to create the load group objects. If you are not using
4055  Clean up a search expression or keyword list. This involves converting the periods  [[ERDBGeneratorPl]], you don't need to override this method.
 in EC numbers to underscores, converting non-leading minus signs to underscores,  
 a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic  
 characters. In addition, any extra spaces are removed.  
4056    
4057  =over 4  =over 4
4058    
4059  =item searchExpression  =item groupName
4060    
4061  Search expression or keyword list to clean. Note that a search expression may  Name of the load group whose object is to be returned. The group name is
4062  contain boolean operators which need to be preserved. This includes leading  guaranteed to be a single word with only the first letter capitalized.
4063  minus signs.  
4064    =item source
4065    
4066    The source object used to access the data from which the load file is derived. This
4067    is the same object returned by L</GetSourceObject>; however, we ask the caller to pass
4068    it in as a parameter so that we don't end up creating multiple copies of a potentially
4069    expensive data structure.
4070    
4071    =item options
4072    
4073    Reference to a hash of command-line options.
4074    
4075  =item RETURN  =item RETURN
4076    
4077  Cleaned expression or keyword list.  Returns an [[ERDBLoadGroupPm]] object that can be used to process the specified load group
4078    for this database.
4079    
4080  =back  =back
4081    
4082  =cut  =cut
4083    
4084  sub CleanKeywords {  sub Loader {
4085      # Get the parameters.      # Get the parameters.
4086      my ($self, $searchExpression) = @_;      my ($self, $groupName, $source, $options) = @_;
4087      # Perform the standard cleanup.      # Compute the loader name.
4088      my $retVal = $self->ERDB::CleanKeywords($searchExpression);      my $loaderClass = "${groupName}SproutLoader";
4089      # Fix the periods in EC and TC numbers.      # Pull in its definition.
4090      $retVal =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g;      require "$loaderClass.pm";
4091      # Fix non-trailing periods.      # Create an object for it.
4092      $retVal =~ s/\.(\w)/_$1/g;      my $retVal = eval("$loaderClass->new(\$self, \$source, \$options)");
4093      # Fix non-leading minus signs.      # Insure it worked.
4094      $retVal =~ s/(\w)[\-]/$1_/g;      Confess("Could not create $loaderClass object: $@") if $@;
4095      # Fix the vertical bars and colons      # Return it to the caller.
     $retVal =~ s/(\w)[|:](\w)/$1'$2/g;  
     # Return the result.  
4096      return $retVal;      return $retVal;
4097  }  }
4098    
4099    =head3 LoadGroupList
4100    
4101        my @groups = $erdb->LoadGroupList();
4102    
4103    Returns a list of the names for this database's load groups. This method is used
4104    by [[ERDBGeneratorPl]] when the user wishes to load all table groups. The default
4105    is a single group called 'All' that loads everything.
4106    
4107    =cut
4108    
4109    sub LoadGroupList {
4110        # Return the list.
4111        return qw(Genome Subsystem Feature Annotation Property Source Reaction Synonym Drug);
4112    }
4113    
4114    =head3 LoadDirectory
4115    
4116        my $dirName = $erdb->LoadDirectory();
4117    
4118    Return the name of the directory in which load files are kept. The default is
4119    the FIG temporary directory, which is a really bad choice, but it's always there.
4120    
4121    =cut
4122    
4123    sub LoadDirectory {
4124        # Get the parameters.
4125        my ($self) = @_;
4126        # Return the directory name.
4127        return $self->{dataDir};
4128    }
4129    
4130  =head2 Internal Utility Methods  =head2 Internal Utility Methods
4131    
4132    =head3 GetStemmer
4133    
4134        my $stermmer = $sprout->GetStemmer();
4135    
4136    Return the stemmer object for this database.
4137    
4138    =cut
4139    
4140    sub GetStemmer {
4141        # Get the parameters.
4142        my ($self) = @_;
4143        # Declare the return variable.
4144        my $retVal = $self->{stemmer};
4145        if (! defined $retVal) {
4146            # We don't have one pre-built, so we build and save it now.
4147            $retVal = BioWords->new(exceptions => "$FIG_Config::sproutData/Exceptions.txt",
4148                                     stops => "$FIG_Config::sproutData/StopWords.txt",
4149                                     cache => 1);
4150            $self->{stemmer} = $retVal;
4151        }
4152        # Return the result.
4153        return $retVal;
4154    }
4155    
4156  =head3 ParseAssignment  =head3 ParseAssignment
4157    
4158  Parse annotation text to determine whether or not it is a functional assignment. If it is,  Parse annotation text to determine whether or not it is a functional assignment. If it is,
# Line 3807  Line 4161 
4161    
4162  A functional assignment is always of the form  A functional assignment is always of the form
4163    
4164      C<set >I<YYYY>C< function to\n>I<ZZZZZ>      set YYYY function to
4165        ZZZZ
4166    
4167  where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,  where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
4168  the user and the assigning user (from MadeAnnotation) will be the same, but that is  the user and the assigning user (from MadeAnnotation) will be the same, but that is
# Line 3860  Line 4215 
4215      return @retVal;      return @retVal;
4216  }  }
4217    
4218    =head3 _CheckFeature
4219    
4220        my $flag = $sprout->_CheckFeature($fid);
4221    
4222    Return TRUE if the specified FID is probably an NMPDR feature ID, else FALSE.
4223    
4224    =over 4
4225    
4226    =item fid
4227    
4228    Feature ID to check.
4229    
4230    =item RETURN
4231    
4232    Returns TRUE if the FID is for one of the NMPDR genomes, else FALSE.
4233    
4234    =back
4235    
4236    =cut
4237    
4238    sub _CheckFeature {
4239        # Get the parameters.
4240        my ($self, $fid) = @_;
4241        # Insure we have a genome hash.
4242        if (! defined $self->{genomeHash}) {
4243            my %genomeHash = map { $_ => 1 } $self->GetFlat(['Genome'], "", [], 'Genome(id)');
4244            $self->{genomeHash} = \%genomeHash;
4245        }
4246        # Get the feature's genome ID.
4247        my ($genomeID) = FIGRules::ParseFeatureID($fid);
4248        # Return an indicator of whether or not the genome ID is in the hash.
4249        return ($self->{genomeHash}->{$genomeID} ? 1 : 0);
4250    }
4251    
4252  =head3 FriendlyTimestamp  =head3 FriendlyTimestamp
4253    
4254  Convert a time number to a user-friendly time stamp for display.  Convert a time number to a user-friendly time stamp for display.
# Line 3887  Line 4276 
4276  }  }
4277    
4278    
4279    =head3 Hint
4280    
4281        my $htmlText = SearchHelper::Hint($wikiPage, $hintText);
4282    
4283    Return the HTML for a small question mark that displays the specified hint text when it is clicked.
4284    This HTML can be put in forms to provide a useful hinting mechanism.
4285    
4286    =over 4
4287    
4288    =item wikiPage
4289    
4290    Name of the wiki page to be popped up when the hint mark is clicked.
4291    
4292    =item hintText
4293    
4294    Text to display for the hint. It is raw html, but may not contain any double quotes.
4295    
4296    =item RETURN
4297    
4298    Returns the html for the hint facility. The resulting html shows a small button-like thing that
4299    uses the standard FIG popup technology.
4300    
4301    =back
4302    
4303    =cut
4304    
4305    sub Hint {
4306        # Get the parameters.
4307        my ($wikiPage, $hintText) = @_;
4308        # Escape the single quotes in the hint text.
4309        my $quotedText = $hintText;
4310        $quotedText =~ s/'/\\'/g;
4311        # Convert the wiki page name to a URL.
4312        my $wikiURL = join("", map { ucfirst $_ } split /\s+/, $wikiPage);
4313        $wikiURL = "$FIG_Config::cgi_url/wiki/view.cgi/FIG/$wikiURL";
4314        # Compute the mouseover script.
4315        my $mouseOver = "doTooltip(this, '$quotedText')";
4316        # Create the html.
4317        my $retVal = "&nbsp;<a href=\"$wikiURL\"><img src=\"$FIG_Config::cgi_url/Html/button-h.png\" class=\"helpicon\" onmouseover=\"$mouseOver\"/></a>";
4318        # Return it.
4319        return $retVal;
4320    }
4321    
4322  1;  1;

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3