[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.81, Thu Aug 24 17:32:09 2006 UTC revision 1.110, Tue Apr 29 20:54:51 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 base qw(ERDB);
19    
20  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
21    
# Line 28  Line 28 
28  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>
29  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>.
30    
31  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' });
32    
33  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
34  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
35  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
36  L</dna_seq> returns the DNA sequence for a specified genome location.  L</DNASeq> returns the DNA sequence for a specified genome location.
37    
38  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.
39    
# Line 45  Line 45 
45    
46  =head3 new  =head3 new
47    
48  C<< my $sprout = Sprout->new($dbName, \%options); >>      my $sprout = Sprout->new($dbName, \%options);
49    
50  This is the constructor for a sprout object. It connects to the database and loads the  This is the constructor for a sprout object. It connects to the database and loads the
51  database definition into memory. The positional first parameter specifies the name of the  database definition into memory. The positional first parameter specifies the name of the
# Line 79  Line 79 
79    
80  * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE  * B<noDBOpen> suppresses the connection to the database if TRUE, else FALSE
81    
82    * B<host> name of the database host
83    
84  =back  =back
85    
86  For example, the following constructor call specifies a database named I<Sprout> and a user name of  For example, the following constructor call specifies a database named I<Sprout> and a user name of
87  I<fig> with a password of I<admin>. The database load files are in the directory  I<fig> with a password of I<admin>. The database load files are in the directory
88  F</usr/fig/SproutData>.  F</usr/fig/SproutData>.
89    
90  C<< my $sprout = Sprout->new('Sprout', { userData =>; 'fig/admin', dataDir => '/usr/fig/SproutData' }); >>      my $sprout = Sprout->new('Sprout', { userData => 'fig/admin', dataDir => '/usr/fig/SproutData' });
91    
92  =cut  =cut
93    
# Line 109  Line 111 
111                         port         => $FIG_Config::dbport,                         port         => $FIG_Config::dbport,
112                                                          # database connection port                                                          # database connection port
113                         sock         => $FIG_Config::dbsock,                         sock         => $FIG_Config::dbsock,
114                         host         => $FIG_Config::dbhost,                         host         => $FIG_Config::sprout_host,
115                         maxSegmentLength => 4500,        # maximum feature segment length                         maxSegmentLength => 4500,        # maximum feature segment length
116                         maxSequenceLength => 8000,       # maximum contig sequence length                         maxSequenceLength => 8000,       # maximum contig sequence length
117                         noDBOpen     => 0,               # 1 to suppress the database open                         noDBOpen     => 0,               # 1 to suppress the database open
# Line 122  Line 124 
124      # Connect to the database.      # Connect to the database.
125      my $dbh;      my $dbh;
126      if (! $optionTable->{noDBOpen}) {      if (! $optionTable->{noDBOpen}) {
127            Trace("Connect data: host = $optionTable->{host}, port = $optionTable->{port}.") if T(3);
128          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
129                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
130      }      }
# Line 131  Line 134 
134      # Add the option table and XML file name.      # Add the option table and XML file name.
135      $retVal->{_options} = $optionTable;      $retVal->{_options} = $optionTable;
136      $retVal->{_xmlName} = $xmlFileName;      $retVal->{_xmlName} = $xmlFileName;
137        # Set up space for the group file data.
138        $retVal->{groupHash} = undef;
139        # Set up space for the genome hash. We use this to identify NMPDR genomes.
140        $retVal->{genomeHash} = undef;
141        # Connect to the attributes.
142        if ($FIG_Config::attrURL) {
143            Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);
144            $retVal->{_ca} = RemoteCustomAttributes->new($FIG_Config::attrURL);
145        } elsif ($FIG_Config::attrDbName) {
146            Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);
147            my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));
148            $retVal->{_ca} = CustomAttributes->new(user => $user);
149        }
150      # Return it.      # Return it.
151      return $retVal;      return $retVal;
152  }  }
153    
154    =head3 CoreGenomes
155    
156        my @genomes = $sprout->CoreGenomes($scope);
157    
158    Return the IDs of NMPDR genomes in the specified scope.
159    
160    =over 4
161    
162    =item scope
163    
164    Scope of the desired genomes. C<core> covers the original core genomes,
165    C<nmpdr> covers all genomes in NMPDR groups, and C<all> covers all
166    genomes in the system.
167    
168    =item RETURN
169    
170    Returns a list of the IDs for the genomes in the specified scope.
171    
172    =back
173    
174    =cut
175    
176    sub CoreGenomes {
177        # Get the parameters.
178        my ($self, $scope) = @_;
179        # Declare the return variable.
180        my @retVal = ();
181        # If we want all genomes, then this is easy.
182        if ($scope eq 'all') {
183            @retVal = $self->Genomes();
184        } else {
185            # Here we're dealing with groups. Get the hash of all the
186            # genome groups.
187            my %groups = $self->GetGroups();
188            # Loop through the groups, keeping the ones that we want.
189            for my $group (keys %groups) {
190                # Decide if we want to keep this group.
191                my $keepGroup = 0;
192                if ($scope eq 'nmpdr') {
193                    # NMPDR mode: keep all groups.
194                    $keepGroup = 1;
195                } elsif ($scope eq 'core') {
196                    # CORE mode. Only keep real core groups.
197                    if (grep { $group =~ /$_/ } @{$FIG_Config::realCoreGroups}) {
198                        $keepGroup = 1;
199                    }
200                }
201                # Add this group if we're keeping it.
202                if ($keepGroup) {
203                    push @retVal, @{$groups{$group}};
204                }
205            }
206        }
207        # Return the result.
208        return @retVal;
209    }
210    
211    =head3 SuperGroup
212    
213        my $superGroup = $sprout->SuperGroup($groupName);
214    
215    Return the name of the super-group containing the specified NMPDR genome
216    group. If no appropriate super-group can be found, an error will be
217    thrown.
218    
219    =over 4
220    
221    =item groupName
222    
223    Name of the group whose super-group is desired.
224    
225    =item RETURN
226    
227    Returns the name of the super-group containing the incoming group.
228    
229    =back
230    
231    =cut
232    
233    sub SuperGroup {
234        # Get the parameters.
235        my ($self, $groupName) = @_;
236        # Declare the return variable.
237        my $retVal;
238        # Get the group hash.
239        my %groupHash = $self->CheckGroupFile();
240        # Find the super-group genus.
241        $groupName =~ /([A-Z]\w+)/;
242        my $nameThing = $1;
243        # See if it's directly in the group hash.
244        if (exists $groupHash{$nameThing}) {
245            # Yes, then it's our result.
246            $retVal = $nameThing;
247        } else {
248            # No, so we have to search.
249            for my $superGroup (keys %groupHash) {
250                # Get this super-group's item list.
251                my $list = $groupHash{$superGroup}->{contents};
252                # Search it.
253                if (grep { $_->[0] eq $nameThing } @{$list}) {
254                    $retVal = $superGroup;
255                }
256            }
257            # Make sure we found something.
258            if (! $retVal) {
259                Confess("No super-group found for \"$groupName\".");
260            }
261        }
262        # Return the result.
263        return $retVal;
264    }
265    
266  =head3 MaxSegment  =head3 MaxSegment
267    
268  C<< my $length = $sprout->MaxSegment(); >>      my $length = $sprout->MaxSegment();
269    
270  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
271  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 282 
282    
283  =head3 MaxSequence  =head3 MaxSequence
284    
285  C<< my $length = $sprout->MaxSequence(); >>      my $length = $sprout->MaxSequence();
286    
287  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
288  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 297 
297    
298  =head3 Load  =head3 Load
299    
300  C<< $sprout->Load($rebuild); >>;      $sprout->Load($rebuild);;
301    
302  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.
303    
# Line 209  Line 337 
337    
338  =head3 LoadUpdate  =head3 LoadUpdate
339    
340  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>      my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList);
341    
342  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
343  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 383 
383              Trace("No load file found for $tableName in $dataDir.") if T(0);              Trace("No load file found for $tableName in $dataDir.") if T(0);
384          } else {          } else {
385              # Attempt to load this table.              # Attempt to load this table.
386              my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);              my $result = $self->LoadTable($fileName, $tableName, truncate => $truncateFlag);
387              # Accumulate the resulting statistics.              # Accumulate the resulting statistics.
388              $retVal->Accumulate($result);              $retVal->Accumulate($result);
389          }          }
# Line 266  Line 394 
394    
395  =head3 GenomeCounts  =head3 GenomeCounts
396    
397  C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>      my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete);
398    
399  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
400  genomes will be included in the counts.  genomes will be included in the counts.
# Line 311  Line 439 
439    
440  =head3 ContigCount  =head3 ContigCount
441    
442  C<< my $count = $sprout->ContigCount($genomeID); >>      my $count = $sprout->ContigCount($genomeID);
443    
444  Return the number of contigs for the specified genome ID.  Return the number of contigs for the specified genome ID.
445    
# Line 338  Line 466 
466      return $retVal;      return $retVal;
467  }  }
468    
469  =head3 GeneMenu  =head3 GenomeMenu
470    
471  C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params); >>      my $html = $sprout->GenomeMenu(%options);
472    
473  Return an HTML select menu of genomes. Each genome will be an option in the menu,  Generate a genome selection control with the specified name and options.
474  and will be displayed by name with the ID and a contig count attached. The selection  This control is almost but not quite the same as the genome control in the
475  value will be the genome ID. The genomes will be sorted by genus/species name.  B<SearchHelper> class. Eventually, the two will be combined.
476    
477  =over 4  =over 4
478    
479  =item attributes  =item options
480    
481    Optional parameters for the control (see below).
482    
483  Reference to a hash mapping attributes to values for the SELECT tag generated.  =item RETURN
484    
485  =item filterString  Returns the HTML for a genome selection control on a form (sometimes called a popup menu).
486    
487  A filter string for use in selecting the genomes. The filter string must conform  =back
 to the rules for the C<< ERDB->Get >> method.  
488    
489  =item params  The valid options are as follows.
490    
491  Reference to a list of values to be substituted in for the parameter marks in  =over 4
 the filter string.  
