[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.83, Wed Sep 6 19:30:22 2006 UTC revision 1.117, Tue Sep 16 18:57:59 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 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    
# Line 104  Line 108 
108                                                          # data file directory                                                          # data file directory
109                         xmlFileName  => "$dbd_dir/SproutDBD.xml",                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
110                                                          # database definition file name                                                          # database definition file name
111                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",                         userData     => "$FIG_Config::sproutUser/$FIG_Config::sproutPass",
112                                                          # user name and password                                                          # user name and password
113                         port         => $FIG_Config::dbport,                         port         => $FIG_Config::sproutPort,
114                                                          # database connection port                                                          # database connection port
115                         sock         => $FIG_Config::dbsock,                         sock         => $FIG_Config::sproutSock,
116                         host         => $FIG_Config::dbhost,                         host         => $FIG_Config::sprout_host,
117                         maxSegmentLength => 4500,        # maximum feature segment length                         maxSegmentLength => 4500,        # maximum feature segment length
118                         maxSequenceLength => 8000,       # maximum contig sequence length                         maxSequenceLength => 8000,       # maximum contig sequence length
119                         noDBOpen     => 0,               # 1 to suppress the database open                         noDBOpen     => 0,               # 1 to suppress the database open
# Line 122  Line 126 
126      # Connect to the database.      # Connect to the database.
127      my $dbh;      my $dbh;
128      if (! $optionTable->{noDBOpen}) {      if (! $optionTable->{noDBOpen}) {
129            Trace("Connect data: host = $optionTable->{host}, port = $optionTable->{port}.") if T(3);
130          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
131                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
132      }      }
# Line 131  Line 136 
136      # Add the option table and XML file name.      # Add the option table and XML file name.
137      $retVal->{_options} = $optionTable;      $retVal->{_options} = $optionTable;
138      $retVal->{_xmlName} = $xmlFileName;      $retVal->{_xmlName} = $xmlFileName;
139        # Set up space for the group file data.
140        $retVal->{groupHash} = undef;
141        # Set up space for the genome hash. We use this to identify NMPDR genomes.
142        $retVal->{genomeHash} = undef;
143        # Connect to the attributes.
144        if ($FIG_Config::attrURL) {
145            Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);
146            $retVal->{_ca} = RemoteCustomAttributes->new($FIG_Config::attrURL);
147        } elsif ($FIG_Config::attrDbName) {
148            Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);
149            my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));
150            $retVal->{_ca} = CustomAttributes->new(user => $user);
151        }
152      # Return it.      # Return it.
153      return $retVal;      return $retVal;
154  }  }
155    
156    =head3 CoreGenomes
157    
158        my @genomes = $sprout->CoreGenomes($scope);
159    
160    Return the IDs of NMPDR genomes in the specified scope.
161    
162    =over 4
163    
164    =item scope
165    
166    Scope of the desired genomes. C<core> covers the original core genomes,
167    C<nmpdr> covers all genomes in NMPDR groups, and C<all> covers all
168    genomes in the system.
169    
170    =item RETURN
171    
172    Returns a list of the IDs for the genomes in the specified scope.
173    
174    =back
175    
176    =cut
177    
178    sub CoreGenomes {
179        # Get the parameters.
180        my ($self, $scope) = @_;
181        # Declare the return variable.
182        my @retVal = ();
183        # If we want all genomes, then this is easy.
184        if ($scope eq 'all') {
185            @retVal = $self->Genomes();
186        } else {
187            # Here we're dealing with groups. Get the hash of all the
188            # genome groups.
189            my %groups = $self->GetGroups();
190            # Loop through the groups, keeping the ones that we want.
191            for my $group (keys %groups) {
192                # Decide if we want to keep this group.
193                my $keepGroup = 0;
194                if ($scope eq 'nmpdr') {
195                    # NMPDR mode: keep all groups.
196                    $keepGroup = 1;
197                } elsif ($scope eq 'core') {
198                    # CORE mode. Only keep real core groups.
199                    if (grep { $group =~ /$_/ } @{$FIG_Config::realCoreGroups}) {
200                        $keepGroup = 1;
201                    }
202                }
203                # Add this group if we're keeping it.
204                if ($keepGroup) {
205                    push @retVal, @{$groups{$group}};
206                }
207            }
208        }
209        # Return the result.
210        return @retVal;
211    }
212    
213    =head3 SuperGroup
214    
215        my $superGroup = $sprout->SuperGroup($groupName);
216    
217    Return the name of the super-group containing the specified NMPDR genome
218    group. If no appropriate super-group can be found, an error will be
219    thrown.
220    
221    =over 4
222    
223    =item groupName
224    
225    Name of the group whose super-group is desired.
226    
227    =item RETURN
228    
229    Returns the name of the super-group containing the incoming group.
230    
231    =back
232    
233    =cut
234    
235    sub SuperGroup {
236        # Get the parameters.
237        my ($self, $groupName) = @_;
238        # Declare the return variable.
239        my $retVal;
240        # Get the group hash.
241        my %groupHash = $self->CheckGroupFile();
242        # Find the super-group genus.
243        $groupName =~ /([A-Z]\w+)/;
244        my $nameThing = $1;
245        # See if it's directly in the group hash.
246        if (exists $groupHash{$nameThing}) {
247            # Yes, then it's our result.
248            $retVal = $nameThing;
249        } else {
250            # No, so we have to search.
251            for my $superGroup (keys %groupHash) {
252                # Get this super-group's item list.
253                my $list = $groupHash{$superGroup}->{contents};
254                # Search it.
255                if (grep { $_->[0] eq $nameThing } @{$list}) {
256                    $retVal = $superGroup;
257                }
258            }
259            # Make sure we found something.
260            if (! $retVal) {
261                Confess("No super-group found for \"$groupName\".");
262            }
263        }
264        # Return the result.
265        return $retVal;
266    }
267    
268  =head3 MaxSegment  =head3 MaxSegment
269    
270  C<< my $length = $sprout->MaxSegment(); >>      my $length = $sprout->MaxSegment();
271    
272  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
273  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 154  Line 284 
284    
285  =head3 MaxSequence  =head3 MaxSequence
286    
287  C<< my $length = $sprout->MaxSequence(); >>      my $length = $sprout->MaxSequence();
288    
289  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
290  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 169  Line 299 
299    
300  =head3 Load  =head3 Load
301    
302  C<< $sprout->Load($rebuild); >>;      $sprout->Load($rebuild);;
303    
304  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.
305    
# Line 209  Line 339 
339    
340  =head3 LoadUpdate  =head3 LoadUpdate
341    
342  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>      my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList);
343    
344  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
345  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 255  Line 385 
385              Trace("No load file found for $tableName in $dataDir.") if T(0);              Trace("No load file found for $tableName in $dataDir.") if T(0);
386          } else {          } else {
387              # Attempt to load this table.              # Attempt to load this table.
388              my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);              my $result = $self->LoadTable($fileName, $tableName, truncate => $truncateFlag);
389              # Accumulate the resulting statistics.              # Accumulate the resulting statistics.
390              $retVal->Accumulate($result);              $retVal->Accumulate($result);
391          }          }
# Line 266  Line 396 
396    
397  =head3 GenomeCounts  =head3 GenomeCounts
398    
399  C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>      my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete);
400    
401  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
402  genomes will be included in the counts.  genomes will be included in the counts.
# Line 311  Line 441 
441    
442  =head3 ContigCount  =head3 ContigCount
443    
444  C<< my $count = $sprout->ContigCount($genomeID); >>      my $count = $sprout->ContigCount($genomeID);
445    
446  Return the number of contigs for the specified genome ID.  Return the number of contigs for the specified genome ID.
447    
# Line 338  Line 468 
468      return $retVal;      return $retVal;
469  }  }
470    
471  =head3 GeneMenu  =head3 GenomeMenu
472    
473        my $html = $sprout->GenomeMenu(%options);
474    
475    Generate a genome selection control with the specified name and options.
476    This control is almost but not quite the same as the genome control in the
477    B<SearchHelper> class. Eventually, the two will be combined.
478    
479    =over 4
480    
481    =item options
482    
483    Optional parameters for the control (see below).
484    
485    =item RETURN
486    
487    Returns the HTML for a genome selection control on a form (sometimes called a popup menu).
488    
489  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params); >>  =back
490    
491  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.  
492    
493  =over 4  =over 4
494    
495  =item attributes  =item name
496    
497    Name to give this control for use in passing it to the form. The default is C<myGenomeControl>.
498    Terrible things will happen if you have two controls with the same name on the same page.
499    
500    =item filter
501    
502    If specified, a filter for the list of genomes to display. The filter should be in the form of a
503    list reference. The first element of the list should be the filter string, and the remaining elements
504    the filter parameters.
505    
506    =item multiSelect
507    
508    If TRUE, then the user can select multiple genomes. If FALSE, the user can only select one genome.
509    
510    =item size
511    
512    Number of rows to display in the control. The default is C<10>
513    
514    =item id
515    
516    ID to give this control. The default is the value of the C<name> option. Nothing will work correctly
517    unless this ID is unique.
518    
519    =item selected
520    
521    A comma-delimited list of selected genomes, or a reference to a list of selected genomes. The
522    default is none.
523    
524    =item class
525    
526    If specified, a style class to assign to the genome control.
527    
528    =back
529    
530    =cut
531    
532    sub GenomeMenu {
533        # Get the parameters.
534        my ($self, %options) = @_;
535        # Get the control's name and ID.
536        my $menuName = $options{name} || $options{id} || 'myGenomeControl';
537        my $menuID = $options{id} || $menuName;
538        Trace("Genome menu name = $menuName with ID $menuID.") if T(3);
539        # Compute the IDs for the status display.
540        my $divID = "${menuID}_status";
541        my $urlID = "${menuID}_url";
542        # Compute the code to show selected genomes in the status area.
543        my $showSelect = "showSelected('$menuID', '$divID', '$urlID', 1000)";
544        # Check for single-select or multi-select.
545        my $multiSelect = $options{multiSelect} || 0;
546        # Get the style data.
547        my $class = $options{class} || '';
548        # Get the list of pre-selected items.
549        my $selections = $options{selected} || [];
550        if (ref $selections ne 'ARRAY') {
551            $selections = [ split /\s*,\s*/, $selections ];
552        }
553        my %selected = map { $_ => 1 } @{$selections};
554        # Extract the filter information. The default is no filtering. It can be passed as a tab-delimited
555        # string or a list reference.
556        my $filterParms = $options{filter} || "";
557        if (! ref $filterParms) {
558            $filterParms = [split /\t|\\t/, $filterParms];
559        }
560        my $filterString = shift @{$filterParms};
561        # Get a list of all the genomes in group order. In fact, we only need them ordered
562        # by name (genus,species,strain), but putting primary-group in front enables us to
563        # take advantage of an existing index.
564        my @genomeList = $self->GetAll(['Genome'], "$filterString ORDER BY Genome(primary-group), Genome(genus), Genome(species), Genome(unique-characterization)",
565                                       $filterParms,
566                                       [qw(Genome(primary-group) Genome(id) Genome(genus) Genome(species) Genome(unique-characterization) Genome(taxonomy) Genome(contigs))]);
567        # Create a hash to organize the genomes by group. Each group will contain a list of
568        # 2-tuples, the first element being the genome ID and the second being the genome
569        # name.
570        my %gHash = ();
571        for my $genome (@genomeList) {
572            # Get the genome data.
573            my ($group, $genomeID, $genus, $species, $strain, $taxonomy, $contigs) = @{$genome};
574            # Compute its name. This is the genus, species, strain (if any), and the contig count.
575            my $name = "$genus $species ";
576            $name .= "$strain " if $strain;
577            my $contigCount = ($contigs == 1 ? "" : ", $contigs contigs");
578            # Now we get the domain. The domain tells us the display style of the organism.
579            my ($domain) = split /\s*;\s*/, $taxonomy, 2;
580            # Now compute the display group. This is normally the primary group, but if the
581            # organism is supporting, we blank it out.
582            my $displayGroup = ($group eq $FIG_Config::otherGroup ? "" : $group);
583            # Push the genome into the group's list. Note that we use the real group
584            # name for the hash key here, not the display group name.
585            push @{$gHash{$group}}, [$genomeID, $name, $contigCount, $domain];
586        }
587        # We are almost ready to unroll the menu out of the group hash. The final step is to separate
588        # the supporting genomes by domain. First, we extract the NMPDR groups and sort them. They
589        # are sorted by the first capitalized word. Groups with "other" are sorted after groups
590        # that aren't "other". At some point, we will want to make this less complicated.
591        my %sortGroups = map { $_ =~ /(other)?(.*)([A-Z].+)/; "$3$1$2" => $_ }
592                             grep { $_ ne $FIG_Config::otherGroup } keys %gHash;
593        my @groups = map { $sortGroups{$_} } sort keys %sortGroups;
594        # Remember the number of NMPDR groups.
595        my $nmpdrGroupCount = scalar @groups;
596        # Loop through the supporting genomes, classifying them by domain. We'll also keep a list
597        # of the domains found.
598        my @otherGenomes = @{$gHash{$FIG_Config::otherGroup}};
599        my @domains = ();
600        for my $genomeData (@otherGenomes) {
601            my ($genomeID, $name, $contigCount, $domain) = @{$genomeData};
602            if (exists $gHash{$domain}) {
603                push @{$gHash{$domain}}, $genomeData;
604            } else {
605                $gHash{$domain} = [$genomeData];
606                push @domains, $domain;
607            }
608        }
609        # Add the domain groups at the end of the main group list. The main group list will now
610        # contain all the categories we need to display the genomes.
611        push @groups, sort @domains;
612        # Delete the supporting group.
613        delete $gHash{$FIG_Config::otherGroup};
614        # Now it gets complicated. We need a way to mark all the NMPDR genomes. We take advantage
615        # of the fact they come first in the list. We'll accumulate a count of the NMPDR genomes
616        # and use that to make the selections.
617        my $nmpdrCount = 0;
618        # Create the type counters.
619        my $groupCount = 1;
620        # Get the number of rows to display.
621        my $rows = $options{size} || 10;
622        # If we're multi-row, create an onChange event.
623        my $onChangeTag = ( $rows > 1 ? " onChange=\"$showSelect;\" onFocus=\"$showSelect;\"" : "" );
624        # Set up the multiple-select flag.
625        my $multipleTag = ($multiSelect ? " multiple" : "" );
626        # Set up the style class.
627        my $classTag = ($class ? " class=\"$class\"" : "" );
628        # Create the SELECT tag and stuff it into the output array.
629        my @lines = ("<SELECT name=\"$menuName\" id=\"$menuID\" $onChangeTag$multipleTag$classTag size=\"$rows\">");
630        # Loop through the groups.
631        for my $group (@groups) {
632            # Get the genomes in the group.
633            for my $genome (@{$gHash{$group}}) {
634                # If this is an NMPDR organism, we add an extra style and count it.
635                my $nmpdrStyle = "";
636                if ($nmpdrGroupCount > 0) {
637                    $nmpdrCount++;
638                    $nmpdrStyle = " Core";
639                }
640                # Get the organism ID, name, contig count, and domain.
641                my ($genomeID, $name, $contigCount, $domain) = @{$genome};
642                # See if we're pre-selected.
643                my $selectTag = ($selected{$genomeID} ? " SELECTED" : "");
644                # Compute the display name.
645                my $nameString = "$name ($genomeID$contigCount)";
646                # Generate the option tag.
647                my $optionTag = "<OPTION class=\"$domain$nmpdrStyle\" title=\"$group\" value=\"$genomeID\"$selectTag>$nameString</OPTION>";
648                push @lines, "    $optionTag";
649            }
650            # Record this group in the nmpdrGroup count. When that gets to 0, we've finished the NMPDR
651            # groups.
652            $nmpdrGroupCount--;
653        }
654        # Close the SELECT tag.
655        push @lines, "</SELECT>";
656        if ($rows > 1) {
657            # We're in a non-compact mode, so we need to add some selection helpers. First is
658            # the search box. This allows the user to type text and change which genomes are
659            # displayed. For multiple-select mode, we include a button that selects the displayed
660            # genes. For single-select mode, we use a plain label instead.
661            my $searchThingName = "${menuID}_SearchThing";
662            my $searchThingLabel = ($multiSelect ? "<INPUT type=\"button\" name=\"MacroSearch\" class=\"button\" value=\"Select genomes containing\" onClick=\"selectShowing('$menuID', '$searchThingName'); $showSelect;\" />"
663                                                 : "Show genomes containing");
664            push @lines, "<br />$searchThingLabel&nbsp;" .
665                         "<INPUT type=\"text\" id=\"$searchThingName\" name=\"$searchThingName\" size=\"30\" onKeyup=\"showTyped('$menuID', '$searchThingName');\" />" .
666                         Hint("GenomeControl", "Type here to filter the genomes displayed.") . "<br />";
667            # For multi-select mode, we also have buttons to set and clear selections.
668            if ($multiSelect) {
669                push @lines, "<INPUT type=\"button\" name=\"ClearAll\" class=\"bigButton\"  value=\"Clear All\" onClick=\"clearAll('$menuID'); $showSelect\" />";
670                push @lines, "<INPUT type=\"button\" name=\"SelectAll\" class=\"bigButton\" value=\"Select All\" onClick=\"selectAll('$menuID'); $showSelect\" />";
671                push @lines, "<INPUT type=\"button\" name=\"NMPDROnly\" class=\"bigButton\"  value=\"Select NMPDR\" onClick=\"selectSome('$menuID', $nmpdrCount, true); $showSelect;\" />";
672            }
673            # Add a hidden field we can use to generate organism page hyperlinks.
674            push @lines, "<INPUT type=\"hidden\" id=\"$urlID\" value=\"$FIG_Config::cgi_url/wiki/rest.cgi/NmpdrPlugin/SeedViewer?page=Organism;organism=\" />";
675            # Add the status display. This tells the user what's selected no matter where the list is scrolled.
676            push @lines, "<DIV id=\"$divID\" class=\"Panel\"></DIV>";
677        }
678        # Assemble all the lines into a string.
679        my $retVal = join("\n", @lines, "");
680        # Return the result.
681        return $retVal;
682    }
683    
684    
685    =head3 Stem
686    
687  Reference to a hash mapping attributes to values for the SELECT tag generated.      my $stem = $sprout->Stem($word);
688    
689  =item filterString  Return the stem of the specified word, or C<undef> if the word is not
690    stemmable. Note that even if the word is stemmable, the stem may be
691    the same as the original word.
692    
693  A filter string for use in selecting the genomes. The filter string must conform  =over 4
 to the rules for the C<< ERDB->Get >> method.  
