[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.32, Wed Sep 14 13:24:14 2005 UTC revision 1.101, Mon Aug 20 23:29:24 2007 UTC
# Line 1  Line 1 
1  package Sprout;  package Sprout;
2    
3        require Exporter;
4        use ERDB;
5        @ISA = qw(Exporter ERDB);
6      use Data::Dumper;      use Data::Dumper;
7      use strict;      use strict;
     use Carp;  
8      use DBKernel;      use DBKernel;
9      use XML::Simple;      use XML::Simple;
10      use DBQuery;      use DBQuery;
11      use DBObject;      use ERDBObject;
     use ERDB;  
12      use Tracer;      use Tracer;
13      use FIGRules;      use FIGRules;
14        use FidCheck;
15      use Stats;      use Stats;
16      use POSIX qw(strftime);      use POSIX qw(strftime);
17        use BasicLocation;
18        use CustomAttributes;
19        use RemoteCustomAttributes;
20    
21  =head1 Sprout Database Manipulation Object  =head1 Sprout Database Manipulation Object
22    
# Line 32  Line 36 
36  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
37  L</dna_seq> returns the DNA sequence for a specified genome location.  L</dna_seq> returns the DNA sequence for a specified genome location.
38    
39    The Sprout object is a subclass of the ERDB object and inherits all its properties and methods.
40    
41  =cut  =cut
42    
43  #: Constructor SFXlate->new_sprout_only();  #: Constructor SFXlate->new_sprout_only();
# Line 62  Line 68 
68    
69  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)  * B<xmlFileName> name of the XML file containing the database definition (default C<SproutDBD.xml>)
70    
71  * B<userData> user name and password, delimited by a slash (default C<root/>)  * B<userData> user name and password, delimited by a slash (default same as SEED)
72    
73  * B<port> connection port (default C<0>)  * B<port> connection port (default C<0>)
74    
75    * B<sock> connection socket (default same as SEED)
76    
77  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)  * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>)
78    
79  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)  * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>)
# Line 85  Line 93 
93  sub new {  sub new {
94      # Get the parameters.      # Get the parameters.
95      my ($class, $dbName, $options) = @_;      my ($class, $dbName, $options) = @_;
96        # Compute the DBD directory.
97        my $dbd_dir = (defined($FIG_Config::dbd_dir) ? $FIG_Config::dbd_dir :
98                                                      $FIG_Config::fig );
99      # Compute the options. We do this by starting with a table of defaults and overwriting with      # Compute the options. We do this by starting with a table of defaults and overwriting with
100      # the incoming data.      # the incoming data.
101      my $optionTable = Tracer::GetOptions({      my $optionTable = Tracer::GetOptions({
# Line 92  Line 103 
103                                                          # database type                                                          # database type
104                         dataDir      => $FIG_Config::sproutData,                         dataDir      => $FIG_Config::sproutData,
105                                                          # data file directory                                                          # data file directory
106                         xmlFileName  => "$FIG_Config::sproutData/SproutDBD.xml",                         xmlFileName  => "$dbd_dir/SproutDBD.xml",
107                                                          # database definition file name                                                          # database definition file name
108                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",                         userData     => "$FIG_Config::dbuser/$FIG_Config::dbpass",
109                                                          # user name and password                                                          # user name and password
110                         port         => $FIG_Config::dbport,                         port         => $FIG_Config::dbport,
111                                                          # database connection port                                                          # database connection port
112                           sock         => $FIG_Config::dbsock,
113                           host         => $FIG_Config::dbhost,
114                         maxSegmentLength => 4500,        # maximum feature segment length                         maxSegmentLength => 4500,        # maximum feature segment length
115                         maxSequenceLength => 8000,       # maximum contig sequence length                         maxSequenceLength => 8000,       # maximum contig sequence length
116                         noDBOpen     => 0,               # 1 to suppress the database open                         noDBOpen     => 0,               # 1 to suppress the database open
# Line 111  Line 124 
124      my $dbh;      my $dbh;
125      if (! $optionTable->{noDBOpen}) {      if (! $optionTable->{noDBOpen}) {
126          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,          $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName,
127                                  $password, $optionTable->{port});                                  $password, $optionTable->{port}, $optionTable->{host}, $optionTable->{sock});
128      }      }
129      # Create the ERDB object.      # Create the ERDB object.
130      my $xmlFileName = "$optionTable->{xmlFileName}";      my $xmlFileName = "$optionTable->{xmlFileName}";
131      my $erdb = ERDB->new($dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
132      # Create this object.      # Add the option table and XML file name.
133      my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName };      $retVal->{_options} = $optionTable;
134      # Bless and return it.      $retVal->{_xmlName} = $xmlFileName;
135      bless $self;      # Set up space for the group file data.
136      return $self;      $retVal->{groupHash} = undef;
137        # Set up space for the genome hash. We use this to identify NMPDR genomes.
138        $retVal->{genomeHash} = undef;
139        # Connect to the attributes.
140        if ($FIG_Config::attrURL) {
141            Trace("Remote attribute server $FIG_Config::attrURL chosen.") if T(3);
142            $retVal->{_ca} = RemoteCustomAttributes->new($FIG_Config::attrURL);
143        } elsif ($FIG_Config::attrDbName) {
144            Trace("Local attribute database $FIG_Config::attrDbName chosen.") if T(3);
145            my $user = ($FIG_Config::arch eq 'win' ? 'self' : scalar(getpwent()));
146            $retVal->{_ca} = CustomAttributes->new(user => $user);
147        }
148        # Return it.
149        return $retVal;
150  }  }
151    
152  =head3 MaxSegment  =head3 MaxSegment
# Line 155  Line 181 
181      return $self->{_options}->{maxSequenceLength};      return $self->{_options}->{maxSequenceLength};
182  }  }
183    
 =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);  
 }  
   
184  =head3 Load  =head3 Load
185    
186  C<< $sprout->Load($rebuild); >>;  C<< $sprout->Load($rebuild); >>;
# Line 379  Line 215 
215  sub Load {  sub Load {
216      # Get the parameters.      # Get the parameters.
217      my ($self, $rebuild) = @_;      my ($self, $rebuild) = @_;
     # Get the database object.  
     my $erdb = $self->{_erdb};  
218      # Load the tables from the data directory.      # Load the tables from the data directory.
219      my $retVal = $erdb->LoadTables($self->{_options}->{dataDir}, $rebuild);      my $retVal = $self->LoadTables($self->{_options}->{dataDir}, $rebuild);
220      # Return the statistics.      # Return the statistics.
221      return $retVal;      return $retVal;
222  }  }
223    
224  =head3 LoadUpdate  =head3 LoadUpdate
225    
226  C<< my %stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>  C<< my $stats = $sprout->LoadUpdate($truncateFlag, \@tableList); >>
227    
228  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
229  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 422  Line 256 
256  sub LoadUpdate {  sub LoadUpdate {
257      # Get the parameters.      # Get the parameters.
258      my ($self, $truncateFlag, $tableList) = @_;      my ($self, $truncateFlag, $tableList) = @_;
     # Get the database object.  
     my $erdb = $self->{_erdb};  
259      # Declare the return value.      # Declare the return value.
260      my $retVal = Stats->new();      my $retVal = Stats->new();
261      # Get the data directory.      # Get the data directory.
# Line 437  Line 269 
269              Trace("No load file found for $tableName in $dataDir.") if T(0);              Trace("No load file found for $tableName in $dataDir.") if T(0);
270          } else {          } else {
271              # Attempt to load this table.              # Attempt to load this table.
272              my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag);              my $result = $self->LoadTable($fileName, $tableName, $truncateFlag);
273              # Accumulate the resulting statistics.              # Accumulate the resulting statistics.
274              $retVal->Accumulate($result);              $retVal->Accumulate($result);
275          }          }
# Line 446  Line 278 
278      return $retVal;      return $retVal;
279  }  }
280    
281    =head3 GenomeCounts
282    
283    C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $sprout->GenomeCounts($complete); >>
284    
285    Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
286    genomes will be included in the counts.
287    
288    =over 4
289    
290    =item complete
291    
292    TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
293    counted
294    
295    =item RETURN
296    
297    A six-element list containing the number of genomes in each of six categories--
298    Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
299    
300    =back
301    
302    =cut
303    
304    sub GenomeCounts {
305        # Get the parameters.
306        my ($self, $complete) = @_;
307        # Set the filter based on the completeness flag.
308        my $filter = ($complete ? "Genome(complete) = 1" : "");
309        # Get all the genomes and the related taxonomy information.
310        my @genomes = $self->GetAll(['Genome'], $filter, [], ['Genome(id)', 'Genome(taxonomy)']);
311        # Clear the counters.
312        my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
313        # Loop through, counting the domains.
314        for my $genome (@genomes) {
315            if    ($genome->[1] =~ /^archaea/i)  { ++$arch }
316            elsif ($genome->[1] =~ /^bacter/i)   { ++$bact }
317            elsif ($genome->[1] =~ /^eukar/i)    { ++$euk }
318            elsif ($genome->[1] =~ /^vir/i)      { ++$vir }
319            elsif ($genome->[1] =~ /^env/i)      { ++$env }
320            else  { ++$unk }
321        }
322        # Return the counts.
323        return ($arch, $bact, $euk, $vir, $env, $unk);
324    }
325    
326    =head3 ContigCount
327    
328    C<< my $count = $sprout->ContigCount($genomeID); >>
329    
330    Return the number of contigs for the specified genome ID.
331    
332    =over 4
333    
334    =item genomeID
335    
336    ID of the genome whose contig count is desired.
337    
338    =item RETURN
339    
340    Returns the number of contigs for the specified genome.
341    
342    =back
343    
344    =cut
345    
346    sub ContigCount {
347        # Get the parameters.
348        my ($self, $genomeID) = @_;
349        # Get the contig count.
350        my $retVal = $self->GetCount(['Contig', 'HasContig'], "HasContig(from-link) = ?", [$genomeID]);
351        # Return the result.
352        return $retVal;
353    }
354    
355    =head3 GeneMenu
356    
357    C<< my $selectHtml = $sprout->GeneMenu(\%attributes, $filterString, \@params, $selected); >>
358    
359    Return an HTML select menu of genomes. Each genome will be an option in the menu,
360    and will be displayed by name with the ID and a contig count attached. The selection
361    value will be the genome ID. The genomes will be sorted by genus/species name.
362    
363    =over 4
364    
365    =item attributes
366    
367    Reference to a hash mapping attributes to values for the SELECT tag generated.
368    
369    =item filterString
370    
371    A filter string for use in selecting the genomes. The filter string must conform
372    to the rules for the C<< ERDB->Get >> method.
373    
374    =item params
375    
376    Reference to a list of values to be substituted in for the parameter marks in
377    the filter string.
378    
379    =item selected (optional)
380    
381    ID of the genome to be initially selected.
382    
383    =item fast (optional)
384    
385    If specified and TRUE, the contig counts will be omitted to improve performance.
386    
387    =item RETURN
388    
389    Returns an HTML select menu with the specified genomes as selectable options.
390    
391    =back
392    
393    =cut
394    
395    sub GeneMenu {
396        # Get the parameters.
397        my ($self, $attributes, $filterString, $params, $selected, $fast) = @_;
398        my $slowMode = ! $fast;
399        # Default to nothing selected. This prevents an execution warning if "$selected"
400        # is undefined.
401        $selected = "" unless defined $selected;
402        Trace("Gene Menu called with slow mode \"$slowMode\" and selection \"$selected\".") if T(3);
403        # Start the menu.
404        my $retVal = "<select " .
405            join(" ", map { "$_=\"$attributes->{$_}\"" } keys %{$attributes}) .
406            ">\n";
407        # Get the genomes.
408        my @genomes = $self->GetAll(['Genome'], $filterString, $params, ['Genome(id)',
409                                                                         'Genome(genus)',
410                                                                         'Genome(species)',
411                                                                         'Genome(unique-characterization)']);
412        # Sort them by name.
413        my @sorted = sort { lc("$a->[1] $a->[2]") cmp lc("$b->[1] $b->[2]") } @genomes;
414        # Loop through the genomes, creating the option tags.
415        for my $genomeData (@sorted) {
416            # Get the data for this genome.
417            my ($genomeID, $genus, $species, $strain) = @{$genomeData};
418            # Get the contig count.
419            my $contigInfo = "";
420            if ($slowMode) {
421                my $count = $self->ContigCount($genomeID);
422                my $counting = ($count == 1 ? "contig" : "contigs");
423                $contigInfo = "[$count $counting]";
424            }
425            # Find out if we're selected.
426            my $selectOption = ($selected eq $genomeID ? " selected" : "");
427            # Build the option tag.
428            $retVal .= "<option value=\"$genomeID\"$selectOption>$genus $species $strain ($genomeID)$contigInfo</option>\n";
429        }
430        # Close the SELECT tag.
431        $retVal .= "</select>\n";
432        # Return the result.
433        return $retVal;
434    }
435    
436  =head3 Build  =head3 Build
437    
438  C<< $sprout->Build(); >>  C<< $sprout->Build(); >>
# Line 460  Line 447 
447      # Get the parameters.      # Get the parameters.
448      my ($self) = @_;      my ($self) = @_;
449      # Create the tables.      # Create the tables.
450      $self->{_erdb}->CreateTables;      $self->CreateTables();
451  }  }
452    
453  =head3 Genomes  =head3 Genomes
# Line 588  Line 575 
575  =back  =back
576    
577  =cut  =cut
578  #: Return Type @;  
 #: Return Type $;  