492    
493  =item RETURN  =item name
494    
495    Name to give this control for use in passing it to the form. The default is C<myGenomeControl>.
496    Terrible things will happen if you have two controls with the same name on the same page.
497    
498    =item filter
499    
500    If specified, a filter for the list of genomes to display. The filter should be in the form of a
501    list reference. The first element of the list should be the filter string, and the remaining elements
502    the filter parameters.
503    
504    =item multiSelect
505    
506  Returns an HTML select menu with the specified genomes as selectable options.  If TRUE, then the user can select multiple genomes. If FALSE, the user can only select one genome.
507    
508    =item size
509    
510    Number of rows to display in the control. The default is C<10>
511    
512    =item id
513    
514    ID to give this control. The default is the value of the C<name> option. Nothing will work correctly
515    unless this ID is unique.
516    
517    =item selected
518    
519    A comma-delimited list of selected genomes, or a reference to a list of selected genomes. The
520    default is none.
521    
522    =item class
523    
524    If specified, a style class to assign to the genome control.
525    
526  =back  =back
527    
528  =cut  =cut
529    
530  sub GeneMenu {  sub GenomeMenu {
531      # Get the parameters.      # Get the parameters.
532      my ($self, $attributes, $filterString, $params) = @_;      my ($self, %options) = @_;
533      # Start the menu.      # Get the control's name and ID.
534      my $retVal = "<select " .      my $menuName = $options{name} || 'myGenomeControl';
535          join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .      my $menuID = $options{id} || $menuName;
536          ">\n";      # Compute the IDs for the status display.
537      # Get the genomes.      my $divID = "${menuID}_status";
538      my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',      my $urlID = "${menuID}_url";
539                                                                       'Genome(genus)',      # Compute the code to show selected genomes in the status area.
540                                                                       'Genome(species)',      my $showSelect = "showSelected('$menuID', '$divID', '$urlID', 1000)";
541                                                                       'Genome(unique-characterization)']);      # Check for single-select or multi-select.
542      # Sort them by name.      my $multiSelect = $options{multiSelect} || 0;
543      my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;      # Get the style data.
544      # Loop through the genomes, creating the option tags.      my $class = $options{class} || '';
545      for my $genomeData (@sorted) {      # Get the list of pre-selected items.
546          # Get the data for this genome.      my $selections = $options{selected} || [];
547          my ($genomeID, $genus, $species, $strain) = @{$genomeData};      if (ref $selections ne 'ARRAY') {
548          # Get the contig count.          $selections = [ split /\s*,\s*/, $selections ];
549          my $count = $self->ContigCount($genomeID);      }
550          my $counting = ($count == 1 ? "contig" : "contigs");      my %selected = map { $_ => } @{$selections};
551          # Build the option tag.      # Extract the filter information. The default is no filtering. It can be passed as a tab-delimited
552          $retVal .= "<option value=\"$genomeID\">$genus $species $strain ($genomeID) [$count $counting]</option>\n";      # string or a list reference.
553          Trace("Option tag built for $genomeID: $genus $species $strain.") if T(3);      my $filterParms = $options{filter} || "";
554        if (! ref $filterParms) {
555            $filterParms = [split /\t|\\t/, $filterParms];
556        }
557        my $filterString = shift @{$filterParms};
558        # Get a list of all the genomes in group order. In fact, we only need them ordered
559        # by name (genus,species,strain), but putting primary-group in front enables us to
560        # take advantage of an existing index.
561        my @genomeList = $self->GetAll(['Genome'], "$filterString ORDER BY Genome(primary-group), Genome(genus), Genome(species), Genome(unique-characterization)",
562                                       $filterParms,
563                                       [qw(Genome(primary-group) Genome(id) Genome(genus) Genome(species) Genome(unique-characterization) Genome(taxonomy) Genome(contigs))]);
564        # Create a hash to organize the genomes by group. Each group will contain a list of
565        # 2-tuples, the first element being the genome ID and the second being the genome
566        # name.
567        my %gHash = ();
568        for my $genome (@genomeList) {
569            # Get the genome data.
570            my ($group, $genomeID, $genus, $species, $strain, $taxonomy, $contigs) = @{$genome};
571            # Compute its name. This is the genus, species, strain (if any), and the contig count.
572            my $name = "$genus $species ";
573            $name .= "$strain " if $strain;
574            my $contigCount = ($contigs == 1 ? "" : ", $contigs contigs");
575            # Now we get the domain. The domain tells us the display style of the organism.
576            my ($domain) = split /\s*;\s*/, $taxonomy, 2;
577            # Now compute the display group. This is normally the primary group, but if the
578            # organism is supporting, we blank it out.
579            my $displayGroup = ($group eq $FIG_Config::otherGroup ? "" : $group);
580            # Push the genome into the group's list. Note that we use the real group
581            # name for the hash key here, not the display group name.
582            push @{$gHash{$group}}, [$genomeID, $name, $contigCount, $domain];
583        }
584        # We are almost ready to unroll the menu out of the group hash. The final step is to separate
585        # the supporting genomes by domain. First, we extract the NMPDR groups and sort them. They
586        # are sorted by the first capitalized word. Groups with "other" are sorted after groups
587        # that aren't "other". At some point, we will want to make this less complicated.
588        my %sortGroups = map { $_ =~ /(other)?(.*)([A-Z].+)/; "$3$1$2" => $_ }
589                             grep { $_ ne $FIG_Config::otherGroup } keys %gHash;
590        my @groups = map { $sortGroups{$_} } sort keys %sortGroups;
591        # Remember the number of NMPDR groups.
592        my $nmpdrGroupCount = scalar @groups;
593        # Loop through the supporting genomes, classifying them by domain. We'll also keep a list
594        # of the domains found.
595        my @otherGenomes = @{$gHash{$FIG_Config::otherGroup}};
596        my @domains = ();
597        for my $genomeData (@otherGenomes) {
598            my ($genomeID, $name, $contigCount, $domain) = @{$genomeData};
599            if (exists $gHash{$domain}) {
600                push @{$gHash{$domain}}, $genomeData;
601            } else {
602                $gHash{$domain} = [$genomeData];
603                push @domains, $domain;
604            }
605        }
606        # Add the domain groups at the end of the main group list. The main group list will now
607        # contain all the categories we need to display the genomes.
608        push @groups, sort @domains;
609        # Delete the supporting group.
610        delete $gHash{$FIG_Config::otherGroup};
611        # Now it gets complicated. We need a way to mark all the NMPDR genomes. We take advantage
612        # of the fact they come first in the list. We'll accumulate a count of the NMPDR genomes
613        # and use that to make the selections.
614        my $nmpdrCount = 0;
615        # Create the type counters.
616        my $groupCount = 1;
617        # Get the number of rows to display.
618        my $rows = $options{size} || 10;
619        # If we're multi-row, create an onChange event.
620        my $onChangeTag = ( $rows > 1 ? " onChange=\"$showSelect;\" onFocus=\"$showSelect;\"" : "" );
621        # Set up the multiple-select flag.
622        my $multipleTag = ($multiSelect ? " multiple" : "" );
623        # Set up the style class.
624        my $classTag = ($class ? " class=\"$class\"" : "" );
625        # Create the SELECT tag and stuff it into the output array.
626        my @lines = ("<SELECT name=\"$menuID\" id=\"$menuID\" $onChangeTag$multipleTag$classTag size=\"$rows\">");
627        # Loop through the groups.
628        for my $group (@groups) {
629            # Get the genomes in the group.
630            for my $genome (@{$gHash{$group}}) {
631                # If this is an NMPDR organism, we add an extra style and count it.
632                my $nmpdrStyle = "";
633                if ($nmpdrGroupCount > 0) {
634                    $nmpdrCount++;
635                    $nmpdrStyle = " Core";
636                }
637                # Get the organism ID, name, contig count, and domain.
638                my ($genomeID, $name, $contigCount, $domain) = @{$genome};
639                # See if we're pre-selected.
640                my $selectTag = ($selected{$genomeID} ? " SELECTED" : "");
641                # Compute the display name.
642                my $nameString = "$name ($genomeID$contigCount)";
643                # Generate the option tag.
644                my $optionTag = "<OPTION class=\"$domain$nmpdrStyle\" title=\"$group\" value=\"$genomeID\"$selectTag>$nameString</OPTION>";
645                push @lines, "    $optionTag";
646            }
647            # Record this group in the nmpdrGroup count. When that gets to 0, we've finished the NMPDR
648            # groups.
649            $nmpdrGroupCount--;
650      }      }
651      # Close the SELECT tag.      # Close the SELECT tag.
652      $retVal .= "</select>\n";      push @lines, "</SELECT>";
653        if ($rows > 1) {
654            # We're in a non-compact mode, so we need to add some selection helpers. First is
655            # the search box. This allows the user to type text and change which genomes are
656            # displayed. For multiple-select mode, we include a button that selects the displayed
657            # genes. For single-select mode, we use a plain label instead.
658            my $searchThingName = "${menuID}_SearchThing";
659            my $searchThingLabel = ($multiSelect ? "<INPUT type=\"button\" name=\"MacroSearch\" class=\"button\" value=\"Select genomes containing\" onClick=\"selectShowing('$menuID', '$searchThingName'); $showSelect;\" />"
660                                                 : "Show genomes containing");
661            push @lines, "<br />$searchThingLabel&nbsp;" .
662                         "<INPUT type=\"text\" id=\"$searchThingName\" name=\"$searchThingName\" size=\"30\" onKeyup=\"showTyped('$menuID', '$searchThingName');\" />";
663            # For multi-select mode, we also have buttons to set and clear selections.
664            if ($multiSelect) {
665                push @lines, "<INPUT type=\"button\" name=\"ClearAll\" class=\"bigButton\"  value=\"Clear All\" onClick=\"clearAll('$menuID'); $showSelect\" />";
666                push @lines, "<INPUT type=\"button\" name=\"SelectAll\" class=\"bigButton\" value=\"Select All\" onClick=\"selectAll('$menuID'); $showSelect\" />";
667                push @lines, "<INPUT type=\"button\" name=\"NMPDROnly\" class=\"bigButton\"  value=\"Select NMPDR\" onClick=\"selectSome('$menuID', $nmpdrCount, true); $showSelect;\" />";
668            }
669            # Add a hidden field we can use to generate organism page hyperlinks.
670            push @lines, "<INPUT type=\"hidden\" id=\"$urlID\" value=\"$FIG_Config::cgi_url/seedviewer.cgi?page=Organism;organism=\" />";
671            # Add the status display. This tells the user what's selected no matter where the list is scrolled.
672            push @lines, "<DIV id=\"$divID\" class=\"Panel\"></DIV>";
673        }
674        # Assemble all the lines into a string.
675        my $retVal = join("\n", @lines, "");
676      # Return the result.      # Return the result.
677      return $retVal;      return $retVal;
678  }  }
679    
680    
681  =head3 Build  =head3 Build
682    
683  C<< $sprout->Build(); >>      $sprout->Build();
684    
685  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.
686  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 697 
697    
698  =head3 Genomes  =head3 Genomes
699    
700  C<< my @genomes = $sprout->Genomes(); >>      my @genomes = $sprout->Genomes();
701    
702  Return a list of all the genome IDs.  Return a list of all the genome IDs.
703    
# Line 436  Line 714 
714    
715  =head3 GenusSpecies  =head3 GenusSpecies
716    
717  C<< my $infoString = $sprout->GenusSpecies($genomeID); >>      my $infoString = $sprout->GenusSpecies($genomeID);
718    
719  Return the genus, species, and unique characterization for a genome.  Return the genus, species, and unique characterization for a genome.
720    
# Line 468  Line 746 
746    
747  =head3 FeaturesOf  =head3 FeaturesOf
748    
749  C<< my @features = $sprout->FeaturesOf($genomeID, $ftype); >>      my @features = $sprout->FeaturesOf($genomeID, $ftype);
750    
751  Return a list of the features relevant to a specified genome.  Return a list of the features relevant to a specified genome.
752    
# Line 513  Line 791 
791    
792  =head3 FeatureLocation  =head3 FeatureLocation
793    
794  C<< my @locations = $sprout->FeatureLocation($featureID); >>      my @locations = $sprout->FeatureLocation($featureID);
795    
796  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
797  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 815 
815  =item RETURN  =item RETURN
816    
817  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
818  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
819    wasn't found.
820    
821  =back  =back
822    
823  =cut  =cut
824  #: Return Type @;  
 #: Return Type $;  