694    
695  =item params  =item word
696    
697  Reference to a list of values to be substituted in for the parameter marks in  Word to convert into a stem.
 the filter string.  
698    
699  =item RETURN  =item RETURN
700    
701  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
702    the word is not stemmable.
703    
704  =back  =back
705    
706  =cut  =cut
707    
708  sub GeneMenu {  sub Stem {
709      # Get the parameters.      # Get the parameters.
710      my ($self, $attributes, $filterString, $params) = @_;      my ($self, $word) = @_;
711      # Start the menu.      # Get the stemmer object.
712      my $retVal = "<select " .      my $stemmer = $self->{stemmer};
713          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .      if (! defined $stemmer) {
714          ">\n";          # We don't have one pre-built, so we build and save it now.
715      # Get the genomes.          $stemmer = BioWords->new(exceptions => "$FIG_Config::sproutData/Exceptions.txt",
716      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',                                   stops => "$FIG_Config::sproutData/StopWords.txt",
717                                                                       'Genome(genus)',                                   cache => 1);
718                                                                       'Genome(species)',          $self->{stemmer} = $stemmer;
                                                                      '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 $count = $self->ContigCount($genomeID);  
         my $counting = ($count == 1 ? "contig" : "contigs");  
         # Build the option tag.  
         $retVal .= "<option value=\"$genomeID\">$genus $species $strain ($genomeID) [$count $counting]</option>\n";  
         Trace("Option tag built for $genomeID: $genus $species $strain.") if T(3);  
719      }      }
720      # Close the SELECT tag.      # Try to stem the word.
721      $retVal .= "</select>\n";      my $retVal = $stemmer->Process($word);
722      # Return the result.      # Return the result.
723      return $retVal;      return $retVal;
724  }  }
725    
726    
727  =head3 Build  =head3 Build
728    
729  C<< $sprout->Build(); >>      $sprout->Build();
730    
731  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.
732  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 419  Line 743 
743    
744  =head3 Genomes  =head3 Genomes
745    
746  C<< my @genomes = $sprout->Genomes(); >>      my @genomes = $sprout->Genomes();
747    
748  Return a list of all the genome IDs.  Return a list of all the genome IDs.
749    
# Line 436  Line 760 
760    
761  =head3 GenusSpecies  =head3 GenusSpecies
762    
763  C<< my $infoString = $sprout->GenusSpecies($genomeID); >>      my $infoString = $sprout->GenusSpecies($genomeID);
764    
765  Return the genus, species, and unique characterization for a genome.  Return the genus, species, and unique characterization for a genome.
766    
# Line 468  Line 792 
792    
793  =head3 FeaturesOf  =head3 FeaturesOf
794    
795  C<< my @features = $sprout->FeaturesOf($genomeID, $ftype); >>      my @features = $sprout->FeaturesOf($genomeID, $ftype);
796    
797  Return a list of the features relevant to a specified genome.  Return a list of the features relevant to a specified genome.
798    
# Line 513  Line 837 
837    
838  =head3 FeatureLocation  =head3 FeatureLocation
839    
840  C<< my @locations = $sprout->FeatureLocation($featureID); >>      my @locations = $sprout->FeatureLocation($featureID);
841    
842  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
843  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 537  Line 861 
861  =item RETURN  =item RETURN
862    
863  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
864  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
865    wasn't found.
866    
867  =back  =back
868    
869  =cut  =cut
870  #: Return Type @;  
 #: Return Type $;  