579  sub FeatureLocation {  sub FeatureLocation {
580      # Get the parameters.      # Get the parameters.
581      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
582      # Create a query for the feature locations.      # Get the feature record.
583      my $query = $self->Get(['IsLocatedIn'], "IsLocatedIn(from-link) = ? ORDER BY IsLocatedIn(locN)",      my $object = $self->GetEntity('Feature', $featureID);
584                             [$featureID]);      Confess("Feature $featureID not found.") if ! defined($object);
585        # Get the location string.
586        my $locString = $object->PrimaryValue('Feature(location-string)');
587      # Create the return list.      # Create the return list.
588      my @retVal = ();      my @retVal = split /\s*,\s*/, $locString;
     # 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);  
         # Compute the initial base pair.  
         my $start = ($dir eq "+" ? $beg : $beg + $len - 1);  
         # Add the specifier to the list.  
         push @retVal, "${contigID}_$beg$dir$len";  
     }  
589      # Return the list in the format indicated by the context.      # Return the list in the format indicated by the context.
590      return (wantarray ? @retVal : join(',', @retVal));      return (wantarray ? @retVal : join(',', @retVal));
591  }  }
# Line 652  Line 611 
611  =back  =back
612    
613  =cut  =cut
614  #: Return Type @;  
615  sub ParseLocation {  sub ParseLocation {
616      # 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
617      # the first parameter.      # the first parameter.
618      shift if UNIVERSAL::isa($_[0],__PACKAGE__);      shift if UNIVERSAL::isa($_[0],__PACKAGE__);
619      my ($location) = @_;      my ($location) = @_;
620      # Parse it into segments.      # Parse it into segments.
621      $location =~ /^(.*)_(\d*)([+-_])(\d*)$/;      $location =~ /^(.+)_(\d+)([+\-_])(\d+)$/;
622      my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);      my ($contigID, $start, $dir, $len) = ($1, $2, $3, $4);
623      # If the direction is an underscore, convert it to a + or -.      # If the direction is an underscore, convert it to a + or -.
624      if ($dir eq "_") {      if ($dir eq "_") {
# Line 675  Line 634 
634      return ($contigID, $start, $dir, $len);      return ($contigID, $start, $dir, $len);
635  }  }
636    
637    
638    
639  =head3 PointLocation  =head3 PointLocation
640    
641  C<< my $found = Sprout::PointLocation($location, $point); >>  C<< my $found = Sprout::PointLocation($location, $point); >>
# Line 706  Line 667 
667  =back  =back
668    
669  =cut  =cut
670  #: Return Type $;  
671  sub PointLocation {  sub PointLocation {
672      # 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
673      # the first parameter.      # the first parameter.
# Line 735  Line 696 
696  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,
697  each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.  each location is of the form I<contigID>C<_>I<begin>I<dir>I<end>.
698    
699    For example, the following would return the DNA sequence for contig C<83333.1:NC_000913>
700    between positions 1401 and 1532, inclusive.
701    
702        my $sequence = $sprout->DNASeq('83333.1:NC_000913_1401_1532');
703    
704  =over 4  =over 4
705    
706  =item locationList  =item locationList
707    
708  List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<end> (see  List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir>I<len> or
709  L</FeatureLocation> for more about this format).  I<contigID>C<_>I<begin>C<_>I<end> (see L</FeatureLocation> for more about this format).
710    
711  =item RETURN  =item RETURN
712    
# Line 767  Line 733 
733          # the start point is the ending. Note that in the latter case we must reverse the DNA string          # the start point is the ending. Note that in the latter case we must reverse the DNA string
734          # before putting it in the return value.          # before putting it in the return value.
735          my ($start, $stop);          my ($start, $stop);
736          Trace("Parsed location is $beg$dir$len.") if T(SDNA => 4);          Trace("Parse of \"$location\" is $beg$dir$len.") if T(SDNA => 4);
737          if ($dir eq "+") {          if ($dir eq "+") {
738              $start = $beg;              $start = $beg;
739              $stop = $beg + $len - 1;              $stop = $beg + $len - 1;
# Line 790  Line 756 
756              Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);              Trace("Sequence is from $startPosition to $stopPosition.") if T(SDNA => 4);
757              # Figure out the start point and length of the relevant section.              # Figure out the start point and length of the relevant section.
758              my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);              my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition);
759              my $len1 = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1;              my $len1 = ($stopPosition < $stop ? $stopPosition : $stop) + 1 - $startPosition - $pos1;
760              Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);              Trace("Position is $pos1 for length $len1.") if T(SDNA => 4);
761              # Add the relevant data to the location data.              # Add the relevant data to the location data.
762              $locationDNA .= substr($sequenceData, $pos1, $len1);              $locationDNA .= substr($sequenceData, $pos1, $len1);
# Line 836  Line 802 
802      return @retVal;      return @retVal;
803  }  }
804    
805    =head3 GenomeLength
806    
807    C<< my $length = $sprout->GenomeLength($genomeID); >>
808    
809    Return the length of the specified genome in base pairs.
810    
811    =over 4
812    
813    =item genomeID
814    
815    ID of the genome whose base pair count is desired.
816    
817    =item RETURN
818    
819    Returns the number of base pairs in all the contigs of the specified
820    genome.
821    
822    =back
823    
824    =cut
825    
826    sub GenomeLength {
827        # Get the parameters.
828        my ($self, $genomeID) = @_;
829        # Declare the return variable.
830        my $retVal = 0;
831        # Get the genome's contig sequence lengths.
832        my @lens = $self->GetFlat(['HasContig', 'IsMadeUpOf'], 'HasContig(from-link) = ?',
833                           [$genomeID], 'IsMadeUpOf(len)');
834        # Sum the lengths.
835        map { $retVal += $_ } @lens;
836        # Return the result.
837        return $retVal;
838    }
839    
840    =head3 FeatureCount
841    
842    C<< my $count = $sprout->FeatureCount($genomeID, $type); >>
843    
844    Return the number of features of the specified type in the specified genome.
845    
846    =over 4
847    
848    =item genomeID
849    
850    ID of the genome whose feature count is desired.
851    
852    =item type
853    
854    Type of feature to count (eg. C<peg>, C<rna>, etc.).
855    
856    =item RETURN
857    
858    Returns the number of features of the specified type for the specified genome.
859    
860    =back
861    
862    =cut
863    
864    sub FeatureCount {
865        # Get the parameters.
866        my ($self, $genomeID, $type) = @_;
867        # Compute the count.
868        my $retVal = $self->GetCount(['HasFeature', 'Feature'],
869                                    "HasFeature(from-link) = ? AND Feature(feature-type) = ?",
870                                    [$genomeID, $type]);
871        # Return the result.
872        return $retVal;
873    }
874    
875    =head3 GenomeAssignments
876    
877    C<< my $fidHash = $sprout->GenomeAssignments($genomeID); >>
878    
879    Return a list of a genome's assigned features. The return hash will contain each
880    assigned feature of the genome mapped to the text of its most recent functional
881    assignment.
882    
883    =over 4
884    
885    =item genomeID
886    
887    ID of the genome whose functional assignments are desired.
888    
889    =item RETURN
890    
891    Returns a reference to a hash which maps each feature to its most recent
892    functional assignment.
893    
894    =back
895    
896    =cut
897    
898    sub GenomeAssignments {
899        # Get the parameters.
900        my ($self, $genomeID) = @_;
901        # Declare the return variable.
902        my $retVal = {};
903        # Query the genome's features.
904        my $query = $self->Get(['HasFeature', 'Feature'], "HasFeature(from-link) = ?",
905                               [$genomeID]);
906        # Loop through the features.
907        while (my $data = $query->Fetch) {
908            # Get the feature ID and assignment.
909            my ($fid, $assignment) = $data->Values(['Feature(id)', 'Feature(assignment)']);
910            if ($assignment) {
911                $retVal->{$fid} = $assignment;
912            }
913        }
914        # Return the result.
915        return $retVal;
916    }
917    
918  =head3 ContigLength  =head3 ContigLength
919    
920  C<< my $length = $sprout->ContigLength($contigID); >>  C<< my $length = $sprout->ContigLength($contigID); >>
# Line 869  Line 948 
948      # Set it from the sequence data, if any.      # Set it from the sequence data, if any.
949      if ($sequence) {      if ($sequence) {
950          my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);          my ($start, $len) = $sequence->Values(['IsMadeUpOf(start-position)', 'IsMadeUpOf(len)']);
951          $retVal = $start + $len;          $retVal = $start + $len - 1;
952      }      }
953      # Return the result.      # Return the result.
954      return $retVal;      return $retVal;
955  }  }
956    
957  =head3 GenesInRegion  =head3 ClusterPEGs
958    
959  C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>  C<< my $clusteredList = $sprout->ClusterPEGs($sub, \@pegs); >>
960    
961  List the features which overlap a specified region in a contig.  Cluster the PEGs in a list according to the cluster coding scheme of the specified
962    subsystem. In order for this to work properly, the subsystem object must have
963    been used recently to retrieve the PEGs using the B<get_pegs_from_cell> method.
964    This causes the cluster numbers to be pulled into the subsystem's color hash.
965    If a PEG is not found in the color hash, it will not appear in the output
966    sequence.
967    
968  =over 4  =over 4
969    
970  =item contigID  =item sub
971    
972  ID of the contig containing the region of interest.  Sprout subsystem object for the relevant subsystem, from the L</get_subsystem>
973    method.
974    
975    =item pegs
976    
977    Reference to the list of PEGs to be clustered.
978    
979    =item RETURN
980    
981    Returns a list of the PEGs, grouped into smaller lists by cluster number.
982    
983    =back
984    
985    =cut
986    #: Return Type $@@;
987    sub ClusterPEGs {
988        # Get the parameters.
989        my ($self, $sub, $pegs) = @_;
990        # Declare the return variable.
991        my $retVal = [];
992        # Loop through the PEGs, creating arrays for each cluster.
993        for my $pegID (@{$pegs}) {
994            my $clusterNumber = $sub->get_cluster_number($pegID);
995            # Only proceed if the PEG is in a cluster.
996            if ($clusterNumber >= 0) {
997                # Push this PEG onto the sub-list for the specified cluster number.
998                push @{$retVal->[$clusterNumber]}, $pegID;
999            }
1000        }
1001        # Return the result.
1002        return $retVal;
1003    }
1004    
1005    =head3 GenesInRegion
1006    
1007    C<< my (\@featureIDList, $beg, $end) = $sprout->GenesInRegion($contigID, $start, $stop); >>
1008    
1009    List the features which overlap a specified region in a contig.
1010    
1011    =over 4
1012    
1013    =item contigID
1014    
1015    ID of the contig containing the region of interest.
1016    
1017  =item start  =item start
1018    
# Line 906  Line 1033 
1033  =back  =back
1034    
1035  =cut  =cut
1036  #: Return Type @@;  
1037  sub GenesInRegion {  sub GenesInRegion {
1038      # Get the parameters.      # Get the parameters.
1039      my ($self, $contigID, $start, $stop) = @_;      my ($self, $contigID, $start, $stop) = @_;
1040      # Get the maximum segment length.      # Get the maximum segment length.
1041      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 = ();  
1042      # Prime the values we'll use for the returned beginning and end.      # Prime the values we'll use for the returned beginning and end.
1043      my @initialMinMax = ($self->ContigLength($contigID), 0);      my @initialMinMax = ($self->ContigLength($contigID), 0);
1044      my ($min, $max) = @initialMinMax;      my ($min, $max) = @initialMinMax;
1045      # Create a table of parameters for each query. Each query looks for features travelling in      # Get the overlapping features.
1046        my @featureObjects = $self->GeneDataInRegion($contigID, $start, $stop);
1047        # We'l use this hash to help us track the feature IDs and sort them. The key is the
1048        # feature ID and the value is a [$left,$right] pair indicating the maximum extent
1049        # of the feature's locations.
1050        my %featureMap = ();
1051        # Loop through them to do the begin/end analysis.
1052        for my $featureObject (@featureObjects) {
1053            # Get the feature's location string. This may contain multiple actual locations.
1054            my ($locations, $fid) = $featureObject->Values([qw(Feature(location-string) Feature(id))]);
1055            my @locationSegments = split /\s*,\s*/, $locations;
1056            # Loop through the locations.
1057            for my $locationSegment (@locationSegments) {
1058                # Construct an object for the location.
1059                my $locationObject = BasicLocation->new($locationSegment);
1060                # Merge the current segment's begin and end into the min and max.
1061                my ($left, $right) = ($locationObject->Left, $locationObject->Right);
1062                my ($beg, $end);
1063                if (exists $featureMap{$fid}) {
1064                    ($beg, $end) = @{$featureMap{$fid}};
1065                    $beg = $left if $left < $beg;
1066                    $end = $right if $right > $end;
1067                } else {
1068                    ($beg, $end) = ($left, $right);
1069                }
1070                $min = $beg if $beg < $min;
1071                $max = $end if $end > $max;
1072                # Store the feature's new extent back into the hash table.
1073                $featureMap{$fid} = [$beg, $end];
1074            }
1075        }
1076        # Now we must compute the list of the IDs for the features found. We start with a list
1077        # of midpoints / feature ID pairs. (It's not really a midpoint, it's twice the midpoint,
1078        # but the result of the sort will be the same.)
1079        my @list = map { [$featureMap{$_}->[0] + $featureMap{$_}->[1], $_] } keys %featureMap;
1080        # Now we sort by midpoint and yank out the feature IDs.
1081        my @retVal = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @list;
1082        # Return it along with the min and max.
1083        return (\@retVal, $min, $max);
1084    }
1085    
1086    =head3 GeneDataInRegion
1087    
1088    C<< my @featureList = $sprout->GenesInRegion($contigID, $start, $stop); >>
1089    
1090    List the features which overlap a specified region in a contig.
1091    
1092    =over 4
1093    
1094    =item contigID
1095    
1096    ID of the contig containing the region of interest.
1097    
1098    =item start
1099    
1100    Offset of the first residue in the region of interest.
1101    
1102    =item stop
1103    
1104    Offset of the last residue in the region of interest.
1105    
1106    =item RETURN
1107    
1108    Returns a list of B<ERDBObjects> for the desired features. Each object will
1109    contain a B<Feature> record.
1110    
1111    =back
1112    
1113    =cut
1114    
1115    sub GeneDataInRegion {
1116        # Get the parameters.
1117        my ($self, $contigID, $start, $stop) = @_;
1118        # Get the maximum segment length.
1119        my $maximumSegmentLength = $self->MaxSegment;
1120        # Create a hash to receive the feature list. We use a hash so that we can eliminate
1121        # duplicates easily. The hash key will be the feature ID. The value will be the feature's
1122        # ERDBObject from the query.
1123        my %featuresFound = ();
1124        # Create a table of parameters for the queries. Each query looks for features travelling in
1125      # 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,
1126      # 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
1127      # 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 929  Line 1130 
1130      # Loop through the query parameters.      # Loop through the query parameters.
1131      for my $parms (values %queryParms) {      for my $parms (values %queryParms) {
1132          # Create the query.          # Create the query.
1133          my $query = $self->Get(['IsLocatedIn'],          my $query = $self->Get([qw(Feature IsLocatedIn)],
1134              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",              "IsLocatedIn(to-link)= ? AND IsLocatedIn(dir) = ? AND IsLocatedIn(beg) >= ? AND IsLocatedIn(beg) <= ?",
1135              $parms);              $parms);
1136          # Loop through the feature segments found.          # Loop through the feature segments found.
1137          while (my $segment = $query->Fetch) {          while (my $segment = $query->Fetch) {
1138              # Get the data about this segment.              # Get the data about this segment.
1139              my ($featureID, $dir, $beg, $len) = $segment->Values(['IsLocatedIn(from-link)',              my ($featureID, $contig, $dir, $beg, $len) = $segment->Values([qw(IsLocatedIn(from-link)
1140                  'IsLocatedIn(dir)', 'IsLocatedIn(beg)', 'IsLocatedIn(len)']);                  IsLocatedIn(to-link) IsLocatedIn(dir) IsLocatedIn(beg) IsLocatedIn(len))]);
1141              # 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
1142              # 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
1143              # 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
1144              # length.              # length.
1145              my ($found, $end) = (0, 0);              my $loc = BasicLocation->new($contig, $beg, $dir, $len);
1146              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;  
                 }  
             }  
1147              if ($found) {              if ($found) {
1148                  # Here we need to record the feature and update the minima and maxima. First,                  # Save this feature in the result list.
1149                  # 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];  
1150              }              }
1151          }          }
1152      }      }
1153      # 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.
1154      # 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);  
1155  }  }
1156    
1157  =head3 FType  =head3 FType
# Line 1019  Line 1186 
1186    
1187  =head3 FeatureAnnotations  =head3 FeatureAnnotations
1188    
1189  C<< my @descriptors = $sprout->FeatureAnnotations($featureID); >>  C<< my @descriptors = $sprout->FeatureAnnotations($featureID, $rawFlag); >>
1190    
1191  Return the annotations of a feature.  Return the annotations of a feature.
1192    
# Line 1029  Line 1196 
1196    
1197  ID of the feature whose annotations are desired.  ID of the feature whose annotations are desired.
1198    
1199    =item rawFlag
1200    
1201    If TRUE, the annotation timestamps will be returned in raw form; otherwise, they
1202    will be returned in human-readable form.
1203    
1204  =item RETURN  =item RETURN
1205    
1206  Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.  Returns a list of annotation descriptors. Each descriptor is a hash with the following fields.
1207    
1208  * B<featureID> ID of the relevant feature.  * B<featureID> ID of the relevant feature.
1209    
1210  * B<timeStamp> time the annotation was made, in user-friendly format.  * B<timeStamp> time the annotation was made.
1211    
1212  * B<user> ID of the user who made the annotation  * B<user> ID of the user who made the annotation
1213    
# Line 1047  Line 1219 
1219  #: Return Type @%;  #: Return Type @%;
1220  sub FeatureAnnotations {  sub FeatureAnnotations {
1221      # Get the parameters.      # Get the parameters.
1222      my ($self, $featureID) = @_;      my ($self, $featureID, $rawFlag) = @_;
1223      # Create a query to get the feature's annotations and the associated users.      # Create a query to get the feature's annotations and the associated users.
1224      my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],      my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1225                             "IsTargetOfAnnotation(from-link) = ?", [$featureID]);                             "IsTargetOfAnnotation(from-link) = ?", [$featureID]);
# Line 1060  Line 1232 
1232              $annotation->Values(['IsTargetOfAnnotation(from-link)',              $annotation->Values(['IsTargetOfAnnotation(from-link)',
1233                                   'Annotation(time)', 'MadeAnnotation(from-link)',                                   'Annotation(time)', 'MadeAnnotation(from-link)',
1234                                   'Annotation(annotation)']);                                   'Annotation(annotation)']);
1235            # Convert the time, if necessary.
1236            if (! $rawFlag) {
1237                $timeStamp = FriendlyTimestamp($timeStamp);
1238            }
1239          # Assemble them into a hash.          # Assemble them into a hash.
1240          my $annotationHash = { featureID => $featureID,          my $annotationHash = { featureID => $featureID,
1241                                 timeStamp => FriendlyTimestamp($timeStamp),                                 timeStamp => $timeStamp,
1242                                 user => $user, text => $text };                                 user => $user, text => $text };
1243          # Add it to the return list.          # Add it to the return list.
1244          push @retVal, $annotationHash;          push @retVal, $annotationHash;
# Line 1091  Line 1267 
1267    
1268  =item RETURN  =item RETURN
1269    
1270  Returns a hash mapping the functional assignment IDs to user IDs.  Returns a hash mapping the user IDs to functional assignment IDs.
1271    
1272  =back  =back
1273    
# Line 1101  Line 1277 
1277      # Get the parameters.      # Get the parameters.
1278      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1279      # Get all of the feature's annotations.      # Get all of the feature's annotations.
1280      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'],      my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1281                              "IsTargetOfAnnotation(from-link) = ?",                              "IsTargetOfAnnotation(from-link) = ?",
1282                              [$featureID], ['Annotation(time)', 'Annotation(annotation)']);                              [$featureID], ['Annotation(time)', 'Annotation(annotation)',
1283                                               'MadeAnnotation(from-link)']);
1284      # Declare the return hash.      # Declare the return hash.
1285      my %retVal;      my %retVal;
     # Declare a hash for insuring we only make one assignment per user.  
     my %timeHash = ();  