825  sub FeatureLocation {  sub FeatureLocation {
826      # Get the parameters.      # Get the parameters.
827      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
828      # 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.  
829      my @retVal = ();      my @retVal = ();
830      # Set up the variables used to determine if we have adjacent segments. This initial setup will      # Get the feature record.
831      # not match anything.      my $object = $self->GetEntity('Feature', $featureID);
832      my ($prevContig, $prevBeg, $prevDir, $prevLen) = ("", 0, "0", 0);      # Only proceed if we found it.
833      # Loop through the query results, creating location specifiers.      if (defined $object) {
834      while (my $location = $query->Fetch()) {          # Get the location string.
835          # Get the location parameters.          my $locString = $object->PrimaryValue('Feature(location-string)');
836          my ($contigID, $beg, $dir, $len) = $location->Values(['IsLocatedIn(to-link)',          # Create the return list.
837              '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";  
838      }      }
839      # Return the list in the format indicated by the context.      # Return the list in the format indicated by the context.
840      return (wantarray ? @retVal : join(',', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
# Line 592  Line 842 
842    
843  =head3 ParseLocation  =head3 ParseLocation
844    
845  C<< my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location); >>      my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location);
846    
847  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
848  length.  length.
# Line 611  Line 861 
861  =back  =back
862    
863  =cut  =cut
864  #: Return Type @;  
865  sub ParseLocation {  sub ParseLocation {
866      # 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
867      # the first parameter.      # the first parameter.
# Line 634  Line 884 
884      return ($contigID, $start, $dir, $len);      return ($contigID, $start, $dir, $len);
885  }  }
886    
887    
888    
889  =head3 PointLocation  =head3 PointLocation
890    
891  C<< my $found = Sprout::PointLocation($location, $point); >>      my $found = Sprout::PointLocation($location, $point);
892    
893  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
894  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 917 
917  =back  =back
918    
919  =cut  =cut
920  #: Return Type $;  
921  sub PointLocation {  sub PointLocation {
922      # 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
923      # the first parameter.      # the first parameter.
# Line 688  Line 940 
940    
941  =head3 DNASeq  =head3 DNASeq
942    
943  C<< my $sequence = $sprout->DNASeq(\@locationList); >>      my $sequence = $sprout->DNASeq(\@locationList);
944    
945  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
946  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 1024 
1024    
1025  =head3 AllContigs  =head3 AllContigs
1026    
1027  C<< my @idList = $sprout->AllContigs($genomeID); >>      my @idList = $sprout->AllContigs($genomeID);
1028    
1029  Return a list of all the contigs for a genome.  Return a list of all the contigs for a genome.
1030    
# Line 802  Line 1054 
1054    
1055  =head3 GenomeLength  =head3 GenomeLength
1056    
1057  C<< my $length = $sprout->GenomeLength($genomeID); >>      my $length = $sprout->GenomeLength($genomeID);
1058    
1059  Return the length of the specified genome in base pairs.  Return the length of the specified genome in base pairs.
1060    
# Line 837  Line 1089 
1089    
1090  =head3 FeatureCount  =head3 FeatureCount
1091    
1092  C<< my $count = $sprout->FeatureCount($genomeID, $type); >>      my $count = $sprout->FeatureCount($genomeID, $type);
1093    
1094  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.
1095    
# Line 872  Line 1124 
1124    
1125  =head3 GenomeAssignments  =head3 GenomeAssignments
1126    
1127  C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>      my $fidHash = $sprout->GenomeAssignments($genomeID);
1128    
1129  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
1130  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 1150 
1150      my ($self, $genomeID) = @_;      my ($self, $genomeID) = @_;
1151      # Declare the return variable.      # Declare the return variable.
1152      my $retVal = {};      my $retVal = {};
1153      # Query the genome's features and annotations. We'll put the oldest annotations      # Query the genome's features.
1154      # 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)",  
1155                             [$genomeID]);                             [$genomeID]);
1156      # Loop through the annotations.      # Loop through the features.
1157      while (my $data = $query->Fetch) {      while (my $data = $query->Fetch) {
1158          # Get the feature ID and annotation text.          # Get the feature ID and assignment.
1159          my ($fid, $annotation) = $data->Values(['HasFeature(to-link)',          my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']);
1160                                                  '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.  
1161              $retVal->{$fid} = $assignment;              $retVal->{$fid} = $assignment;
1162          }          }
1163      }      }
# Line 924  Line 1167 
1167    
1168  =head3 ContigLength  =head3 ContigLength
1169    
1170  C<< my $length = $sprout->ContigLength($contigID); >>      my $length = $sprout->ContigLength($contigID);
1171    
1172  Compute the length of a contig.  Compute the length of a contig.
1173    
# Line 963  Line 1206 
1206    
1207  =head3 ClusterPEGs  =head3 ClusterPEGs
1208    
1209  C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>      my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs);
1210    
1211  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
1212  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
1213  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
1214  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
1215  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
1216  sequence.  appear in the output sequence.
1217    
1218  =over 4  =over 4
1219    
# Line 1011  Line 1254 
1254    
1255  =head3 GenesInRegion  =head3 GenesInRegion
1256    
1257  C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>      my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop);
1258    
1259  List the features which overlap a specified region in a contig.  List the features which overlap a specified region in a contig.
1260    
# Line 1040  Line 1283 
1283  =back  =back
1284    
1285  =cut  =cut
1286  #: Return Type @@;  
1287  sub GenesInRegion {  sub GenesInRegion {
1288      # Get the parameters.      # Get the parameters.
1289      my ($self, $contigID, $start, $stop) = @_;      my ($self, $contigID, $start, $stop) = @_;
1290      # Get the maximum segment length.      # Get the maximum segment length.
1291      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 = ();  
1292      # Prime the values we'll use for the returned beginning and end.      # Prime the values we'll use for the returned beginning and end.
1293      my @initialMinMax = ($self->ContigLength($contigID), 0);      my @initialMinMax = ($self->ContigLength($contigID), 0);
1294      my ($min, $max) = @initialMinMax;      my ($min, $max) = @initialMinMax;
1295      # Create a table of parameters for each query. Each query looks for features travelling in      # Get the overlapping features.
1296        my @featureObjects = $self->GeneDataInRegion($contigID, $start, $stop);
1297        # We'l use this hash to help us track the feature IDs and sort them. The key is the
1298        # feature ID and the value is a [$left,$right] pair indicating the maximum extent
1299        # of the feature's locations.
1300        my %featureMap = ();
1301        # Loop through them to do the begin/end analysis.
1302        for my $featureObject (@featureObjects) {
1303            # Get the feature's location string. This may contain multiple actual locations.
1304            my ($locations, $fid) = $featureObject->Values([qw(Feature(location-string) Feature(id))]);
1305            my @locationSegments = split /\s*,\s*/, $locations;
1306            # Loop through the locations.
1307            for my $locationSegment (@locationSegments) {
1308                # Construct an object for the location.
1309                my $locationObject = BasicLocation->new($locationSegment);
1310                # Merge the current segment's begin and end into the min and max.
1311                my ($left, $right) = ($locationObject->Left, $locationObject->Right);
1312                my ($beg, $end);
1313                if (exists $featureMap{$fid}) {
1314                    ($beg, $end) = @{$featureMap{$fid}};
1315                    $beg = $left if $left < $beg;
1316                    $end = $right if $right > $end;
1317                } else {
1318                    ($beg, $end) = ($left, $right);
1319                }
1320                $min = $beg if $beg < $min;
1321                $max = $end if $end > $max;
1322                # Store the feature's new extent back into the hash table.
1323                $featureMap{$fid} = [$beg, $end];
1324            }
1325        }
1326        # Now we must compute the list of the IDs for the features found. We start with a list
1327        # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1328        # but the result of the sort will be the same.)
1329        my @list = map { [$featureMap{$_}->[0] + $featureMap{$_}->[1], $_] } keys %featureMap;
1330        # Now we sort by midpoint and yank out the feature IDs.
1331        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1332        # Return it along with the min and max.
1333        return (\@retVal, $min, $max);
1334    }
1335    
1336    =head3 GeneDataInRegion
1337    
1338        my @featureList = $sprout->GenesInRegion($contigID, $start, $stop);
1339    
1340    List the features which overlap a specified region in a contig.
1341    
1342    =over 4
1343    
1344    =item contigID
1345    
1346    ID of the contig containing the region of interest.
1347    
1348    =item start
1349    
1350    Offset of the first residue in the region of interest.
1351    
1352    =item stop
1353    
1354    Offset of the last residue in the region of interest.
1355    
1356    =item RETURN
1357    
1358    Returns a list of B<ERDBObjects> for the desired features. Each object will
1359    contain a B<Feature> record.
1360    
1361    =back
1362    
1363    =cut
1364    
1365    sub GeneDataInRegion {
1366        # Get the parameters.
1367        my ($self, $contigID, $start, $stop) = @_;
1368        # Get the maximum segment length.
1369        my $maximumSegmentLength = $self->MaxSegment;
1370        # Create a hash to receive the feature list. We use a hash so that we can eliminate
1371        # duplicates easily. The hash key will be the feature ID. The value will be the feature's
1372        # ERDBObject from the query.
1373        my %featuresFound = ();
1374        # Create a table of parameters for the queries. Each query looks for features travelling in
1375      # 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,
1376      # 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
1377      # 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 1380 
1380      # Loop through the query parameters.      # Loop through the query parameters.
1381      for my $parms (values %queryParms) {      for my $parms (values %queryParms) {
1382          # Create the query.          # Create the query.
1383          my $query = $self->Get(['IsLocatedIn'],          my $query = $self->Get([qw(Feature IsLocatedIn)],
1384              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
1385              $parms);              $parms);
1386          # Loop through the feature segments found.          # Loop through the feature segments found.
1387          while (my $segment = $query->Fetch) {          while (my $segment = $query->Fetch) {
1388              # Get the data about this segment.              # Get the data about this segment.
1389              my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',              my ($featureID, $contig, $dir, $beg, $len) = $segment->Values([qw(IsLocatedIn(from-link)
1390                  'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);                  IsLocatedIn(to-link) IsLocatedIn(dir) IsLocatedIn(beg) IsLocatedIn(len))]);
1391              # 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
1392              # 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
1393              # 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
1394              # length.              # length.
1395              my ($found, $end) = (0, 0);              my $loc = BasicLocation->new($contig, $beg, $dir, $len);
1396              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;  
                 }  
             }  
1397              if ($found) {              if ($found) {
1398                  # Here we need to record the feature and update the minima and maxima. First,                  # Save this feature in the result list.
1399                  # get the current entry for the specified feature.                  $featuresFound{$featureID} = $segment;
                 my ($loc1, $loc2) = (exists $featuresFound{$featureID} ? @{$featuresFound{$featureID}} :  
                                      @initialMinMax);  
                 # Merge the current segment's begin and end into the feature begin and end and the  
                 # global min and max.  
                 if ($beg < $loc1) {  
                     $loc1 = $beg;  
                     $min = $beg if $beg < $min;  
                 }  
                 if ($end > $loc2) {  
                     $loc2 = $end;  
                     $max = $end if $end > $max;  
                 }  
                 # Store the entry back into the hash table.  
                 $featuresFound{$featureID} = [$loc1, $loc2];  
1400              }              }
1401          }          }
1402      }      }
1403      # Now we must compute the list of the IDs for the features found. We start with a list      # Return the ERDB objects for the features found.
1404      # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,      return values %featuresFound;
     # but the result of the sort will be the same.)  
     my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;  
     # Now we sort by midpoint and yank out the feature IDs.  
     my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;  
     # Return it along with the min and max.  
     return (\@retVal, $min, $max);  
1405  }  }
1406    
1407  =head3 FType  =head3 FType
1408    
1409  C<< my $ftype = $sprout->FType($featureID); >>      my $ftype = $sprout->FType($featureID);
1410    
1411  Return the type of a feature.  Return the type of a feature.
1412    
# Line 1153  Line 1436 
1436    
1437  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1438    
1439  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>      my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag);
1440    
1441  Return the annotations of a feature.  Return the annotations of a feature.
1442    
# Line 1216  Line 1499 
1499    
1500  =head3 AllFunctionsOf  =head3 AllFunctionsOf
1501    
1502  C<< my %functions = $sprout->AllFunctionsOf($featureID); >>      my %functions = $sprout->AllFunctionsOf($featureID);
1503    
1504  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
1505  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 1554 
1554    
1555  =head3 FunctionOf  =head3 FunctionOf
1556    
1557  C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>      my $functionText = $sprout->FunctionOf($featureID, $userID);
1558    
1559  Return the most recently-determined functional assignment of a particular feature.  Return the most recently-determined functional assignment of a particular feature.
1560    
1561  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
1562  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
1563  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.  
1564    
1565  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
1566  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
# Line 1299  Line 1579 
1579    
1580  =item userID (optional)  =item userID (optional)
1581    
1582  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
1583  C<FIG> assignment will be returned.  functional assignment in the B<Feature> table will be returned.
1584    
1585  =item RETURN  =item RETURN
1586    
# Line 1317  Line 1597 
1597      my $retVal;      my $retVal;
1598      # Determine the ID type.      # Determine the ID type.
1599      if ($featureID =~ m/^fig\|/) {      if ($featureID =~ m/^fig\|/) {
1600          # Here we have a FIG feature ID. We must build the list of trusted          # Here we have a FIG feature ID.
1601          # users.          if (!$userID) {
1602                # Use the primary assignment.
1603                ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']);
1604            } else {
1605                # We must build the list of trusted users.
1606          my %trusteeTable = ();          my %trusteeTable = ();
1607          # Check the user ID.          # Check the user ID.
1608          if (!$userID) {          if (!$userID) {
# Line 1361  Line 1645 
1645                  }                  }
1646              }              }
1647          }          }
1648            }
1649      } else {      } else {
1650          # Here we have a non-FIG feature ID. In this case the user ID does not          # Here we have a non-FIG feature ID. In this case the user ID does not
1651          # matter. We simply get the information from the External Alias Function          # matter. We simply get the information from the External Alias Function
# Line 1373  Line 1658 
1658    
1659  =head3 FunctionsOf  =head3 FunctionsOf
1660    
1661  C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>      my @functionList = $sprout->FunctionOf($featureID, $userID);
1662    
1663  Return the functional assignments of a particular feature.  Return the functional assignments of a particular feature.
1664    
# Line 1445  Line 1730 
1730    
1731  =head3 BBHList  =head3 BBHList
1732    
1733  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>      my $bbhHash = $sprout->BBHList($genomeID, \@featureList);
1734    
1735  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
1736  on a specified target genome.  on a specified target genome.
# Line 1476  Line 1761 
1761      my %retVal = ();      my %retVal = ();
1762      # Loop through the incoming features.      # Loop through the incoming features.
1763      for my $featureID (@{$featureList}) {      for my $featureID (@{$featureList}) {
1764          # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1765          my $query = $self->Get(['IsBidirectionalBestHitOf'],          my @bbhData = FIGRules::BBHData($featureID);
                                "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",  
                                [$featureID, $genomeID]);  
1766          # Peel off the BBHs found.          # Peel off the BBHs found.
1767          my @found = ();          my @found = ();
1768          while (my $bbh = $query->Fetch) {          for my $bbh (@bbhData) {
1769              push @found, $bbh->Value('IsBidirectionalBestHitOf(to-link)');              my $fid = $bbh->[0];
1770                my $bbGenome = $self->GenomeOf($fid);
1771                if ($bbGenome eq $genomeID) {
1772                    push @found, $fid;
1773                }
1774          }          }
1775          $retVal{$featureID} = \@found;          $retVal{$featureID} = \@found;
1776      }      }
# Line 1493  Line 1780 
1780    
1781  =head3 SimList  =head3 SimList
1782    
1783  C<< my %similarities = $sprout->SimList($featureID, $count); >>      my %similarities = $sprout->SimList($featureID, $count);
1784    
1785  Return a list of the similarities to the specified feature.  Return a list of the similarities to the specified feature.
1786    
1787  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.  
1788    
1789  =over 4  =over 4
1790    
# Line 1518  Line 1804 
1804      # Get the parameters.      # Get the parameters.
1805      my ($self, $featureID, $count) = @_;      my ($self, $featureID, $count) = @_;
1806      # Ask for the best hits.      # Ask for the best hits.
1807      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);  
1808      # Create the return value.      # Create the return value.
1809      my %retVal = ();      my %retVal = ();
1810      for my $tuple (@lists) {      for my $tuple (@lists) {
# Line 1531  Line 1814 
1814      return %retVal;      return %retVal;
1815  }  }
1816    
   
   
1817  =head3 IsComplete  =head3 IsComplete
1818    
1819  C<< my $flag = $sprout->IsComplete($genomeID); >>      my $flag = $sprout->IsComplete($genomeID);
1820    
1821  Return TRUE if the specified genome is complete, else FALSE.  Return TRUE if the specified genome is complete, else FALSE.
1822    
# Line 1563  Line 1844 
1844      my $genomeData = $self->GetEntity('Genome', $genomeID);      my $genomeData = $self->GetEntity('Genome', $genomeID);
1845      if ($genomeData) {      if ($genomeData) {
1846          # The genome exists, so get the completeness flag.          # The genome exists, so get the completeness flag.
1847          ($retVal) = $genomeData->Value('Genome(complete)');          $retVal = $genomeData->PrimaryValue('Genome(complete)');
1848      }      }
1849      # Return the result.      # Return the result.
1850      return $retVal;      return $retVal;
# Line 1571  Line 1852 
1852    
1853  =head3 FeatureAliases  =head3 FeatureAliases
1854    
1855  C<< my @aliasList = $sprout->FeatureAliases($featureID); >>      my @aliasList = $sprout->FeatureAliases($featureID);
1856    
1857  Return a list of the aliases for a specified feature.  Return a list of the aliases for a specified feature.
1858    
# Line 1594  Line 1875 
1875      # Get the parameters.      # Get the parameters.
1876      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1877      # Get the desired feature's aliases      # Get the desired feature's aliases
1878      my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);      my @retVal = $self->GetFlat(['IsAliasOf'], "IsAliasOf(to-link) = ?", [$featureID], 'IsAliasOf(from-link)');
1879      # Return the result.      # Return the result.
1880      return @retVal;      return @retVal;
1881  }  }
1882    
1883  =head3 GenomeOf  =head3 GenomeOf
1884    
1885  C<< my $genomeID = $sprout->GenomeOf($featureID); >>      my $genomeID = $sprout->GenomeOf($featureID);
1886    
1887  Return the genome that contains a specified feature or contig.  Return the genome that contains a specified feature or contig.
1888    
# Line 1623  Line 1904 
1904  sub GenomeOf {  sub GenomeOf {
1905      # Get the parameters.      # Get the parameters.
1906      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]);  
1907      # Declare the return value.      # Declare the return value.
1908      my $retVal;      my $retVal;
1909      # Get the genome ID.      # Parse the genome ID from the feature ID.
1910      if (my $relationship = $query->Fetch()) {      if ($featureID =~ /^fig\|(\d+\.\d+)/) {
1911          ($retVal) = $relationship->Value('HasContig(from-link)');          $retVal = $1;
1912        } else {
1913            Confess("Invalid feature ID $featureID.");
1914      }      }
1915      # Return the value found.      # Return the value found.
1916      return $retVal;      return $retVal;
# Line 1638  Line 1918 
1918    
1919  =head3 CoupledFeatures  =head3 CoupledFeatures
1920    
1921  C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >>      my %coupleHash = $sprout->CoupledFeatures($featureID);
1922    
1923  Return the features functionally coupled with a specified feature. Features are considered  Return the features functionally coupled with a specified feature. Features are considered
1924  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 1940 
1940  sub CoupledFeatures {  sub CoupledFeatures {
1941      # Get the parameters.      # Get the parameters.
1942      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1943        # Ask the coupling server for the data.
1944      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1945      # Create a query to retrieve the functionally-coupled features.      my @rawPairs = FIGRules::NetCouplingData('coupled_to', id1 => $featureID);
1946      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      Trace(scalar(@rawPairs) . " couplings returned.") if T(coupling => 3);
1947                             "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.  
1948      my %retVal = ();      my %retVal = ();
1949      # Retrieve the relationship records and store them in the hash.      for my $pair (@rawPairs) {
1950      while (my $clustering = $query->Fetch()) {          # Get the feature ID and score.
1951          # Get the ID and score of the coupling.          my ($featureID2, $score) = @{$pair};
1952          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          # Only proceed if the feature is in NMPDR.
1953                                                          'Coupling(score)']);          if ($self->_CheckFeature($featureID2)) {
1954          Trace("$featureID coupled with score $score to ID $couplingID.") if T(coupling => 4);              $retVal{$featureID2} = $score;
1955          # 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;  
1956      }      }
1957      # 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
1958      # the incoming feature as well.      # the incoming feature as well.
1959      if ($found) {      if (keys %retVal) {
1960          $retVal{$featureID} = 9999;          $retVal{$featureID} = 9999;
1961      }      }
1962      # Return the hash.      # Return the hash.
# Line 1694  Line 1965 
1965    
1966  =head3 CouplingEvidence  =head3 CouplingEvidence
1967    
1968  C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>      my @evidence = $sprout->CouplingEvidence($peg1, $peg2);
1969    
1970  Return the evidence for a functional coupling.  Return the evidence for a functional coupling.
1971    
# Line 1742  Line 2013 
2013      my ($self, $peg1, $peg2) = @_;      my ($self, $peg1, $peg2) = @_;
2014      # Declare the return variable.      # Declare the return variable.
2015      my @retVal = ();      my @retVal = ();
2016      # Our first task is to find out the nature of the coupling: whether or not      # Get the coupling and evidence data.
2017      # it exists, its score, and whether the features are stored in the same      my @rawData = FIGRules::NetCouplingData('coupling_evidence', id1 => $peg1, id2 => $peg2);
2018      # order as the ones coming in.      # Loop through the raw data, saving the ones that are in NMPDR genomes.
2019      my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);      for my $rawTuple (@rawData) {
2020      # Only proceed if a coupling exists.          if ($self->_CheckFeature($rawTuple->[0]) && $self->_CheckFeature($rawTuple->[1])) {
2021      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;  
2022  }  }
   
 =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);  