871  sub FeatureLocation {  sub FeatureLocation {
872      # Get the parameters.      # Get the parameters.
873      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
874      # 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.  
875      my @retVal = ();      my @retVal = ();
876      # Set up the variables used to determine if we have adjacent segments. This initial setup will      # Get the feature record.
877      # not match anything.      my $object = $self->GetEntity('Feature', $featureID);
878      my ($prevContig, $prevBeg, $prevDir, $prevLen) = ("", 0, "0", 0);      # Only proceed if we found it.
879      # Loop through the query results, creating location specifiers.      if (defined $object) {
880      while (my $location = $query->Fetch()) {          # Get the location string.
881          # Get the location parameters.          my $locString = $object->PrimaryValue('Feature(location-string)');
882          my ($contigID, $beg, $dir, $len) = $location->Values(['IsLocatedIn(to-link)',          # Create the return list.
883              '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";  
884      }      }
885      # Return the list in the format indicated by the context.      # Return the list in the format indicated by the context.
886      return (wantarray ? @retVal : join(',', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
# Line 592  Line 888 
888    
889  =head3 ParseLocation  =head3 ParseLocation
890    
891  C<< my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location); >>      my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location);
892    
893  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
894  length.  length.
# Line 611  Line 907 
907  =back  =back
908    
909  =cut  =cut
910  #: Return Type @;  
911  sub ParseLocation {  sub ParseLocation {
912      # 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
913      # the first parameter.      # the first parameter.
# Line 634  Line 930 
930      return ($contigID, $start, $dir, $len);      return ($contigID, $start, $dir, $len);
931  }  }
932    
933    
934    
935  =head3 PointLocation  =head3 PointLocation
936    
937  C<< my $found = Sprout::PointLocation($location, $point); >>      my $found = Sprout::PointLocation($location, $point);
938    
939  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
940  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 665  Line 963 
963  =back  =back
964    
965  =cut  =cut
966  #: Return Type $;  
967  sub PointLocation {  sub PointLocation {
968      # 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
969      # the first parameter.      # the first parameter.
# Line 688  Line 986 
986    
987  =head3 DNASeq  =head3 DNASeq
988    
989  C<< my $sequence = $sprout->DNASeq(\@locationList); >>      my $sequence = $sprout->DNASeq(\@locationList);
990    
991  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
992  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 772  Line 1070 
1070    
1071  =head3 AllContigs  =head3 AllContigs
1072    
1073  C<< my @idList = $sprout->AllContigs($genomeID); >>      my @idList = $sprout->AllContigs($genomeID);
1074    
1075  Return a list of all the contigs for a genome.  Return a list of all the contigs for a genome.
1076    
# Line 802  Line 1100 
1100    
1101  =head3 GenomeLength  =head3 GenomeLength
1102    
1103  C<< my $length = $sprout->GenomeLength($genomeID); >>      my $length = $sprout->GenomeLength($genomeID);
1104    
1105  Return the length of the specified genome in base pairs.  Return the length of the specified genome in base pairs.
1106    
# Line 837  Line 1135 
1135    
1136  =head3 FeatureCount  =head3 FeatureCount
1137    
1138  C<< my $count = $sprout->FeatureCount($genomeID, $type); >>      my $count = $sprout->FeatureCount($genomeID, $type);
1139    
1140  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.
1141    
# Line 872  Line 1170 
1170    
1171  =head3 GenomeAssignments  =head3 GenomeAssignments
1172    
1173  C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>      my $fidHash = $sprout->GenomeAssignments($genomeID);
1174    
1175  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
1176  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 898  Line 1196 
1196      my ($self, $genomeID) = @_;      my ($self, $genomeID) = @_;
1197      # Declare the return variable.      # Declare the return variable.
1198      my $retVal = {};      my $retVal = {};
1199      # Query the genome's features and annotations. We'll put the oldest annotations      # Query the genome's features.
1200      # first so that the last assignment to go into the hash will be the correct one.      my $query = $self->Get(['HasFeature', 'Feature'], "HasFeature(from-link) = ?",
     my $query = $self->Get(['HasFeature', 'IsTargetOfAnnotation', 'Annotation'],  
                            "HasFeature(from-link) = ? ORDER BY Annotation(time)",  
1201                             [$genomeID]);                             [$genomeID]);
1202      # Loop through the annotations.      # Loop through the features.
1203      while (my $data = $query->Fetch) {      while (my $data = $query->Fetch) {
1204          # Get the feature ID and annotation text.          # Get the feature ID and assignment.
1205          my ($fid, $annotation) = $data->Values(['HasFeature(to-link)',          my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']);
1206                                                  'Annotation(annotation)']);          if ($assignment) {
         # Check to see if this is an assignment. Note that the user really  
         # doesn't matter to us, other than we use it to determine whether or  
         # not this is an assignment.  
         my ($user, $assignment) = _ParseAssignment('fig', $annotation);  
         if ($user) {  
             # Here it's an assignment. We put it in the return hash, overwriting  
             # any older assignment that might be present.  
1207              $retVal->{$fid} = $assignment;              $retVal->{$fid} = $assignment;
1208          }          }
1209      }      }
# Line 924  Line 1213 
1213    
1214  =head3 ContigLength  =head3 ContigLength
1215    
1216  C<< my $length = $sprout->ContigLength($contigID); >>      my $length = $sprout->ContigLength($contigID);
1217    
1218  Compute the length of a contig.  Compute the length of a contig.
1219    
# Line 963  Line 1252 
1252    
1253  =head3 ClusterPEGs  =head3 ClusterPEGs
1254    
1255  C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>      my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs);
1256    
1257  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
1258  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
1259  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
1260  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
1261  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
1262  sequence.  appear in the output sequence.
1263    
1264  =over 4  =over 4
1265    
# Line 1011  Line 1300 
1300    
1301  =head3 GenesInRegion  =head3 GenesInRegion
1302    
1303  C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>      my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop);
1304    
1305  List the features which overlap a specified region in a contig.  List the features which overlap a specified region in a contig.
1306    
# Line 1040  Line 1329 
1329  =back  =back
1330    
1331  =cut  =cut
1332  #: Return Type @@;  
1333  sub GenesInRegion {  sub GenesInRegion {
1334      # Get the parameters.      # Get the parameters.
1335      my ($self, $contigID, $start, $stop) = @_;      my ($self, $contigID, $start, $stop) = @_;
1336      # Get the maximum segment length.      # Get the maximum segment length.
1337      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 = ();  
1338      # Prime the values we'll use for the returned beginning and end.      # Prime the values we'll use for the returned beginning and end.
1339      my @initialMinMax = ($self->ContigLength($contigID), 0);      my @initialMinMax = ($self->ContigLength($contigID), 0);
1340      my ($min, $max) = @initialMinMax;      my ($min, $max) = @initialMinMax;
1341      # Create a table of parameters for each query. Each query looks for features travelling in      # Get the overlapping features.
1342        my @featureObjects = $self->GeneDataInRegion($contigID, $start, $stop);
1343        # We'l use this hash to help us track the feature IDs and sort them. The key is the
1344        # feature ID and the value is a [$left,$right] pair indicating the maximum extent
1345        # of the feature's locations.
1346        my %featureMap = ();
1347        # Loop through them to do the begin/end analysis.
1348        for my $featureObject (@featureObjects) {
1349            # Get the feature's location string. This may contain multiple actual locations.
1350            my ($locations, $fid) = $featureObject->Values([qw(Feature(location-string) Feature(id))]);
1351            my @locationSegments = split /\s*,\s*/, $locations;
1352            # Loop through the locations.
1353            for my $locationSegment (@locationSegments) {
1354                # Construct an object for the location.
1355                my $locationObject = BasicLocation->new($locationSegment);
1356                # Merge the current segment's begin and end into the min and max.
1357                my ($left, $right) = ($locationObject->Left, $locationObject->Right);
1358                my ($beg, $end);
1359                if (exists $featureMap{$fid}) {
1360                    ($beg, $end) = @{$featureMap{$fid}};
1361                    $beg = $left if $left < $beg;
1362                    $end = $right if $right > $end;
1363                } else {
1364                    ($beg, $end) = ($left, $right);
1365                }
1366                $min = $beg if $beg < $min;
1367                $max = $end if $end > $max;
1368                # Store the feature's new extent back into the hash table.
1369                $featureMap{$fid} = [$beg, $end];
1370            }
1371        }
1372        # Now we must compute the list of the IDs for the features found. We start with a list
1373        # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1374        # but the result of the sort will be the same.)
1375        my @list = map { [$featureMap{$_}->[0] + $featureMap{$_}->[1], $_] } keys %featureMap;
1376        # Now we sort by midpoint and yank out the feature IDs.
1377        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1378        # Return it along with the min and max.
1379        return (\@retVal, $min, $max);
1380    }
1381    
1382    =head3 GeneDataInRegion
1383    
1384        my @featureList = $sprout->GenesInRegion($contigID, $start, $stop);
1385    
1386    List the features which overlap a specified region in a contig.
1387    
1388    =over 4
1389    
1390    =item contigID
1391    
1392    ID of the contig containing the region of interest.
1393    
1394    =item start
1395    
1396    Offset of the first residue in the region of interest.
1397    
1398    =item stop
1399    
1400    Offset of the last residue in the region of interest.
1401    
1402    =item RETURN
1403    
1404    Returns a list of B<ERDBObjects> for the desired features. Each object will
1405    contain a B<Feature> record.
1406    
1407    =back
1408    
1409    =cut
1410    
1411    sub GeneDataInRegion {
1412        # Get the parameters.
1413        my ($self, $contigID, $start, $stop) = @_;
1414        # Get the maximum segment length.
1415        my $maximumSegmentLength = $self->MaxSegment;
1416        # Create a hash to receive the feature list. We use a hash so that we can eliminate
1417        # duplicates easily. The hash key will be the feature ID. The value will be the feature's
1418        # ERDBObject from the query.
1419        my %featuresFound = ();
1420        # Create a table of parameters for the queries. Each query looks for features travelling in
1421      # 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,
1422      # 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
1423      # 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 1063  Line 1426 
1426      # Loop through the query parameters.      # Loop through the query parameters.
1427      for my $parms (values %queryParms) {      for my $parms (values %queryParms) {
1428          # Create the query.          # Create the query.
1429          my $query = $self->Get(['IsLocatedIn'],          my $query = $self->Get([qw(Feature IsLocatedIn)],
1430              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
1431              $parms);              $parms);
1432          # Loop through the feature segments found.          # Loop through the feature segments found.
1433          while (my $segment = $query->Fetch) {          while (my $segment = $query->Fetch) {
1434              # Get the data about this segment.              # Get the data about this segment.
1435              my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',              my ($featureID, $contig, $dir, $beg, $len) = $segment->Values([qw(IsLocatedIn(from-link)
1436                  'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);                  IsLocatedIn(to-link) IsLocatedIn(dir) IsLocatedIn(beg) IsLocatedIn(len))]);
1437              # 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
1438              # 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
1439              # 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
1440              # length.              # length.
1441              my ($found, $end) = (0, 0);              my $loc = BasicLocation->new($contig, $beg, $dir, $len);
1442              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;  
                 }  
             }  
1443              if ($found) {              if ($found) {
1444                  # Here we need to record the feature and update the minima and maxima. First,                  # Save this feature in the result list.
1445                  # 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;  
1446                  }                  }
                 # Store the entry back into the hash table.  
                 $featuresFound{$featureID} = [$loc1, $loc2];  
1447              }              }
1448          }          }
1449      }      # Return the ERDB objects for the features found.
1450      # Now we must compute the list of the IDs for the features found. We start with a list      return values %featuresFound;
     # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,  
     # but the result of the sort will be the same.)  
     my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;  
     # Now we sort by midpoint and yank out the feature IDs.  
     my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;  
     # Return it along with the min and max.  
     return (\@retVal, $min, $max);  
1451  }  }
1452    
1453  =head3 FType  =head3 FType
1454    
1455  C<< my $ftype = $sprout->FType($featureID); >>      my $ftype = $sprout->FType($featureID);
1456    
1457  Return the type of a feature.  Return the type of a feature.
1458    
# Line 1153  Line 1482 
1482    
1483  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1484    
1485  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>      my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag);
1486    
1487  Return the annotations of a feature.  Return the annotations of a feature.
1488    
# Line 1216  Line 1545 
1545    
1546  =head3 AllFunctionsOf  =head3 AllFunctionsOf
1547    
1548  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>      my %functions = $sprout->AllFunctionsOf($featureID);
1549    
1550  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
1551  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 1271  Line 1600 
1600    
1601  =head3 FunctionOf  =head3 FunctionOf
1602    
1603  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>      my $functionText = $sprout->FunctionOf($featureID, $userID);
1604    
1605  Return the most recently-determined functional assignment of a particular feature.  Return the most recently-determined functional assignment of a particular feature.
1606    
1607  The functional assignment is handled differently depending on the type of feature. If  The functional assignment is handled differently depending on the type of feature. If
1608  the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional  the feature is identified by a FIG ID (begins with the string C<fig|>), then the functional
1609  assignment is a type of annotation. The format of an assignment is described in  assignment is taken from the B<Feature> or C<Annotation> table, depending.
 L</ParseAssignment>. Its worth noting that we cannot filter on the content of the  
 annotation itself because it's a text field; however, this is not a big problem because  
 most features only have a small number of annotations.  