1286      # Now we sort the assignments by timestamp in reverse.      # Now we sort the assignments by timestamp in reverse.
1287      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;      my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query;
1288      # Loop until we run out of annotations.      # Loop until we run out of annotations.
1289      for my $annotation (@sortedQuery) {      for my $annotation (@sortedQuery) {
1290          # Get the annotation fields.          # Get the annotation fields.
1291          my ($timeStamp, $text) = @{$annotation};          my ($timeStamp, $text, $user) = @{$annotation};
1292          # Check to see if this is a functional assignment.          # Check to see if this is a functional assignment.
1293          my ($user, $function) = _ParseAssignment($text);          my ($actualUser, $function) = _ParseAssignment($user, $text);
1294          if ($user && ! exists $timeHash{$user}) {          if ($actualUser && ! exists $retVal{$actualUser}) {
1295              # Here it is a functional assignment and there has been no              # Here it is a functional assignment and there has been no
1296              # previous assignment for this user, so we stuff it in the              # previous assignment for this user, so we stuff it in the
1297              # return hash.              # return hash.
1298              $retVal{$function} = $user;              $retVal{$actualUser} = $function;
             # Insure we don't assign to this user again.  
             $timeHash{$user} = 1;  
1299          }          }
1300      }      }
1301      # Return the hash of assignments found.      # Return the hash of assignments found.
# Line 1136  Line 1309 
1309  Return the most recently-determined functional assignment of a particular feature.  Return the most recently-determined functional assignment of a particular feature.
1310    
1311  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
1312  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
1313  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</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.  
1314    
1315  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
1316  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 1159  Line 1329 
1329    
1330  =item userID (optional)  =item userID (optional)
1331    
1332  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
1333  C<FIG> assignment will be returned.  functional assignment in the B<Feature> table will be returned.
1334    
1335  =item RETURN  =item RETURN
1336    
# Line 1177  Line 1347 
1347      my $retVal;      my $retVal;
1348      # Determine the ID type.      # Determine the ID type.
1349      if ($featureID =~ m/^fig\|/) {      if ($featureID =~ m/^fig\|/) {
1350          # Here we have a FIG feature ID. We must build the list of trusted          # Here we have a FIG feature ID.
1351          # users.          if (!$userID) {
1352                # Use the primary assignment.
1353                ($retVal) = $self->GetEntityValues('Feature', $featureID, ['Feature(assignment)']);
1354            } else {
1355                # We must build the list of trusted users.
1356          my %trusteeTable = ();          my %trusteeTable = ();
1357          # Check the user ID.          # Check the user ID.
1358          if (!$userID) {          if (!$userID) {
# Line 1200  Line 1374 
1374              }              }
1375          }          }
1376          # Build a query for all of the feature's annotations, sorted by date.          # Build a query for all of the feature's annotations, sorted by date.
1377          my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation'],              my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1378                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",                                 "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1379                                 [$featureID]);                                 [$featureID]);
1380          my $timeSelected = 0;          my $timeSelected = 0;
1381          # Loop until we run out of annotations.          # Loop until we run out of annotations.
1382          while (my $annotation = $query->Fetch()) {          while (my $annotation = $query->Fetch()) {
1383              # Get the annotation text.              # Get the annotation text.
1384              my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']);                  my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1385                                                             'Annotation(time)', 'MadeAnnotation(from-link)']);
1386              # Check to see if this is a functional assignment for a trusted user.              # Check to see if this is a functional assignment for a trusted user.
1387              my ($user, $function) = _ParseAssignment($text);                  my ($actualUser, $function) = _ParseAssignment($user, $text);
1388              if ($user) {                  Trace("Assignment user is $actualUser, text is $function.") if T(4);
1389                    if ($actualUser) {
1390                  # Here it is a functional assignment. Check the time and the user                  # Here it is a functional assignment. Check the time and the user
1391                  # name. The time must be recent and the user must be trusted.                  # name. The time must be recent and the user must be trusted.
1392                  if ((exists $trusteeTable{$user}) && ($time > $timeSelected)) {                      if ((exists $trusteeTable{$actualUser}) && ($time > $timeSelected)) {
1393                      $retVal = $function;                      $retVal = $function;
1394                      $timeSelected = $time;                      $timeSelected = $time;
1395                  }                  }
1396              }              }
1397          }          }
1398            }
1399      } else {      } else {
1400          # 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
1401          # matter. We simply get the information from the External Alias Function          # matter. We simply get the information from the External Alias Function
# Line 1229  Line 1406 
1406      return $retVal;      return $retVal;
1407  }  }
1408    
1409    =head3 FunctionsOf
1410    
1411    C<< my @functionList = $sprout->FunctionOf($featureID, $userID); >>
1412    
1413    Return the functional assignments of a particular feature.
1414    
1415    The functional assignment is handled differently depending on the type of feature. If
1416    the feature is identified by a FIG ID (begins with the string C<fig|>), then a functional
1417    assignment is a type of annotation. The format of an assignment is described in
1418    L</ParseAssignment>. Its worth noting that we cannot filter on the content of the
1419    annotation itself because it's a text field; however, this is not a big problem because
1420    most features only have a small number of annotations.
1421    
1422    If the feature is B<not> identified by a FIG ID, then the functional assignment
1423    information is taken from the B<ExternalAliasFunc> table. If the table does
1424    not contain an entry for the feature, an empty list is returned.
1425    
1426    =over 4
1427    
1428    =item featureID
1429    
1430    ID of the feature whose functional assignments are desired.
1431    
1432    =item RETURN
1433    
1434    Returns a list of 2-tuples, each consisting of a user ID and the text of an assignment by
1435    that user.
1436    
1437    =back
1438    
1439    =cut
1440    #: Return Type @@;
1441    sub FunctionsOf {
1442        # Get the parameters.
1443        my ($self, $featureID) = @_;
1444        # Declare the return value.
1445        my @retVal = ();
1446        # Determine the ID type.
1447        if ($featureID =~ m/^fig\|/) {
1448            # Here we have a FIG feature ID. We must build the list of trusted
1449            # users.
1450            my %trusteeTable = ();
1451            # Build a query for all of the feature's annotations, sorted by date.
1452            my $query = $self->Get(['IsTargetOfAnnotation', 'Annotation', 'MadeAnnotation'],
1453                                   "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC",
1454                                   [$featureID]);
1455            my $timeSelected = 0;
1456            # Loop until we run out of annotations.
1457            while (my $annotation = $query->Fetch()) {
1458                # Get the annotation text.
1459                my ($text, $time, $user) = $annotation->Values(['Annotation(annotation)',
1460                                                                'Annotation(time)',
1461                                                                'MadeAnnotation(user)']);
1462                # Check to see if this is a functional assignment for a trusted user.
1463                my ($actualUser, $function) = _ParseAssignment($user, $text);
1464                if ($actualUser) {
1465                    # Here it is a functional assignment.
1466                    push @retVal, [$actualUser, $function];
1467                }
1468            }
1469        } else {
1470            # Here we have a non-FIG feature ID. In this case the user ID does not
1471            # matter. We simply get the information from the External Alias Function
1472            # table.
1473            my @assignments = $self->GetEntityValues('ExternalAliasFunc', $featureID,
1474                                                     ['ExternalAliasFunc(func)']);
1475            push @retVal, map { ['master', $_] } @assignments;
1476        }
1477        # Return the assignments found.
1478        return @retVal;
1479    }
1480    
1481  =head3 BBHList  =head3 BBHList
1482    
1483  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>  C<< my $bbhHash = $sprout->BBHList($genomeID, \@featureList); >>
# Line 1262  Line 1511 
1511      my %retVal = ();      my %retVal = ();
1512      # Loop through the incoming features.      # Loop through the incoming features.
1513      for my $featureID (@{$featureList}) {      for my $featureID (@{$featureList}) {
1514          # Create a query to get the feature's best hit.          # Ask the server for the feature's best hit.
1515          my $query = $self->Get(['IsBidirectionalBestHitOf'],          my @bbhData = FIGRules::BBHData($featureID);
1516                                 "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?",          # Peel off the BBHs found.
1517                                 [$featureID, $genomeID]);          my @found = ();
1518          # Look for the best hit.          for my $bbh (@bbhData) {
1519          my $bbh = $query->Fetch;              my $fid = $bbh->[0];
1520          if ($bbh) {              my $bbGenome = $self->GenomeOf($fid);
1521              my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)');              if ($bbGenome eq $genomeID) {
1522              $retVal{$featureID} = $targetFeature;                  push @found, $fid;
1523          }          }
1524      }      }
1525            $retVal{$featureID} = \@found;
1526        }
1527      # Return the mapping.      # Return the mapping.
1528      return \%retVal;      return \%retVal;
1529  }  }
# Line 1283  Line 1534 
1534    
1535  Return a list of the similarities to the specified feature.  Return a list of the similarities to the specified feature.
1536    
1537  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.  
1538    
1539  =over 4  =over 4
1540    
# Line 1304  Line 1554 
1554      # Get the parameters.      # Get the parameters.
1555      my ($self, $featureID, $count) = @_;      my ($self, $featureID, $count) = @_;
1556      # Ask for the best hits.      # Ask for the best hits.
1557      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);  
1558      # Create the return value.      # Create the return value.
1559      my %retVal = ();      my %retVal = ();
1560      for my $tuple (@lists) {      for my $tuple (@lists) {
# Line 1317  Line 1564 
1564      return %retVal;      return %retVal;
1565  }  }
1566    
   
   
1567  =head3 IsComplete  =head3 IsComplete
1568    
1569  C<< my $flag = $sprout->IsComplete($genomeID); >>  C<< my $flag = $sprout->IsComplete($genomeID); >>
# Line 1349  Line 1594 
1594      my $genomeData = $self->GetEntity('Genome', $genomeID);      my $genomeData = $self->GetEntity('Genome', $genomeID);
1595      if ($genomeData) {      if ($genomeData) {
1596          # The genome exists, so get the completeness flag.          # The genome exists, so get the completeness flag.
1597          ($retVal) = $genomeData->Value('complete');          $retVal = $genomeData->PrimaryValue('Genome(complete)');
1598      }      }
1599      # Return the result.      # Return the result.
1600      return $retVal;      return $retVal;
# Line 1380  Line 1625 
1625      # Get the parameters.      # Get the parameters.
1626      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1627      # Get the desired feature's aliases      # Get the desired feature's aliases
1628      my @retVal = $self->GetEntityValues('Feature', $featureID, ['Feature(alias)']);      my @retVal = $self->GetFlat(['IsAliasOf'], "IsAliasOf(to-link) = ?", [$featureID], 'IsAliasOf(from-link)');
1629      # Return the result.      # Return the result.
1630      return @retVal;      return @retVal;
1631  }  }
# Line 1389  Line 1634 
1634    
1635  C<< my $genomeID = $sprout->GenomeOf($featureID); >>  C<< my $genomeID = $sprout->GenomeOf($featureID); >>
1636    
1637  Return the genome that contains a specified feature.  Return the genome that contains a specified feature or contig.
1638    
1639  =over 4  =over 4
1640    
1641  =item featureID  =item featureID
1642    
1643  ID of the feature whose genome is desired.  ID of the feature or contig whose genome is desired.
1644    
1645  =item RETURN  =item RETURN
1646    
1647  Returns the ID of the genome for the specified feature. If the feature is not found, returns  Returns the ID of the genome for the specified feature or contig. If the feature or contig is not
1648  an undefined value.  found, returns an undefined value.
1649    
1650  =back  =back
1651    
# Line 1409  Line 1654 
1654  sub GenomeOf {  sub GenomeOf {
1655      # Get the parameters.      # Get the parameters.
1656      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
     # Create a query to find the genome associated with the feature.  
     my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]);  