2023      }      }
2024      # Return the result.      # Return the result.
2025      return ($retVal, $inverted, $score);      return @retVal;
2026  }  }
2027    
2028  =head3 GetSynonymGroup  =head3 GetSynonymGroup
2029    
2030  C<< my $id = $sprout->GetSynonymGroup($fid); >>      my $id = $sprout->GetSynonymGroup($fid);
2031    
2032  Return the synonym group name for the specified feature.  Return the synonym group name for the specified feature.
2033    
# Line 1873  Line 2066 
2066    
2067  =head3 GetBoundaries  =head3 GetBoundaries
2068    
2069  C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>      my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList);
2070    
2071  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
2072  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 2128 
2128      return ($contig, $beg, $end);      return ($contig, $beg, $end);
2129  }  }
2130    
 =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);  
 }  
   
2131  =head3 ReadFasta  =head3 ReadFasta
2132    
2133  C<< my %sequenceData = Sprout::ReadFasta($fileName, $prefix); >>      my %sequenceData = Sprout::ReadFasta($fileName, $prefix);
2134    
2135  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
2136  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 2196 
2196    
2197  =head3 FormatLocations  =head3 FormatLocations
2198    
2199  C<< my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat); >>      my @locations = $sprout->FormatLocations($prefix, \@locations, $oldFormat);
2200    
2201  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
2202  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 2261 
2261    
2262  =head3 DumpData  =head3 DumpData
2263    
2264  C<< $sprout->DumpData(); >>      $sprout->DumpData();
2265    
2266  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.
2267    
# Line 2124  Line 2278 
2278    
2279  =head3 XMLFileName  =head3 XMLFileName
2280    
2281  C<< my $fileName = $sprout->XMLFileName(); >>      my $fileName = $sprout->XMLFileName();
2282    
2283  Return the name of this database's XML definition file.  Return the name of this database's XML definition file.
2284    
# Line 2135  Line 2289 
2289      return $self->{_xmlName};      return $self->{_xmlName};
2290  }  }
2291    
2292  =head3 Insert  =head3 GetGenomeNameData
   
 C<< $sprout->Insert($objectType, \%fieldHash); >>  
   
 Insert an entity or relationship instance into the database. The entity or relationship of interest  
 is defined by a type name and then a hash of field names to values. Field values in the primary  
 relation are represented by scalars. (Note that for relationships, the primary relation is  
 the B<only> relation.) Field values for the other relations comprising the entity are always  
 list references. For example, the following line inserts an inactive PEG feature named  
 C<fig|188.1.peg.1> with aliases C<ZP_00210270.1> and C<gi|46206278>.  
   
 C<< $sprout->Insert('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >>  
2293    
2294  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and      my ($genus, $species, $strain) = $sprout->GenomeNameData($genomeID);
 property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.  
2295    
2296  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
2297    is similar to L</GenusSpecies>, with the exception that it returns the
2298    values in three seperate fields.
2299    
2300  =over 4  =over 4
2301    
2302  =item newObjectType  =item genomeID
2303    
2304  Type name of the entity or relationship to insert.  ID of the genome whose name data is desired.
2305    
2306  =item fieldHash  =item RETURN
2307    
2308  Hash of field names to values.  Returns a three-element list, consisting of the genus, species, and strain
2309    of the specified genome. If the genome is not found, an error occurs.
2310    
2311  =back  =back
2312    
2313  =cut  =cut
2314  #: Return Type ;  
2315  sub Insert {  sub GetGenomeNameData {
2316      # Get the parameters.      # Get the parameters.
2317      my ($self, $objectType, $fieldHash) = @_;      my ($self, $genomeID) = @_;
2318      # Call the underlying method.      # Get the desired values.
2319      $self->InsertObject($objectType, $fieldHash);      my ($genus, $species, $strain) = $self->GetEntityValues('Genome', $genomeID =>
2320                                                                [qw(Genome(genus) Genome(species) Genome(unique-characterization))]);
2321        # Throw an error if they were not found.
2322        if (! defined $genus) {
2323            Confess("Genome $genomeID not found in database.");
2324        }
2325        # Return the results.
2326        return ($genus, $species, $strain);
2327  }  }
2328    
2329  =head3 Annotate  =head3 GetGenomeByNameData
2330    
2331  C<< my $ok = $sprout->Annotate($fid, $timestamp, $user, $text); >>      my @genomes = $sprout->GetGenomeByNameData($genus, $species, $strain);
2332    
2333  Annotate a feature. This inserts an Annotation record into the database and links it to the  Return a list of the IDs of the genomes with the specified genus,
2334  specified feature and user.  species, and strain. In almost every case, there will be either zero or
2335    one IDs returned; however, two or more IDs could be returned if there are
2336    multiple versions of the genome in the database.
2337    
2338    =over 4
2339    
2340    =item genus
2341    
2342    Genus of the desired genome.
2343    
2344    =item species
2345    
2346    Species of the desired genome.
2347    
2348    =item strain
2349    
2350    Strain (unique characterization) of the desired genome. This may be an empty
2351    string, in which case it is presumed that the desired genome has no strain
2352    specified.
2353    
2354    =item RETURN
2355    
2356    Returns a list of the IDs of the genomes having the specified genus, species, and
2357    strain.
2358    
2359    =back
2360    
2361    =cut
2362    
2363    sub GetGenomeByNameData {
2364        # Get the parameters.
2365        my ($self, $genus, $species, $strain) = @_;
2366        # Try to find the genomes.
2367        my @retVal = $self->GetFlat(['Genome'], "Genome(genus) = ? AND Genome(species) = ? AND Genome(unique-characterization) = ?",
2368                                    [$genus, $species, $strain], 'Genome(id)');
2369        # Return the result.
2370        return @retVal;
2371    }
2372    
2373    =head3 Insert
2374    
2375        $sprout->Insert($objectType, \%fieldHash);
2376    
2377    Insert an entity or relationship instance into the database. The entity or relationship of interest
2378    is defined by a type name and then a hash of field names to values. Field values in the primary
2379    relation are represented by scalars. (Note that for relationships, the primary relation is
2380    the B<only> relation.) Field values for the other relations comprising the entity are always
2381    list references. For example, the following line inserts an inactive PEG feature named
2382    C<fig|188.1.peg.1> with aliases C<ZP_00210270.1> and C<gi|46206278>.
2383    
2384        $sprout->Insert('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']});
2385    
2386    The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
2387    property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
2388    
2389        $sprout->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'});
2390    
2391    =over 4
2392    
2393    =item newObjectType
2394    
2395    Type name of the entity or relationship to insert.
2396    
2397    =item fieldHash
2398    
2399    Hash of field names to values.
2400    
2401    =back
2402    
2403    =cut
2404    #: Return Type ;
2405    sub Insert {
2406        # Get the parameters.
2407        my ($self, $objectType, $fieldHash) = @_;
2408        # Call the underlying method.
2409        $self->InsertObject($objectType, $fieldHash);
2410    }
2411    
2412    =head3 Annotate
2413    
2414        my $ok = $sprout->Annotate($fid, $timestamp, $user, $text);
2415    
2416    Annotate a feature. This inserts an Annotation record into the database and links it to the
2417    specified feature and user.
2418    
2419  =over 4  =over 4
2420    
# Line 2230  Line 2465 
2465    
2466  =head3 AssignFunction  =head3 AssignFunction
2467    
2468  C<< my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser); >>      my $ok = $sprout->AssignFunction($featureID, $user, $function, $assigningUser);
2469    
2470  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
2471  format is described in L</ParseAssignment>.  format is described in L</ParseAssignment>.
# Line 2290  Line 2525 
2525    
2526  =head3 FeaturesByAlias  =head3 FeaturesByAlias
2527    
2528  C<< my @features = $sprout->FeaturesByAlias($alias); >>      my @features = $sprout->FeaturesByAlias($alias);
2529    
2530  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
2531  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 2559 
2559          push @retVal, $mappedAlias;          push @retVal, $mappedAlias;
2560      } else {      } else {
2561          # 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.
2562          @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');          @retVal = $self->GetFlat(['IsAliasOf'], 'IsAliasOf(from-link) = ?', [$mappedAlias], 'IsAliasOf(to-link)');
2563      }      }
2564      # Return the result.      # Return the result.
2565      return @retVal;      return @retVal;
# Line 2332  Line 2567 
2567    
2568  =head3 FeatureTranslation  =head3 FeatureTranslation
2569    
2570  C<< my $translation = $sprout->FeatureTranslation($featureID); >>      my $translation = $sprout->FeatureTranslation($featureID);
2571    
2572  Return the translation of a feature.  Return the translation of a feature.
2573    
# Line 2360  Line 2595 
2595    
2596  =head3 Taxonomy  =head3 Taxonomy
2597    
2598  C<< my @taxonomyList = $sprout->Taxonomy($genome); >>      my @taxonomyList = $sprout->Taxonomy($genome);
2599    
2600  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
2601  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>,
2602  or C<Eukaryote>) to sub-species. For example,  or C<Eukaryote>) to sub-species. For example,
2603    
2604  C<< (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12) >>      (Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli, Escherichia coli K12)
2605    
2606  =over 4  =over 4
2607    
# Line 2401  Line 2636 
2636    
2637  =head3 CrudeDistance  =head3 CrudeDistance
2638    
2639  C<< my $distance = $sprout->CrudeDistance($genome1, $genome2); >>      my $distance = $sprout->CrudeDistance($genome1, $genome2);
2640    
2641  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
2642  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 2688 
2688    
2689  =head3 RoleName  =head3 RoleName
2690    
2691  C<< my $roleName = $sprout->RoleName($roleID); >>      my $roleName = $sprout->RoleName($roleID);
2692    
2693  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
2694  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 2722 
2722    
2723  =head3 RoleDiagrams  =head3 RoleDiagrams
2724    
2725  C<< my @diagrams = $sprout->RoleDiagrams($roleID); >>      my @diagrams = $sprout->RoleDiagrams($roleID);
2726    
2727  Return a list of the diagrams containing a specified functional role.  Return a list of the diagrams containing a specified functional role.
2728    
# Line 2517  Line 2752 
2752    
2753  =head3 GetProperties  =head3 GetProperties
2754    
2755  C<< my @list = $sprout->GetProperties($fid, $key, $value, $url); >>      my @list = $sprout->GetProperties($fid, $key, $value, $url);
2756    
2757  Return a list of the properties with the specified characteristics.  Return a list of the properties with the specified characteristics.
2758    
2759  Properties are arbitrary key-value pairs associated with a feature. (At some point they  Properties are the Sprout analog of the FIG attributes. The call is
2760  will also be associated with genomes.) A property value is represented by a 4-tuple of  passed directly to the CustomAttributes or RemoteCustomAttributes object
2761  the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter  contained in this object.
2762    
2763  =over 4  This method returns a series of tuples that match the specified criteria. Each tuple
2764    will contain an object ID, a key, and one or more values. The parameters to this
2765    method therefore correspond structurally to the values expected in each tuple. In
2766    addition, you can ask for a generic search by suffixing a percent sign (C<%>) to any
2767    of the parameters. So, for example,
2768    
2769  =item fid      my @attributeList = $sprout->GetProperties('fig|100226.1.peg.1004', 'structure%', 1, 2);
2770    
2771  ID of the feature possessing the property.  would return something like
2772    
2773  =item key      ['fig}100226.1.peg.1004', 'structure', 1, 2]
2774        ['fig}100226.1.peg.1004', 'structure1', 1, 2]
2775        ['fig}100226.1.peg.1004', 'structure2', 1, 2]
2776        ['fig}100226.1.peg.1004', 'structureA', 1, 2]
2777    
2778  Name or key of the property.  Use of C<undef> in any position acts as a wild card (all values). You can also specify
2779    a list reference in the ID column. Thus,
2780    
2781  =item value      my @attributeList = $sprout->GetProperties(['100226.1', 'fig|100226.1.%'], 'PUBMED');
2782    
2783  Value of the property.  would get the PUBMED attribute data for Streptomyces coelicolor A3(2) and all its
2784    features.
2785    
2786  =item url  In addition to values in multiple sections, a single attribute key can have multiple
2787    values, so even
2788    
2789  URL of the document that indicated the property should have this particular value, or an      my @attributeList = $sprout->GetProperties($peg, 'virulent');
 empty string if no such document exists.  
