[Bio] / Sprout / Sprout.pm Repository:
ViewVC logotype

View of /Sprout/Sprout.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.21 - (download) (as text) (annotate)
Fri Sep 9 20:40:41 2005 UTC (14 years ago) by parrello
Branch: MAIN
Changes since 1.20: +2 -0 lines
Added trace messages for Coupling.

package Sprout;

    use Data::Dumper;
    use strict;
    use Carp;
    use DBKernel;
    use XML::Simple;
    use DBQuery;
    use DBObject;
    use ERDB;
    use Tracer;
    use FIGRules;
    use Stats;
    use POSIX qw(strftime);


=head1 Sprout Database Manipulation Object

=head2 Introduction

This object enables the user to load and query the Sprout genome database using a few simple methods.
To construct the object, specify the name of the database. By default, the database is assumed to be a
MySQL database accessed via the user ID I<root> with no password and the database definition will
be in a file called F<SproutDBD.xml>. All of these defaults can be overridden
on the constructor. For example, the following invocation specifies a PostgreSQL database named I<GenDB>
whose definition and data files are in a co-directory named F<Data>.

C<< my $sprout = Sprout->new('GenDB', { dbType => 'pg', dataDir => '../Data', xmlFileName => '../Data/SproutDBD.xml' }); >>

Once you have a sprout object, you may use it to re-create the database, load the tables from
tab-delimited flat files and perform queries. Several special methods are provided for common
query tasks. For example, L</genomes> lists the IDs of all the genomes in the database and
L</dna_seq> returns the DNA sequence for a specified genome location.

=cut

#: Constructor SFXlate->new_sprout_only();

=head2 Public Methods

=head3 new

C<< my $sprout = Sprout->new($dbName, \%options); >>

This is the constructor for a sprout object. It connects to the database and loads the
database definition into memory. The positional first parameter specifies the name of the
database.

=over 4

=item dbName

Name of the database.

=item options

Table of options.

* B<dbType> type of database (currently C<mysql> for MySQL and C<pg> for PostgreSQL) (default C<mysql>)

* B<dataDir> directory containing the database definition file and the flat files used to load the data (default C<Data>)

* B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)

* B<userData> user name and password, delimited by a slash (default C<root/>)

* B<port> connection port (default C<0>)

* B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)

* B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)

=back

For example, the following constructor call specifies a database named I<Sprout> and a user name of
I<fig> with a password of I<admin>. The database load files are in the directory
F</usr/fig/SproutData>.

C<< my $sprout = Sprout->new('Sprout', { userData =>; 'fig/admin', dataDir => '/usr/fig/SproutData' }); >>

=cut

sub new {
    # Get the parameters.
    my ($class, $dbName, $options) = @_;
    # Compute the options. We do this by starting with a table of defaults and overwriting with
    # the incoming data.
    my $optionTable = Tracer::GetOptions({
                       dbType       => $FIG_Config::dbms,
                                                        # database type
                       dataDir      => $FIG_Config::sproutData,
                                                        # data file directory
                       xmlFileName  => "$FIG_Config::sproutData/SproutDBD.xml",
                                                        # database definition file name
                       userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
                                                        # user name and password
                       port         => $FIG_Config::dbport,
                                                        # database connection port
                       maxSegmentLength => 4500,        # maximum feature segment length
                       maxSequenceLength => 8000,       # maximum contig sequence length
                      }, $options);
    # Get the data directory.
    my $dataDir = $optionTable->{dataDir};
    # Extract the user ID and password.
    $optionTable->{userData} =~ m!([^/]*)/(.*)$!;
    my ($userName, $password) = ($1, $2);
    # Connect to the database.
    my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port});
    # Create the ERDB object.
    my $xmlFileName = "$optionTable->{xmlFileName}";
    my $erdb = ERDB->new($dbh, $xmlFileName);
    # Create this object.
    my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };
    # Bless and return it.
    bless $self;
    return $self;
}

=head3 MaxSegment

C<< my $length = $sprout->MaxSegment(); >>

This method returns the maximum permissible length of a feature segment. The length is important
because it enables us to make reasonable guesses at how to find features inside a particular
contig region. For example, if the maximum length is 4000 and we're looking for a feature that
overlaps the region from 6000 to 7000 we know that the starting position must be between 2001
and 10999.

=cut
#: Return Type $;
sub MaxSegment {
    my ($self) = @_;
    return $self->{_options}->{maxSegmentLength};
}

=head3 MaxSequence

C<< my $length = $sprout->MaxSequence(); >>

This method returns the maximum permissible length of a contig sequence. A contig is broken
into sequences in order to save memory resources. In particular, when manipulating features,
we generally only need a few sequences in memory rather than the entire contig.

=cut
#: Return Type $;
sub MaxSequence {
    my ($self) = @_;
    return $self->{_options}->{maxSequenceLength};
}

=head3 Get

C<< my $query = $sprout->Get(\@objectNames, $filterClause, \@parameterList); >>

This method allows a general query against the Sprout data using a specified filter clause.

The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each
field name represented in the form B<I<objectName>(I<fieldName>)>. For example, the
following call requests all B<Genome> objects for the genus specified in the variable
$genus.

C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>