1610    
1611  Each user has an associated list of trusted users. The assignment returned will be the most  Each user has an associated list of trusted users. The assignment returned will be the most
1612  recent one by at least one of the trusted users. If no trusted user list is available, then  recent one by at least one of the trusted users. If no trusted user list is available, then
1613  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
1614  is trusted.  is trusted.
1615    
1616  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.
1617  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.  
1618    
1619  =over 4  =over 4
1620    
# Line 1299  Line 1624 
1624    
1625  =item userID (optional)  =item userID (optional)
1626    
1627  ID of the user whose function determination is desired. If omitted, only the latest  ID of the user whose function determination is desired. If omitted, the primary
1628  C<FIG> assignment will be returned.  functional assignment in the B<Feature> table will be returned.
1629    
1630  =item RETURN  =item RETURN
1631    
# Line 1315  Line 1640 
1640      my ($self, $featureID, $userID) = @_;      my ($self, $featureID, $userID) = @_;
1641      # Declare the return value.      # Declare the return value.
1642      my $retVal;      my $retVal;
1643      # Determine the ID type.      # Find a FIG ID for this feature.
1644      if ($featureID =~ m/^fig\|/) {      my ($fid) = $self->FeaturesByAlias($featureID);
1645          # Here we have a FIG feature ID. We must build the list of trusted      # Only proceed if we have an ID.
1646          # users.      if ($fid) {
1647            # Here we have a FIG feature ID.
1648            if (!$userID) {
1649                # Use the primary assignment.
1650                ($retVal) = $self->GetEntityValues('Feature', $fid, ['Feature(assignment)']);
1651            } else {
1652                # We must build the list of trusted users.
1653          my %trusteeTable = ();          my %trusteeTable = ();
1654          # Check the user ID.          # Check the user ID.
1655          if (!$userID) {          if (!$userID) {
# Line 1342  Line 1673 
1673          # 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.
1674          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1675                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1676                                 [$featureID]);                                     [$fid]);
1677          my $timeSelected = 0;          my $timeSelected = 0;
1678          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1679          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
# Line 1361  Line 1692 
1692                  }                  }
1693              }              }
1694          }          }
1695      } 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)']);  
1696      }      }
1697      # Return the assignment found.      # Return the assignment found.
1698      return $retVal;      return $retVal;
# Line 1373  Line 1700 
1700    
1701  =head3 FunctionsOf  =head3 FunctionsOf
1702    
1703  C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>      my @functionList = $sprout->FunctionOf($featureID, $userID);
1704    
1705  Return the functional assignments of a particular feature.  Return the functional assignments of a particular feature.
1706    
# Line 1384  Line 1711 
1711  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
1712  most features only have a small number of annotations.  most features only have a small number of annotations.
1713    
 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.  
   
1714  =over 4  =over 4
1715    
1716  =item featureID  =item featureID
# Line 1408  Line 1731 
1731      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1732      # Declare the return value.      # Declare the return value.
1733      my @retVal = ();      my @retVal = ();
1734      # Determine the ID type.      # Convert to a FIG ID.
1735      if ($featureID =~ m/^fig\|/) {      my ($fid) = $self->FeaturesByAlias($featureID);
1736        # Only proceed if we found one.
1737        if ($fid) {
1738          # 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
1739          # users.          # users.
1740          my %trusteeTable = ();          my %trusteeTable = ();
1741          # 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.
1742          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1743                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1744                                 [$featureID]);                                 [$fid]);
1745          my $timeSelected = 0;          my $timeSelected = 0;
1746          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1747          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
# Line 1431  Line 1756 
1756                  push @retVal, [$actualUser, $function];                  push @retVal, [$actualUser, $function];
1757              }              }
1758          }          }
     } 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;  
1759      }      }
1760      # Return the assignments found.      # Return the assignments found.
1761      return @retVal;      return @retVal;
# Line 1445  Line 1763 
1763    
1764  =head3 BBHList  =head3 BBHList
1765    
1766  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>      my $bbhHash = $sprout->BBHList($genomeID, \@featureList);
1767    
1768  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
1769  on a specified target genome.  on a specified target genome.
# Line 1476  Line 1794 
1794      my %retVal = ();      my %retVal = ();
1795      # Loop through the incoming features.      # Loop through the incoming features.
1796      for my $featureID (@{$featureList}) {      for my $featureID (@{$featureList}) {
1797          # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1798          my $query = $self->Get(['IsBidirectionalBestHitOf'],          my @bbhData = FIGRules::BBHData($featureID);
                                "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",  
                                [$featureID, $genomeID]);  
1799          # Peel off the BBHs found.          # Peel off the BBHs found.
1800          my @found = ();          my @found = ();
1801          while (my $bbh = $query->Fetch) {          for my $bbh (@bbhData) {
1802              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');              my $fid = $bbh->[0];
1803                my $bbGenome = $self->GenomeOf($fid);
1804                if ($bbGenome eq $genomeID) {
1805                    push @found, $fid;
1806                }
1807          }          }
1808          $retVal{$featureID} = \@found;          $retVal{$featureID} = \@found;
1809      }      }
# Line 1493  Line 1813 
1813    
1814  =head3 SimList  =head3 SimList
1815    
1816  C<< my %similarities = $sprout->SimList($featureID, $count); >>      my %similarities = $sprout->SimList($featureID, $count);
1817    
1818  Return a list of the similarities to the specified feature.  Return a list of the similarities to the specified feature.
1819    
1820  Sprout does not support real similarities, so this method just returns the bidirectional  This method just returns the bidirectional best hits for performance reasons.
 best hits.  
1821    
1822  =over 4  =over 4
1823    
# Line 1518  Line 1837 
1837      # Get the parameters.      # Get the parameters.
1838      my ($self, $featureID, $count) = @_;      my ($self, $featureID, $count) = @_;
1839      # Ask for the best hits.      # Ask for the best hits.
1840      my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],      my @lists = FIGRules::BBHData($featureID);
                               "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",  
                               [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],  
                               $count);  