2790    
2791  =back  which has no wildcard in the key or the object ID, may return multiple tuples.
2792    
2793    =over 4
2794    
2795  The parameters act as a filter for the desired data. Any non-null parameter will  =item objectID
 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.  
2796    
2797  A single property key can have many values, representing different ideas about the  ID of object whose attributes are desired. If the attributes are desired for multiple
2798  feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is  objects, this parameter can be specified as a list reference. If the attributes are
2799  virulent, and another may declare that it is not virulent. A query about the virulence of  desired for all objects, specify C<undef> or an empty string. Finally, you can specify
2800  C<fig|83333.1.peg.10> would be coded as  attributes for a range of object IDs by putting a percent sign (C<%>) at the end.
2801    
2802      my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');  =item key
2803    
2804    Attribute key name. A value of C<undef> or an empty string will match all
2805    attribute keys. If the values are desired for multiple keys, this parameter can be
2806    specified as a list reference. Finally, you can specify attributes for a range of
2807    keys by putting a percent sign (C<%>) at the end.
2808    
2809    =item values
2810    
2811    List of the desired attribute values, section by section. If C<undef>
2812    or an empty string is specified, all values in that section will match. A
2813    generic match can be requested by placing a percent sign (C<%>) at the end.
2814    In that case, all values that match up to and not including the percent sign
2815    will match. You may also specify a regular expression enclosed
2816    in slashes. All values that match the regular expression will be returned. For
2817    performance reasons, only values have this extra capability.
2818    
2819  Here the I<$value> and I<$url> fields are left blank, indicating that those fields are  =item RETURN
 not to be filtered. The tuples returned would be  