The WHERE clause contains a single question mark, so there is a single additional
parameter representing the parameter value. It would also be possible to code

C<< $query = $sprout->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>

however, this version of the call would generate a syntax error if there were any quote
characters inside the variable C<$genus>.

The use of the strange parenthesized notation for field names enables us to distinguish
hyphens contained within field names from minus signs that participate in the computation
of the WHERE clause. All of the methods that manipulate fields will use this same notation.

It is possible to specify multiple entity and relationship names in order to retrieve more than
one object's data at the same time, which allows highly complex joined queries. For example,

C<< $query = $sprout->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>

This query returns all the genomes for a particular genus and allows access to the
sources from which they came. The join clauses to go from Genome to Source are generated
automatically.

Finally, the filter clause can contain sort information. To do this, simply put an C<ORDER BY>
clause at the end of the filter. Field references in the ORDER BY section follow the same rules
as they do in the filter itself; in other words, each one must be of the form B<I<objectName>(I<fieldName>)>.
For example, the following filter string gets all genomes for a particular genus and sorts
them by species name.

C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ? ORDER BY Genome(species)", [$genus]); >>

It is also permissible to specify I<only> an ORDER BY clause. For example, the following invocation gets
all genomes ordered by genus and species.

C<< $query = $sprout->Get(['Genome'], "ORDER BY Genome(genus), Genome(species)"); >>

Odd things may happen if one of the ORDER BY fields is in a secondary relation. So, for example, an
attempt to order B<Feature>s by alias may (depending on the underlying database engine used) cause
a single feature to appear more than once.

If multiple names are specified, then the query processor will automatically determine a
join path between the entities and relationships. The algorithm used is very simplistic.
In particular, you can't specify any entity or relationship more than once, and if a
relationship is recursive, the path is determined by the order in which the entity
and the relationship appear. For example, consider a recursive relationship B<IsParentOf>
which relates B<People> objects to other B<People> objects. If the join path is
coded as C<['People', 'IsParentOf']>, then the people returned will be parents. If, however,
the join path is C<['IsParentOf', 'People']>, then the people returned will be children.

=over 4

=item objectNames

List containing the names of the entity and relationship objects to be retrieved.

=item filterClause

WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
parameter list as additional parameters. The fields in a filter clause can come from primary
entity relations, relationship relations, or secondary entity relations; however, all of the
entities and relationships involved must be included in the list of object names.

=item parameterList

List of the parameters to be substituted in for the parameters marks in the filter clause.

=item RETURN

Returns a B<DBQuery> that can be used to iterate through all of the results.

=back

=cut

sub Get {
    # Get the parameters.
    my ($self, $objectNames, $filterClause, $parameterList) = @_;
    # We differ from the ERDB Get method in that the parameter list is passed in as a list reference
    # rather than a list of parameters. The next step is to convert the parameters from a reference
    # to a real list. We can only do this if the parameters have been specified.
    my @parameters;
    if ($parameterList) { @parameters = @{$parameterList}; }
    return $self->{_erdb}->Get($objectNames, $filterClause, @parameters);
}

=head3 GetEntity

C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>

Return an object describing the entity instance with a specified ID.

=over 4

=item entityType

Entity type name.

=item ID

ID of the desired entity.

=item RETURN

Returns a B<DBObject> representing the desired entity instance, or an undefined value if no
instance is found with the specified key.

=back

=cut

sub GetEntity {
    # Get the parameters.
    my ($self, $entityType, $ID) = @_;
    # Call the ERDB method.
    return $self->{_erdb}->GetEntity($entityType, $ID);
}

=head3 GetEntityValues

C<< my @values = GetEntityValues($entityType, $ID, \@fields); >>

Return a list of values from a specified entity instance.

=over 4

=item entityType

Entity type name.

=item ID

ID of the desired entity.

=item fields

List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.

=item RETURN

Returns a flattened list of the values of the specified fields for the specified entity.

=back

=cut
#: Return Type @;
sub GetEntityValues {
    # Get the parameters.
    my ($self, $entityType, $ID, $fields) = @_;
    # Call the ERDB method.
    return $self->{_erdb}->GetEntityValues($entityType, $ID, $fields);
}

=head3 ShowMetaData

C<< $sprout->ShowMetaData($fileName); >>

This method outputs a description of the database to an HTML file in the data directory.

=over 4

=item fileName

Fully-qualified name to give to the output file.

=back

=cut

sub ShowMetaData {
    # Get the parameters.
    my ($self, $fileName) = @_;
    # Compute the file name.
    my $options = $self->{_options};
    # Call the show method on the underlying ERDB object.
    $self->{_erdb}->ShowMetaData($fileName);
}

=head3 Load

C<< $sprout->Load($rebuild); >>;

Load the database from files in the data directory, optionally re-creating the tables.

This method always deletes the data from the database before loading, even if the tables are not
re-created. The data is loaded into the relations from files in the data directory either having the
same name as the target relation with no extension or with an extension of C<.dtx>. Files without an
extension are used in preference to the files with an extension.

The files are loaded based on the presumption that each line of the file is a record in the
relation, and the individual fields are delimited by tabs. Tab and new-line characters inside
fields must be represented by the escape sequences C<\t> and C<\n>, respectively. The fields must
be presented in the order given in the relation tables produced by the L</ShowMetaData> method.