1841      # Create the return value.      # Create the return value.
1842      my %retVal = ();      my %retVal = ();
1843      for my $tuple (@lists) {      for my $tuple (@lists) {
# Line 1531  Line 1847 
1847      return %retVal;      return %retVal;
1848  }  }
1849    
   
   
1850  =head3 IsComplete  =head3 IsComplete
1851    
1852  C<< my $flag = $sprout->IsComplete($genomeID); >>      my $flag = $sprout->IsComplete($genomeID);
1853    
1854  Return TRUE if the specified genome is complete, else FALSE.  Return TRUE if the specified genome is complete, else FALSE.
1855    
# Line 1563  Line 1877 
1877      my $genomeData = $self->GetEntity('Genome', $genomeID);      my $genomeData = $self->GetEntity('Genome', $genomeID);
1878      if ($genomeData) {      if ($genomeData) {
1879          # The genome exists, so get the completeness flag.          # The genome exists, so get the completeness flag.
1880          ($retVal) = $genomeData->Value('Genome(complete)');          $retVal = $genomeData->PrimaryValue('Genome(complete)');
1881      }      }
1882      # Return the result.      # Return the result.
1883      return $retVal;      return $retVal;
# Line 1571  Line 1885 
1885    
1886  =head3 FeatureAliases  =head3 FeatureAliases
1887    
1888  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>      my @aliasList = $sprout->FeatureAliases($featureID);
1889    
1890  Return a list of the aliases for a specified feature.  Return a list of the aliases for a specified feature.
1891    
# Line 1594  Line 1908 
1908      # Get the parameters.      # Get the parameters.
1909      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1910      # Get the desired feature's aliases      # Get the desired feature's aliases
1911      my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);      my @retVal = $self->GetFlat(['IsAliasOf'], "IsAliasOf(to-link) = ?", [$featureID], 'IsAliasOf(from-link)');
1912      # Return the result.      # Return the result.
1913      return @retVal;      return @retVal;
1914  }  }
1915    
1916  =head3 GenomeOf  =head3 GenomeOf
1917    
1918  C<< my $genomeID = $sprout->GenomeOf($featureID); >>      my $genomeID = $sprout->GenomeOf($featureID);
1919    
1920  Return the genome that contains a specified feature or contig.  Return the genome that contains a specified feature or contig.
1921    
# Line 1623  Line 1937 
1937  sub GenomeOf {  sub GenomeOf {
1938      # Get the parameters.      # Get the parameters.
1939      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]);  
1940      # Declare the return value.      # Declare the return value.
1941      my $retVal;      my $retVal;
1942      # Get the genome ID.      # Parse the genome ID from the feature ID.
1943      if (my $relationship = $query->Fetch()) {      if ($featureID =~ /^fig\|(\d+\.\d+)/) {
1944          ($retVal) = $relationship->Value('HasContig(from-link)');          $retVal = $1;
1945        } else {
1946            # Find the feature by alias.
1947            my ($realFeatureID) = $self->FeaturesByAlias($featureID);
1948            if ($realFeatureID && $realFeatureID =~ /^fig\|(\d+\.\d+)/) {
1949                $retVal = $1;
1950            }
1951      }      }
1952      # Return the value found.      # Return the value found.
1953      return $retVal;      return $retVal;
# Line 1638  Line 1955 
1955    
1956  =head3 CoupledFeatures  =head3 CoupledFeatures
1957    
1958  C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >>      my %coupleHash = $sprout->CoupledFeatures($featureID);
1959    
1960  Return the features functionally coupled with a specified feature. Features are considered  Return the features functionally coupled with a specified feature. Features are considered
1961  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 1660  Line 1977 
1977  sub CoupledFeatures {  sub CoupledFeatures {
1978      # Get the parameters.      # Get the parameters.
1979      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1980        # Ask the coupling server for the data.
1981      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1982      # Create a query to retrieve the functionally-coupled features.      my @rawPairs = FIGRules::NetCouplingData('coupled_to', id1 => $featureID);
1983      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      Trace(scalar(@rawPairs) . " couplings returned.") if T(coupling => 3);
1984                             "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.  
1985      my %retVal = ();      my %retVal = ();
1986      # Retrieve the relationship records and store them in the hash.      for my $pair (@rawPairs) {
1987      while (my $clustering = $query->Fetch()) {          # Get the feature ID and score.
1988          # Get the ID and score of the coupling.          my ($featureID2, $score) = @{$pair};
1989          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          # Only proceed if the feature is in NMPDR.
1990                                                          'Coupling(score)']);          if ($self->_CheckFeature($featureID2)) {
1991          Trace("$featureID coupled with score $score to ID $couplingID.") if T(coupling => 4);              $retVal{$featureID2} = $score;
1992          # 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;  
1993      }      }
1994      # 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
1995      # the incoming feature as well.      # the incoming feature as well.
1996      if ($found) {      if (keys %retVal) {
1997          $retVal{$featureID} = 9999;          $retVal{$featureID} = 9999;
1998      }      }
1999      # Return the hash.      # Return the hash.
# Line 1694  Line 2002 
2002    
2003  =head3 CouplingEvidence  =head3 CouplingEvidence
2004    
2005  C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>      my @evidence = $sprout->CouplingEvidence($peg1, $peg2);
2006    
2007  Return the evidence for a functional coupling.  Return the evidence for a functional coupling.
2008    
# Line 1742  Line 2050 
2050      my ($self, $peg1, $peg2) = @_;      my ($self, $peg1, $peg2) = @_;
2051      # Declare the return variable.      # Declare the return variable.
2052      my @retVal = ();      my @retVal = ();
2053      # Our first task is to find out the nature of the coupling: whether or not      # Get the coupling and evidence data.
2054      # it exists, its score, and whether the features are stored in the same      my @rawData = FIGRules::NetCouplingData('coupling_evidence', id1 => $peg1, id2 => $peg2);
2055      # order as the ones coming in.      # Loop through the raw data, saving the ones that are in NMPDR genomes.
2056      my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);      for my $rawTuple (@rawData) {
2057      # Only proceed if a coupling exists.          if ($self->_CheckFeature($rawTuple->[0]) && $self->_CheckFeature($rawTuple->[1])) {
2058      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;  
2059  }  }
   
 =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);  
2060      }      }
2061      # Return the result.      # Return the result.
2062      return ($retVal, $inverted, $score);      return @retVal;
2063  }  }
2064    
2065  =head3 GetSynonymGroup  =head3 GetSynonymGroup
2066    
2067  C<< my $id = $sprout->GetSynonymGroup($fid); >>      my $id = $sprout->GetSynonymGroup($fid);
2068    
2069  Return the synonym group name for the specified feature.  Return the synonym group name for the specified feature.
2070    
# Line 1873  Line 2103 
2103    
2104  =head3 GetBoundaries  =head3 GetBoundaries
2105    
2106  C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>      my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList);
2107    
2108  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
2109  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 1935  Line 2165 
2165      return ($contig, $beg, $end);      return ($contig, $beg, $end);
2166  }  }
2167    
 =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);  
 }  
   
2168  =head3 ReadFasta  =head3 ReadFasta
2169    
2170  C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>      my %sequenceData = Sprout::ReadFasta($fileName, $prefix);
2171    
2172  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
2173  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 2042  Line 2233 
2233    
2234  =head3 FormatLocations  =head3 FormatLocations
2235    
2236  C<< my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat); >>      my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat);
2237    
2238  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
2239  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 2107  Line 2298 
2298    
2299  =head3 DumpData  =head3 DumpData
2300    
2301  C<< $sprout->DumpData(); >>      $sprout->DumpData();
2302    
2303  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.
2304    
# Line 2124  Line 2315 
2315    
2316  =head3 XMLFileName  =head3 XMLFileName
2317    
2318  C<< my $fileName = $sprout->XMLFileName(); >>      my $fileName = $sprout->XMLFileName();
2319    
2320  Return the name of this database's XML definition file.  Return the name of this database's XML definition file.
2321    
# Line 2135  Line 2326 
2326      return $self->{_xmlName};      return $self->{_xmlName};
2327  }  }
2328    
2329  =head3 Insert  =head3 GetGenomeNameData
   
 C<< $sprout->Insert($objectType, \%fieldHash); >>  
2330    
2331  Insert an entity or relationship instance into the database. The entity or relationship of interest      my ($genus, $species, $strain) = $sprout->GenomeNameData($genomeID);
 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']}); >>  
   
 The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and  
 property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.  
2332    
2333  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
2334    is similar to L</GenusSpecies>, with the exception that it returns the
2335    values in three seperate fields.
2336    
2337  =over 4  =over 4
2338    
2339  =item newObjectType  =item genomeID
2340    
2341  Type name of the entity or relationship to insert.  ID of the genome whose name data is desired.
2342    
2343  =item fieldHash  =item RETURN
2344    
2345  Hash of field names to values.  Returns a three-element list, consisting of the genus, species, and strain
2346    of the specified genome. If the genome is not found, an error occurs.
2347    
2348    =back
2349    
2350    =cut
2351    
2352    sub GetGenomeNameData {
2353        # Get the parameters.
2354        my ($self, $genomeID) = @_;
2355        # Get the desired values.
2356        my ($genus, $species, $strain) = $self->GetEntityValues('Genome', $genomeID =>
2357                                                                [qw(Genome(genus) Genome(species) Genome(unique-characterization))]);
2358        # Throw an error if they were not found.
2359        if (! defined $genus) {
2360            Confess("Genome $genomeID not found in database.");
2361        }
2362        # Return the results.
2363        return ($genus, $species, $strain);
2364    }
2365    
2366    =head3 GetGenomeByNameData
2367    
2368        my @genomes = $sprout->GetGenomeByNameData($genus, $species, $strain);
2369    
2370    Return a list of the IDs of the genomes with the specified genus,
2371    species, and strain. In almost every case, there will be either zero or
2372    one IDs returned; however, two or more IDs could be returned if there are
2373    multiple versions of the genome in the database.
2374    
2375    =over 4
2376    
2377    =item genus
2378    
2379    Genus of the desired genome.
2380    
2381    =item species
2382    
2383    Species of the desired genome.
2384    
2385    =item strain
2386    
2387    Strain (unique characterization) of the desired genome. This may be an empty
2388    string, in which case it is presumed that the desired genome has no strain
2389    specified.
2390    
2391    =item RETURN
2392    
2393    Returns a list of the IDs of the genomes having the specified genus, species, and
2394    strain.
2395    
2396    =back
2397    
2398    =cut
2399    
2400    sub GetGenomeByNameData {
2401        # Get the parameters.
2402        my ($self, $genus, $species, $strain) = @_;
2403        # Try to find the genomes.
2404        my @retVal = $self->GetFlat(['Genome'], "Genome(genus) = ? AND Genome(species) = ? AND Genome(unique-characterization) = ?",
2405                                    [$genus, $species, $strain], 'Genome(id)');
2406        # Return the result.
2407        return @retVal;
2408    }
2409    
2410    =head3 Insert
2411    
2412        $sprout->Insert($objectType, \%fieldHash);
2413    
2414    Insert an entity or relationship instance into the database. The entity or relationship of interest
2415    is defined by a type name and then a hash of field names to values. Field values in the primary
2416    relation are represented by scalars. (Note that for relationships, the primary relation is
2417    the B<only> relation.) Field values for the other relations comprising the entity are always
2418    list references. For example, the following line inserts an inactive PEG feature named
2419    C<fig|188.1.peg.1> with aliases C<ZP_00210270.1> and C<gi|46206278>.
2420    
2421        $sprout->Insert('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']});
2422    
2423    The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
2424    property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
2425    
2426        $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'});
2427    
2428    =over 4
2429    
2430    =item newObjectType
2431    
2432    Type name of the entity or relationship to insert.
2433    
2434    =item fieldHash
2435    
2436    Hash of field names to values.
2437    
2438  =back  =back
2439    
# Line 2176  Line 2448 
2448    
2449  =head3 Annotate  =head3 Annotate
2450    
2451  C<< my $ok = $sprout->Annotate($fid, $timestamp, $user, $text); >>      my $ok = $sprout->Annotate($fid, $timestamp, $user, $text);
2452    
2453  Annotate a feature. This inserts an Annotation record into the database and links it to the  Annotate a feature. This inserts an Annotation record into the database and links it to the
2454  specified feature and user.  specified feature and user.
# Line 2230  Line 2502 
2502    
2503  =head3 AssignFunction  =head3 AssignFunction
2504    
2505  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>      my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser);
2506    
2507  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
2508  format is described in L</ParseAssignment>.  format is described in L</ParseAssignment>.
# Line 2290  Line 2562 
2562    
2563  =head3 FeaturesByAlias  =head3 FeaturesByAlias
2564    
2565  C<< my @features = $sprout->FeaturesByAlias($alias); >>      my @features = $sprout->FeaturesByAlias($alias);
2566    
2567  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
2568  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 2324  Line 2596 
2596          push @retVal, $mappedAlias;          push @retVal, $mappedAlias;
2597      } else {      } else {
2598          # 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.
2599          @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');          @retVal = $self->GetFlat(['IsAliasOf'], 'IsAliasOf(from-link) = ?', [$mappedAlias], 'IsAliasOf(to-link)');
2600      }      }
2601      # Return the result.      # Return the result.
2602      return @retVal;      return @retVal;
# Line 2332  Line 2604 
2604    
2605  =head3 FeatureTranslation  =head3 FeatureTranslation
2606    
2607  C<< my $translation = $sprout->FeatureTranslation($featureID); >>      my $translation = $sprout->FeatureTranslation($featureID);
2608    
2609  Return the translation of a feature.  Return the translation of a feature.
2610    
# Line 2360  Line 2632 
2632    
2633  =head3 Taxonomy  =head3 Taxonomy
2634    
2635  C<< my @taxonomyList = $sprout->Taxonomy($genome); >>      my @taxonomyList = $sprout->Taxonomy($genome);
2636    
2637  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
2638  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>,
2639  or C<Eukaryote>) to sub-species. For example,  or C<Eukaryote>) to sub-species. For example,
2640    
2641  C<< (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12) >>      (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12)
2642    
2643  =over 4  =over 4
2644    
# Line 2401  Line 2673 
2673    
2674  =head3 CrudeDistance  =head3 CrudeDistance
2675    
2676  C<< my $distance = $sprout->CrudeDistance($genome1, $genome2); >>      my $distance = $sprout->CrudeDistance($genome1, $genome2);
2677    
2678  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
2679  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 2453  Line 2725 
2725    
2726  =head3 RoleName  =head3 RoleName
2727    
2728  C<< my $roleName = $sprout->RoleName($roleID); >>      my $roleName = $sprout->RoleName($roleID);
2729    
2730  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
2731  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 2487  Line 2759 
2759    
2760  =head3 RoleDiagrams  =head3 RoleDiagrams
2761    
2762  C<< my @diagrams = $sprout->RoleDiagrams($roleID); >>      my @diagrams = $sprout->RoleDiagrams($roleID);
2763    
2764  Return a list of the diagrams containing a specified functional role.  Return a list of the diagrams containing a specified functional role.
2765    
# Line 2515  Line 2787 
2787      return @retVal;      return @retVal;
2788  }  }
2789    
 =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;  
 }  
   