1657      # Declare the return value.      # Declare the return value.
1658      my $retVal;      my $retVal;
1659      # Get the genome ID.      # Parse the genome ID from the feature ID.
1660      if (my $relationship = $query->Fetch()) {      if ($featureID =~ /^fig\|(\d+\.\d+)/) {
1661          ($retVal) = $relationship->Value('HasContig(from-link)');          $retVal = $1;
1662        } else {
1663            Confess("Invalid feature ID $featureID.");
1664      }      }
1665      # Return the value found.      # Return the value found.
1666      return $retVal;      return $retVal;
# Line 1445  Line 1690 
1690  sub CoupledFeatures {  sub CoupledFeatures {
1691      # Get the parameters.      # Get the parameters.
1692      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
1693      # Create a query to retrieve the functionally-coupled features.      # Ask the coupling server for the data.
1694      my $query = $self->Get(['ParticipatesInCoupling', 'Coupling'],      Trace("Looking for features coupled to $featureID.") if T(coupling => 3);
1695                             "ParticipatesInCoupling(from-link) = ?", [$featureID]);      my @rawPairs = FIGRules::NetCouplingData('coupled_to', id1 => $featureID);
1696      # This value will be set to TRUE if we find at least one coupled feature.      Trace(scalar(@rawPairs) . " couplings returned.") if T(coupling => 3);
1697      my $found = 0;      # Form them into a hash.
     # Create the return hash.  
1698      my %retVal = ();      my %retVal = ();
1699      # Retrieve the relationship records and store them in the hash.      for my $pair (@rawPairs) {
1700      while (my $clustering = $query->Fetch()) {          # Get the feature ID and score.
1701          # Get the ID and score of the coupling.          my ($featureID2, $score) = @{$pair};
1702          my ($couplingID, $score) = $clustering->Values(['Coupling(id)',          # Only proceed if the feature is in NMPDR.
1703                                                          'Coupling(score)']);          if ($self->_CheckFeature($featureID2)) {
1704          # The coupling ID contains the two feature IDs separated by a space. We use              $retVal{$featureID2} = $score;
1705          # 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;  
1706      }      }
1707      # 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
1708      # the incoming feature as well.      # the incoming feature as well.
1709      if ($found) {      if (keys %retVal) {
1710          $retVal{$featureID} = 9999;          $retVal{$featureID} = 9999;
1711      }      }
1712      # Return the hash.      # Return the hash.
# Line 1524  Line 1763 
1763      my ($self, $peg1, $peg2) = @_;      my ($self, $peg1, $peg2) = @_;
1764      # Declare the return variable.      # Declare the return variable.
1765      my @retVal = ();      my @retVal = ();
1766      # Our first task is to find out the nature of the coupling: whether or not      # Get the coupling and evidence data.
1767      # it exists, its score, and whether the features are stored in the same      my @rawData = FIGRules::NetCouplingData('coupling_evidence', id1 => $peg1, id2 => $peg2);
1768      # order as the ones coming in.      # Loop through the raw data, saving the ones that are in NMPDR genomes.
1769      my ($couplingID, $inverted, $score) = $self->GetCoupling($peg1, $peg2);      for my $rawTuple (@rawData) {
1770      # Only proceed if a coupling exists.          if ($self->_CheckFeature($rawTuple->[0]) && $self->_CheckFeature($rawTuple->[1])) {
1771      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]];  
1772          }          }
         Trace("Last index in evidence result is is $#retVal.") if T(Coupling => 4);  
1773      }      }
1774      # Return the result.      # Return the result.
1775      return @retVal;      return @retVal;
1776  }  }
1777    
1778  =head3 GetCoupling  =head3 GetSynonymGroup
1779    
1780  C<< my ($couplingID, $inverted, $score) = $sprout->GetCoupling($peg1, $peg2); >>  C<< my $id = $sprout->GetSynonymGroup($fid); >>
1781    
1782  Return the coupling (if any) for the specified pair of PEGs. If a coupling  Return the synonym group name for the specified feature.
 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.  