=over 4

=item rebuild

TRUE if the data tables need to be created or re-created, else FALSE

=item RETURN

Returns a statistical object containing the number of records read, the number of duplicates found,
the number of errors, and a list of the error messages.

=back

=cut
#: Return Type %;
sub Load {
    # Get the parameters.
    my ($self, $rebuild) = @_;
    # Get the database object.
    my $erdb = $self->{_erdb};
    # Load the tables from the data directory.
    my $retVal = $erdb->LoadTables($self->{_options}->{dataDir}, $rebuild);
    # Return the statistics.
    return $retVal;
}

=head3 LoadUpdate

C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>

Load updates to one or more database tables. This method enables the client to make changes to one
or two tables without reloading the whole database. For each table, there must be a corresponding
file in the data directory, either with the same name as the table, or with a C<.dtx> suffix. So,
for example, to make updates to the B<FeatureTranslation> relation, there must be a
C<FeatureTranslation.dtx> file in the data directory. Unlike a full load, files without an extension
are not examined. This allows update files to co-exist with files from an original load.

=over 4

=item truncateFlag

TRUE if the tables should be rebuilt before loading, else FALSE. A value of TRUE therefore causes
current data and schema of the tables to be replaced, while a value of FALSE means the new data
is added to the existing data in the various relations.

=item tableList

List of the tables to be updated.

=item RETURN

Returns a statistical object containing the number of records read, the number of duplicates found,
the number of errors encountered, and a list of error messages.

=back

=cut
#: Return Type $%;
sub LoadUpdate {
    # Get the parameters.
    my ($self, $truncateFlag, $tableList) = @_;
    # Get the database object.
    my $erdb = $self->{_erdb};
    # Declare the return value.
    my $retVal = Stats->new();
    # Get the data directory.
    my $optionTable = $self->{_options};
    my $dataDir = $optionTable->{dataDir};
    # Loop through the incoming table names.
    for my $tableName (@{$tableList}) {
        # Find the table's file.
        my $fileName = LoadFileName($dataDir, $tableName);
        if (! $fileName) {
            Trace("No load file found for $tableName in $dataDir.") if T(0);
        } else {
            # Attempt to load this table.
            my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);
            # Accumulate the resulting statistics.
            $retVal->Accumulate($result);
        }
    }
    # Return the statistics.
    return $retVal;
}

=head3 Build

C<< $sprout->Build(); >>

Build the database. The database will be cleared and the tables re-created from the metadata.
This method is useful when a database is brand new or when the database definition has
changed.

=cut
#: Return Type ;
sub Build {
    # Get the parameters.
    my ($self) = @_;
    # Create the tables.
    $self->{_erdb}->CreateTables;
}

=head3 Genomes

C<< my @genomes = $sprout->Genomes(); >>

Return a list of all the genome IDs.

=cut
#: Return Type @;
sub Genomes {
    # Get the parameters.
    my ($self) = @_;
    # Get all the genomes.
    my @retVal = $self->GetFlat(['Genome'], "", [], 'Genome(id)');
    # Return the list of IDs.
    return @retVal;
}

=head3 GenusSpecies

C<< my $infoString = $sprout->GenusSpecies($genomeID); >>

Return the genus, species, and unique characterization for a genome.

=over 4

=item genomeID

ID of the genome whose genus and species is desired

=item RETURN

Returns the genus and species of the genome, with the unique characterization (if any). If the genome
does not exist, returns an undefined value.

=back

=cut
#: Return Type $;
sub GenusSpecies {
    # Get the parameters.
    my ($self, $genomeID) = @_;
    # Get the data for the specified genome.
    my @values = $self->GetEntityValues('Genome', $genomeID, ['Genome(genus)', 'Genome(species)',
                                                              'Genome(unique-characterization)']);
    # Format the result and return it.
    my $retVal = join(' ', @values);
    return $retVal;
}

=head3 FeaturesOf

C<< my @features = $sprout->FeaturesOf($genomeID, $ftype); >>

Return a list of the features relevant to a specified genome.

=over 4

=item genomeID

Genome whose features are desired.

=item ftype

Type of feature desired. If omitted, all features will be returned.

=item RETURN

Returns a list of the feature IDs for features relevant to the genome. If the genome does not exist,
will return an empty list.

=back

=cut
#: Return Type @;
sub FeaturesOf {
    # Get the parameters.
    my ($self, $genomeID,$ftype) = @_;
    # Get the features we want.
    my @features;
    if (!$ftype) {
        @features = $self->GetFlat(['HasContig', 'IsLocatedIn'], "HasContig(from-link) = ?",
                                   [$genomeID], 'IsLocatedIn(from-link)');
    } else {
        @features = $self->GetFlat(['HasContig', 'IsLocatedIn', 'Feature'],
                            "HasContig(from-link) = ? AND Feature(feature-type) = ?",
                            [$genomeID, $ftype], 'IsLocatedIn(from-link)');
    }
    # Return the list with duplicates merged out. We need to merge out duplicates because
    # a feature will appear twice if it spans more than one contig.
    my @retVal = Tracer::Merge(@features);
    # Return the list of feature IDs.
    return @retVal;
}