2820    
2821      ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')  Returns a list of tuples. The first element in the tuple is an object ID, the
2822      ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')  second is an attribute key, and the remaining elements are the sections of
2823    the attribute value. All of the tuples will match the criteria set forth in
2824    the parameter list.
2825    
2826    =back
2827    
2828  =cut  =cut
2829  #: Return Type @@;  
2830  sub GetProperties {  sub GetProperties {
2831      # Get the parameters.      # Get the parameters.
2832      my ($self, @parms) = @_;      my ($self, @parms) = @_;
2833      # Declare the return variable.      # Declare the return variable.
2834      my @retVal = ();      my @retVal = $self->{_ca}->GetAttributes(@parms);
     # 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;  
     }  
2835      # Return the result.      # Return the result.
2836      return @retVal;      return @retVal;
2837  }  }
2838    
2839  =head3 FeatureProperties  =head3 FeatureProperties
2840    
2841  C<< my @properties = $sprout->FeatureProperties($featureID); >>      my @properties = $sprout->FeatureProperties($featureID);
2842    
2843  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
2844  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
2845  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
2846  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
2847  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.  
2848    
2849  =over 4  =over 4
2850    
# Line 2618  Line 2854 
2854    
2855  =item RETURN  =item RETURN
2856    
2857  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.  
2858    
2859  =back  =back
2860    
# Line 2629  Line 2864 
2864      # Get the parameters.      # Get the parameters.
2865      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2866      # Get the properties.      # Get the properties.
2867      my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],      my @attributes = $self->{_ca}->GetAttributes($featureID);
2868                              ['Property(property-name)', 'Property(property-value)',      # Strip the feature ID off each tuple.
2869                               'HasProperty(evidence)']);      my @retVal = ();
2870        for my $attributeRow (@attributes) {
2871            shift @{$attributeRow};
2872            push @retVal, $attributeRow;
2873        }
2874      # Return the resulting list.      # Return the resulting list.
2875      return @retVal;      return @retVal;
2876  }  }
2877    
2878  =head3 DiagramName  =head3 DiagramName
2879    
2880  C<< my $diagramName = $sprout->DiagramName($diagramID); >>      my $diagramName = $sprout->DiagramName($diagramID);
2881    
2882  Return the descriptive name of a diagram.  Return the descriptive name of a diagram.
2883    
# Line 2664  Line 2903 
2903      return $retVal;      return $retVal;
2904  }  }
2905    
2906    =head3 PropertyID
2907    
2908        my $id = $sprout->PropertyID($propName, $propValue);
2909    
2910    Return the ID of the specified property name and value pair, if the
2911    pair exists. Only a small subset of the FIG attributes are stored as
2912    Sprout properties, mostly for use in search optimization.
2913    
2914    =over 4
2915    
2916    =item propName
2917    
2918    Name of the desired property.
2919    
2920    =item propValue
2921    
2922    Value expected for the desired property.
2923    
2924    =item RETURN
2925    
2926    Returns the ID of the name/value pair, or C<undef> if the pair does not exist.
2927    
2928    =back
2929    
2930    =cut
2931    
2932    sub PropertyID {
2933        # Get the parameters.
2934        my ($self, $propName, $propValue) = @_;
2935        # Try to find the ID.
2936        my ($retVal) = $self->GetFlat(['Property'],
2937                                      "Property(property-name) = ? AND Property(property-value) = ?",
2938                                      [$propName, $propValue], 'Property(id)');
2939        # Return the result.
2940        return $retVal;
2941    }
2942    
2943  =head3 MergedAnnotations  =head3 MergedAnnotations
2944    
2945  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>      my @annotationList = $sprout->MergedAnnotations(\@list);
2946    
2947  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
2948  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 2991 
2991    
2992  =head3 RoleNeighbors  =head3 RoleNeighbors
2993    
2994  C<< my @roleList = $sprout->RoleNeighbors($roleID); >>      my @roleList = $sprout->RoleNeighbors($roleID);
2995    
2996  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
2997  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 3034 
3034    
3035  =head3 FeatureLinks  =head3 FeatureLinks
3036    
3037  C<< my @links = $sprout->FeatureLinks($featureID); >>      my @links = $sprout->FeatureLinks($featureID);
3038    
3039  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
3040  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 3065 
3065    
3066  =head3 SubsystemsOf  =head3 SubsystemsOf
3067    
3068  C<< my %subsystems = $sprout->SubsystemsOf($featureID); >>      my %subsystems = $sprout->SubsystemsOf($featureID);
3069    
3070  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
3071  to the roles the feature performs.  to the roles the feature performs.
# Line 2837  Line 3113 
3113    
3114  =head3 SubsystemList  =head3 SubsystemList
3115    
3116  C<< my @subsystems = $sprout->SubsystemList($featureID); >>      my @subsystems = $sprout->SubsystemList($featureID);
3117    
3118  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
3119  feature participates. Unlike L</SubsystemsOf>, this method only returns the  feature participates. Unlike L</SubsystemsOf>, this method only returns the
# Line 2861  Line 3137 
3137      # Get the parameters.      # Get the parameters.
3138      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
3139      # Get the list of names.      # Get the list of names.
3140      my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",      my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?",
3141                                  [$featureID], 'HasSSCell(from-link)');                                  [$featureID], 'HasRoleInSubsystem(to-link)');
3142      # Return the result.      # Return the result, sorted.
3143      return @retVal;      return sort @retVal;
3144  }  }
3145    
3146  =head3 GenomeSubsystemData  =head3 GenomeSubsystemData
3147    
3148  C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>      my %featureData = $sprout->GenomeSubsystemData($genomeID);
3149    
3150  Return a hash mapping genome features to their subsystem roles.  Return a hash mapping genome features to their subsystem roles.
3151    
# Line 2929  Line 3205 
3205    
3206  =head3 RelatedFeatures  =head3 RelatedFeatures
3207    
3208  C<< my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID); >>      my @relatedList = $sprout->RelatedFeatures($featureID, $function, $userID);
3209    
3210  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
3211  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 3238 
3238      # Get the parameters.      # Get the parameters.
3239      my ($self, $featureID, $function, $userID) = @_;      my ($self, $featureID, $function, $userID) = @_;
3240      # 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.
3241      my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
                                      "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],  
                                      'IsBidirectionalBestHitOf(to-link)');  