1783    
1784  =over 4  =over 4
1785    
1786  =item peg1  =item fid
   
 ID of the feature of interest.  
   
 =item peg2  
1787    
1788  ID of the potentially coupled feature.  ID of the feature whose synonym group is desired.
1789    
1790  =item RETURN  =item RETURN
1791    
1792  Returns a three-element list. The first element contains the database ID of  The name of the synonym group to which the feature belongs. If the feature does
1793  the coupling. The second element is FALSE if the coupling is stored in the  not belong to a synonym group, the feature ID itself is returned.
 database in the caller specified order and TRUE if it is stored in the  
 inverted order. The third element is the coupling's score. If the coupling  
 does not exist, all three list elements will be C<undef>.  
1794    
1795  =back  =back
1796    
1797  =cut  =cut
1798  #: Return Type $%@;  
1799  sub GetCoupling {  sub GetSynonymGroup {
1800      # Get the parameters.      # Get the parameters.
1801      my ($self, $peg1, $peg2) = @_;      my ($self, $fid) = @_;
1802      # Declare the return values. We'll start with the coupling ID and undefine the      # Declare the return variable.
1803      # flag and score until we have more information.      my $retVal;
1804      my ($retVal, $inverted, $score) = (CouplingID($peg1, $peg2), undef, undef);      # Find the synonym group.
1805      # Find the coupling data.      my @groups = $self->GetFlat(['IsSynonymGroupFor'], "IsSynonymGroupFor(to-link) = ?",
1806      my @pegs = $self->GetAll(['Coupling', 'ParticipatesInCoupling'],                                     [$fid], 'IsSynonymGroupFor(from-link)');
                                  "Coupling(id) = ? ORDER BY ParticipatesInCoupling(pos)",  
                                  [$retVal], ["ParticipatesInCoupling(from-link)", "Coupling(score)"]);  
1807      # Check to see if we found anything.      # Check to see if we found anything.
1808      if (!@pegs) {      if (@groups) {
1809          Trace("No coupling found.") if T(Coupling => 4);          $retVal = $groups[0];
         # No coupling, so undefine the return value.  
         $retVal = undef;  
1810      } else {      } else {
1811          # We have a coupling! Get the score and check for inversion.          $retVal = $fid;
         $score = $pegs[0]->[1];  
         my $firstFound = $pegs[0]->[0];  
         $inverted = ($firstFound ne $peg1);  
         Trace("Coupling score is $score. First peg is $firstFound, peg 1 is $peg1.") if T(Coupling => 4);  
1812      }      }
1813      # Return the result.      # Return the result.
1814      return ($retVal, $inverted, $score);      return $retVal;
1815  }  }
1816    
1817  =head3 CouplingID  =head3 GetBoundaries
1818    
1819  C<< my $couplingID = Sprout::CouplingID($peg1, $peg2); >>  C<< my ($contig, $beg, $end) = $sprout->GetBoundaries(@locList); >>
1820    
1821  Return the coupling ID for a pair of feature IDs.  Determine the begin and end boundaries for the locations in a list. All of the
1822    locations must belong to the same contig and have mostly the same direction in
1823  The coupling ID is currently computed by joining the feature IDs in  order for this method to produce a meaningful result. The resulting
1824  sorted order with a space. Client modules (that is, modules which  begin/end pair will contain all of the bases in any of the locations.
 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")>.  
1825    
1826  =over 4  =over 4
1827    
1828  =item peg1  =item locList
   
 First feature of interest.  
   
 =item peg2  
1829    
1830  Second feature of interest.  List of locations to process.
1831    
1832  =item RETURN  =item RETURN
1833    
1834  Returns the ID that would be used to represent a functional coupling of  Returns a 3-tuple consisting of the contig ID, the beginning boundary,
1835  the two specified PEGs.  and the ending boundary. The beginning boundary will be left of the
1836    end for mostly-forward locations and right of the end for mostly-backward
1837    locations.
1838    
1839  =back  =back
1840    
1841  =cut  =cut
 #: Return Type $;  
 sub CouplingID {  
     return join " ", sort @_;  
 }  
   
 =head3 GetEntityTypes  
   
 C<< my @entityList = $sprout->GetEntityTypes(); >>  
   
 Return the list of supported entity types.  
1842    
1843  =cut  sub GetBoundaries {
 #: Return Type @;  
 sub GetEntityTypes {  
1844      # Get the parameters.      # Get the parameters.
1845      my ($self) = @_;      my ($self, @locList) = @_;
1846      # Get the underlying database object.      # Set up the counters used to determine the most popular direction.
1847      my $erdb = $self->{_erdb};      my %counts = ( '+' => 0, '-' => 0 );
1848      # Get its entity type list.      # Get the last location and parse it.
1849      my @retVal = $erdb->GetEntityTypes();      my $locObject = BasicLocation->new(pop @locList);
1850        # Prime the loop with its data.
1851        my ($contig, $beg, $end) = ($locObject->Contig, $locObject->Left, $locObject->Right);
1852        # Count its direction.
1853        $counts{$locObject->Dir}++;
1854        # Loop through the remaining locations. Note that in most situations, this loop
1855        # will not iterate at all, because most of the time we will be dealing with a
1856        # singleton list.
1857        for my $loc (@locList) {
1858            # Create a location object.
1859            my $locObject = BasicLocation->new($loc);
1860            # Count the direction.
1861            $counts{$locObject->Dir}++;
1862            # Get the left end and the right end.
1863            my $left = $locObject->Left;
1864            my $right = $locObject->Right;
1865            # Merge them into the return variables.
1866            if ($left < $beg) {
1867                $beg = $left;
1868            }
1869            if ($right > $end) {
1870                $end = $right;
1871            }
1872        }
1873        # If the most common direction is reverse, flip the begin and end markers.
1874        if ($counts{'-'} > $counts{'+'}) {
1875            ($beg, $end) = ($end, $beg);
1876        }
1877        # Return the result.
1878        return ($contig, $beg, $end);
1879  }  }
1880    
1881  =head3 ReadFasta  =head3 ReadFasta
# Line 1814  Line 2023 
2023      # Get the data directory name.      # Get the data directory name.
2024      my $outputDirectory = $self->{_options}->{dataDir};      my $outputDirectory = $self->{_options}->{dataDir};
2025      # Dump the relations.      # Dump the relations.
2026      $self->{_erdb}->DumpRelations($outputDirectory);      $self->DumpRelations($outputDirectory);
2027  }  }
2028    
2029  =head3 XMLFileName  =head3 XMLFileName
# Line 1866  Line 2075 
2075      # Get the parameters.      # Get the parameters.
2076      my ($self, $objectType, $fieldHash) = @_;      my ($self, $objectType, $fieldHash) = @_;
2077      # Call the underlying method.      # Call the underlying method.
2078      $self->{_erdb}->InsertObject($objectType, $fieldHash);      $self->InsertObject($objectType, $fieldHash);
2079  }  }
2080    
2081  =head3 Annotate  =head3 Annotate
# Line 2019  Line 2228 
2228          push @retVal, $mappedAlias;          push @retVal, $mappedAlias;
2229      } else {      } else {
2230          # 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.
2231          @retVal = $self->GetFlat(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)');          @retVal = $self->GetFlat(['IsAliasOf'], 'IsAliasOf(from-link) = ?', [$mappedAlias], 'IsAliasOf(to-link)');
2232      }      }
2233      # Return the result.      # Return the result.
2234      return @retVal;      return @retVal;
2235  }  }
2236    
 =head3 Exists  
   
 C<< my $found = $sprout->Exists($entityName, $entityID); >>  
   
 Return TRUE if an entity exists, else FALSE.  
   
 =over 4  
   
 =item entityName  
   
 Name of the entity type (e.g. C<Feature>) relevant to the existence check.  
   
 =item entityID  
   
 ID of the entity instance whose existence is to be checked.  
   
 =item RETURN  
   
 Returns TRUE if the entity instance exists, else FALSE.  
   
 =back  
   
 =cut  
 #: Return Type $;  
 sub Exists {  
     # Get the parameters.  
     my ($self, $entityName, $entityID) = @_;  
     # Check for the entity instance.  
     Trace("Checking existence of $entityName with ID=$entityID.") if T(4);  
     my $testInstance = $self->GetEntity($entityName, $entityID);  
     # Return an existence indicator.  
     my $retVal = ($testInstance ? 1 : 0);  
     return $retVal;  
 }  
   
2237  =head3 FeatureTranslation  =head3 FeatureTranslation
2238    
2239  C<< my $translation = $sprout->FeatureTranslation($featureID); >>  C<< my $translation = $sprout->FeatureTranslation($featureID); >>
# Line 2251  Line 2425 
2425    
2426  Return a list of the properties with the specified characteristics.  Return a list of the properties with the specified characteristics.
2427    
2428  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
2429  will also be associated with genomes.) A property value is represented by a 4-tuple of  passed directly to the CustomAttributes or RemoteCustomAttributes object
2430  the form B<($fid, $key, $value, $url)>. These exactly correspond to the parameter  contained in this object.
2431    
2432  =over 4  This method returns a series of tuples that match the specified criteria. Each tuple
2433    will contain an object ID, a key, and one or more values. The parameters to this
2434    method therefore correspond structurally to the values expected in each tuple. In
2435    addition, you can ask for a generic search by suffixing a percent sign (C<%>) to any
2436    of the parameters. So, for example,
2437    
2438  =item fid      my @attributeList = $sprout->GetProperties('fig|100226.1.peg.1004', 'structure%', 1, 2);
2439    
2440  ID of the feature possessing the property.  would return something like
2441    
2442  =item key      ['fig}100226.1.peg.1004', 'structure', 1, 2]
2443        ['fig}100226.1.peg.1004', 'structure1', 1, 2]
2444        ['fig}100226.1.peg.1004', 'structure2', 1, 2]
2445        ['fig}100226.1.peg.1004', 'structureA', 1, 2]
2446    
2447  Name or key of the property.  Use of C<undef> in any position acts as a wild card (all values). You can also specify
2448    a list reference in the ID column. Thus,
2449    
2450  =item value      my @attributeList = $sprout->GetProperties(['100226.1', 'fig|100226.1.%'], 'PUBMED');
2451    
2452  Value of the property.  would get the PUBMED attribute data for Streptomyces coelicolor A3(2) and all its
2453    features.
2454    
2455  =item url  In addition to values in multiple sections, a single attribute key can have multiple
2456    values, so even
2457    
2458  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.  
2459    
2460  =back  which has no wildcard in the key or the object ID, may return multiple tuples.
2461    
2462    =over 4
2463    
2464    =item objectID
2465    
2466    ID of object whose attributes are desired. If the attributes are desired for multiple
2467    objects, this parameter can be specified as a list reference. If the attributes are
2468    desired for all objects, specify C<undef> or an empty string. Finally, you can specify
2469    attributes for a range of object IDs by putting a percent sign (C<%>) at the end.
2470    
2471  The parameters act as a filter for the desired data. Any non-null parameter will  =item key
 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.  
2472    
2473  A single property key can have many values, representing different ideas about the  Attribute key name. A value of C<undef> or an empty string will match all
2474  feature in question. For example, one paper may declare that a feature C<fig|83333.1.peg.10> is  attribute keys. If the values are desired for multiple keys, this parameter can be
2475  virulent, and another may declare that it is not virulent. A query about the virulence of  specified as a list reference. Finally, you can specify attributes for a range of
2476  C<fig|83333.1.peg.10> would be coded as  keys by putting a percent sign (C<%>) at the end.
2477    
2478    =item values
2479    
2480    List of the desired attribute values, section by section. If C<undef>
2481    or an empty string is specified, all values in that section will match. A
2482    generic match can be requested by placing a percent sign (C<%>) at the end.
2483    In that case, all values that match up to and not including the percent sign
2484    will match. You may also specify a regular expression enclosed
2485    in slashes. All values that match the regular expression will be returned. For
2486    performance reasons, only values have this extra capability.
2487    
2488      my @list = $sprout->GetProperties('fig|83333.1.peg.10', 'virulence', '', '');  =item RETURN
2489    
2490  Here the I<$value> and I<$url> fields are left blank, indicating that those fields are  Returns a list of tuples. The first element in the tuple is an object ID, the
2491  not to be filtered. The tuples returned would be  second is an attribute key, and the remaining elements are the sections of
2492    the attribute value. All of the tuples will match the criteria set forth in
2493    the parameter list.
2494    
2495      ('fig|83333.1.peg.10', 'virulence', 'yes', 'http://www.somewhere.edu/first.paper.pdf')  =back
     ('fig|83333.1.peg.10', 'virulence', 'no', 'http://www.somewhere.edu/second.paper.pdf')  