=head3 FeatureLocation

C<< my @locations = $sprout->FeatureLocation($featureID); >>

Return the location of a feature in its genome's contig segments. In a list context, this method
will return a list of the locations. In a scalar context, it will return the locations as a space-
delimited string. Each location will be of the form I<contigID>C<_>I<begin>I<dir>I<len> where
I<begin> is the starting position, I<dir> is C<+> for a forward transcription or C<-> for a backward
transcription, and I<len> is the length. So, for example, C<1999.1_NC123_4000+200> describes a location
beginning at position 4000 of contig C<1999.1_NC123> and ending at position 4199. Similarly,
C<1999.1_NC123_2000-400> describes a location in the same contig starting at position 2000 and ending
at position 1601.

This process is complicated by the fact that we automatically split up feature segments longer than
the maximum segment length. When we find two segments that are adjacent to each other, we must
put them back together.

=over 4

=item featureID

FIG ID of the desired feature

=item RETURN

Returns a list of the feature's contig segments. The locations are returned as a list in a list
context and as a comma-delimited string in a scalar context.

=back

=cut
#: Return Type @;
#: Return Type $;
sub FeatureLocation {
    # Get the parameters.
    my ($self, $featureID) = @_;
    # Create a query for the feature locations.
    my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",
                           [$featureID]);
    # Create the return list.
    my @retVal = ();
    # Set up the variables used to determine if we have adjacent segments. This initial setup will
    # not match anything.
    my ($prevContig, $prevBeg, $prevDir, $prevLen) = ("", 0, "0", 0);
    # Loop through the query results, creating location specifiers.
    while (my $location = $query->Fetch()) {
        # Get the location parameters.
        my ($contigID, $beg, $dir, $len) = $location->Values(['IsLocatedIn(to-link)',
            'IsLocatedIn(beg)', 'IsLocatedIn(dir)', 'IsLocatedIn(len)']);
        # 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 == $prevBeg - $prevLen) ||
                ($dir eq "+" && $beg == $prevBeg + $prevLen)) {
                # Here we need to merge two segments. 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);
        # Add the specifier to the list.
        push @retVal, "${contigID}_$beg$dir$len";
    }
    # Return the list in the format indicated by the context.
    return (wantarray ? @retVal : join(',', @retVal));
}

=head3 ParseLocation

C<< my ($contigID, $start, $dir, $len) = Sprout::ParseLocation($location); >>

Split a location specifier into the contig ID, the starting point, the direction, and the
length.

=over 4

=item location

A location specifier (see L</FeatureLocation> for a description).

=item RETURN

Returns a list containing the contig ID, the start position, the direction (C<+> or C<->),
and the length indicated by the incoming location specifier.

=back

=cut
#: Return Type @;
sub ParseLocation {
    # Get the parameter. Note that if we're called as an instance method, we ignore
    # the first parameter.
    shift if UNIVERSAL::isa($_[0],__PACKAGE__);
    my ($location) = @_;
    # Parse it into segments.
    $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;
    my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
    # If the direction is an underscore, convert it to a + or -.
    if ($dir eq "_") {
        if ($start < $len) {
            $dir = "+";
            $len = $len - $start + 1;
        } else {
            $dir = "-";
            $len = $start - $len + 1;
        }
    }
    # Return the result.
    return ($contigID, $start, $dir, $len);
}

=head3 PointLocation

C<< my $found = Sprout::PointLocation($location, $point); >>