3242      # 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
3243      # functional assignment.      # functional assignment.
3244      my @retVal = ();      my @retVal = ();
# Line 2982  Line 3256 
3256    
3257  =head3 TaxonomySort  =head3 TaxonomySort
3258    
3259  C<< my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs); >>      my @sortedFeatureIDs = $sprout->TaxonomySort(\@featureIDs);
3260    
3261  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
3262  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 3291 
3291          my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",          my ($taxonomy) = $self->GetFlat(['IsLocatedIn', 'HasContig', 'Genome'], "IsLocatedIn(from-link) = ?",
3292                                          [$fid], 'Genome(taxonomy)');                                          [$fid], 'Genome(taxonomy)');
3293          # Add this feature to the hash buffer.          # Add this feature to the hash buffer.
3294          Tracer::AddToListMap(\%hashBuffer, $taxonomy, $fid);          push @{$hashBuffer{$taxonomy}}, $fid;
3295      }      }
3296      # Sort the keys and get the elements.      # Sort the keys and get the elements.
3297      my @retVal = ();      my @retVal = ();
# Line 3030  Line 3304 
3304    
3305  =head3 Protein  =head3 Protein
3306    
3307  C<< my $protein = Sprout::Protein($sequence, $table); >>      my $protein = Sprout::Protein($sequence, $table);
3308    
3309  Translate a DNA sequence into a protein sequence.  Translate a DNA sequence into a protein sequence.
3310    
# Line 3100  Line 3374 
3374      # Loop through the input triples.      # Loop through the input triples.
3375      my $n = length $sequence;      my $n = length $sequence;
3376      for (my $i = 0; $i < $n; $i += 3) {      for (my $i = 0; $i < $n; $i += 3) {
3377          # Get the current triple from the sequence.          # Get the current triple from the sequence. Note we convert to
3378          my $triple = substr($sequence, $i, 3);          # upper case to insure a match.
3379            my $triple = uc substr($sequence, $i, 3);
3380          # Translate it using the table.          # Translate it using the table.
3381          my $protein = "X";          my $protein = "X";
3382          if (exists $table->{$triple}) { $protein = $table->{$triple}; }          if (exists $table->{$triple}) { $protein = $table->{$triple}; }
# Line 3115  Line 3390 
3390    
3391  =head3 LoadInfo  =head3 LoadInfo
3392    
3393  C<< my ($dirName, @relNames) = $sprout->LoadInfo(); >>      my ($dirName, @relNames) = $sprout->LoadInfo();
3394    
3395  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
3396  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 3409 
3409      return @retVal;      return @retVal;
3410  }  }
3411    
3412    =head3 BBHMatrix
3413    
3414        my %bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets);
3415    
3416    Find all the bidirectional best hits for the features of a genome in a
3417    specified list of target genomes. The return value will be a hash mapping
3418    features in the original genome to their bidirectional best hits in the
3419    target genomes.
3420    
3421    =over 4
3422    
3423    =item genomeID
3424    
3425    ID of the genome whose features are to be examined for bidirectional best hits.
3426    
3427    =item cutoff
3428    
3429    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3430    
3431    =item targets
3432    
3433    List of target genomes. Only pairs originating in the original
3434    genome and landing in one of the target genomes will be returned.
3435    
3436    =item RETURN
3437    
3438    Returns a hash mapping each feature in the original genome to a hash mapping its
3439    BBH pegs in the target genomes to their scores.
3440    
3441    =back
3442    
3443    =cut
3444    
3445    sub BBHMatrix {
3446        # Get the parameters.
3447        my ($self, $genomeID, $cutoff, @targets) = @_;
3448        # Declare the return variable.
3449        my %retVal = ();
3450        # Ask for the BBHs.
3451        my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets);
3452        # We now have a set of 4-tuples that we need to convert into a hash of hashes.
3453        for my $bbhData (@bbhList) {
3454            my ($peg1, $peg2, $score) = @{$bbhData};
3455            if (! exists $retVal{$peg1}) {
3456                $retVal{$peg1} = { $peg2 => $score };
3457            } else {
3458                $retVal{$peg1}->{$peg2} = $score;
3459            }
3460        }
3461        # Return the result.
3462        return %retVal;
3463    }
3464    
3465    
3466    =head3 SimMatrix
3467    
3468        my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets);
3469    
3470    Find all the similarities for the features of a genome in a
3471    specified list of target genomes. The return value will be a hash mapping
3472    features in the original genome to their similarites in the
3473    target genomes.
3474    
3475    =over 4
3476    
3477    =item genomeID
3478    
3479    ID of the genome whose features are to be examined for similarities.
3480    
3481    =item cutoff
3482    
3483    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3484    
3485    =item targets
3486    
3487    List of target genomes. Only pairs originating in the original
3488    genome and landing in one of the target genomes will be returned.
3489    
3490    =item RETURN
3491    
3492    Returns a hash mapping each feature in the original genome to a hash mapping its
3493    similar pegs in the target genomes to their scores.
3494    
3495    =back
3496    
3497    =cut
3498    
3499    sub SimMatrix {
3500        # Get the parameters.
3501        my ($self, $genomeID, $cutoff, @targets) = @_;
3502        # Declare the return variable.
3503        my %retVal = ();
3504        # Get the list of features in the source organism.
3505        my @fids = $self->FeaturesOf($genomeID);
3506        # Ask for the sims. We only want similarities to fig features.
3507        my $simList = FIGRules::GetNetworkSims($self, \@fids, {}, 1000, $cutoff, "fig");
3508        if (! defined $simList) {
3509            Confess("Unable to retrieve similarities from server.");
3510        } else {
3511            Trace("Processing sims.") if T(3);
3512            # We now have a set of sims that we need to convert into a hash of hashes. First, we
3513            # Create a hash for the target genomes.
3514            my %targetHash = map { $_ => 1 } @targets;
3515            for my $simData (@{$simList}) {
3516                # Get the PEGs and the score.
3517                my ($peg1, $peg2, $score) = ($simData->id1, $simData->id2, $simData->psc);
3518                # Insure the second ID is in the target list.
3519                my ($genome2) = FIGRules::ParseFeatureID($peg2);
3520                if (exists $targetHash{$genome2}) {
3521                    # Here it is. Now we need to add it to the return hash. How we do that depends
3522                    # on whether or not $peg1 is new to us.
3523                    if (! exists $retVal{$peg1}) {
3524                        $retVal{$peg1} = { $peg2 => $score };
3525                    } else {
3526                        $retVal{$peg1}->{$peg2} = $score;
3527                    }
3528                }
3529            }
3530        }
3531        # Return the result.
3532        return %retVal;
3533    }
3534    
3535    
3536  =head3 LowBBHs  =head3 LowBBHs
3537    
3538  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>      my %bbhMap = $sprout->LowBBHs($featureID, $cutoff);
3539    
3540  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
3541  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 3564 
3564      my ($self, $featureID, $cutoff) = @_;      my ($self, $featureID, $cutoff) = @_;
3565      # Create the return hash.      # Create the return hash.
3566      my %retVal = ();      my %retVal = ();
3567      # Create a query to get the desired BBHs.      # Query for the desired BBHs.
3568      my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BBHData($featureID, $cutoff);
                                 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',  
                                 [$cutoff, $featureID],  
                                 ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);  
3569      # Form the results into the return hash.      # Form the results into the return hash.
3570      for my $pair (@bbhList) {      for my $pair (@bbhList) {
3571          $retVal{$pair->[0]} = $pair->[1];          my $fid = $pair->[0];
3572            if ($self->Exists('Feature', $fid)) {
3573                $retVal{$fid} = $pair->[1];
3574            }
3575      }      }
3576      # Return the result.      # Return the result.
3577      return %retVal;      return %retVal;
# Line 3180  Line 3579 
3579    
3580  =head3 Sims  =head3 Sims
3581    
3582  C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>      my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters);
3583    
3584  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
3585  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 3589 
3589  Similarities can be either raw or expanded. The raw similarities are basic  Similarities can be either raw or expanded. The raw similarities are basic
3590  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
3591  features considered substantially identical. So, for example, if features B<A1>,  features considered substantially identical. So, for example, if features B<A1>,
3592  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
3593  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]>.
3594    
3595  =over 4  =over 4
3596    
3597  =item fid  =item fid
3598    
3599  ID of the feature whose similarities are desired.  ID of the feature whose similarities are desired, or reference to a list of IDs
3600    of features whose similarities are desired.
3601    
3602  =item maxN  =item maxN
3603    
# Line 3243  Line 3643 
3643      return $retVal;      return $retVal;
3644  }  }
3645    
3646    =head3 IsAllGenomes
3647    
3648        my $flag = $sprout->IsAllGenomes(\@list, \@checkList);
3649    
3650    Return TRUE if all genomes in the second list are represented in the first list at
3651    least one. Otherwise, return FALSE. If the second list is omitted, the first list is
3652    compared to a list of all the genomes.
3653    
3654    =over 4
3655    
3656    =item list
3657    
3658    Reference to the list to be compared to the second list.
3659    
3660    =item checkList (optional)
3661    
3662    Reference to the comparison target list. Every genome ID in this list must occur at
3663    least once in the first list. If this parameter is omitted, a list of all the genomes
3664    is used.
3665    
3666    =item RETURN
3667    
3668    Returns TRUE if every item in the second list appears at least once in the
3669    first list, else FALSE.
3670    
3671    =back
3672    
3673    =cut
3674    
3675    sub IsAllGenomes {
3676        # Get the parameters.
3677        my ($self, $list, $checkList) = @_;
3678        # Supply the checklist if it was omitted.
3679        $checkList = [$self->Genomes()] if ! defined($checkList);
3680        # Create a hash of the original list.
3681        my %testList = map { $_ => 1 } @{$list};
3682        # Declare the return variable. We assume that the representation
3683        # is complete and stop at the first failure.
3684        my $retVal = 1;
3685        my $n = scalar @{$checkList};
3686        for (my $i = 0; $retVal && $i < $n; $i++) {
3687            if (! $testList{$checkList->[$i]}) {
3688                $retVal = 0;
3689            }
3690        }
3691        # Return the result.
3692        return $retVal;
3693    }
3694    
3695  =head3 GetGroups  =head3 GetGroups
3696    
3697  C<< my %groups = $sprout->GetGroups(\@groupList); >>      my %groups = $sprout->GetGroups(\@groupList);
3698    
3699  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.
3700  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 3713 
3713          # Here we have a group list. Loop through them individually,          # Here we have a group list. Loop through them individually,
3714          # getting a list of the relevant genomes.          # getting a list of the relevant genomes.
3715          for my $group (@{$groupList}) {          for my $group (@{$groupList}) {
3716              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3717                  [$group], "Genome(id)");                  [$group], "Genome(id)");
3718              $retVal{$group} = \@genomeIDs;              $retVal{$group} = \@genomeIDs;
3719          }          }
# Line 3272  Line 3721 
3721          # 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
3722          # of the genome records, putting each one found into the appropriate          # of the genome records, putting each one found into the appropriate
3723          # 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
3724          # in groups are included in the return set.          # in real NMPDR groups are included in the return set.
3725          my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],          my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3726                                      ['Genome(id)', 'Genome(group-name)']);                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3727          # Loop through the genomes found.          # Loop through the genomes found.
3728          for my $genome (@genomes) {          for my $genome (@genomes) {
3729              # Pop this genome's ID off the current list.              # Get the genome ID and group, and add this genome to the group's list.
3730              my @groups = @{$genome};              my ($genomeID, $group) = @{$genome};
3731              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);  
             }  