2496    
2497  =cut  =cut
2498  #: Return Type @@;  
2499  sub GetProperties {  sub GetProperties {
2500      # Get the parameters.      # Get the parameters.
2501      my ($self, @parms) = @_;      my ($self, @parms) = @_;
2502      # Declare the return variable.      # Declare the return variable.
2503      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;  
     }  
2504      # Return the result.      # Return the result.
2505      return @retVal;      return @retVal;
2506  }  }
# Line 2336  Line 2513 
2513  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
2514  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
2515  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
2516  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.  
2517    
2518  =over 4  =over 4
2519    
# Line 2348  Line 2523 
2523    
2524  =item RETURN  =item RETURN
2525    
2526  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.  
2527    
2528  =back  =back
2529    
# Line 2359  Line 2533 
2533      # Get the parameters.      # Get the parameters.
2534      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2535      # Get the properties.      # Get the properties.
2536      my @retVal = $self->GetAll(['HasProperty', 'Property'], "HasProperty(from-link) = ?", [$featureID],      my @attributes = $self->{_ca}->GetAttributes($featureID);
2537                              ['Property(property-name)', 'Property(property-value)',      # Strip the feature ID off each tuple.
2538                               'HasProperty(evidence)']);      my @retVal = ();
2539        for my $attributeRow (@attributes) {
2540            shift @{$attributeRow};
2541            push @retVal, $attributeRow;
2542        }
2543      # Return the resulting list.      # Return the resulting list.
2544      return @retVal;      return @retVal;
2545  }  }
# Line 2394  Line 2572 
2572      return $retVal;      return $retVal;
2573  }  }
2574    
2575    =head3 PropertyID
2576    
2577    C<< my $id = $sprout->PropertyID($propName, $propValue); >>
2578    
2579    Return the ID of the specified property name and value pair, if the
2580    pair exists. Only a small subset of the FIG attributes are stored as
2581    Sprout properties, mostly for use in search optimization.
2582    
2583    =over 4
2584    
2585    =item propName
2586    
2587    Name of the desired property.
2588    
2589    =item propValue
2590    
2591    Value expected for the desired property.
2592    
2593    =item RETURN
2594    
2595    Returns the ID of the name/value pair, or C<undef> if the pair does not exist.
2596    
2597    =back
2598    
2599    =cut
2600    
2601    sub PropertyID {
2602        # Get the parameters.
2603        my ($self, $propName, $propValue) = @_;
2604        # Try to find the ID.
2605        my ($retVal) = $self->GetFlat(['Property'],
2606                                      "Property(property-name) = ? AND Property(property-value) = ?",
2607                                      [$propName, $propValue], 'Property(id)');
2608        # Return the result.
2609        return $retVal;
2610    }
2611    
2612  =head3 MergedAnnotations  =head3 MergedAnnotations
2613    
2614  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>  C<< my @annotationList = $sprout->MergedAnnotations(\@list); >>
# Line 2547  Line 2762 
2762                                      ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);                                      ['HasSSCell(from-link)', 'IsRoleOf(from-link)']);
2763      # Create the return value.      # Create the return value.
2764      my %retVal = ();      my %retVal = ();
2765        # Build a hash to weed out duplicates. Sometimes the same PEG and role appears
2766        # in two spreadsheet cells.
2767        my %dupHash = ();
2768      # Loop through the results, adding them to the hash.      # Loop through the results, adding them to the hash.
2769      for my $record (@subsystems) {      for my $record (@subsystems) {
2770            # Get this subsystem and role.
2771          my ($subsys, $role) = @{$record};          my ($subsys, $role) = @{$record};
2772          if (exists $retVal{$subsys}) {          # Insure it's the first time for both.
2773            my $dupKey = "$subsys\n$role";
2774            if (! exists $dupHash{"$subsys\n$role"}) {
2775                $dupHash{$dupKey} = 1;
2776              push @{$retVal{$subsys}}, $role;              push @{$retVal{$subsys}}, $role;
         } else {  
             $retVal{$subsys} = [$role];  
2777          }          }
2778      }      }
2779      # Return the hash.      # Return the hash.
# Line 2586  Line 2806 
2806      # Get the parameters.      # Get the parameters.
2807      my ($self, $featureID) = @_;      my ($self, $featureID) = @_;
2808      # Get the list of names.      # Get the list of names.
2809      my @retVal = $self->GetFlat(['ContainsFeature', 'HasSSCell'], "ContainsFeature(to-link) = ?",      my @retVal = $self->GetFlat(['HasRoleInSubsystem'], "HasRoleInSubsystem(from-link) = ?",
2810                                  [$featureID], 'HasSSCell(from-link)');                                  [$featureID], 'HasRoleInSubsystem(to-link)');
2811        # Return the result, sorted.
2812        return sort @retVal;
2813    }
2814    
2815    =head3 GenomeSubsystemData
2816    
2817    C<< my %featureData = $sprout->GenomeSubsystemData($genomeID); >>
2818    
2819    Return a hash mapping genome features to their subsystem roles.
2820    
2821    =over 4
2822    
2823    =item genomeID
2824    
2825    ID of the genome whose subsystem feature map is desired.
2826    
2827    =item RETURN
2828    
2829    Returns a hash mapping each feature of the genome to a list of 2-tuples. Eacb
2830    2-tuple contains a subsystem name followed by a role ID.
2831    
2832    =back
2833    
2834    =cut
2835    
2836    sub GenomeSubsystemData {
2837        # Get the parameters.
2838        my ($self, $genomeID) = @_;
2839        # Declare the return variable.
2840        my %retVal = ();
2841        # Get a list of the genome features that participate in subsystems. For each
2842        # feature we get its spreadsheet cells and the corresponding roles.
2843        my @roleData = $self->GetAll(['HasFeature', 'ContainsFeature', 'IsRoleOf'],
2844                                 "HasFeature(from-link) = ?", [$genomeID],
2845                                 ['HasFeature(to-link)', 'IsRoleOf(to-link)', 'IsRoleOf(from-link)']);
2846        # Now we get a list of the spreadsheet cells and their associated subsystems. Subsystems
2847        # with an unknown variant code (-1) are skipped. Note the genome ID is at both ends of the
2848        # list. We use it at the beginning to get all the spreadsheet cells for the genome and
2849        # again at the end to filter out participation in subsystems with a negative variant code.
2850        my @cellData = $self->GetAll(['IsGenomeOf', 'HasSSCell', 'ParticipatesIn'],
2851                                     "IsGenomeOf(from-link) = ? AND ParticipatesIn(variant-code) >= 0 AND ParticipatesIn(from-link) = ?",
2852                                     [$genomeID, $genomeID], ['HasSSCell(to-link)', 'HasSSCell(from-link)']);
2853        # Now "@roleData" lists the spreadsheet cell and role for each of the genome's features.
2854        # "@cellData" lists the subsystem name for each of the genome's spreadsheet cells. We
2855        # link these two lists together to create the result. First, we want a hash mapping
2856        # spreadsheet cells to subsystem names.
2857        my %subHash = map { $_->[0] => $_->[1] } @cellData;
2858        # We loop through @cellData to build the hash.
2859        for my $roleEntry (@roleData) {
2860            # Get the data for this feature and cell.
2861            my ($fid, $cellID, $role) = @{$roleEntry};
2862            # Check for a subsystem name.
2863            my $subsys = $subHash{$cellID};
2864            if ($subsys) {
2865                # Insure this feature has an entry in the return hash.
2866                if (! exists $retVal{$fid}) { $retVal{$fid} = []; }
2867                # Merge in this new data.
2868                push @{$retVal{$fid}}, [$subsys, $role];
2869            }
2870        }
2871      # Return the result.      # Return the result.
2872      return @retVal;      return %retVal;
2873  }  }
2874    
2875  =head3 RelatedFeatures  =head3 RelatedFeatures
# Line 2627  Line 2907 
2907      # Get the parameters.      # Get the parameters.
2908      my ($self, $featureID, $function, $userID) = @_;      my ($self, $featureID, $function, $userID) = @_;
2909      # 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.
2910      my @bbhFeatures = $self->GetFlat(['IsBidirectionalBestHitOf'],      my @bbhFeatures = map { $_->[0] } FIGRules::BBHData($featureID);
                                      "IsBidirectionalBestHitOf(from-link) = ?", [$featureID],  
                                      'IsBidirectionalBestHitOf(to-link)');  
2911      # 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
2912      # functional assignment.      # functional assignment.
2913      my @retVal = ();      my @retVal = ();
# Line 2693  Line 2971 
2971      return @retVal;      return @retVal;
2972  }  }
2973    
 =head3 GetAll  
   
 C<< my @list = $sprout->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>  
   
 Return a list of values taken from the objects returned by a query. The first three  
 parameters correspond to the parameters of the L</Get> method. The final parameter is  
 a list of the fields desired from each record found by the query. The field name  
 syntax is the standard syntax used for fields in the B<ERDB> system--  
 B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity  
 or relationship and I<fieldName> is the name of the field.  
   
 The list returned will be a list of lists. Each element of the list will contain  
 the values returned for the fields specified in the fourth parameter. If one of the  
 fields specified returns multiple values, they are flattened in with the rest. For  
 example, the following call will return a list of the features in a particular  
 spreadsheet cell, and each feature will be represented by a list containing the  
 feature ID followed by all of its aliases.  
   
 C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>  
   
 =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 fields  
   
 List of the fields to be returned in each element of the list returned.  
   
 =item count  
   
 Maximum number of records to return. If omitted or 0, all available records will be returned.  
   
 =item RETURN  
   
 Returns a list of list references. Each element of the return list contains the values for the  
 fields specified in the B<fields> parameter.  
   
 =back  
   
 =cut  
 #: Return Type @@;  
 sub GetAll {  
     # Get the parameters.  
     my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;  
     # Call the ERDB method.  
     my @retVal = $self->{_erdb}->GetAll($objectNames, $filterClause, $parameterList,  
                                         $fields, $count);  
     # Return the resulting list.  
     return @retVal;  
 }  
   
 =head3 GetFlat  
   
 C<< my @list = $sprout->GetFlat(\@objectNames, $filterClause, $parameterList, $field); >>  
   
 This is a variation of L</GetAll> that asks for only a single field per record and  
 returns a single flattened list.  
   
 =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 field  
   
 Name of the field to be used to get the elements of the list returned.  
   
 =item RETURN  
   
 Returns a list of values.  
   
 =back  
   
 =cut  
 #: Return Type @;  
 sub GetFlat {  
     # Get the parameters.  
     my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;  
     # Construct the query.  
     my $query = $self->Get($objectNames, $filterClause, $parameterList);  
     # Create the result list.  
     my @retVal = ();  
     # Loop through the records, adding the field values found to the result list.  
     while (my $row = $query->Fetch()) {  
         push @retVal, $row->Value($field);  
     }  
     # Return the list created.  
     return @retVal;  
 }  
   