Return the offset into the specified location of the specified point on the contig. If
the specified point is before the location, a negative value will be returned. If it is
beyond the location, an undefined value will be returned. It is assumed that the offset
is for the location's contig. The location can either be new-style (using a C<+> or C<->
and a length) or old-style (using C<_> and start and end positions.

=over 4

=item location

A location specifier (see L</FeatureLocation> for a description).

=item point

The offset into the contig of the point in which we're interested.

=item RETURN

Returns the offset inside the specified location of the specified point, a negative
number if the point is before the location, or an undefined value if the point is past
the location. If the length of the location is 0, this method will B<always> denote
that it is outside the location. The offset will always be relative to the left-most
position in the location.

=back

=cut
#: Return Type $;
sub PointLocation {
    # Get the parameter. Note that if we're called as an instance method, we ignore
    # the first parameter.
    shift if UNIVERSAL::isa($_[0],__PACKAGE__);
    my ($location, $point) = @_;
    # Parse out the location elements. Note that this works on both old-style and new-style
    # locations.
    my ($contigID, $start, $dir, $len) = ParseLocation($location);
    # Declare the return variable.
    my $retVal;
    # Compute the offset. The computation is dependent on the direction of the location.
    my $offset = (($dir == '+') ? $point - $start : $point - ($start - $len + 1));
    # Return the offset if it's valid.
    if ($offset < $len) {
        $retVal = $offset;
    }
    # Return the offset found.
    return $retVal;
}

=head3 DNASeq

C<< my $sequence = $sprout->DNASeq(\@locationList); >>

This method returns the DNA sequence represented by a list of locations. The list of locations
should be of the form returned by L</featureLocation> when in a list context. In other words,
each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.

=over 4

=item locationList

List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<end> (see
L</FeatureLocation> for more about this format).

=item RETURN

Returns a string of nucleotides corresponding to the DNA segments in the location list.

=back

=cut
#: Return Type $;
sub DNASeq {
    # Get the parameters.
    my ($self, $locationList) = @_;
    # Create the return string.
    my $retVal = "";
    # Loop through the locations.
    for my $location (@{$locationList}) {
        # Set up a variable to contain the DNA at this location.
        my $locationDNA = "";
        # Parse out the contig ID, the beginning point, the direction, and the end point.
        my ($contigID, $beg, $dir, $len) = ParseLocation($location);
        # Now we must create a query to return all the sequences in the contig relevant to the region
        # specified. First, we compute the start and stop points when reading through the sequences.
        # For a forward transcription, the start point is the beginning; for a backward transcription,
        # the start point is the ending. Note that in the latter case we must reverse the DNA string
        # before putting it in the return value.
        my ($start, $stop);
        if ($dir eq "+") {
            $start = $beg;
            $stop = $beg + $len - 1;
        } else {
            $start = $beg + $len + 1;
            $stop = $beg;
        }
        my $query = $self->Get(['IsMadeUpOf','Sequence'],
            "IsMadeUpOf(from-link) = ? AND IsMadeUpOf(start-position) + IsMadeUpOf(len) > ? AND " .
            " IsMadeUpOf(start-position) <= ? ORDER BY IsMadeUpOf(start-position)",
            [$contigID, $start, $stop]);
        # Loop through the sequences.
        while (my $sequence = $query->Fetch()) {
            # Determine whether the location starts, stops, or continues through this sequence.
            my ($startPosition, $sequenceData, $sequenceLength) =
                $sequence->Values(['IsMadeUpOf(start-position)', 'Sequence(sequence)',
                                   'IsMadeUpOf(len)']);
            my $stopPosition = $startPosition + $sequenceLength;
            # Figure out the start point and length of the relevant section.
            my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
            my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;
            # Add the relevant data to the location data.
            $locationDNA .= substr($sequenceData, $pos1, $len);
        }
        # Add this location's data to the return string. Note that we may need to reverse it.
        if ($dir eq '+') {
            $retVal .= $locationDNA;
        } else {
            $locationDNA = join('', reverse split //, $locationDNA);
            $retVal .= $locationDNA;
        }
    }
    # Return the result.
    return $retVal;
}

=head3 AllContigs

C<< my @idList = $sprout->AllContigs($genomeID); >>

Return a list of all the contigs for a genome.

=over 4

=item genomeID

Genome whose contigs are desired.

=item RETURN

Returns a list of the IDs for the genome's contigs.

=back

=cut
#: Return Type @;
sub AllContigs {
    # Get the parameters.
    my ($self, $genomeID) = @_;
    # Ask for the genome's Contigs.
    my @retVal = $self->GetFlat(['HasContig'], "HasContig(from-link) = ?", [$genomeID],
                                'HasContig(to-link)');
    # Return the list of Contigs.
    return @retVal;
}

=head3 ContigLength

C<< my $length = $sprout->ContigLength($contigID); >>

Compute the length of a contig.

=over 4

=item contigID

ID of the contig whose length is desired.

=item RETURN

Returns the number of positions in the contig.

=back

=cut
#: Return Type $;
sub ContigLength {
    # Get the parameters.
    my ($self, $contigID) = @_;
    # Get the contig's last sequence.
    my $query = $self->Get(['IsMadeUpOf'],
        "IsMadeUpOf(from-link) = ? ORDER BY IsMadeUpOf(start-position) DESC",
        [$contigID]);
    my $sequence = $query->Fetch();
    # Declare the return value.
    my $retVal = 0;
    # Set it from the sequence data, if any.
    if ($sequence) {
        my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
        $retVal = $start + $len;
    }
    # Return the result.
    return $retVal;
}

=head3 GenesInRegion

C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>

List the features which overlap a specified region in a contig.

=over 4

=item contigID

ID of the contig containing the region of interest.

=item start

Offset of the first residue in the region of interest.

=item stop

Offset of the last residue in the region of interest.

=item RETURN

Returns a three-element list. The first element is a list of feature IDs for the features that
overlap the region of interest. The second and third elements are the minimum and maximum
locations of the features provided on the specified contig. These may extend outside
the start and stop values. The first element (that is, the list of features) is sorted
roughly by location.

=back

=cut
#: Return Type @@;
sub GenesInRegion {
    # Get the parameters.
    my ($self, $contigID, $start, $stop) = @_;
    # Get the maximum segment length.
    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 = ();
    # Prime the values we'll use for the returned beginning and end.
    my @initialMinMax = ($self->ContigLength($contigID), 0);
    my ($min, $max) = @initialMinMax;
    # Create a table of parameters for each query. Each query looks for features travelling in
    # a particular direction. The query parameters include the contig ID, the feature direction,
    # the lowest possible start position, and the highest possible start position. This works
    # because each feature segment length must be no greater than the maximum segment length.
    my %queryParms = (forward => [$contigID, '+', $start - $maximumSegmentLength + 1, $stop],
                      reverse => [$contigID, '-', $start, $stop + $maximumSegmentLength - 1]);
    # Loop through the query parameters.
    for my $parms (values %queryParms) {
        # Create the query.
        my $query = $self->Get(['IsLocatedIn'],
            "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
            $parms);
        # Loop through the feature segments found.
        while (my $segment = $query->Fetch) {
            # Get the data about this segment.
            my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',
                'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);
            # Determine if this feature actually overlaps the region. The query insures that
            # this will be the case if the segment is the maximum length, so to fine-tune
            # the results we insure that the inequality from the query holds using the actual
            # length.
            my ($found, $end) = (0, 0);
            if ($dir eq '+') {
                $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;
                }
            }
            if ($found) {
                # Here we need to record the feature and update the minima and maxima. First,
                # get the current entry for the specified feature.
                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];
            }
        }
    }
    # Now we must compute the list of the IDs for the features found. We start with a list
    # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
    # but the result of the sort will be the same.)
    my @list = map { [$featuresFound{$_}->[0] + $featuresFound{$_}->[1], $_] } keys %featuresFound;
    # Now we sort by midpoint and yank out the feature IDs.
    my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
    # Return it along with the min and max.
    return (\@retVal, $min, $max);
}