2790  =head3 FeatureProperties  =head3 FeatureProperties
2791    
2792  C<< my @properties = $sprout->FeatureProperties($featureID); >>      my @properties = $sprout->FeatureProperties($featureID);
2793    
2794  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
2795  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
2796  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
2797  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
2798  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.  
2799    
2800  =over 4  =over 4
2801    
# Line 2618  Line 2805 
2805    
2806  =item RETURN  =item RETURN
2807    
2808  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.  
2809    
2810  =back  =back
2811    
# Line 2629  Line 2815 
2815      # Get the parameters.      # Get the parameters.
2816      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2817      # Get the properties.      # Get the properties.
2818      my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],      my @attributes = $self->{_ca}->GetAttributes($featureID);
2819                              ['Property(property-name)', 'Property(property-value)',      # Strip the feature ID off each tuple.
2820                               'HasProperty(evidence)']);      my @retVal = ();
2821        for my $attributeRow (@attributes) {
2822            shift @{$attributeRow};
2823            push @retVal, $attributeRow;
2824        }
2825      # Return the resulting list.      # Return the resulting list.
2826      return @retVal;      return @retVal;
2827  }  }
2828    
2829  =head3 DiagramName  =head3 DiagramName
2830    
2831  C<< my $diagramName = $sprout->DiagramName($diagramID); >>      my $diagramName = $sprout->DiagramName($diagramID);
2832    
2833  Return the descriptive name of a diagram.  Return the descriptive name of a diagram.
2834    
# Line 2664  Line 2854 
2854      return $retVal;      return $retVal;
2855  }  }
2856    
2857    =head3 PropertyID
2858    
2859        my $id = $sprout->PropertyID($propName, $propValue);
2860    
2861    Return the ID of the specified property name and value pair, if the
2862    pair exists. Only a small subset of the FIG attributes are stored as
2863    Sprout properties, mostly for use in search optimization.
2864    
2865    =over 4
2866    
2867    =item propName
2868    
2869    Name of the desired property.
2870    
2871    =item propValue
2872    
2873    Value expected for the desired property.
2874    
2875    =item RETURN
2876    
2877    Returns the ID of the name/value pair, or C<undef> if the pair does not exist.
2878    
2879    =back
2880    
2881    =cut
2882    
2883    sub PropertyID {
2884        # Get the parameters.
2885        my ($self, $propName, $propValue) = @_;
2886        # Try to find the ID.
2887        my ($retVal) = $self->GetFlat(['Property'],
2888                                      "Property(property-name) = ? AND Property(property-value) = ?",
2889                                      [$propName, $propValue], 'Property(id)');
2890        # Return the result.
2891        return $retVal;
2892    }
2893    
2894  =head3 MergedAnnotations  =head3 MergedAnnotations
2895    
2896  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>      my @annotationList = $sprout->MergedAnnotations(\@list);
2897    
2898  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
2899  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 2715  Line 2942 
2942    
2943  =head3 RoleNeighbors  =head3 RoleNeighbors
2944    
2945  C<< my @roleList = $sprout->RoleNeighbors($roleID); >>      my @roleList = $sprout->RoleNeighbors($roleID);
2946    
2947  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
2948  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 2758  Line 2985 
2985    
2986  =head3 FeatureLinks  =head3 FeatureLinks
2987    
2988  C<< my @links = $sprout->FeatureLinks($featureID); >>      my @links = $sprout->FeatureLinks($featureID);
2989    
2990  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
2991  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 2789  Line 3016 
3016    
3017  =head3 SubsystemsOf  =head3 SubsystemsOf
3018    
3019  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>      my %subsystems = $sprout->SubsystemsOf($featureID);
3020    
3021  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
3022  to the roles the feature performs.  to the roles the feature performs.
# Line 2837  Line 3064 
3064    
3065  =head3 SubsystemList  =head3 SubsystemList
3066    
3067  C<< my @subsystems = $sprout->SubsystemList($featureID); >>      my @subsystems = $sprout->SubsystemList($featureID);
3068    
3069  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
3070  feature participates. Unlike L</SubsystemsOf>, this method only returns the  feature participates. Unlike L</SubsystemsOf>, this method only returns the
# Line 2860  Line 3087 
3087  sub SubsystemList {  sub SubsystemList {
3088      # Get the parameters.      # Get the parameters.
3089      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
3090      # Get the list of names.      # Get the list of names. We do a join to the Subsystem table because we have missing subsystems in
3091      my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",      # the Sprout database!
3092                                  [$featureID], 'HasSSCell(from-link)');      my @retVal = $self->GetFlat(['HasRoleInSubsystem', 'Subsystem'], "HasRoleInSubsystem(from-link) = ?",
3093      # Return the result.                                  [$featureID], 'HasRoleInSubsystem(to-link)');
3094      return @retVal;      # Return the result, sorted.
3095        return sort @retVal;
3096  }  }
3097    
3098  =head3 GenomeSubsystemData  =head3 GenomeSubsystemData
3099    
3100  C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>      my %featureData = $sprout->GenomeSubsystemData($genomeID);
3101    
3102  Return a hash mapping genome features to their subsystem roles.  Return a hash mapping genome features to their subsystem roles.
3103    
# Line 2929  Line 3157 
3157    
3158  =head3 RelatedFeatures  =head3 RelatedFeatures
3159    
3160  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>      my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID);
3161    
3162  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
3163  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 2962  Line 3190 
3190      # Get the parameters.      # Get the parameters.
3191      my ($self, $featureID, $function, $userID) = @_;      my ($self, $featureID, $function, $userID) = @_;
3192      # Get a list of the features that are BBHs of the incoming feature.      # Get a list of the features that are BBHs of the incoming feature.
3193      my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
                                      "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],  
                                      'IsBidirectionalBestHitOf(to-link)');  
3194      # Now we loop through the features, pulling out the ones that have the correct      # Now we loop through the features, pulling out the ones that have the correct
3195      # functional assignment.      # functional assignment.
3196      my @retVal = ();      my @retVal = ();
# Line 2982  Line 3208 
3208    
3209  =head3 TaxonomySort  =head3 TaxonomySort
3210    
3211  C<< my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs); >>      my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs);
3212    
3213  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
3214  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 3017  Line 3243 
3243          my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",          my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
3244                                          [$fid], 'Genome(taxonomy)');                                          [$fid], 'Genome(taxonomy)');
3245          # Add this feature to the hash buffer.          # Add this feature to the hash buffer.
3246          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);          push @{$hashBuffer{$taxonomy}}, $fid;
3247      }      }
3248      # Sort the keys and get the elements.      # Sort the keys and get the elements.
3249      my @retVal = ();      my @retVal = ();
# Line 3030  Line 3256 
3256    
3257  =head3 Protein  =head3 Protein
3258    
3259  C<< my $protein = Sprout::Protein($sequence, $table); >>      my $protein = Sprout::Protein($sequence, $table);
3260    
3261  Translate a DNA sequence into a protein sequence.  Translate a DNA sequence into a protein sequence.
3262    
# Line 3100  Line 3326 
3326      # Loop through the input triples.      # Loop through the input triples.
3327      my $n = length $sequence;      my $n = length $sequence;
3328      for (my $i = 0; $i < $n; $i += 3) {      for (my $i = 0; $i < $n; $i += 3) {
3329          # Get the current triple from the sequence.          # Get the current triple from the sequence. Note we convert to
3330          my $triple = substr($sequence, $i, 3);          # upper case to insure a match.
3331            my $triple = uc substr($sequence, $i, 3);
3332          # Translate it using the table.          # Translate it using the table.
3333          my $protein = "X";          my $protein = "X";
3334          if (exists $table->{$triple}) { $protein = $table->{$triple}; }          if (exists $table->{$triple}) { $protein = $table->{$triple}; }
# Line 3115  Line 3342 
3342    
3343  =head3 LoadInfo  =head3 LoadInfo
3344    
3345  C<< my ($dirName, @relNames) = $sprout->LoadInfo(); >>      my ($dirName, @relNames) = $sprout->LoadInfo();
3346    
3347  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
3348  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 3134  Line 3361 
3361      return @retVal;      return @retVal;
3362  }  }
3363    
3364    =head3 BBHMatrix
3365    
3366        my %bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets);
3367    
3368    Find all the bidirectional best hits for the features of a genome in a
3369    specified list of target genomes. The return value will be a hash mapping
3370    features in the original genome to their bidirectional best hits in the
3371    target genomes.
3372    
3373    =over 4
3374    
3375    =item genomeID
3376    
3377    ID of the genome whose features are to be examined for bidirectional best hits.
3378    
3379    =item cutoff
3380    
3381    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3382    
3383    =item targets
3384    
3385    List of target genomes. Only pairs originating in the original
3386    genome and landing in one of the target genomes will be returned.
3387    
3388    =item RETURN
3389    
3390    Returns a hash mapping each feature in the original genome to a hash mapping its
3391    BBH pegs in the target genomes to their scores.
3392    
3393    =back
3394    
3395    =cut
3396    
3397    sub BBHMatrix {
3398        # Get the parameters.
3399        my ($self, $genomeID, $cutoff, @targets) = @_;
3400        # Declare the return variable.
3401        my %retVal = ();
3402        # Ask for the BBHs.
3403        my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets);
3404        # We now have a set of 4-tuples that we need to convert into a hash of hashes.
3405        for my $bbhData (@bbhList) {
3406            my ($peg1, $peg2, $score) = @{$bbhData};
3407            if (! exists $retVal{$peg1}) {
3408                $retVal{$peg1} = { $peg2 => $score };
3409            } else {
3410                $retVal{$peg1}->{$peg2} = $score;
3411            }
3412        }
3413        # Return the result.
3414        return %retVal;
3415    }
3416    
3417    
3418    =head3 SimMatrix
3419    
3420        my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets);
3421    
3422    Find all the similarities for the features of a genome in a
3423    specified list of target genomes. The return value will be a hash mapping
3424    features in the original genome to their similarites in the
3425    target genomes.
3426    
3427    =over 4
3428    
3429    =item genomeID
3430    
3431    ID of the genome whose features are to be examined for similarities.
3432    
3433    =item cutoff
3434    
3435    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3436    
3437    =item targets
3438    
3439    List of target genomes. Only pairs originating in the original
3440    genome and landing in one of the target genomes will be returned.
3441    
3442    =item RETURN
3443    
3444    Returns a hash mapping each feature in the original genome to a hash mapping its
3445    similar pegs in the target genomes to their scores.
3446    
3447    =back
3448    
3449    =cut
3450    
3451    sub SimMatrix {
3452        # Get the parameters.
3453        my ($self, $genomeID, $cutoff, @targets) = @_;
3454        # Declare the return variable.
3455        my %retVal = ();
3456        # Get the list of features in the source organism.
3457        my @fids = $self->FeaturesOf($genomeID);
3458        # Ask for the sims. We only want similarities to fig features.
3459        my $simList = FIGRules::GetNetworkSims($self, \@fids, {}, 1000, $cutoff, "fig");
3460        if (! defined $simList) {
3461            Confess("Unable to retrieve similarities from server.");
3462        } else {
3463            Trace("Processing sims.") if T(3);
3464            # We now have a set of sims that we need to convert into a hash of hashes. First, we
3465            # Create a hash for the target genomes.
3466            my %targetHash = map { $_ => 1 } @targets;
3467            for my $simData (@{$simList}) {
3468                # Get the PEGs and the score.
3469                my ($peg1, $peg2, $score) = ($simData->id1, $simData->id2, $simData->psc);
3470                # Insure the second ID is in the target list.
3471                my ($genome2) = FIGRules::ParseFeatureID($peg2);
3472                if (exists $targetHash{$genome2}) {
3473                    # Here it is. Now we need to add it to the return hash. How we do that depends
3474                    # on whether or not $peg1 is new to us.
3475                    if (! exists $retVal{$peg1}) {
3476                        $retVal{$peg1} = { $peg2 => $score };
3477                    } else {
3478                        $retVal{$peg1}->{$peg2} = $score;
3479                    }
3480                }
3481            }
3482        }
3483        # Return the result.
3484        return %retVal;
3485    }
3486    
3487    
3488  =head3 LowBBHs  =head3 LowBBHs
3489    
3490  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>      my %bbhMap = $sprout->LowBBHs($featureID, $cutoff);
3491    
3492  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
3493  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 3165  Line 3516 
3516      my ($self, $featureID, $cutoff) = @_;      my ($self, $featureID, $cutoff) = @_;
3517      # Create the return hash.      # Create the return hash.
3518      my %retVal = ();      my %retVal = ();
3519      # Create a query to get the desired BBHs.      # Query for the desired BBHs.
3520      my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BBHData($featureID, $cutoff);
                                 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',  
                                 [$cutoff, $featureID],  
                                 ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);  