2974  =head3 Protein  =head3 Protein
2975    
2976  C<< my $protein = Sprout::Protein($sequence, $table); >>  C<< my $protein = Sprout::Protein($sequence, $table); >>
# Line 2884  Line 3043 
3043      # Loop through the input triples.      # Loop through the input triples.
3044      my $n = length $sequence;      my $n = length $sequence;
3045      for (my $i = 0; $i < $n; $i += 3) {      for (my $i = 0; $i < $n; $i += 3) {
3046          # Get the current triple from the sequence.          # Get the current triple from the sequence. Note we convert to
3047          my $triple = substr($sequence, $i, 3);          # upper case to insure a match.
3048            my $triple = uc substr($sequence, $i, 3);
3049          # Translate it using the table.          # Translate it using the table.
3050          my $protein = "X";          my $protein = "X";
3051          if (exists $table->{$triple}) { $protein = $table->{$triple}; }          if (exists $table->{$triple}) { $protein = $table->{$triple}; }
# Line 2913  Line 3073 
3073      # Create the return list, priming it with the name of the data directory.      # Create the return list, priming it with the name of the data directory.
3074      my @retVal = ($self->{_options}->{dataDir});      my @retVal = ($self->{_options}->{dataDir});
3075      # Concatenate the table names.      # Concatenate the table names.
3076      push @retVal, $self->{_erdb}->GetTableNames();      push @retVal, $self->GetTableNames();
3077      # Return the result.      # Return the result.
3078      return @retVal;      return @retVal;
3079  }  }
3080    
3081    =head3 BBHMatrix
3082    
3083    C<< my %bbhMap = $sprout->BBHMatrix($genomeID, $cutoff, @targets); >>
3084    
3085    Find all the bidirectional best hits for the features of a genome in a
3086    specified list of target genomes. The return value will be a hash mapping
3087    features in the original genome to their bidirectional best hits in the
3088    target genomes.
3089    
3090    =over 4
3091    
3092    =item genomeID
3093    
3094    ID of the genome whose features are to be examined for bidirectional best hits.
3095    
3096    =item cutoff
3097    
3098    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3099    
3100    =item targets
3101    
3102    List of target genomes. Only pairs originating in the original
3103    genome and landing in one of the target genomes will be returned.
3104    
3105    =item RETURN
3106    
3107    Returns a hash mapping each feature in the original genome to a hash mapping its
3108    BBH pegs in the target genomes to their scores.
3109    
3110    =back
3111    
3112    =cut
3113    
3114    sub BBHMatrix {
3115        # Get the parameters.
3116        my ($self, $genomeID, $cutoff, @targets) = @_;
3117        # Declare the return variable.
3118        my %retVal = ();
3119        # Ask for the BBHs.
3120        my @bbhList = FIGRules::BatchBBHs("fig|$genomeID.%", $cutoff, @targets);
3121        # We now have a set of 4-tuples that we need to convert into a hash of hashes.
3122        for my $bbhData (@bbhList) {
3123            my ($peg1, $peg2, $score) = @{$bbhData};
3124            if (! exists $retVal{$peg1}) {
3125                $retVal{$peg1} = { $peg2 => $score };
3126            } else {
3127                $retVal{$peg1}->{$peg2} = $score;
3128            }
3129        }
3130        # Return the result.
3131        return %retVal;
3132    }
3133    
3134    
3135    =head3 SimMatrix
3136    
3137    C<< my %simMap = $sprout->SimMatrix($genomeID, $cutoff, @targets); >>
3138    
3139    Find all the similarities for the features of a genome in a
3140    specified list of target genomes. The return value will be a hash mapping
3141    features in the original genome to their similarites in the
3142    target genomes.
3143    
3144    =over 4
3145    
3146    =item genomeID
3147    
3148    ID of the genome whose features are to be examined for similarities.
3149    
3150    =item cutoff
3151    
3152    A cutoff value. Only hits with a score lower than the cutoff will be returned.
3153    
3154    =item targets
3155    
3156    List of target genomes. Only pairs originating in the original
3157    genome and landing in one of the target genomes will be returned.
3158    
3159    =item RETURN
3160    
3161    Returns a hash mapping each feature in the original genome to a hash mapping its
3162    similar pegs in the target genomes to their scores.
3163    
3164    =back
3165    
3166    =cut
3167    
3168    sub SimMatrix {
3169        # Get the parameters.
3170        my ($self, $genomeID, $cutoff, @targets) = @_;
3171        # Declare the return variable.
3172        my %retVal = ();
3173        # Get the list of features in the source organism.
3174        my @fids = $self->FeaturesOf($genomeID);
3175        # Ask for the sims. We only want similarities to fig features.
3176        my $simList = FIGRules::GetNetworkSims($self, \@fids, {}, 1000, $cutoff, "fig");
3177        if (! defined $simList) {
3178            Confess("Unable to retrieve similarities from server.");
3179        } else {
3180            Trace("Processing sims.") if T(3);
3181            # We now have a set of sims that we need to convert into a hash of hashes. First, we
3182            # Create a hash for the target genomes.
3183            my %targetHash = map { $_ => 1 } @targets;
3184            for my $simData (@{$simList}) {
3185                # Get the PEGs and the score.
3186                my ($peg1, $peg2, $score) = ($simData->id1, $simData->id2, $simData->psc);
3187                # Insure the second ID is in the target list.
3188                my ($genome2) = FIGRules::ParseFeatureID($peg2);
3189                if (exists $targetHash{$genome2}) {
3190                    # Here it is. Now we need to add it to the return hash. How we do that depends
3191                    # on whether or not $peg1 is new to us.
3192                    if (! exists $retVal{$peg1}) {
3193                        $retVal{$peg1} = { $peg2 => $score };
3194                    } else {
3195                        $retVal{$peg1}->{$peg2} = $score;
3196                    }
3197                }
3198            }
3199        }
3200        # Return the result.
3201        return %retVal;
3202    }
3203    
3204    
3205  =head3 LowBBHs  =head3 LowBBHs
3206    
3207  C<< my %bbhMap = $sprout->GoodBBHs($featureID, $cutoff); >>  C<< my %bbhMap = $sprout->LowBBHs($featureID, $cutoff); >>
3208    
3209  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
3210  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 2949  Line 3233 
3233      my ($self, $featureID, $cutoff) = @_;      my ($self, $featureID, $cutoff) = @_;
3234      # Create the return hash.      # Create the return hash.
3235      my %retVal = ();      my %retVal = ();
3236      # Create a query to get the desired BBHs.      # Query for the desired BBHs.
3237      my @bbhList = $self->GetAll(['IsBidirectionalBestHitOf'],      my @bbhList = FIGRules::BBHData($featureID, $cutoff);
                                 'IsBidirectionalBestHitOf(sc) <= ? AND IsBidirectionalBestHitOf(from-link) = ?',  
                                 [$cutoff, $featureID],  
                                 ['IsBidirectionalBestHitOf(to-link)', 'IsBidirectionalBestHitOf(sc)']);  