=head3 FType

C<< my $ftype = $sprout->FType($featureID); >>

Return the type of a feature.

=over 4

=item featureID

ID of the feature whose type is desired.

=item RETURN

A string indicating the type of feature (e.g. peg, rna). If the feature does not exist, returns an
undefined value.

=back

=cut
#: Return Type $;
sub FType {
    # Get the parameters.
    my ($self, $featureID) = @_;
    # Get the specified feature's type.
    my ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(feature-type)']);
    # Return the result.
    return $retVal;
}

=head3 FeatureAnnotations

C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>

Return the annotations of a feature.

=over 4

=item featureID

ID of the feature whose annotations are desired.

=item RETURN

Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.

* B<featureID> ID of the relevant feature.

* B<timeStamp> time the annotation was made, in user-friendly format.

* B<user> ID of the user who made the annotation

* B<text> text of the annotation.

=back

=cut
#: Return Type @%;
sub FeatureAnnotations {
    # Get the parameters.
    my ($self, $featureID) = @_;
    # Create a query to get the feature's annotations and the associated users.
    my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
                           "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
    # Create the return list.
    my @retVal = ();
    # Loop through the annotations.
    while (my $annotation = $query->Fetch) {
        # Get the fields to return.
        my ($featureID, $timeStamp, $user, $text) =
            $annotation->Values(['IsTargetOfAnnotation(from-link)',
                                 'Annotation(time)', 'MadeAnnotation(from-link)',
                                 'Annotation(annotation)']);
        # Assemble them into a hash.
        my $annotationHash = { featureID => $featureID,
                               timeStamp => FriendlyTimestamp($timeStamp),
                               user => $user, text => $text };
        # Add it to the return list.
        push @retVal, $annotationHash;
    }
    # Return the result list.
    return @retVal;
}

=head3 AllFunctionsOf

C<< my %functions = $sprout->AllFunctionsOf($featureID); >>

Return all of the functional assignments for a particular feature. The data is returned as a
hash of functional assignments to user IDs. A functional assignment is a type of annotation,
Functional assignments are described in the L</ParseAssignment> function. 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.
Finally, if a single user has multiple functional assignments, we will only keep the most
recent one.

=over 4

=item featureID

ID of the feature whose functional assignments are desired.

=item RETURN

Returns a hash mapping the functional assignment IDs to user IDs.

=back

=cut
#: Return Type %;
sub AllFunctionsOf {
    # Get the parameters.
    my ($self, $featureID) = @_;
    # Get all of the feature's annotations.
    my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],
                            "IsTargetOfAnnotation(from-link) = ?",
                            [$featureID], ['Annotation(time)', 'Annotation(annotation)']);
    # Declare the return hash.
    my %retVal;
    # Declare a hash for insuring we only make one assignment per user.
    my %timeHash = ();
    # Now we sort the assignments by timestamp in reverse.
    my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
    # Loop until we run out of annotations.
    for my $annotation (@sortedQuery) {
        # Get the annotation fields.
        my ($timeStamp, $text) = @{$annotation};
        # Check to see if this is a functional assignment.
        my ($user, $function) = _ParseAssignment($text);
        if ($user && ! exists $timeHash{$user}) {
            # Here it is a functional assignment and there has been no
            # previous assignment for this user, so we stuff it in the
            # return hash.
            $retVal{$function} = $user;
            # Insure we don't assign to this user again.
            $timeHash{$user} = 1;
        }
    }
    # Return the hash of assignments found.
    return %retVal;
}

=head3 FunctionOf

C<< my $functionText = $sprout->FunctionOf($featureID, $userID); >>

Return the most recently-determined functional assignment of a particular feature.

The functional assignment is handled differently depending on the type of feature. If
the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
assignment is a type of annotation. The format of an assignment is described in
L</ParseLocation>. 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.

Each user has an associated list of trusted users. The assignment returned will be the most
recent one by at least one of the trusted users. If no trusted user list is available, then
the specified user and FIG are considered trusted. If the user ID is omitted, only FIG
is trusted.