3521      # Form the results into the return hash.      # Form the results into the return hash.
3522      for my $pair (@bbhList) {      for my $pair (@bbhList) {
3523          $retVal{$pair->[0]} = $pair->[1];          my $fid = $pair->[0];
3524            if ($self->Exists('Feature', $fid)) {
3525                $retVal{$fid} = $pair->[1];
3526            }
3527      }      }
3528      # Return the result.      # Return the result.
3529      return %retVal;      return %retVal;
# Line 3180  Line 3531 
3531    
3532  =head3 Sims  =head3 Sims
3533    
3534  C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>      my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters);
3535    
3536  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
3537  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 3190  Line 3541 
3541  Similarities can be either raw or expanded. The raw similarities are basic  Similarities can be either raw or expanded. The raw similarities are basic
3542  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
3543  features considered substantially identical. So, for example, if features B<A1>,  features considered substantially identical. So, for example, if features B<A1>,
3544  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
3545  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]>.
3546    
3547  =over 4  =over 4
3548    
3549  =item fid  =item fid
3550    
3551  ID of the feature whose similarities are desired.  ID of the feature whose similarities are desired, or reference to a list of IDs
3552    of features whose similarities are desired.
3553    
3554  =item maxN  =item maxN
3555    
# Line 3243  Line 3595 
3595      return $retVal;      return $retVal;
3596  }  }
3597    
3598    =head3 IsAllGenomes
3599    
3600        my $flag = $sprout->IsAllGenomes(\@list, \@checkList);
3601    
3602    Return TRUE if all genomes in the second list are represented in the first list at
3603    least one. Otherwise, return FALSE. If the second list is omitted, the first list is
3604    compared to a list of all the genomes.
3605    
3606    =over 4
3607    
3608    =item list
3609    
3610    Reference to the list to be compared to the second list.
3611    
3612    =item checkList (optional)
3613    
3614    Reference to the comparison target list. Every genome ID in this list must occur at
3615    least once in the first list. If this parameter is omitted, a list of all the genomes
3616    is used.
3617    
3618    =item RETURN
3619    
3620    Returns TRUE if every item in the second list appears at least once in the
3621    first list, else FALSE.
3622    
3623    =back
3624    
3625    =cut
3626    
3627    sub IsAllGenomes {
3628        # Get the parameters.
3629        my ($self, $list, $checkList) = @_;
3630        # Supply the checklist if it was omitted.
3631        $checkList = [$self->Genomes()] if ! defined($checkList);
3632        # Create a hash of the original list.
3633        my %testList = map { $_ => 1 } @{$list};
3634        # Declare the return variable. We assume that the representation
3635        # is complete and stop at the first failure.
3636        my $retVal = 1;
3637        my $n = scalar @{$checkList};
3638        for (my $i = 0; $retVal && $i < $n; $i++) {
3639            if (! $testList{$checkList->[$i]}) {
3640                $retVal = 0;
3641            }
3642        }
3643        # Return the result.
3644        return $retVal;
3645    }
3646    
3647  =head3 GetGroups  =head3 GetGroups
3648    
3649  C<< my %groups = $sprout->GetGroups(\@groupList); >>      my %groups = $sprout->GetGroups(\@groupList);
3650    
3651  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.
3652  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 3264  Line 3665 
3665          # Here we have a group list. Loop through them individually,          # Here we have a group list. Loop through them individually,
3666          # getting a list of the relevant genomes.          # getting a list of the relevant genomes.
3667          for my $group (@{$groupList}) {          for my $group (@{$groupList}) {
3668              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3669                  [$group], "Genome(id)");                  [$group], "Genome(id)");
3670              $retVal{$group} = \@genomeIDs;              $retVal{$group} = \@genomeIDs;
3671          }          }
# Line 3272  Line 3673 
3673          # Here we need all of the groups. In this case, we run through all          # Here we need all of the groups. In this case, we run through all
3674          # of the genome records, putting each one found into the appropriate          # of the genome records, putting each one found into the appropriate
3675          # group. Note that we use a filter clause to insure that only genomes          # group. Note that we use a filter clause to insure that only genomes
3676          # in groups are included in the return set.          # in real NMPDR groups are included in the return set.
3677          my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],          my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3678                                      ['Genome(id)', 'Genome(group-name)']);                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3679          # Loop through the genomes found.          # Loop through the genomes found.
3680          for my $genome (@genomes) {          for my $genome (@genomes) {
3681              # Pop this genome's ID off the current list.              # Get the genome ID and group, and add this genome to the group's list.
3682              my @groups = @{$genome};              my ($genomeID, $group) = @{$genome};
3683              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);  
             }  
3684          }          }
3685      }      }
3686      # Return the hash we just built.      # Return the hash we just built.
# Line 3293  Line 3689 
3689    
3690  =head3 MyGenomes  =head3 MyGenomes
3691    
3692  C<< my @genomes = Sprout::MyGenomes($dataDir); >>      my @genomes = Sprout::MyGenomes($dataDir);
3693    
3694  Return a list of the genomes to be included in the Sprout.  Return a list of the genomes to be included in the Sprout.
3695    
# Line 3325  Line 3721 
3721    
3722  =head3 LoadFileName  =head3 LoadFileName
3723    
3724  C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>      my $fileName = Sprout::LoadFileName($dataDir, $tableName);
3725    
3726  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
3727  directory.  directory.
# Line 3366  Line 3762 
3762    
3763  =head3 DeleteGenome  =head3 DeleteGenome
3764    
3765  C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>      my $stats = $sprout->DeleteGenome($genomeID, $testFlag);
3766    
3767  Delete a genome from the database.  Delete a genome from the database.
3768    
# Line 3392  Line 3788 
3788      # Get the parameters.      # Get the parameters.
3789      my ($self, $genomeID, $testFlag) = @_;      my ($self, $genomeID, $testFlag) = @_;
3790      # Perform the delete for the genome's features.      # Perform the delete for the genome's features.
3791      my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);      my $retVal = $self->Delete('Feature', "fig|$genomeID.%", testMode => $testFlag);
3792      # Perform the delete for the primary genome data.      # Perform the delete for the primary genome data.
3793      my $stats = $self->Delete('Genome', $genomeID, $testFlag);      my $stats = $self->Delete('Genome', $genomeID, testMode => $testFlag);
3794      $retVal->Accumulate($stats);      $retVal->Accumulate($stats);
3795      # Return the result.      # Return the result.
3796      return $retVal;      return $retVal;
# Line 3402  Line 3798 
3798    
3799  =head3 Fix  =head3 Fix
3800    
3801  C<< my %fixedHash = Sprout::Fix(%groupHash); >>      my %fixedHash = $sprout->Fix(%groupHash);
3802    
3803  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.
3804  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.  
3805    
3806  =over 4  =over 4
3807    
# Line 3424  Line 3819 
3819    
3820  sub Fix {  sub Fix {
3821      # Get the parameters.      # Get the parameters.
3822      my (%groupHash) = @_;      my ($self, %groupHash) = @_;
3823      # Create the result hash.      # Create the result hash.
3824      my %retVal = ();      my %retVal = ();
3825      # Copy over the genomes.      # Copy over the genomes.
3826      for my $groupID (keys %groupHash) {      for my $groupID (keys %groupHash) {
3827          # Make a safety copy of the group ID.          # Get the super-group name.
3828          my $realGroupID = $groupID;          my $realGroupID = $self->SuperGroup($groupID);
3829          # Yank the primary name.          # Append this group's genomes into the result hash
3830          if ($groupID =~ /([A-Z]\w+)/) {          # using the super-group name.
3831              $realGroupID = $1;          push @{$retVal{$realGroupID}}, @{$groupHash{$groupID}};
         }  
         # Append this group's genomes into the result hash.  
         Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}});  
3832      }      }
3833      # Return the result hash.      # Return the result hash.
3834      return %retVal;      return %retVal;
3835  }  }
3836    
3837  =head3 ReadGroupFile  =head3 GroupPageName
3838    
3839  C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >>      my $name = $sprout->GroupPageName($group);
3840    
3841  Read in the data from the specified group file. The group file contains information  Return the name of the page for the specified NMPDR group.
 about each of the NMPDR groups.  