3732          }          }
3733      }      }
3734      # Return the hash we just built.      # Return the hash we just built.
# Line 3293  Line 3737 
3737    
3738  =head3 MyGenomes  =head3 MyGenomes
3739    
3740  C<< my @genomes = Sprout::MyGenomes($dataDir); >>      my @genomes = Sprout::MyGenomes($dataDir);
3741    
3742  Return a list of the genomes to be included in the Sprout.  Return a list of the genomes to be included in the Sprout.
3743    
# Line 3325  Line 3769 
3769    
3770  =head3 LoadFileName  =head3 LoadFileName
3771    
3772  C<< my $fileName = Sprout::LoadFileName($dataDir, $tableName); >>      my $fileName = Sprout::LoadFileName($dataDir, $tableName);
3773    
3774  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
3775  directory.  directory.
# Line 3366  Line 3810 
3810    
3811  =head3 DeleteGenome  =head3 DeleteGenome
3812    
3813  C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>      my $stats = $sprout->DeleteGenome($genomeID, $testFlag);
3814    
3815  Delete a genome from the database.  Delete a genome from the database.
3816    
# Line 3392  Line 3836 
3836      # Get the parameters.      # Get the parameters.
3837      my ($self, $genomeID, $testFlag) = @_;      my ($self, $genomeID, $testFlag) = @_;
3838      # Perform the delete for the genome's features.      # Perform the delete for the genome's features.
3839      my $retVal = $self->Delete('Feature', "fig|$genomeID.%", $testFlag);      my $retVal = $self->Delete('Feature', "fig|$genomeID.%", testMode => $testFlag);
3840      # Perform the delete for the primary genome data.      # Perform the delete for the primary genome data.
3841      my $stats = $self->Delete('Genome', $genomeID, $testFlag);      my $stats = $self->Delete('Genome', $genomeID, testMode => $testFlag);
3842      $retVal->Accumulate($stats);      $retVal->Accumulate($stats);
3843      # Return the result.      # Return the result.
3844      return $retVal;      return $retVal;
3845  }  }
3846    
3847    =head3 Fix
3848    
3849        my %fixedHash = $sprout->Fix(%groupHash);
3850    
3851    Prepare a genome group hash (like that returned by L</GetGroups>) for processing.
3852    The groups will be combined into the appropriate super-groups.
3853    
3854    =over 4
3855    
3856    =item groupHash
3857    
3858    Hash to be fixed up.
3859    
3860    =item RETURN
3861    
3862    Returns a fixed-up version of the hash.
3863    
3864    =back
3865    
3866    =cut
3867    
3868    sub Fix {
3869        # Get the parameters.
3870        my ($self, %groupHash) = @_;
3871        # Create the result hash.
3872        my %retVal = ();
3873        # Copy over the genomes.
3874        for my $groupID (keys %groupHash) {
3875            # Get the super-group name.
3876            my $realGroupID = $self->SuperGroup($groupID);
3877            # Append this group's genomes into the result hash
3878            # using the super-group name.
3879            push @{$retVal{$realGroupID}}, @{$groupHash{$groupID}};
3880        }
3881        # Return the result hash.
3882        return %retVal;
3883    }
3884    
3885    =head3 GroupPageName
3886    
3887        my $name = $sprout->GroupPageName($group);
3888    
3889    Return the name of the page for the specified NMPDR group.
3890    
3891    =over 4
3892    
3893    =item group
3894    
3895    Name of the relevant group.
3896    
3897    =item RETURN
3898    
3899    Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3900    memory it will be read in.
3901    
3902    =back
3903    
3904    =cut
3905    
3906    sub GroupPageName {
3907        # Get the parameters.
3908        my ($self, $group) = @_;
3909        # Check for the group file data.
3910        my %superTable = $self->CheckGroupFile();
3911        # Compute the real group name.
3912        my $realGroup = $self->SuperGroup($group);
3913        # Get the associated page name.
3914        my $retVal = "../content/$superTable{$realGroup}->{page}";
3915        # Return the result.
3916        return $retVal;
3917    }
3918    
3919    
3920    =head3 AddProperty
3921    
3922        $sprout->AddProperty($featureID, $key, @values);
3923    
3924    Add a new attribute value (Property) to a feature.
3925    
3926    =over 4
3927    
3928    =item peg
3929    
3930    ID of the feature to which the attribute is to be added.
3931    
3932    =item key
3933    
3934    Name of the attribute (key).
3935    
3936    =item values
3937    
3938    Values of the attribute.
3939    
3940    =back
3941    
3942    =cut
3943    #: Return Type ;
3944    sub AddProperty {
3945        # Get the parameters.
3946        my ($self, $featureID, $key, @values) = @_;
3947        # Add the property using the attached attributes object.
3948        $self->{_ca}->AddAttribute($featureID, $key, @values);
3949    }
3950    
3951    =head3 CheckGroupFile
3952    
3953        my %groupData = $sprout->CheckGroupFile();
3954    
3955    Get the group file hash. The group file hash describes the relationship
3956    between a group and the super-group to which it belongs for purposes of
3957    display. The super-group name is computed from the first capitalized word
3958    in the actual group name. For each super-group, the group file contains
3959    the page name and a list of the species expected to be in the group.
3960    Each species is specified by a genus and a species name. A species name
3961    of C<0> implies an entire genus.
3962    
3963    This method returns a hash from super-group names to a hash reference. Each
3964    resulting hash reference contains the following fields.
3965    
3966    =over 4
3967    
3968    =item page
3969    
3970    The super-group's web page in the NMPDR.
3971    
3972    =item contents
3973    
3974    A list of 2-tuples, each containing a genus name followed by a species name
3975    (or 0, indicating all species). This list indicates which organisms belong
3976    in the super-group.
3977    
3978    =back
3979    
3980    =cut
3981    
3982    sub CheckGroupFile {
3983        # Get the parameters.
3984        my ($self) = @_;
3985        # Check to see if we already have this hash.
3986        if (! defined $self->{groupHash}) {
3987            # We don't, so we need to read it in.
3988            my %groupHash;
3989            # Read the group file.
3990            my @groupLines = Tracer::GetFile("$FIG_Config::sproutData/groups.tbl");
3991            # Loop through the list of sort-of groups.
3992            for my $groupLine (@groupLines) {
3993                my ($name, $page, @contents) = split /\t/, $groupLine;
3994                $groupHash{$name} = { page => $page,
3995                                      contents => [ map { [ split /\s*,\s*/, $_ ] } @contents ]
3996                                    };
3997            }
3998            # Save the hash.
3999            $self->{groupHash} = \%groupHash;
4000        }
4001        # Return the result.
4002        return %{$self->{groupHash}};
4003    }
4004    
4005    =head2 Virtual Methods
4006    
4007    =head3 CleanKeywords
4008    
4009        my $cleanedString = $sprout->CleanKeywords($searchExpression);
4010    
4011    Clean up a search expression or keyword list. This involves converting the periods
4012    in EC numbers to underscores, converting non-leading minus signs to underscores,
4013    a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
4014    characters. In addition, any extra spaces are removed.
4015    
4016    =over 4
4017    
4018    =item searchExpression
4019    
4020    Search expression or keyword list to clean. Note that a search expression may
4021    contain boolean operators which need to be preserved. This includes leading
4022    minus signs.
4023    
4024    =item RETURN
4025    
4026    Cleaned expression or keyword list.
4027    
4028    =back
4029    
4030    =cut
4031    
4032    sub CleanKeywords {
4033        # Get the parameters.
4034        my ($self, $searchExpression) = @_;
4035        # Perform the standard cleanup.
4036        my $retVal = $self->ERDB::CleanKeywords($searchExpression);
4037        # Fix the periods in EC and TC numbers.
4038        $retVal =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g;
4039        # Fix non-trailing periods.
4040        $retVal =~ s/\.(\w)/_$1/g;
4041        # Fix non-leading minus signs.
4042        $retVal =~ s/(\w)[\-]/$1_/g;
4043        # Fix the vertical bars and colons
4044        $retVal =~ s/(\w)[|:](\w)/$1'$2/g;
4045        # Return the result.
4046        return $retVal;
4047    }
4048    
4049  =head2 Internal Utility Methods  =head2 Internal Utility Methods
4050    
4051  =head3 ParseAssignment  =head3 ParseAssignment
# Line 3410  Line 4056 
4056    
4057  A functional assignment is always of the form  A functional assignment is always of the form
4058    
4059      C<set >I<YYYY>C< function to\n>I<ZZZZZ>      set YYYY function to
4060        ZZZZ
4061    
4062  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,
4063  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 3463  Line 4110 
4110      return @retVal;      return @retVal;
4111  }  }
4112    
4113  =head3 FriendlyTimestamp  =head3 _CheckFeature
4114    
4115  Convert a time number to a user-friendly time stamp for display.      my $flag = $sprout->_CheckFeature($fid);
4116    
4117  This is a static method.  Return TRUE if the specified FID is probably an NMPDR feature ID, else FALSE.
4118    
4119  =over 4  =over 4
4120    
4121  =item timeValue  =item fid
4122    
4123  Numeric time value.  Feature ID to check.
4124    
4125  =item RETURN  =item RETURN
4126    
4127  Returns a string containing the same time in user-readable format.  Returns TRUE if the FID is for one of the NMPDR genomes, else FALSE.
4128    
4129  =back  =back
4130    
4131  =cut  =cut
4132    
4133  sub FriendlyTimestamp {  sub _CheckFeature {
4134      my ($timeValue) = @_;      # Get the parameters.
4135      my $retVal = localtime($timeValue);      my ($self, $fid) = @_;
4136      return $retVal;      # Insure we have a genome hash.
4137        if (! defined $self->{genomeHash}) {
4138            my %genomeHash = map { $_ => 1 } $self->GetFlat(['Genome'], "", [], 'Genome(id)');
4139            $self->{genomeHash} = \%genomeHash;
4140        }
4141        # Get the feature's genome ID.
4142        my ($genomeID) = FIGRules::ParseFeatureID($fid);
4143        # Return an indicator of whether or not the genome ID is in the hash.
4144        return ($self->{genomeHash}->{$genomeID} ? 1 : 0);
4145  }  }
4146    
4147  =head3 AddProperty  =head3 FriendlyTimestamp
4148    
4149  C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>  Convert a time number to a user-friendly time stamp for display.
4150    
4151  Add a new attribute value (Property) to a feature. In the SEED system, attributes can  This is a static method.
 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.  
4152    
4153  =over 4  =over 4
4154    
4155  =item peg  =item timeValue
   
 ID of the feature to which the attribute is to be replied.  
   
 =item key  
   
 Name of the attribute (key).  
   
 =item value  
4156    
4157  Value of the attribute.  Numeric time value.
4158    
4159  =item url  =item RETURN
4160    
4161  URL or text citation from which the property was obtained.  Returns a string containing the same time in user-readable format.
4162    
4163  =back  =back
4164    
4165  =cut  =cut
4166  #: Return Type ;  
4167  sub AddProperty {  sub FriendlyTimestamp {
4168      # Get the parameters.      my ($timeValue) = @_;
4169      my ($self, $featureID, $key, $value, $url) = @_;      my $retVal = localtime($timeValue);
4170      # Declare the variable to hold the desired property ID.      return $retVal;
     my $propID;  
     # Attempt to find a property record for this key/value pair.  
     my @properties = $self->GetFlat(['Property'],  
                                    "Property(property-name) = ? AND Property(property-value) = ?",  
                                    [$key, $value], 'Property(id)');  
     if (@properties) {  
         # Here the property is already in the database. We save its ID.  
         $propID = $properties[0];  
         # Here the property value does not exist. We need to generate an ID. It will be set  
         # to a number one greater than the maximum value in the database. This call to  
         # GetAll will stop after one record.  
         my @maxProperty = $self->GetAll(['Property'], "ORDER BY Property(id) DESC", [], ['Property(id)'],  
                                         1);  
         $propID = $maxProperty[0]->[0] + 1;  
         # Insert the new property value.  
         $self->Insert('Property', { 'property-name' => $key, 'property-value' => $value, id => $propID });  
     }  
     # Now we connect the incoming feature to the property.  
     $self->Insert('HasProperty', { 'from-link' => $featureID, 'to-link' => $propID, evidence => $url });  
4171  }  }
4172    
4173    

Legend:
Removed from v.1.81  
changed lines
  Added in v.1.110

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3