If the feature is B<not> identified by a FIG ID, then the functional assignment
information is taken from the B<ExternalAliasFunc> table. If the table does
not contain an entry for the feature, an undefined value is returned.

=over 4

=item featureID

ID of the feature whose functional assignment is desired.

=item userID (optional)

ID of the user whose function determination is desired. If omitted, only the latest
C<FIG> assignment will be returned.

=item RETURN

Returns the text of the assigned function.

=back

=cut
#: Return Type $;
sub FunctionOf {
    # Get the parameters.
    my ($self, $featureID, $userID) = @_;
    # Declare the return value.
    my $retVal;
    # Determine the ID type.
    if ($featureID =~ m/^fig\|/) {
        # Here we have a FIG feature ID. We must build the list of trusted
        # users.
        my %trusteeTable = ();
        # Check the user ID.
        if (!$userID) {
            # No user ID, so only FIG is trusted.
            $trusteeTable{FIG} = 1;
        } else {
            # Add this user's ID.
            $trusteeTable{$userID} = 1;
            # Look for the trusted users in the database.
            my @trustees = $self->GetFlat(['IsTrustedBy'], 'IsTrustedBy(from-link) = ?', [$userID], 'IsTrustedBy(to-link)');
            if (! @trustees) {
                # None were found, so build a default list.
                $trusteeTable{FIG} = 1;
            } else {
                # Otherwise, put all the trustees in.
                for my $trustee (@trustees) {
                    $trusteeTable{$trustee} = 1;
                }
            }
        }
        # Build a query for all of the feature's annotations, sorted by date.
        my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],
                               "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
                               [$featureID]);
        my $timeSelected = 0;
        # Loop until we run out of annotations.
        while (my $annotation = $query->Fetch()) {
            # Get the annotation text.
            my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);
            # Check to see if this is a functional assignment for a trusted user.
            my ($user, $function) = _ParseAssignment($text);
            if ($user) {
                # Here it is a functional assignment. Check the time and the user
                # name. The time must be recent and the user must be trusted.
                if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {
                    $retVal = $function;
                    $timeSelected = $time;
                }
            }
        }
    } else {
        # Here we have a non-FIG feature ID. In this case the user ID does not
        # matter. We simply get the information from the External Alias Function
        # table.
        ($retVal) = $self->GetEntityValues('ExternalAliasFunc', $featureID, ['ExternalAliasFunc(func)']);
    }
    # Return the assignment found.
    return $retVal;
}

=head3 BBHList

C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>

Return a hash mapping the features in a specified list to their bidirectional best hits
on a specified target genome.

=over 4

=item genomeID

ID of the genome from which the best hits should be taken.

=item featureList

List of the features whose best hits are desired.

=item RETURN

Returns a reference to a hash that maps the IDs of the incoming features to the best hits
on the target genome.

=back

=cut
#: Return Type %;
sub BBHList {
    # Get the parameters.
    my ($self, $genomeID, $featureList) = @_;
    # Create the return structure.
    my %retVal = ();
    # Loop through the incoming features.
    for my $featureID (@{$featureList}) {
        # Create a query to get the feature's best hit.
        my $query = $self->Get(['IsBidirectionalBestHitOf'],
                               "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",
                               [$featureID, $genomeID]);
        # Look for the best hit.
        my $bbh = $query->Fetch;
        if ($bbh) {
            my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');
            $retVal{$featureID} = $targetFeature;
        }
    }
    # Return the mapping.
    return \%retVal;
}

=head3 SimList

C<< my %similarities = $sprout->SimList($featureID, $count); >>

Return a list of the similarities to the specified feature.

Sprout does not support real similarities, so this method just returns the bidirectional
best hits.

=over 4

=item featureID

ID of the feature whose similarities are desired.

=item count

Maximum number of similar features to be returned, or C<0> to return them all.

=back

=cut
#: Return Type %;
sub SimList {
    # Get the parameters.
    my ($self, $featureID, $count) = @_;
    # Ask for the best hits.
    my @lists = $self->GetAll(['IsBidirectionalBestHitOf'],
                              "IsBidirectionalBestHitOf(from-link) = ? ORDER BY IsBidirectionalBestHitOf(score) DESC",
                              [$featureID], ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(score)'],
                              $count);
    # Create the return value.
    my %retVal = ();
    for my $tuple (@lists) {
        $retVal{$tuple->[0]} = $tuple->[1];
    }
    # Return the result.
    return %retVal;
}



=head3 IsComplete

C<< my $flag = $sprout->IsComplete($genomeID); >>

Return TRUE if the specified genome is complete, else FALSE.

=over 4

=item genomeID

ID of the genome whose completeness status is desired.

=item RETURN

Returns TRUE if the genome is complete, FALSE if it is incomplete, and C<undef> if it is
not found.

=back

=cut
#: Return Type $;
sub IsComplete {
    # Get the parameters.
    my ($self, $genomeID) = @_;
    # Declare the return variable.
    my $retVal;
    # Get the genome's data.
    my $genomeData = $self->GetEntity('Genome', $genomeID);
    if ($genomeData) {
        # The genome exists, so get the completeness flag.
        ($retVal) = $genomeData->Value('complete');
    }
    # Return the result.
    return $retVal;
}