3842    
3843  =over 4  =over 4
3844    
3845  =item name  =item group
3846    
3847  Name of the group.  Name of the relevant group.
3848    
3849  =item page  =item RETURN
3850    
3851  Name of the group's page on the web site (e.g. C<campy.php> for  Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3852  Campylobacter)  memory it will be read in.
3853    
3854  =item genus  =back
3855    
3856  Genus of the group  =cut
3857    
3858  =item species  sub GroupPageName {
3859        # Get the parameters.
3860        my ($self, $group) = @_;
3861        # Check for the group file data.
3862        my %superTable = $self->CheckGroupFile();
3863        # Compute the real group name.
3864        my $realGroup = $self->SuperGroup($group);
3865        # Get the associated page name.
3866        my $retVal = "../content/$superTable{$realGroup}->{page}";
3867        # Return the result.
3868        return $retVal;
3869    }
3870    
3871    
3872    =head3 AddProperty
3873    
3874        $sprout->AddProperty($featureID, $key, @values);
3875    
3876    Add a new attribute value (Property) to a feature.
3877    
3878    =over 4
3879    
3880    =item peg
3881    
3882    ID of the feature to which the attribute is to be added.
3883    
3884    =item key
3885    
3886  Species of the group, or an empty string if the group is for an entire  Name of the attribute (key).
3887  genus. If the group contains more than one species, the species names  
3888  should be separated by commas.  =item values
3889    
3890    Values of the attribute.
3891    
3892  =back  =back
3893    
3894  The parameters to this method are as follows  =cut
3895    #: Return Type ;
3896    sub AddProperty {
3897        # Get the parameters.
3898        my ($self, $featureID, $key, @values) = @_;
3899        # Add the property using the attached attributes object.
3900        $self->{_ca}->AddAttribute($featureID, $key, @values);
3901    }
3902    
3903    =head3 CheckGroupFile
3904    
3905        my %groupData = $sprout->CheckGroupFile();
3906    
3907    Get the group file hash. The group file hash describes the relationship
3908    between a group and the super-group to which it belongs for purposes of
3909    display. The super-group name is computed from the first capitalized word
3910    in the actual group name. For each super-group, the group file contains
3911    the page name and a list of the species expected to be in the group.
3912    Each species is specified by a genus and a species name. A species name
3913    of C<0> implies an entire genus.
3914    
3915    This method returns a hash from super-group names to a hash reference. Each
3916    resulting hash reference contains the following fields.
3917    
3918  =over 4  =over 4
3919    
3920  =item groupFile  =item page
3921    
3922  Name of the file containing the group data.  The super-group's web page in the NMPDR.
3923    
3924  =item RETURN  =item contents
3925    
3926  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
3927    (or 0, indicating all species). This list indicates which organisms belong
3928    in the super-group.
3929    
3930  =back  =back
3931    
3932  =cut  =cut
3933    
3934  sub ReadGroupFile {  sub CheckGroupFile {
3935      # Get the parameters.      # Get the parameters.
3936      my ($groupFileName) = @_;      my ($self) = @_;
3937      # Declare the return variable.      # Check to see if we already have this hash.
3938      my %retVal;      if (! defined $self->{groupHash}) {
3939            # We don't, so we need to read it in.
3940            my %groupHash;
3941      # Read the group file.      # Read the group file.
3942      my @groupLines = Tracer::GetFile($groupFileName);          my @groupLines = Tracer::GetFile("$FIG_Config::sproutData/groups.tbl");
3943            # Loop through the list of sort-of groups.
3944      for my $groupLine (@groupLines) {      for my $groupLine (@groupLines) {
3945          my ($name, $page, $genus, $species) = split(/\t/, $groupLine);              my ($name, $page, @contents) = split /\t/, $groupLine;
3946          $retVal{$name} = [$page, $genus, $species];              $groupHash{$name} = { page => $page,
3947                                      contents => [ map { [ split /\s*,\s*/, $_ ] } @contents ]
3948                                    };
3949            }
3950            # Save the hash.
3951            $self->{groupHash} = \%groupHash;
3952      }      }
3953      # Return the result.      # Return the result.
3954      return %retVal;      return %{$self->{groupHash}};
3955    }
3956    
3957    =head2 Virtual Methods
3958    
3959    =head3 CleanKeywords
3960    
3961        my $cleanedString = $sprout->CleanKeywords($searchExpression);
3962    
3963    Clean up a search expression or keyword list. This involves converting the periods
3964    in EC numbers to underscores, converting non-leading minus signs to underscores,
3965    a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
3966    characters. In addition, any extra spaces are removed.
3967    
3968    =over 4
3969    
3970    =item searchExpression
3971    
3972    Search expression or keyword list to clean. Note that a search expression may
3973    contain boolean operators which need to be preserved. This includes leading
3974    minus signs.
3975    
3976    =item RETURN
3977    
3978    Cleaned expression or keyword list.
3979    
3980    =back
3981    
3982    =cut
3983    
3984    sub CleanKeywords {
3985        # Get the parameters.
3986        my ($self, $searchExpression) = @_;
3987        # Perform the standard cleanup.
3988        my $words = $self->ERDB::CleanKeywords($searchExpression);
3989        # Fix the periods in EC and TC numbers.
3990        $words =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g;
3991        # Fix non-trailing periods.
3992        $words =~ s/\.(\w)/_$1/g;
3993        # Fix non-leading minus signs.
3994        $words =~ s/(\w)[\-]/$1_/g;
3995        # Fix the vertical bars and colons
3996        $words =~ s/(\w)[|:](\w)/$1'$2/g;
3997        # Now split up the list so that each keyword is in its own string. We keep the delimiters
3998        # because they may contain boolean expression data.
3999        my @words = split /([^A-Za-z'0-9_]+)/, $words;
4000        # We'll convert the stemmable words into stems and re-assemble the result.
4001        my $retVal = "";
4002        for my $word (@words) {
4003            my $stem = $self->Stem($word);
4004            if (defined $stem) {
4005                $retVal .= $stem;
4006            } else {
4007                $retVal .= $word;
4008            }
4009        }
4010        Trace("Cleaned keyword list for \"$searchExpression\" is \"$retVal\".") if T(3);
4011        # Return the result.
4012        return $retVal;
4013  }  }
4014    
4015  =head2 Internal Utility Methods  =head2 Internal Utility Methods
# Line 3513  Line 4022 
4022    
4023  A functional assignment is always of the form  A functional assignment is always of the form
4024    
4025      C<set >I<YYYY>C< function to\n>I<ZZZZZ>      set YYYY function to
4026        ZZZZ
4027    
4028  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,
4029  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 3566  Line 4076 
4076      return @retVal;      return @retVal;
4077  }  }
4078    
4079    =head3 _CheckFeature
4080    
4081        my $flag = $sprout->_CheckFeature($fid);
4082    
4083    Return TRUE if the specified FID is probably an NMPDR feature ID, else FALSE.
4084    
4085    =over 4
4086    
4087    =item fid
4088    
4089    Feature ID to check.
4090    
4091    =item RETURN
4092    
4093    Returns TRUE if the FID is for one of the NMPDR genomes, else FALSE.
4094    
4095    =back
4096    
4097    =cut
4098    
4099    sub _CheckFeature {
4100        # Get the parameters.
4101        my ($self, $fid) = @_;
4102        # Insure we have a genome hash.
4103        if (! defined $self->{genomeHash}) {
4104            my %genomeHash = map { $_ => 1 } $self->GetFlat(['Genome'], "", [], 'Genome(id)');
4105            $self->{genomeHash} = \%genomeHash;
4106        }
4107        # Get the feature's genome ID.
4108        my ($genomeID) = FIGRules::ParseFeatureID($fid);
4109        # Return an indicator of whether or not the genome ID is in the hash.
4110        return ($self->{genomeHash}->{$genomeID} ? 1 : 0);
4111    }
4112    
4113  =head3 FriendlyTimestamp  =head3 FriendlyTimestamp
4114    
4115  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 3592  Line 4136 
4136      return $retVal;      return $retVal;
4137  }  }
4138    
 =head3 AddProperty  
   
 C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>  
4139    
4140  Add a new attribute value (Property) to a feature. In the SEED system, attributes can  =head3 Hint
 be added to almost any object. In Sprout, they can only be added to features. In  
 Sprout, attributes are implemented using I<properties>. A property represents a key/value  
 pair. If the particular key/value pair coming in is not already in the database, a new  
 B<Property> record is created to hold it.  
4141    
4142  =over 4      my $htmlText = SearchHelper::Hint($wikiPage, $hintText);
4143    
4144  =item peg  Return the HTML for a small question mark that displays the specified hint text when it is clicked.
4145    This HTML can be put in forms to provide a useful hinting mechanism.
4146    
4147  ID of the feature to which the attribute is to be replied.  =over 4
4148    
4149  =item key  =item wikiPage
4150    
4151  Name of the attribute (key).  Name of the wiki page to be popped up when the hint mark is clicked.
4152    
4153  =item value  =item hintText
4154    
4155  Value of the attribute.  Text to display for the hint. It is raw html, but may not contain any double quotes.
4156    
4157  =item url  =item RETURN
4158    
4159  URL or text citation from which the property was obtained.  Returns the html for the hint facility. The resulting html shows a small button-like thing that
4160    uses the standard FIG popup technology.
4161    
4162  =back  =back
4163    
4164  =cut  =cut
4165  #: Return Type ;  
4166  sub AddProperty {  sub Hint {
4167      # Get the parameters.      # Get the parameters.
4168      my ($self, $featureID, $key, $value, $url) = @_;      my ($wikiPage, $hintText) = @_;
4169      # Declare the variable to hold the desired property ID.      # Escape the single quotes in the hint text.
4170      my $propID;      my $quotedText = $hintText;
4171      # Attempt to find a property record for this key/value pair.      $quotedText =~ s/'/\\'/g;
4172      my @properties = $self->GetFlat(['Property'],      # Convert the wiki page name to a URL.
4173                                     "Property(property-name) = ? AND Property(property-value) = ?",      my $wikiURL = join("", map { ucfirst $_ } split /\s+/, $wikiPage);
4174                                     [$key, $value], 'Property(id)');      $wikiURL = "$FIG_Config::cgi_url/wiki/view.cgi/FIG/$wikiURL";
4175      if (@properties) {      # Compute the mouseover script.
4176          # Here the property is already in the database. We save its ID.      my $mouseOver = "doTooltip(this, '$quotedText')";
4177          $propID = $properties[0];      # Create the html.
4178          # Here the property value does not exist. We need to generate an ID. It will be set      my $retVal = "&nbsp;<a href=\"$wikiURL\"><img src=\"$FIG_Config::cgi_url/Html/button-h.png\" class=\"helpicon\" onmouseover=\"$mouseOver\"/></a>";
4179          # to a number one greater than the maximum value in the database. This call to      # Return it.
4180          # GetAll will stop after one record.      return $retVal;
         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 });  
4181  }  }
4182    
   
4183  1;  1;

Legend:
Removed from v.1.83  
changed lines
  Added in v.1.117

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3