3238      # Form the results into the return hash.      # Form the results into the return hash.
3239      for my $pair (@bbhList) {      for my $pair (@bbhList) {
3240          $retVal{$pair->[0]} = $pair->[1];          my $fid = $pair->[0];
3241            if ($self->Exists('Feature', $fid)) {
3242                $retVal{$fid} = $pair->[1];
3243            }
3244      }      }
3245      # Return the result.      # Return the result.
3246      return %retVal;      return %retVal;
3247  }  }
3248    
3249    =head3 Sims
3250    
3251    C<< my $simList = $sprout->Sims($fid, $maxN, $maxP, $select, $max_expand, $filters); >>
3252    
3253    Get a list of similarities for a specified feature. Similarity information is not kept in the
3254    Sprout database; rather, they are retrieved from a network server. The similarities are
3255    returned as B<Sim> objects. A Sim object is actually a list reference that has been blessed
3256    so that its elements can be accessed by name.
3257    
3258    Similarities can be either raw or expanded. The raw similarities are basic
3259    hits between features with similar DNA. Expanding a raw similarity drags in any
3260    features considered substantially identical. So, for example, if features B<A1>,
3261    B<A2>, and B<A3> are all substantially identical to B<A>, then a raw similarity
3262    B<[C,A]> would be expanded to B<[C,A] [C,A1] [C,A2] [C,A3]>.
3263    
3264    =over 4
3265    
3266    =item fid
3267    
3268    ID of the feature whose similarities are desired, or reference to a list of IDs
3269    of features whose similarities are desired.
3270    
3271    =item maxN
3272    
3273    Maximum number of similarities to return.
3274    
3275    =item maxP
3276    
3277    Minumum allowable similarity score.
3278    
3279    =item select
3280    
3281    Selection criterion: C<raw> means only raw similarities are returned; C<fig>
3282    means only similarities to FIG features are returned; C<all> means all expanded
3283    similarities are returned; and C<figx> means similarities are expanded until the
3284    number of FIG features equals the maximum.
3285    
3286    =item max_expand
3287    
3288    The maximum number of features to expand.
3289    
3290    =item filters
3291    
3292    Reference to a hash containing filter information, or a subroutine that can be
3293    used to filter the sims.
3294    
3295    =item RETURN
3296    
3297    Returns a reference to a list of similarity objects, or C<undef> if an error
3298    occurred.
3299    
3300    =back
3301    
3302    =cut
3303    
3304    sub Sims {
3305        # Get the parameters.
3306        my ($self, $fid, $maxN, $maxP, $select, $max_expand, $filters) = @_;
3307        # Create the shim object to test for deleted FIDs.
3308        my $shim = FidCheck->new($self);
3309        # Ask the network for sims.
3310        my $retVal = FIGRules::GetNetworkSims($shim, $fid, {}, $maxN, $maxP, $select, $max_expand, $filters);
3311        # Return the result.
3312        return $retVal;
3313    }
3314    
3315    =head3 IsAllGenomes
3316    
3317    C<< my $flag = $sprout->IsAllGenomes(\@list, \@checkList); >>
3318    
3319    Return TRUE if all genomes in the second list are represented in the first list at
3320    least one. Otherwise, return FALSE. If the second list is omitted, the first list is
3321    compared to a list of all the genomes.
3322    
3323    =over 4
3324    
3325    =item list
3326    
3327    Reference to the list to be compared to the second list.
3328    
3329    =item checkList (optional)
3330    
3331    Reference to the comparison target list. Every genome ID in this list must occur at
3332    least once in the first list. If this parameter is omitted, a list of all the genomes
3333    is used.
3334    
3335    =item RETURN
3336    
3337    Returns TRUE if every item in the second list appears at least once in the
3338    first list, else FALSE.
3339    
3340    =back
3341    
3342    =cut
3343    
3344    sub IsAllGenomes {
3345        # Get the parameters.
3346        my ($self, $list, $checkList) = @_;
3347        # Supply the checklist if it was omitted.
3348        $checkList = [$self->Genomes()] if ! defined($checkList);
3349        # Create a hash of the original list.
3350        my %testList = map { $_ => 1 } @{$list};
3351        # Declare the return variable. We assume that the representation
3352        # is complete and stop at the first failure.
3353        my $retVal = 1;
3354        my $n = scalar @{$checkList};
3355        for (my $i = 0; $retVal && $i < $n; $i++) {
3356            if (! $testList{$checkList->[$i]}) {
3357                $retVal = 0;
3358            }
3359        }
3360        # Return the result.
3361        return $retVal;
3362    }
3363    
3364  =head3 GetGroups  =head3 GetGroups
3365    
3366  C<< my %groups = $sprout->GetGroups(\@groupList); >>  C<< my %groups = $sprout->GetGroups(\@groupList); >>
# Line 2983  Line 3382 
3382          # Here we have a group list. Loop through them individually,          # Here we have a group list. Loop through them individually,
3383          # getting a list of the relevant genomes.          # getting a list of the relevant genomes.
3384          for my $group (@{$groupList}) {          for my $group (@{$groupList}) {
3385              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(group-name) = ?",              my @genomeIDs = $self->GetFlat(['Genome'], "Genome(primary-group) = ?",
3386                  [$group], "Genome(id)");                  [$group], "Genome(id)");
3387              $retVal{$group} = \@genomeIDs;              $retVal{$group} = \@genomeIDs;
3388          }          }
# Line 2991  Line 3390 
3390          # 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
3391          # of the genome records, putting each one found into the appropriate          # of the genome records, putting each one found into the appropriate
3392          # 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
3393          # in groups are included in the return set.          # in real NMPDR groups are included in the return set.
3394          my @genomes = $self->GetAll(['Genome'], "Genome(group-name) > ' '", [],          my @genomes = $self->GetAll(['Genome'], "Genome(primary-group) <> ?",
3395                                      ['Genome(id)', 'Genome(group-name)']);                                      [$FIG_Config::otherGroup], ['Genome(id)', 'Genome(primary-group)']);
3396          # Loop through the genomes found.          # Loop through the genomes found.
3397          for my $genome (@genomes) {          for my $genome (@genomes) {
3398              # Pop this genome's ID off the current list.              # Pop this genome's ID off the current list.
# Line 3083  Line 3482 
3482      return $retVal;      return $retVal;
3483  }  }
3484    
3485    =head3 DeleteGenome
3486    
3487    C<< my $stats = $sprout->DeleteGenome($genomeID, $testFlag); >>
3488    
3489    Delete a genome from the database.
3490    
3491    =over 4
3492    
3493    =item genomeID
3494    
3495    ID of the genome to delete
3496    
3497    =item testFlag
3498    
3499    If TRUE, then the DELETE statements will be traced, but no deletions will occur.
3500    
3501    =item RETURN
3502    
3503    Returns a statistics object describing the rows deleted.
3504    
3505    =back
3506    
3507    =cut
3508    #: Return Type $%;
3509    sub DeleteGenome {
3510        # Get the parameters.
3511        my ($self, $genomeID, $testFlag) = @_;
3512        # Perform the delete for the genome's features.
3513        my $retVal = $self->Delete('Feature', "fig|$genomeID.%", testMode => $testFlag);
3514        # Perform the delete for the primary genome data.
3515        my $stats = $self->Delete('Genome', $genomeID, testMode => $testFlag);
3516        $retVal->Accumulate($stats);
3517        # Return the result.
3518        return $retVal;
3519    }
3520    
3521    =head3 Fix
3522    
3523    C<< my %fixedHash = Sprout::Fix(%groupHash); >>
3524    
3525    Prepare a genome group hash (like that returned by L</GetGroups>) for processing.
3526    Groups with the same primary name will be combined. The primary name is the
3527    first capitalized word in the group name.
3528    
3529    =over 4
3530    
3531    =item groupHash
3532    
3533    Hash to be fixed up.
3534    
3535    =item RETURN
3536    
3537    Returns a fixed-up version of the hash.
3538    
3539    =back
3540    
3541    =cut
3542    
3543    sub Fix {
3544        # Get the parameters.
3545        my (%groupHash) = @_;
3546        # Create the result hash.
3547        my %retVal = ();
3548        # Copy over the genomes.
3549        for my $groupID (keys %groupHash) {
3550            # Make a safety copy of the group ID.
3551            my $realGroupID = $groupID;
3552            # Yank the primary name.
3553            if ($groupID =~ /([A-Z]\w+)/) {
3554                $realGroupID = $1;
3555            }
3556            # Append this group's genomes into the result hash.
3557            Tracer::AddToListMap(\%retVal, $realGroupID, @{$groupHash{$groupID}});
3558        }
3559        # Return the result hash.
3560        return %retVal;
3561    }
3562    
3563    =head3 GroupPageName
3564    
3565    C<< my $name = $sprout->GroupPageName($group); >>
3566    
3567    Return the name of the page for the specified NMPDR group.
3568    
3569    =over 4
3570    
3571    =item group
3572    
3573    Name of the relevant group.
3574    
3575    =item RETURN
3576    
3577    Returns the relative page name (e.g. C<../content/campy.php>). If the group file is not in
3578    memory it will be read in.
3579    
3580    =back
3581    
3582    =cut
3583    
3584    sub GroupPageName {
3585        # Get the parameters.
3586        my ($self, $group) = @_;
3587        # Declare the return variable.
3588        my $retVal;
3589        # Check for the group file data.
3590        if (! defined $self->{groupHash}) {
3591            # Read the group file.
3592            my %groupData = Sprout::ReadGroupFile($self->{_options}->{dataDir} . "/groups.tbl");
3593            # Store it in our object.
3594            $self->{groupHash} = \%groupData;
3595        }
3596        # Compute the real group name.
3597        my $realGroup = $group;
3598        if ($group =~ /([A-Z]\w+)/) {
3599            $realGroup = $1;
3600        }
3601        # Return the page name.
3602        $retVal = "../content/" . $self->{groupHash}->{$realGroup}->[1];
3603        # Return the result.
3604        return $retVal;
3605    }
3606    
3607    =head3 ReadGroupFile
3608    
3609    C<< my %groupData = Sprout::ReadGroupFile($groupFileName); >>
3610    
3611    Read in the data from the specified group file. The group file contains information
3612    about each of the NMPDR groups.
3613    
3614    =over 4
3615    
3616    =item name
3617    
3618    Name of the group.
3619    
3620    =item page
3621    
3622    Name of the group's page on the web site (e.g. C<campy.php> for
3623    Campylobacter)
3624    
3625    =item genus
3626    
3627    Genus of the group
3628    
3629    =item species
3630    
3631    Species of the group, or an empty string if the group is for an entire
3632    genus. If the group contains more than one species, the species names
3633    should be separated by commas.
3634    
3635    =back
3636    
3637    The parameters to this method are as follows
3638    
3639    =over 4
3640    
3641    =item groupFile
3642    
3643    Name of the file containing the group data.
3644    
3645    =item RETURN
3646    
3647    Returns a hash keyed on group name. The value of each hash
3648    
3649    =back
3650    
3651    =cut
3652    
3653    sub ReadGroupFile {
3654        # Get the parameters.
3655        my ($groupFileName) = @_;
3656        # Declare the return variable.
3657        my %retVal;
3658        # Read the group file.
3659        my @groupLines = Tracer::GetFile($groupFileName);
3660        for my $groupLine (@groupLines) {
3661            my ($name, $page, $genus, $species) = split(/\t/, $groupLine);
3662            $retVal{$name} = [$page, $genus, $species];
3663        }
3664        # Return the result.
3665        return %retVal;
3666    }
3667    
3668    =head3 AddProperty
3669    
3670    C<< my  = $sprout->AddProperty($featureID, $key, @values); >>
3671    
3672    Add a new attribute value (Property) to a feature.
3673    
3674    =over 4
3675    
3676    =item peg
3677    
3678    ID of the feature to which the attribute is to be added.
3679    
3680    =item key
3681    
3682    Name of the attribute (key).
3683    
3684    =item values
3685    
3686    Values of the attribute.
3687    
3688    =back
3689    
3690    =cut
3691    #: Return Type ;
3692    sub AddProperty {
3693        # Get the parameters.
3694        my ($self, $featureID, $key, @values) = @_;
3695        # Add the property using the attached attributes object.
3696        $self->{_ca}->AddAttribute($featureID, $key, @values);
3697    }
3698    
3699    =head2 Virtual Methods
3700    
3701    =head3 CleanKeywords
3702    
3703    C<< my $cleanedString = $sprout->CleanKeywords($searchExpression); >>
3704    
3705    Clean up a search expression or keyword list. This involves converting the periods
3706    in EC numbers to underscores, converting non-leading minus signs to underscores,
3707    a vertical bar or colon to an apostrophe, and forcing lower case for all alphabetic
3708    characters. In addition, any extra spaces are removed.
3709    
3710    =over 4
3711    
3712    =item searchExpression
3713    
3714    Search expression or keyword list to clean. Note that a search expression may
3715    contain boolean operators which need to be preserved. This includes leading
3716    minus signs.
3717    
3718    =item RETURN
3719    
3720    Cleaned expression or keyword list.
3721    
3722    =back
3723    
3724    =cut
3725    
3726    sub CleanKeywords {
3727        # Get the parameters.
3728        my ($self, $searchExpression) = @_;
3729        # Perform the standard cleanup.
3730        my $retVal = $self->ERDB::CleanKeywords($searchExpression);
3731        # Fix the periods in EC and TC numbers.
3732        $retVal =~ s/(\d+|\-)\.(\d+|-)\.(\d+|-)\.(\d+|-)/$1_$2_$3_$4/g;
3733        # Fix non-trailing periods.
3734        $retVal =~ s/\.(\w)/_$1/g;
3735        # Fix non-leading minus signs.
3736        $retVal =~ s/(\w)[\-]/$1_/g;
3737        # Fix the vertical bars and colons
3738        $retVal =~ s/(\w)[|:](\w)/$1'$2/g;
3739        # Return the result.
3740        return $retVal;
3741    }
3742    
3743  =head2 Internal Utility Methods  =head2 Internal Utility Methods
3744    
3745  =head3 ParseAssignment  =head3 ParseAssignment
# Line 3093  Line 3750 
3750    
3751  A functional assignment is always of the form  A functional assignment is always of the form
3752    
3753      I<XXXX>C<\nset >I<YYYY>C< function to\n>I<ZZZZZ>      C<set >I<YYYY>C< function to\n>I<ZZZZZ>
3754    
3755    where I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases,
3756    the user and the assigning user (from MadeAnnotation) will be the same, but that is
3757    not always the case.
3758    
3759  where I<XXXX> is the B<assigning user>, I<YYYY> is the B<user>, and I<ZZZZ> is the  In addition, the functional role may contain extra data that is stripped, such as
3760  actual functional role. In most cases, the user and the assigning user will be the  terminating spaces or a comment separated from the rest of the text by a tab.
 same, but that is not always the case.  
3761    
3762  This is a static method.  This is a static method.
3763    
3764  =over 4  =over 4
3765    
3766    =item user
3767    
3768    Name of the assigning user.
3769    
3770  =item text  =item text
3771    
3772  Text of the annotation.  Text of the annotation.
# Line 3118  Line 3782 
3782    
3783  sub _ParseAssignment {  sub _ParseAssignment {
3784      # Get the parameters.      # Get the parameters.
3785      my ($text) = @_;      my ($user, $text) = @_;
3786      # Declare the return value.      # Declare the return value.
3787      my @retVal = ();      my @retVal = ();
3788      # Check to see if this is a functional assignment.      # Check to see if this is a functional assignment.
3789      my ($user, $type, $function) = split(/\n/, $text);      my ($type, $function) = split(/\n/, $text);
3790      if ($type =~ m/^set ([^ ]+) function to$/i) {      if ($type =~ m/^set function to$/i) {
3791          # Here it is, so we return the user name (which is in $1), the functional role text,          # Here we have an assignment without a user, so we use the incoming user ID.
3792          # and the assigning user.          @retVal = ($user, $function);
3793          @retVal = ($1, $function, $user);      } elsif ($type =~ m/^set (\S+) function to$/i) {
3794            # Here we have an assignment with a user that is passed back to the caller.
3795            @retVal = ($1, $function);
3796        }
3797        # If we have an assignment, we need to clean the function text. There may be
3798        # extra junk at the end added as a note from the user.
3799        if (defined( $retVal[1] )) {
3800            $retVal[1] =~ s/(\t\S)?\s*$//;
3801      }      }
3802      # Return the result list.      # Return the result list.
3803      return @retVal;      return @retVal;
3804  }  }
3805    
3806  =head3 FriendlyTimestamp  =head3 _CheckFeature
3807    
3808  Convert a time number to a user-friendly time stamp for display.  C<< my $flag = $sprout->_CheckFeature($fid); >>
3809    
3810  This is a static method.  Return TRUE if the specified FID is probably an NMPDR feature ID, else FALSE.
3811    
3812  =over 4  =over 4
3813    
3814  =item timeValue  =item fid
3815    
3816  Numeric time value.  Feature ID to check.
3817    
3818  =item RETURN  =item RETURN
3819    
3820  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.
3821    
3822  =back  =back
3823    
3824  =cut  =cut
3825    
3826  sub FriendlyTimestamp {  sub _CheckFeature {
3827      my ($timeValue) = @_;      # Get the parameters.
3828      my $retVal = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue));      my ($self, $fid) = @_;
3829      return $retVal;      # Insure we have a genome hash.
3830        if (! defined $self->{genomeHash}) {
3831            my %genomeHash = map { $_ => 1 } $self->GetFlat(['Genome'], "", [], 'Genome(id)');
3832            $self->{genomeHash} = \%genomeHash;
3833        }
3834        # Get the feature's genome ID.
3835        my ($genomeID) = FIGRules::ParseFeatureID($fid);
3836        # Return an indicator of whether or not the genome ID is in the hash.
3837        return ($self->{genomeHash}->{$genomeID} ? 1 : 0);
3838  }  }
3839    
3840  =head3 AddProperty  =head3 FriendlyTimestamp
3841    
3842  C<< my  = $sprout->AddProperty($featureID, $key, $value, $url); >>  Convert a time number to a user-friendly time stamp for display.
3843    
3844  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.  
3845    
3846  =over 4  =over 4
3847    
3848  =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  
3849    
3850  Value of the attribute.  Numeric time value.
3851    
3852  =item url  =item RETURN
3853    
3854  URL or text citation from which the property was obtained.  Returns a string containing the same time in user-readable format.
3855    
3856  =back  =back
3857    
3858  =cut  =cut
 #: Return Type ;  
 sub AddProperty {  
     # Get the parameters.  
     my ($self, $featureID, $key, $value, $url) = @_;  
     # Declare the variable to hold the desired property ID.  
     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 });  
 }  
3859    
3860    sub FriendlyTimestamp {
3861        my ($timeValue) = @_;
3862        my $retVal = localtime($timeValue);
3863        return $retVal;
3864    }
3865    
3866    
3867  1;  1;

Legend:
Removed from v.1.32  
changed lines
  Added in v.1.101

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3