=head3 FeatureAliases

C<< my @aliasList = $sprout->FeatureAliases($featureID); >>

Return a list of the aliases for a specified feature.

=over 4

=item featureID

ID of the feature whose aliases are desired.

=item RETURN

Returns a list of the feature's aliases. If the feature is not found or has no aliases, it will
return an empty list.

=back

=cut
#: Return Type @;
sub FeatureAliases {
    # Get the parameters.
    my ($self, $featureID) = @_;
    # Get the desired feature's aliases
    my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);
    # Return the result.
    return @retVal;
}

=head3 GenomeOf

C<< my $genomeID = $sprout->GenomeOf($featureID); >>

Return the genome that contains a specified feature.

=over 4

=item featureID

ID of the feature whose genome is desired.

=item RETURN

Returns the ID of the genome for the specified feature. If the feature is not found, returns
an undefined value.

=back

=cut
#: Return Type $;
sub GenomeOf {
    # Get the parameters.
    my ($self, $featureID) = @_;
    # Create a query to find the genome associated with the feature.
    my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);
    # Declare the return value.
    my $retVal;
    # Get the genome ID.
    if (my $relationship = $query->Fetch()) {
        ($retVal) = $relationship->Value('HasContig(from-link)');
    }
    # Return the value found.
    return $retVal;
}

=head3 CoupledFeatures

C<< my %coupleHash = $sprout->CoupledFeatures($featureID); >>

Return the features functionally coupled with a specified feature. Features are considered
functionally coupled if they tend to be clustered on the same chromosome.

=over 4

=item featureID

ID of the feature whose functionally-coupled brethren are desired.

=item RETURN

A hash mapping the functionally-coupled feature IDs to the coupling score.

=back

=cut
#: Return Type %;
sub CoupledFeatures {
    # Get the parameters.
    my ($self, $featureID) = @_;
    # Create a query to retrieve the functionally-coupled features.
    my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],
                           "ParticipatesInCoupling(from-link) = ?", [$featureID]);
    # This value will be set to TRUE if we find at least one coupled feature.
    my $found = 0;
    # Create the return hash.
    my %retVal = ();
    # Retrieve the relationship records and store them in the hash.
    while (my $clustering = $query->Fetch()) {
        # Get the ID and score of the coupling.
        my ($couplingID, $score) = $clustering->Values(['Coupling(id)',
                                                        'Coupling(score)']);
        # The coupling ID contains the two feature IDs separated by a space. We use
        # this information to find the ID of the other feature.
        my ($fid1, $fid2) = split / /, $couplingID;
        my $otherFeatureID = ($featureID eq $fid1 ? $fid2 : $fid1);
        # Attach the other feature's score to its ID.
        $retVal{$otherFeatureID} = $score;
        $found = 1;
    }
    # Functional coupling is reflexive. If we found at least one coupled feature, we must add
    # the incoming feature as well.
    if ($found) {
        $retVal{$featureID} = 9999;
    }
    # Return the hash.
    return %retVal;
}

=head3 CouplingEvidence

C<< my @evidence = $sprout->CouplingEvidence($peg1, $peg2); >>

Return the evidence for a functional coupling.

A pair of features is considered evidence of a coupling between two other
features if they occur close together on a contig and both are similar to
the coupled features. So, if B<A1> and B<A2> are close together on a contig,
B<B1> and B<B2> are considered evidence for the coupling if (1) B<B1> and
B<B2> are close together, (2) B<B1> is similar to B<A1>, and (3) B<B2> is
similar to B<A2>.

The score of a coupling is determined by the number of pieces of evidence
that are considered I<representative>. If several evidence items belong to
a group of genomes that are close to each other, only one of those items
is considered representative. The other evidence items are presumed to be
there because of the relationship between the genomes rather than because
the two proteins generated by the features have a related functionality.

Each evidence item is returned as a three-tuple in the form C<[>I<$peg1a>C<,>
I<$peg2a>C<,> I<$rep>C<]>, where I<$peg1a> is similar to I<$peg1>, I<$peg2a>
is similar to I<$peg2>, and I<$rep> is TRUE if the evidence is representative
and FALSE otherwise.

=over 4

=item peg1

ID of the feature of interest.

=item peg2

ID of a feature functionally coupled to the feature of interest.

=item RETURN

Returns a list of 3-tuples. Each tuple consists of a feature similar to the feature
of interest, a feature similar to the functionally coupled feature, and a flag
that is TRUE for a representative piece of evidence and FALSE otherwise.

=back

=cut
#: Return Type @@;
sub CouplingEvidence {
    # Get the parameters.
    my ($self, $peg1, $peg2) = @_;
    # Declare the return variable.
    my @retVal = ();
    # Our first task is to find out the nature of the coupling: whether or not
    # it exists, its score, and whether the features are stored in the same
    # order as the ones coming in.
    my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);
    # Only proceed if a coupling exists.
    if ($couplingID) {
        # 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]];
        }
    }
    # Return the result.
    return @retVal;
}

=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) = (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) {
        # 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];
        $inverted = ($pegs[0]->[0] eq $peg1);
    }
    # Return the result.
    return ($retVal, $inverted, $score);
}

=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