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

Diff of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.7, Tue Sep 13 19:05:20 2005 UTC revision 1.81, Wed Feb 21 13:21:42 2007 UTC
# Line 10  Line 10 
10      use Sprout;      use Sprout;
11      use Stats;      use Stats;
12      use BasicLocation;      use BasicLocation;
13        use HTML;
14    
15  =head1 Sprout Load Methods  =head1 Sprout Load Methods
16    
# Line 29  Line 30 
30      $stats->Accumulate($spl->LoadFeatureData());      $stats->Accumulate($spl->LoadFeatureData());
31      print $stats->Show();      print $stats->Show();
32    
 This module makes use of the internal Sprout property C<_erdb>.  
   
33  It is worth noting that the FIG object does not need to be a real one. Any object  It is worth noting that the FIG object does not need to be a real one. Any object
34  that implements the FIG methods for data retrieval could be used. So, for example,  that implements the FIG methods for data retrieval could be used. So, for example,
35  this object could be used to copy data from one Sprout database to another, or  this object could be used to copy data from one Sprout database to another, or
# Line 51  Line 50 
50    
51  =head3 new  =head3 new
52    
53  C<< my $spl = SproutLoad->new($sprout, $fig, $genomeFile, $subsysFile); >>  C<< my $spl = SproutLoad->new($sprout, $fig, $genomeFile, $subsysFile, $options); >>
54    
55  Construct a new Sprout Loader object, specifying the two participating databases and  Construct a new Sprout Loader object, specifying the two participating databases and
56  the name of the files containing the list of genomes and subsystems to use.  the name of the files containing the list of genomes and subsystems to use.
# Line 79  Line 78 
78  =item subsysFile  =item subsysFile
79    
80  Either the name of the file containing the list of trusted subsystems or a reference  Either the name of the file containing the list of trusted subsystems or a reference
81  to a list of subsystem names. If nothing is specified, all known subsystems will be  to a list of subsystem names. If nothing is specified, all NMPDR subsystems will be
82  considered trusted. Only subsystem data related to the trusted subsystems is loaded.  considered trusted. (A subsystem is considered NMPDR if it has a file named C<NMPDR>
83    in its data directory.) Only subsystem data related to the NMPDR subsystems is loaded.
84    
85    =item options
86    
87    Reference to a hash of command-line options.
88    
89  =back  =back
90    
# Line 88  Line 92 
92    
93  sub new {  sub new {
94      # Get the parameters.      # Get the parameters.
95      my ($class, $sprout, $fig, $genomeFile, $subsysFile) = @_;      my ($class, $sprout, $fig, $genomeFile, $subsysFile, $options) = @_;
96      # Load the list of genomes into a hash.      # Create the genome hash.
97      my %genomes;      my %genomes = ();
98        # We only need it if load-only is NOT specified.
99        if (! $options->{loadOnly}) {
100      if (! defined($genomeFile) || $genomeFile eq '') {      if (! defined($genomeFile) || $genomeFile eq '') {
101          # Here we want all the complete genomes and an access code of 1.          # Here we want all the complete genomes and an access code of 1.
102          my @genomeList = $fig->genomes(1);          my @genomeList = $fig->genomes(1);
# Line 114  Line 120 
120                  # an omitted access code can be defaulted to 1.                  # an omitted access code can be defaulted to 1.
121                  for my $genomeLine (@genomeList) {                  for my $genomeLine (@genomeList) {
122                      my ($genomeID, $accessCode) = split("\t", $genomeLine);                      my ($genomeID, $accessCode) = split("\t", $genomeLine);
123                      if (undef $accessCode) {                          if (! defined($accessCode)) {
124                          $accessCode = 1;                          $accessCode = 1;
125                      }                      }
126                      $genomes{$genomeID} = $accessCode;                      $genomes{$genomeID} = $accessCode;
# Line 124  Line 130 
130              Confess("Invalid genome parameter ($type) in SproutLoad constructor.");              Confess("Invalid genome parameter ($type) in SproutLoad constructor.");
131          }          }
132      }      }
133        }
134      # Load the list of trusted subsystems.      # Load the list of trusted subsystems.
135      my %subsystems = ();      my %subsystems = ();
136        # We only need it if load-only is NOT specified.
137        if (! $options->{loadOnly}) {
138      if (! defined $subsysFile || $subsysFile eq '') {      if (! defined $subsysFile || $subsysFile eq '') {
139          # Here we want all the subsystems.              # Here we want all the usable subsystems. First we get the whole list.
140          %subsystems = map { $_ => 1 } $fig->all_subsystems();              my @subs = $fig->all_subsystems();
141                # Loop through, checking for the NMPDR file.
142                for my $sub (@subs) {
143                    if ($fig->nmpdr_subsystem($sub)) {
144                        $subsystems{$sub} = 1;
145                    }
146                }
147      } else {      } else {
148          my $type = ref $subsysFile;          my $type = ref $subsysFile;
149          if ($type eq 'ARRAY') {          if ($type eq 'ARRAY') {
# Line 148  Line 163 
163              Confess("Invalid subsystem parameter in SproutLoad constructor.");              Confess("Invalid subsystem parameter in SproutLoad constructor.");
164          }          }
165      }      }
166            # Go through the subsys hash again, creating the keyword list for each subsystem.
167            for my $subsystem (keys %subsystems) {
168                my $name = $subsystem;
169                $name =~ s/_/ /g;
170                my $classes = $fig->subsystem_classification($subsystem);
171                $name .= " " . join(" ", @{$classes});
172                $subsystems{$subsystem} = $name;
173            }
174        }
175      # Get the data directory from the Sprout object.      # Get the data directory from the Sprout object.
176      my ($directory) = $sprout->LoadInfo();      my ($directory) = $sprout->LoadInfo();
177      # Create the Sprout load object.      # Create the Sprout load object.
# Line 157  Line 181 
181                    subsystems => \%subsystems,                    subsystems => \%subsystems,
182                    sprout => $sprout,                    sprout => $sprout,
183                    loadDirectory => $directory,                    loadDirectory => $directory,
184                    erdb => $sprout->{_erdb},                    erdb => $sprout,
185                    loaders => []                    loaders => [],
186                      options => $options
187                   };                   };
188      # Bless and return it.      # Bless and return it.
189      bless $retVal, $class;      bless $retVal, $class;
190      return $retVal;      return $retVal;
191  }  }
192    
193    =head3 LoadOnly
194    
195    C<< my $flag = $spl->LoadOnly; >>
196    
197    Return TRUE if we are in load-only mode, else FALSE.
198    
199    =cut
200    
201    sub LoadOnly {
202        my ($self) = @_;
203        return $self->{options}->{loadOnly};
204    }
205    
206    =head3 PrimaryOnly
207    
208    C<< my $flag = $spl->PrimaryOnly; >>
209    
210    Return TRUE if only the main entity is to be loaded, else FALSE.
211    
212    =cut
213    
214    sub PrimaryOnly {
215        my ($self) = @_;
216        return $self->{options}->{primaryOnly};
217    }
218    
219  =head3 LoadGenomeData  =head3 LoadGenomeData
220    
221  C<< my $stats = $spl->LoadGenomeData(); >>  C<< my $stats = $spl->LoadGenomeData(); >>
# Line 192  Line 243 
243    
244  =back  =back
245    
 B<TO DO>  
   
 Real quality vectors instead of C<unknown> for everything.  
   
 GenomeGroup relation. (The original script took group information from the C<NMPDR> file  
 in each genome's main directory, but no such file exists anywhere in my version of the  
 data store.)  
   
246  =cut  =cut
247  #: Return Type $%;  #: Return Type $%;
248  sub LoadGenomeData {  sub LoadGenomeData {
# Line 210  Line 253 
253      # Get the genome count.      # Get the genome count.
254      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
255      my $genomeCount = (keys %{$genomeHash});      my $genomeCount = (keys %{$genomeHash});
     Trace("Beginning genome data load.") if T(2);  
256      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
257      my $loadGenome = $self->_TableLoader('Genome', $genomeCount);      my $loadGenome = $self->_TableLoader('Genome');
258      my $loadHasContig = $self->_TableLoader('HasContig', $genomeCount * 300);      my $loadHasContig = $self->_TableLoader('HasContig', $self->PrimaryOnly);
259      my $loadContig = $self->_TableLoader('Contig', $genomeCount * 300);      my $loadContig = $self->_TableLoader('Contig', $self->PrimaryOnly);
260      my $loadIsMadeUpOf = $self->_TableLoader('IsMadeUpOf', $genomeCount * 60000);      my $loadIsMadeUpOf = $self->_TableLoader('IsMadeUpOf', $self->PrimaryOnly);
261      my $loadSequence = $self->_TableLoader('Sequence', $genomeCount * 60000);      my $loadSequence = $self->_TableLoader('Sequence', $self->PrimaryOnly);
262        if ($self->{options}->{loadOnly}) {
263            Trace("Loading from existing files.") if T(2);
264        } else {
265            Trace("Generating genome data.") if T(2);
266      # Now we loop through the genomes, generating the data for each one.      # Now we loop through the genomes, generating the data for each one.
267      for my $genomeID (sort keys %{$genomeHash}) {      for my $genomeID (sort keys %{$genomeHash}) {
268          Trace("Loading data for genome $genomeID.") if T(3);              Trace("Generating data for genome $genomeID.") if T(3);
269          $loadGenome->Add("genomeIn");          $loadGenome->Add("genomeIn");
270          # The access code comes in via the genome hash.          # The access code comes in via the genome hash.
271          my $accessCode = $genomeHash->{$genomeID};          my $accessCode = $genomeHash->{$genomeID};
272          # Get the genus, species, and strain from the scientific name. Note that we append              # Get the genus, species, and strain from the scientific name.
         # the genome ID to the strain. In some cases this is the totality of the strain name.  
273          my ($genus, $species, @extraData) = split / /, $self->{fig}->genus_species($genomeID);          my ($genus, $species, @extraData) = split / /, $self->{fig}->genus_species($genomeID);
274          my $extra = join " ", @extraData, "[$genomeID]";              my $extra = join " ", @extraData;
275          # Get the full taxonomy.          # Get the full taxonomy.
276          my $taxonomy = $fig->taxonomy_of($genomeID);          my $taxonomy = $fig->taxonomy_of($genomeID);
277                # Open the NMPDR group file for this genome.
278                my $group;
279                if (open(TMP, "<$FIG_Config::organisms/$genomeID/NMPDR") &&
280                    defined($group = <TMP>)) {
281                    # Clean the line ending.
282                    chomp $group;
283                } else {
284                    # No group, so use the default.
285                    $group = $FIG_Config::otherGroup;
286                }
287                close TMP;
288          # Output the genome record.          # Output the genome record.
289          $loadGenome->Put($genomeID, $accessCode, $fig->is_complete($genomeID), $genus,          $loadGenome->Put($genomeID, $accessCode, $fig->is_complete($genomeID), $genus,
290                           $species, $extra, $taxonomy);                               $group, $species, $extra, $taxonomy);
291          # Now we loop through each of the genome's contigs.          # Now we loop through each of the genome's contigs.
292          my @contigs = $fig->all_contigs($genomeID);          my @contigs = $fig->all_contigs($genomeID);
293          for my $contigID (@contigs) {          for my $contigID (@contigs) {
# Line 262  Line 318 
318              }              }
319          }          }
320      }      }
321        }
322      # Finish the loads.      # Finish the loads.
323      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
324      # Return the result.      # Return the result.
# Line 302  Line 359 
359      my $fig = $self->{fig};      my $fig = $self->{fig};
360      # Get the genome hash.      # Get the genome hash.
361      my $genomeFilter = $self->{genomes};      my $genomeFilter = $self->{genomes};
362      my $genomeCount = (keys %{$genomeFilter});      # Set up an ID counter for the PCHs.
363      my $featureCount = $genomeCount * 4000;      my $pchID = 0;
364      # Start the loads.      # Start the loads.
365      my $loadCoupling = $self->_TableLoader('Coupling', $featureCount * $genomeCount);      my $loadCoupling = $self->_TableLoader('Coupling');
366      my $loadIsEvidencedBy = $self->_TableLoader('IsEvidencedBy', $featureCount * 8000);      my $loadIsEvidencedBy = $self->_TableLoader('IsEvidencedBy', $self->PrimaryOnly);
367      my $loadPCH = $self->_TableLoader('PCH', $featureCount * 2000);      my $loadPCH = $self->_TableLoader('PCH', $self->PrimaryOnly);
368      my $loadParticipatesInCoupling = $self->_TableLoader('ParticipatesInCoupling', $featureCount * 2000);      my $loadParticipatesInCoupling = $self->_TableLoader('ParticipatesInCoupling', $self->PrimaryOnly);
369      my $loadUsesAsEvidence = $self->_TableLoader('UsesAsEvidence', $featureCount * 8000);      my $loadUsesAsEvidence = $self->_TableLoader('UsesAsEvidence', $self->PrimaryOnly);
370      Trace("Beginning coupling data load.") if T(2);      if ($self->{options}->{loadOnly}) {
371            Trace("Loading from existing files.") if T(2);
372        } else {
373            Trace("Generating coupling data.") if T(2);
374      # Loop through the genomes found.      # Loop through the genomes found.
375      for my $genome (sort keys %{$genomeFilter}) {      for my $genome (sort keys %{$genomeFilter}) {
376          Trace("Generating coupling data for $genome.") if T(3);          Trace("Generating coupling data for $genome.") if T(3);
# Line 334  Line 394 
394              for my $coupleData (@couplings) {              for my $coupleData (@couplings) {
395                  my ($peg2, $score) = @{$coupleData};                  my ($peg2, $score) = @{$coupleData};
396                  # Compute the coupling ID.                  # Compute the coupling ID.
397                  my $coupleID = Sprout::CouplingID($peg1, $peg2);                      my $coupleID = $self->{erdb}->CouplingID($peg1, $peg2);
398                  if (! exists $dupHash{$coupleID}) {                  if (! exists $dupHash{$coupleID}) {
399                      $loadCoupling->Add("couplingIn");                      $loadCoupling->Add("couplingIn");
400                      # Here we have a new coupling to store in the load files.                      # Here we have a new coupling to store in the load files.
# Line 362  Line 422 
422                              # We store this evidence in the hash if the usage                              # We store this evidence in the hash if the usage
423                              # is nonzero or no prior evidence has been found. This                              # is nonzero or no prior evidence has been found. This
424                              # insures that if there is duplicate evidence, we                              # insures that if there is duplicate evidence, we
425                              # at least keep the meaningful ones. Only evidence is                                  # at least keep the meaningful ones. Only evidence in
426                              # the hash makes it to the output.                              # the hash makes it to the output.
427                              if ($usage || ! exists $evidenceMap{$evidenceKey}) {                              if ($usage || ! exists $evidenceMap{$evidenceKey}) {
428                                  $evidenceMap{$evidenceKey} = $evidenceData;                                  $evidenceMap{$evidenceKey} = $evidenceData;
# Line 370  Line 430 
430                          }                          }
431                      }                      }
432                      for my $evidenceID (keys %evidenceMap) {                      for my $evidenceID (keys %evidenceMap) {
433                                # Get the ID for this evidence.
434                                $pchID++;
435                          # Create the evidence record.                          # Create the evidence record.
436                          my ($peg3, $peg4, $usage) = @{$evidenceMap{$evidenceID}};                          my ($peg3, $peg4, $usage) = @{$evidenceMap{$evidenceID}};
437                          $loadPCH->Put($evidenceID, $usage);                              $loadPCH->Put($pchID, $usage);
438                          # Connect it to the coupling.                          # Connect it to the coupling.
439                          $loadIsEvidencedBy->Put($coupleID, $evidenceID);                              $loadIsEvidencedBy->Put($coupleID, $pchID);
440                          # Connect it to the features.                          # Connect it to the features.
441                          $loadUsesAsEvidence->Put($evidenceID, $peg3, 1);                              $loadUsesAsEvidence->Put($pchID, $peg3, 1);
442                          $loadUsesAsEvidence->Put($evidenceID, $peg4, 1);                              $loadUsesAsEvidence->Put($pchID, $peg4, 2);
443                            }
444                      }                      }
445                  }                  }
446              }              }
# Line 404  Line 467 
467      FeatureTranslation      FeatureTranslation
468      FeatureUpstream      FeatureUpstream
469      IsLocatedIn      IsLocatedIn
470        HasFeature
471        HasRoleInSubsystem
472        FeatureEssential
473        FeatureVirulent
474        FeatureIEDB
475    
476  =over 4  =over 4
477    
# Line 418  Line 486 
486  sub LoadFeatureData {  sub LoadFeatureData {
487      # Get this object instance.      # Get this object instance.
488      my ($self) = @_;      my ($self) = @_;
489      # Get the FIG object.      # Get the FIG and Sprout objects.
490      my $fig = $self->{fig};      my $fig = $self->{fig};
491        my $sprout = $self->{sprout};
492      # Get the table of genome IDs.      # Get the table of genome IDs.
493      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
     my $featureCount = $genomeCount * 4000;  
494      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
495      my $loadFeature = $self->_TableLoader('Feature', $featureCount);      my $loadFeature = $self->_TableLoader('Feature');
496      my $loadFeatureAlias = $self->_TableLoader('FeatureAlias', $featureCount * 6);      my $loadIsLocatedIn = $self->_TableLoader('IsLocatedIn', $self->PrimaryOnly);
497      my $loadFeatureLink = $self->_TableLoader('FeatureLink', $featureCount * 10);      my $loadFeatureAlias = $self->_TableLoader('FeatureAlias');
498      my $loadFeatureTranslation = $self->_TableLoader('FeatureTranslation', $featureCount);      my $loadFeatureLink = $self->_TableLoader('FeatureLink');
499      my $loadFeatureUpstream = $self->_TableLoader('FeatureUpstream', $featureCount);      my $loadFeatureTranslation = $self->_TableLoader('FeatureTranslation');
500      my $loadIsLocatedIn = $self->_TableLoader('IsLocatedIn', $featureCount);      my $loadFeatureUpstream = $self->_TableLoader('FeatureUpstream');
501        my $loadHasFeature = $self->_TableLoader('HasFeature', $self->PrimaryOnly);
502        my $loadHasRoleInSubsystem = $self->_TableLoader('HasRoleInSubsystem', $self->PrimaryOnly);
503        my $loadFeatureEssential = $self->_TableLoader('FeatureEssential');
504        my $loadFeatureVirulent = $self->_TableLoader('FeatureVirulent');
505        my $loadFeatureIEDB = $self->_TableLoader('FeatureIEDB');
506        # Get the subsystem hash.
507        my $subHash = $self->{subsystems};
508      # Get the maximum sequence size. We need this later for splitting up the      # Get the maximum sequence size. We need this later for splitting up the
509      # locations.      # locations.
510      my $chunkSize = $self->{sprout}->MaxSegment();      my $chunkSize = $self->{sprout}->MaxSegment();
511      Trace("Beginning feature data load.") if T(2);      if ($self->{options}->{loadOnly}) {
512            Trace("Loading from existing files.") if T(2);
513        } else {
514            Trace("Generating feature data.") if T(2);
515      # Now we loop through the genomes, generating the data for each one.      # Now we loop through the genomes, generating the data for each one.
516      for my $genomeID (sort keys %{$genomeHash}) {      for my $genomeID (sort keys %{$genomeHash}) {
517          Trace("Loading features for genome $genomeID.") if T(3);          Trace("Loading features for genome $genomeID.") if T(3);
518          $loadFeature->Add("genomeIn");          $loadFeature->Add("genomeIn");
519          # Get the feature list for this genome.          # Get the feature list for this genome.
520          my $features = $fig->all_features_detailed($genomeID);          my $features = $fig->all_features_detailed($genomeID);
521                # Sort and count the list.
522                my @featureTuples = sort { $a->[0] cmp $b->[0] } @{$features};
523                my $count = scalar @featureTuples;
524                my @fids = map { $_->[0] } @featureTuples;
525                Trace("$count features found for genome $genomeID.") if T(3);
526                # Get the attributes for this genome and put them in a hash by feature ID.
527                my $attributes = GetGenomeAttributes($fig, $genomeID, \@fids);
528                # Set up for our duplicate-feature check.
529                my $oldFeatureID = "";
530          # Loop through the features.          # Loop through the features.
531          for my $featureData (@{$features}) {              for my $featureTuple (@featureTuples) {
             $loadFeature->Add("featureIn");  
532              # Split the tuple.              # Split the tuple.
533              my ($featureID, $locations, $aliases, $type) = @{$featureData};                  my ($featureID, $locations, undef, $type) = @{$featureTuple};
534              # Create the feature record.                  # Check for duplicates.
535              $loadFeature->Put($featureID, 1, $type);                  if ($featureID eq $oldFeatureID) {
536                        Trace("Duplicate feature $featureID found.") if T(1);
537                    } else {
538                        $oldFeatureID = $featureID;
539                        # Count this feature.
540                        $loadFeature->Add("featureIn");
541                        # Begin building the keywords. We start with the genome ID, the
542                        # feature ID, the taxonomy, and the organism name.
543                        my @keywords = ($genomeID, $featureID, $fig->genus_species($genomeID),
544                                        $fig->taxonomy_of($genomeID));
545                        # Get the functional assignment and aliases.
546                        my $assignment = $fig->function_of($featureID);
547              # Create the aliases.              # Create the aliases.
548              for my $alias (split /\s*,\s*/, $aliases) {                      for my $alias ($fig->feature_aliases($featureID)) {
549                  $loadFeatureAlias->Put($featureID, $alias);                  $loadFeatureAlias->Put($featureID, $alias);
550                            push @keywords, $alias;
551              }              }
552                        Trace("Assignment for $featureID is: $assignment") if T(4);
553                        # Break the assignment into words and shove it onto the
554                        # keyword list.
555                        push @keywords, split(/\s+/, $assignment);
556                        # Link this feature to the parent genome.
557                        $loadHasFeature->Put($genomeID, $featureID, $type);
558              # Get the links.              # Get the links.
559              my @links = $fig->fid_links($featureID);              my @links = $fig->fid_links($featureID);
560              for my $link (@links) {              for my $link (@links) {
# Line 470  Line 573 
573                      $loadFeatureUpstream->Put($featureID, $upstream);                      $loadFeatureUpstream->Put($featureID, $upstream);
574                  }                  }
575              }              }
576                        # Now we need to find the subsystems this feature participates in.
577                        # We also add the subsystems to the keyword list. Before we do that,
578                        # we must convert underscores to spaces and tack on the classifications.
579                        my @subsystems = $fig->peg_to_subsystems($featureID);
580                        for my $subsystem (@subsystems) {
581                            # Only proceed if we like this subsystem.
582                            if (exists $subHash->{$subsystem}) {
583                                # Store the has-role link.
584                                $loadHasRoleInSubsystem->Put($featureID, $subsystem, $genomeID, $type);
585                                # Save the subsystem's keyword data.
586                                my $subKeywords = $subHash->{$subsystem};
587                                push @keywords, split /\s+/, $subKeywords;
588                                # Now we need to get this feature's role in the subsystem.
589                                my $subObject = $fig->get_subsystem($subsystem);
590                                my @roleColumns = $subObject->get_peg_roles($featureID);
591                                my @allRoles = $subObject->get_roles();
592                                for my $col (@roleColumns) {
593                                    my $role = $allRoles[$col];
594                                    push @keywords, split /\s+/, $role;
595                                    push @keywords, $subObject->get_role_abbr($col);
596                                }
597                            }
598                        }
599                        # There are three special attributes computed from property
600                        # data that we build next. If the special attribute is non-empty,
601                        # its name will be added to the keyword list. First, we get all
602                        # the attributes for this feature. They will come back as
603                        # 4-tuples: [peg, name, value, URL]. We use a 3-tuple instead:
604                        # [name, value, value with URL]. (We don't need the PEG, since
605                        # we already know it.)
606                        my @attributes = map { [$_->[1], $_->[2], Tracer::CombineURL($_->[2], $_->[3])] }
607                                             @{$attributes->{$featureID}};
608                        # Now we process each of the special attributes.
609                        if (SpecialAttribute($featureID, \@attributes,
610                                             1, [0,2], '^(essential|potential_essential)$',
611                                             $loadFeatureEssential)) {
612                            push @keywords, 'essential';
613                            $loadFeature->Add('essential');
614                        }
615                        if (SpecialAttribute($featureID, \@attributes,
616                                             0, [2], '^virulen',
617                                             $loadFeatureVirulent)) {
618                            push @keywords, 'virulent';
619                            $loadFeature->Add('virulent');
620                        }
621                        if (SpecialAttribute($featureID, \@attributes,
622                                             0, [0,2], '^iedb_',
623                                             $loadFeatureIEDB)) {
624                            push @keywords, 'iedb';
625                            $loadFeature->Add('iedb');
626                        }
627                        # Now we need to bust up hyphenated words in the keyword
628                        # list. We keep them separate and put them at the end so
629                        # the original word order is available.
630                        my $keywordString = "";
631                        my $bustedString = "";
632                        for my $keyword (@keywords) {
633                            if (length $keyword >= 3) {
634                                $keywordString .= " $keyword";
635                                if ($keyword =~ /-/) {
636                                    my @words = split /-/, $keyword;
637                                    $bustedString .= join(" ", "", @words);
638                                }
639                            }
640                        }
641                        $keywordString .= $bustedString;
642                        # Get rid of annoying punctuation.
643                        $keywordString =~ s/[();]//g;
644                        # Clean the keyword list.
645                        my $cleanWords = $sprout->CleanKeywords($keywordString);
646                        Trace("Keyword string for $featureID: $cleanWords") if T(4);
647                        # Create the feature record.
648                        $loadFeature->Put($featureID, 1, $type, $assignment, $cleanWords);
649              # This part is the roughest. We need to relate the features to contig              # This part is the roughest. We need to relate the features to contig
650              # locations, and the locations must be split so that none of them exceed              # locations, and the locations must be split so that none of them exceed
651              # the maximum segment size. This simplifies the genes_in_region processing              # the maximum segment size. This simplifies the genes_in_region processing
652              # for Sprout.              # for Sprout.
653              my @locationList = split /\s*,\s*/, $locations;              my @locationList = split /\s*,\s*/, $locations;
654                        # Create the location position indicator.
655                        my $i = 1;
656              # Loop through the locations.              # Loop through the locations.
657              for my $location (@locationList) {              for my $location (@locationList) {
658                  # Parse the location.                  # Parse the location.
659                  my $locObject = BasicLocation->new($location);                          my $locObject = BasicLocation->new("$genomeID:$location");
660                  # Split it into a list of chunks.                  # Split it into a list of chunks.
661                  my @locOList = ();                  my @locOList = ();
662                  while (my $peeling = $locObject->Peel($chunkSize)) {                  while (my $peeling = $locObject->Peel($chunkSize)) {
# Line 488  Line 666 
666                  push @locOList, $locObject;                  push @locOList, $locObject;
667                  # Loop through the chunks, creating IsLocatedIn records. The variable                  # Loop through the chunks, creating IsLocatedIn records. The variable
668                  # "$i" will be used to keep the location index.                  # "$i" will be used to keep the location index.
                 my $i = 1;  
669                  for my $locChunk (@locOList) {                  for my $locChunk (@locOList) {
670                      $loadIsLocatedIn->Put($featureID, $locChunk->Contig, $locChunk->Left,                      $loadIsLocatedIn->Put($featureID, $locChunk->Contig, $locChunk->Left,
671                                            $locChunk->Dir, $locChunk->Length, $i);                                            $locChunk->Dir, $locChunk->Length, $i);
# Line 497  Line 674 
674              }              }
675          }          }
676      }      }
     # Finish the loads.  
     my $retVal = $self->_FinishAll();  
     return $retVal;  
 }  
   
 =head3 LoadBBHData  
   
 C<< my $stats = $spl->LoadBBHData(); >>  
   
 Load the bidirectional best hit data from FIG into Sprout.  
   
 Sprout does not store information on similarities. Instead, it has only the  
 bi-directional best hits. Even so, the BBH table is one of the largest in  
 the database.  
   
 The following relations are loaded by this method.  
   
     IsBidirectionalBestHitOf  
   
 =over 4  
   
 =item RETURNS  
   
 Returns a statistics object for the loads.  
   
 =back  
   
 =cut  
 #: Return Type $%;  
 sub LoadBBHData {  
     # Get this object instance.  
     my ($self) = @_;  
     # Get the FIG object.  
     my $fig = $self->{fig};  
     # Get the table of genome IDs.  
     my $genomeHash = $self->{genomes};  
     my $genomeCount = (keys %{$genomeHash});  
     my $featureCount = $genomeCount * 4000;  
     # Create load objects for each of the tables we're loading.  
     my $loadIsBidirectionalBestHitOf = $self->_TableLoader('IsBidirectionalBestHitOf',  
                                                            $featureCount * $genomeCount);  
     Trace("Beginning BBH load.") if T(2);  
     # Now we loop through the genomes, generating the data for each one.  
     for my $genomeID (sort keys %{$genomeHash}) {  
         $loadIsBidirectionalBestHitOf->Add("genomeIn");  
         Trace("Processing features for genome $genomeID.") if T(3);  
         # Get the feature list for this genome.  
         my $features = $fig->all_features_detailed($genomeID);  
         # Loop through the features.  
         for my $featureData (@{$features}) {  
             # Split the tuple.  
             my ($featureID, $locations, $aliases, $type) = @{$featureData};  
             # Get the bi-directional best hits.  
             my @bbhList = $fig->bbhs($featureID);  
             for my $bbhEntry (@bbhList) {  
                 # Get the target feature ID and the score.  
                 my ($targetID, $score) = @{$bbhEntry};  
                 # Check the target feature's genome.  
                 my $targetGenomeID = $fig->genome_of($targetID);  
                 # Only proceed if it's one of our genomes.  
                 if ($genomeHash->{$targetGenomeID}) {  
                     $loadIsBidirectionalBestHitOf->Put($featureID, $targetID, $targetGenomeID,  
                                                        $score);  
                 }  
             }  
677          }          }
678      }      }
679      # Finish the loads.      # Finish the loads.
# Line 584  Line 696 
696  The following relations are loaded by this method.  The following relations are loaded by this method.
697    
698      Subsystem      Subsystem
699        SubsystemClass
700      Role      Role
701        RoleEC
702      SSCell      SSCell
703      ContainsFeature      ContainsFeature
704      IsGenomeOf      IsGenomeOf
# Line 592  Line 706 
706      OccursInSubsystem      OccursInSubsystem
707      ParticipatesIn      ParticipatesIn
708      HasSSCell      HasSSCell
709        ConsistsOfRoles
710        RoleSubset
711        HasRoleSubset
712        ConsistsOfGenomes
713        GenomeSubset
714        HasGenomeSubset
715        Catalyzes
716        Diagram
717        RoleOccursIn
718    
719  =over 4  =over 4
720    
# Line 601  Line 724 
724    
725  =back  =back
726    
 B<TO DO>  
   
 Generate RoleName table?  
   
727  =cut  =cut
728  #: Return Type $%;  #: Return Type $%;
729  sub LoadSubsystemData {  sub LoadSubsystemData {
# Line 618  Line 737 
737      # Get the subsystem hash. This lists the subsystems we'll process.      # Get the subsystem hash. This lists the subsystems we'll process.
738      my $subsysHash = $self->{subsystems};      my $subsysHash = $self->{subsystems};
739      my @subsysIDs = sort keys %{$subsysHash};      my @subsysIDs = sort keys %{$subsysHash};
740      my $subsysCount = @subsysIDs;      # Get the map list.
741      my $genomeCount = (keys %{$genomeHash});      my @maps = $fig->all_maps;
     my $featureCount = $genomeCount * 4000;  
742      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
743      my $loadSubsystem = $self->_TableLoader('Subsystem', $subsysCount);      my $loadDiagram = $self->_TableLoader('Diagram', $self->PrimaryOnly);
744      my $loadRole = $self->_TableLoader('Role', $featureCount * 6);      my $loadRoleOccursIn = $self->_TableLoader('RoleOccursIn', $self->PrimaryOnly);
745      my $loadSSCell = $self->_TableLoader('SSCell', $featureCount * $genomeCount);      my $loadSubsystem = $self->_TableLoader('Subsystem');
746      my $loadContainsFeature = $self->_TableLoader('ContainsFeature', $featureCount * $subsysCount);      my $loadRole = $self->_TableLoader('Role', $self->PrimaryOnly);
747      my $loadIsGenomeOf = $self->_TableLoader('IsGenomeOf', $featureCount * $genomeCount);      my $loadRoleEC = $self->_TableLoader('RoleEC', $self->PrimaryOnly);
748      my $loadIsRoleOf = $self->_TableLoader('IsRoleOf', $featureCount * $genomeCount);      my $loadCatalyzes = $self->_TableLoader('Catalyzes', $self->PrimaryOnly);
749      my $loadOccursInSubsystem = $self->_TableLoader('OccursInSubsystem', $featureCount * 6);      my $loadSSCell = $self->_TableLoader('SSCell', $self->PrimaryOnly);
750      my $loadParticipatesIn = $self->_TableLoader('ParticipatesIn', $subsysCount * $genomeCount);      my $loadContainsFeature = $self->_TableLoader('ContainsFeature', $self->PrimaryOnly);
751      my $loadHasSSCell = $self->_TableLoader('HasSSCell', $featureCount * $genomeCount);      my $loadIsGenomeOf = $self->_TableLoader('IsGenomeOf', $self->PrimaryOnly);
752      Trace("Beginning subsystem data load.") if T(2);      my $loadIsRoleOf = $self->_TableLoader('IsRoleOf', $self->PrimaryOnly);
753        my $loadOccursInSubsystem = $self->_TableLoader('OccursInSubsystem', $self->PrimaryOnly);
754        my $loadParticipatesIn = $self->_TableLoader('ParticipatesIn', $self->PrimaryOnly);
755        my $loadHasSSCell = $self->_TableLoader('HasSSCell', $self->PrimaryOnly);
756        my $loadRoleSubset = $self->_TableLoader('RoleSubset', $self->PrimaryOnly);
757        my $loadGenomeSubset = $self->_TableLoader('GenomeSubset', $self->PrimaryOnly);
758        my $loadConsistsOfRoles = $self->_TableLoader('ConsistsOfRoles', $self->PrimaryOnly);
759        my $loadConsistsOfGenomes = $self->_TableLoader('ConsistsOfGenomes', $self->PrimaryOnly);
760        my $loadHasRoleSubset = $self->_TableLoader('HasRoleSubset', $self->PrimaryOnly);
761        my $loadHasGenomeSubset = $self->_TableLoader('HasGenomeSubset', $self->PrimaryOnly);
762        my $loadSubsystemClass = $self->_TableLoader('SubsystemClass', $self->PrimaryOnly);
763        if ($self->{options}->{loadOnly}) {
764            Trace("Loading from existing files.") if T(2);
765        } else {
766            Trace("Generating subsystem data.") if T(2);
767            # This hash will contain the role for each EC. When we're done, this
768            # information will be used to generate the Catalyzes table.
769            my %ecToRoles = ();
770      # Loop through the subsystems. Our first task will be to create the      # Loop through the subsystems. Our first task will be to create the
771      # roles. We do this by looping through the subsystems and creating a      # roles. We do this by looping through the subsystems and creating a
772      # role hash. The hash tracks each role ID so that we don't create      # role hash. The hash tracks each role ID so that we don't create
773      # duplicates. As we move along, we'll connect the roles and subsystems.          # duplicates. As we move along, we'll connect the roles and subsystems
774            # and memorize up the reactions.
775            my ($genomeID, $roleID);
776      my %roleData = ();      my %roleData = ();
777      for my $subsysID (@subsysIDs) {      for my $subsysID (@subsysIDs) {
778                # Get the subsystem object.
779                my $sub = $fig->get_subsystem($subsysID);
780                # Only proceed if the subsystem has a spreadsheet.
781                if (! $sub->{empty_ss}) {
782          Trace("Creating subsystem $subsysID.") if T(3);          Trace("Creating subsystem $subsysID.") if T(3);
783          $loadSubsystem->Add("subsystemIn");          $loadSubsystem->Add("subsystemIn");
784          # Create the subsystem record.          # Create the subsystem record.
785          $loadSubsystem->Put($subsysID);                  my $curator = $sub->get_curator();
786          # Get the subsystem's roles.                  my $notes = $sub->get_notes();
787          my @roles = $fig->subsystem_to_roles($subsysID);                  $loadSubsystem->Put($subsysID, $curator, $notes);
788          # Connect the roles to the subsystem. If a role is new, we create                  # Now for the classification string. This comes back as a list
789          # a role record for it.                  # reference and we convert it to a space-delimited string.
790          for my $roleID (@roles) {                  my $classList = $fig->subsystem_classification($subsysID);
791                    my $classString = join($FIG_Config::splitter, grep { $_ } @$classList);
792                    $loadSubsystemClass->Put($subsysID, $classString);
793                    # Connect it to its roles. Each role is a column in the subsystem spreadsheet.
794                    for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {
795                        # Connect to this role.
796              $loadOccursInSubsystem->Add("roleIn");              $loadOccursInSubsystem->Add("roleIn");
797              $loadOccursInSubsystem->Put($roleID, $subsysID);                      $loadOccursInSubsystem->Put($roleID, $subsysID, $col);
798                        # If it's a new role, add it to the role table.
799              if (! exists $roleData{$roleID}) {              if (! exists $roleData{$roleID}) {
800                  $loadRole->Put($roleID);                          # Get the role's abbreviation.
801                            my $abbr = $sub->get_role_abbr($col);
802                            # Add the role.
803                            $loadRole->Put($roleID, $abbr);
804                  $roleData{$roleID} = 1;                  $roleData{$roleID} = 1;
805                            # Check for an EC number.
806                            if ($roleID =~ /\(EC ([^.]+\.[^.]+\.[^.]+\.[^)]+)\)\s*$/) {
807                                my $ec = $1;
808                                $loadRoleEC->Put($roleID, $ec);
809                                $ecToRoles{$ec} = $roleID;
810                            }
811              }              }
812          }          }
813          # Now all roles for this subsystem have been filled in. We create the                  # Now we create the spreadsheet for the subsystem by matching roles to
814          # spreadsheet by matches roles to genomes. To do this, we need to                  # genomes. Each genome is a row and each role is a column. We may need
815          # get the genomes on the sheet.                  # to actually create the roles as we find them.
816          Trace("Creating subsystem $subsysID spreadsheet.") if T(3);          Trace("Creating subsystem $subsysID spreadsheet.") if T(3);
817          my @genomes = map { $_->[0] } @{$fig->subsystem_genomes($subsysID)};                  for (my $row = 0; defined($genomeID = $sub->get_genome($row)); $row++) {
818          for my $genomeID (@genomes) {                      # Only proceed if this is one of our genomes.
             # Only process this genome if it's one of ours.  
819              if (exists $genomeHash->{$genomeID}) {              if (exists $genomeHash->{$genomeID}) {
820                  # Connect the genome to the subsystem.                          # Count the PEGs and cells found for verification purposes.
821                  $loadParticipatesIn->Put($genomeID, $subsysID);                          my $pegCount = 0;
822                            my $cellCount = 0;
823                            # Create a list for the PEGs we find. This list will be used
824                            # to generate cluster numbers.
825                            my @pegsFound = ();
826                            # Create a hash that maps spreadsheet IDs to PEGs. We will
827                            # use this to generate the ContainsFeature data after we have
828                            # the cluster numbers.
829                            my %cellPegs = ();
830                            # Get the genome's variant code for this subsystem.
831                            my $variantCode = $sub->get_variant_code($row);
832                  # Loop through the subsystem's roles. We use an index because it is                  # Loop through the subsystem's roles. We use an index because it is
833                  # part of the spreadsheet cell ID.                  # part of the spreadsheet cell ID.
834                  for (my $i = 0; $i <= $#roles; $i++) {                          for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {
                     my $role = $roles[$i];  
835                      # Get the features in the spreadsheet cell for this genome and role.                      # Get the features in the spreadsheet cell for this genome and role.
836                      my @pegs = $fig->pegs_in_subsystem_cell($subsysID, $genomeID, $i);                              my @pegs = grep { !$fig->is_deleted_fid($_) } $sub->get_pegs_from_cell($row, $col);
837                      # Only proceed if features exist.                      # Only proceed if features exist.
838                      if (@pegs > 0) {                      if (@pegs > 0) {
839                          # Create the spreadsheet cell.                          # Create the spreadsheet cell.
840                          my $cellID = "$subsysID:$genomeID:$i";                                  $cellCount++;
841                                    my $cellID = "$subsysID:$genomeID:$col";
842                          $loadSSCell->Put($cellID);                          $loadSSCell->Put($cellID);
843                          $loadIsGenomeOf->Put($genomeID, $cellID);                          $loadIsGenomeOf->Put($genomeID, $cellID);
844                          $loadIsRoleOf->Put($role, $cellID);                                  $loadIsRoleOf->Put($roleID, $cellID);
845                          $loadHasSSCell->Put($subsysID, $cellID);                          $loadHasSSCell->Put($subsysID, $cellID);
846                          # Attach the features to it.                                  # Remember its features.
847                          for my $pegID (@pegs) {                                  push @pegsFound, @pegs;
848                              $loadContainsFeature->Put($cellID, $pegID);                                  $cellPegs{$cellID} = \@pegs;
849                                    $pegCount += @pegs;
850                                }
851                            }
852                            # If we found some cells for this genome, we need to compute clusters and
853                            # denote it participates in the subsystem.
854                            if ($pegCount > 0) {
855                                Trace("$pegCount PEGs in $cellCount cells for $genomeID.") if T(3);
856                                $loadParticipatesIn->Put($genomeID, $subsysID, $variantCode);
857                                # Create a hash mapping PEG IDs to cluster numbers.
858                                # We default to -1 for all of them.
859                                my %clusterOf = map { $_ => -1 } @pegsFound;
860                                # Partition the PEGs found into clusters.
861                                my @clusters = $fig->compute_clusters([keys %clusterOf], $sub);
862                                for (my $i = 0; $i <= $#clusters; $i++) {
863                                    my $subList = $clusters[$i];
864                                    for my $peg (@{$subList}) {
865                                        $clusterOf{$peg} = $i;
866                                    }
867                                }
868                                # Create the ContainsFeature data.
869                                for my $cellID (keys %cellPegs) {
870                                    my $cellList = $cellPegs{$cellID};
871                                    for my $cellPeg (@$cellList) {
872                                        $loadContainsFeature->Put($cellID, $cellPeg, $clusterOf{$cellPeg});
873                          }                          }
874                      }                      }
875                  }                  }
876              }              }
877          }          }
878                    # Now we need to generate the subsets. The subset names must be concatenated to
879                    # the subsystem name to make them unique keys. There are two types of subsets:
880                    # genome subsets and role subsets. We do the role subsets first.
881                    my @subsetNames = $sub->get_subset_names();
882                    for my $subsetID (@subsetNames) {
883                        # Create the subset record.
884                        my $actualID = "$subsysID:$subsetID";
885                        $loadRoleSubset->Put($actualID);
886                        # Connect the subset to the subsystem.
887                        $loadHasRoleSubset->Put($subsysID, $actualID);
888                        # Connect the subset to its roles.
889                        my @roles = $sub->get_subsetC_roles($subsetID);
890                        for my $roleID (@roles) {
891                            $loadConsistsOfRoles->Put($actualID, $roleID);
892      }      }
     # Finish the load.  
     my $retVal = $self->_FinishAll();  
     return $retVal;  
893  }  }
894                    # Next the genome subsets.
895  =head3 LoadDiagramData                  @subsetNames = $sub->get_subset_namesR();
896                    for my $subsetID (@subsetNames) {
897  C<< my $stats = $spl->LoadDiagramData(); >>                      # Create the subset record.
898                        my $actualID = "$subsysID:$subsetID";
899  Load the diagram data from FIG into Sprout.                      $loadGenomeSubset->Put($actualID);
900                        # Connect the subset to the subsystem.
901  Diagrams are used to organize functional roles. The diagram shows the                      $loadHasGenomeSubset->Put($subsysID, $actualID);
902  connections between chemicals that interact with a subsystem.                      # Connect the subset to its genomes.
903                        my @genomes = $sub->get_subsetR($subsetID);
904  The following relations are loaded by this method.                      for my $genomeID (@genomes) {
905                            $loadConsistsOfGenomes->Put($actualID, $genomeID);
906      Diagram                      }
907      RoleOccursIn                  }
908                }
909  =over 4          }
910            # Now we loop through the diagrams. We need to create the diagram records
911  =item RETURNS          # and link each diagram to its roles. Note that only roles which occur
912            # in subsystems (and therefore appear in the %ecToRoles hash) are
913  Returns a statistics object for the loads.          # included.
914            for my $map (@maps) {
 =back  
   
 =cut  
 #: Return Type $%;  
 sub LoadDiagramData {  
     # Get this object instance.  
     my ($self) = @_;  
     # Get the FIG object.  
     my $fig = $self->{fig};  
     # Get the map list.  
     my @maps = $fig->all_maps;  
     my $mapCount = @maps;  
     my $genomeCount = (keys %{$self->{genomes}});  
     my $featureCount = $genomeCount * 4000;  
     # Create load objects for each of the tables we're loading.  
     my $loadDiagram = $self->_TableLoader('Diagram', $mapCount);  
     my $loadRoleOccursIn = $self->_TableLoader('RoleOccursIn', $featureCount * 6);  
     Trace("Beginning diagram data load.") if T(2);  
     # Loop through the diagrams.  
     for my $map ($fig->all_maps) {  
915          Trace("Loading diagram $map.") if T(3);          Trace("Loading diagram $map.") if T(3);
916          # Get the diagram's descriptive name.          # Get the diagram's descriptive name.
917          my $name = $fig->map_name($map);          my $name = $fig->map_name($map);
# Line 740  Line 920 
920          # A hash is used to prevent duplicates.          # A hash is used to prevent duplicates.
921          my %roleHash = ();          my %roleHash = ();
922          for my $role ($fig->map_to_ecs($map)) {          for my $role ($fig->map_to_ecs($map)) {
923              if (! $roleHash{$role}) {                  if (exists $ecToRoles{$role} && ! $roleHash{$role}) {
924                  $loadRoleOccursIn->Put($role, $map);                      $loadRoleOccursIn->Put($ecToRoles{$role}, $map);
925                  $roleHash{$role} = 1;                  $roleHash{$role} = 1;
926              }              }
927          }          }
928      }      }
929            # Before we leave, we must create the Catalyzes table. We start with the reactions,
930            # then use the "ecToRoles" table to convert EC numbers to role IDs.
931            my @reactions = $fig->all_reactions();
932            for my $reactionID (@reactions) {
933                # Get this reaction's list of roles. The results will be EC numbers.
934                my @roles = $fig->catalyzed_by($reactionID);
935                # Loop through the roles, creating catalyzation records.
936                for my $thisRole (@roles) {
937                    if (exists $ecToRoles{$thisRole}) {
938                        $loadCatalyzes->Put($ecToRoles{$thisRole}, $reactionID);
939                    }
940                }
941            }
942        }
943      # Finish the load.      # Finish the load.
944      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
945      return $retVal;      return $retVal;
# Line 787  Line 981 
981      my $fig = $self->{fig};      my $fig = $self->{fig};
982      # Get the genome hash.      # Get the genome hash.
983      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
984      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
985      my $loadProperty = $self->_TableLoader('Property', $genomeCount * 1500);      my $loadProperty = $self->_TableLoader('Property');
986      my $loadHasProperty = $self->_TableLoader('HasProperty', $genomeCount * 1500);      my $loadHasProperty = $self->_TableLoader('HasProperty', $self->PrimaryOnly);
987      Trace("Beginning property data load.") if T(2);      if ($self->{options}->{loadOnly}) {
988            Trace("Loading from existing files.") if T(2);
989        } else {
990            Trace("Generating property data.") if T(2);
991      # Create a hash for storing property IDs.      # Create a hash for storing property IDs.
992      my %propertyKeys = ();      my %propertyKeys = ();
993      my $nextID = 1;      my $nextID = 1;
994      # Loop through the genomes.      # Loop through the genomes.
995      for my $genomeID (keys %{$genomeHash}) {          for my $genomeID (sort keys %{$genomeHash}) {
996          $loadProperty->Add("genomeIn");          $loadProperty->Add("genomeIn");
997                Trace("Generating properties for $genomeID.") if T(3);
998          # Get the genome's features. The feature ID is the first field in the          # Get the genome's features. The feature ID is the first field in the
999          # tuples returned by "all_features_detailed". We use "all_features_detailed"          # tuples returned by "all_features_detailed". We use "all_features_detailed"
1000          # rather than "all_features" because we want all features regardless of type.          # rather than "all_features" because we want all features regardless of type.
1001          my @features = map { $_->[0] } @{$fig->all_features_detailed($genomeID)};          my @features = map { $_->[0] } @{$fig->all_features_detailed($genomeID)};
1002                my $featureCount = 0;
1003                my $propertyCount = 0;
1004                # Get the properties for this genome's features.
1005                my $attributes = GetGenomeAttributes($fig, $genomeID, \@features);
1006                Trace("Property hash built for $genomeID.") if T(3);
1007          # Loop through the features, creating HasProperty records.          # Loop through the features, creating HasProperty records.
1008          for my $fid (@features) {          for my $fid (@features) {
             $loadProperty->Add("featureIn");  
1009              # Get all attributes for this feature. We do this one feature at a time              # Get all attributes for this feature. We do this one feature at a time
1010              # to insure we do not get any genome attributes.              # to insure we do not get any genome attributes.
1011              my @attributeList = $fig->get_attributes($fid, '', '', '');                  my @attributeList = @{$attributes->{$fid}};
1012                    if (scalar @attributeList) {
1013                        $featureCount++;
1014                    }
1015              # Loop through the attributes.              # Loop through the attributes.
1016              for my $tuple (@attributeList) {              for my $tuple (@attributeList) {
1017                        $propertyCount++;
1018                  # Get this attribute value's data. Note that we throw away the FID,                  # Get this attribute value's data. Note that we throw away the FID,
1019                  # since it will always be the same as the value if "$fid".                  # since it will always be the same as the value if "$fid".
1020                  my (undef, $key, $value, $url) = @{$tuple};                  my (undef, $key, $value, $url) = @{$tuple};
# Line 831  Line 1036 
1036                  $loadHasProperty->Put($fid, $propertyID, $url);                  $loadHasProperty->Put($fid, $propertyID, $url);
1037              }              }
1038          }          }
1039                # Update the statistics.
1040                Trace("$propertyCount attributes processed for $featureCount features.") if T(3);
1041                $loadHasProperty->Add("featuresIn", $featureCount);
1042                $loadHasProperty->Add("propertiesIn", $propertyCount);
1043            }
1044      }      }
1045      # Finish the load.      # Finish the load.
1046      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
# Line 871  Line 1081 
1081      my $fig = $self->{fig};      my $fig = $self->{fig};
1082      # Get the genome hash.      # Get the genome hash.
1083      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
1084      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
1085      my $loadAnnotation = $self->_TableLoader('Annotation', $genomeCount * 4000);      my $loadAnnotation = $self->_TableLoader('Annotation');
1086      my $loadIsTargetOfAnnotation = $self->_TableLoader('IsTargetOfAnnotation', $genomeCount * 4000);      my $loadIsTargetOfAnnotation = $self->_TableLoader('IsTargetOfAnnotation', $self->PrimaryOnly);
1087      my $loadSproutUser = $self->_TableLoader('SproutUser', 100);      my $loadSproutUser = $self->_TableLoader('SproutUser', $self->PrimaryOnly);
1088      my $loadUserAccess = $self->_TableLoader('UserAccess', 1000);      my $loadUserAccess = $self->_TableLoader('UserAccess', $self->PrimaryOnly);
1089      my $loadMadeAnnotation = $self->_TableLoader('MadeAnnotation', $genomeCount * 4000);      my $loadMadeAnnotation = $self->_TableLoader('MadeAnnotation', $self->PrimaryOnly);
1090      Trace("Beginning annotation data load.") if T(2);      if ($self->{options}->{loadOnly}) {
1091            Trace("Loading from existing files.") if T(2);
1092        } else {
1093            Trace("Generating annotation data.") if T(2);
1094      # Create a hash of user names. We'll use this to prevent us from generating duplicate      # Create a hash of user names. We'll use this to prevent us from generating duplicate
1095      # user records.      # user records.
1096      my %users = ( FIG => 1, master => 1 );      my %users = ( FIG => 1, master => 1 );
# Line 892  Line 1104 
1104      # Loop through the genomes.      # Loop through the genomes.
1105      for my $genomeID (sort keys %{$genomeHash}) {      for my $genomeID (sort keys %{$genomeHash}) {
1106          Trace("Processing $genomeID.") if T(3);          Trace("Processing $genomeID.") if T(3);
         # Get the genome's PEGs.  
         my @pegs = $fig->pegs_of($genomeID);  
         for my $peg (@pegs) {  
             Trace("Processing $peg.") if T(4);  
1107              # Create a hash of timestamps. We use this to prevent duplicate time stamps              # Create a hash of timestamps. We use this to prevent duplicate time stamps
1108              # from showing up for a single PEG's annotations.              # from showing up for a single PEG's annotations.
1109              my %seenTimestamps = ();              my %seenTimestamps = ();
1110              # Check for a functional assignment.              # Get the genome's annotations.
1111              my $func = $fig->function_of($peg);              my @annotations = $fig->read_all_annotations($genomeID);
1112              if ($func) {              Trace("Processing annotations.") if T(2);
1113                  # If this is NOT a hypothetical assignment, we create an              for my $tuple (@annotations) {
1114                  # assignment annotation for it.                  # Get the annotation tuple.
1115                  if (! FIG::hypo($peg)) {                  my ($peg, $timestamp, $user, $text) = @{$tuple};
                     # Note that we double the slashes so that what goes into the database is  
                     # a new-line escape sequence rather than an actual new-line.  
                     $loadAnnotation->Put("$peg:$time", $time, "FIG\\nSet function to\\n$func");  
                     $loadIsTargetOfAnnotation->Put($peg, "$peg:$time");  
                     $loadMadeAnnotation->Put("FIG", "$peg:$time");  
                     # Denote we've seen this timestamp.  
                     $seenTimestamps{$time} = 1;  
                 }  
                 # Now loop through the real annotations.  
                 for my $tuple ($fig->feature_annotations($peg, "raw")) {  
                     my ($fid, $timestamp, $user, $text) = @{$tuple};  
1116                      # Here we fix up the annotation text. "\r" is removed,                      # Here we fix up the annotation text. "\r" is removed,
1117                      # and "\t" and "\n" are escaped. Note we use the "s"                  # and "\t" and "\n" are escaped. Note we use the "gs"
1118                      # modifier so that new-lines inside the text do not                      # modifier so that new-lines inside the text do not
1119                      # stop the substitution search.                      # stop the substitution search.
1120                      $text =~ s/\r//gs;                      $text =~ s/\r//gs;
# Line 927  Line 1124 
1124                      $text =~ s/Set master function/Set FIG function/s;                      $text =~ s/Set master function/Set FIG function/s;
1125                      # Insure the time stamp is valid.                      # Insure the time stamp is valid.
1126                      if ($timestamp =~ /^\d+$/) {                      if ($timestamp =~ /^\d+$/) {
1127                          # Here it's a number. We need to insure it's unique.                      # Here it's a number. We need to insure the one we use to form
1128                          while ($seenTimestamps{$timestamp}) {                      # the key is unique.
1129                              $timestamp++;                      my $keyStamp = $timestamp;
1130                        while ($seenTimestamps{"$peg:$keyStamp"}) {
1131                            $keyStamp++;
1132                          }                          }
1133                          $seenTimestamps{$timestamp} = 1;                      my $annotationID = "$peg:$keyStamp";
1134                          my $annotationID = "$peg:$timestamp";                      $seenTimestamps{$annotationID} = 1;
1135                          # Insure the user exists.                          # Insure the user exists.
1136                          if (! $users{$user}) {                          if (! $users{$user}) {
1137                              $loadSproutUser->Put($user, "SEED user");                              $loadSproutUser->Put($user, "SEED user");
# Line 940  Line 1139 
1139                              $users{$user} = 1;                              $users{$user} = 1;
1140                          }                          }
1141                          # Generate the annotation.                          # Generate the annotation.
1142                          $loadAnnotation->Put($annotationID, $timestamp, "$user\\n$text");                      $loadAnnotation->Put($annotationID, $timestamp, $text);
1143                          $loadIsTargetOfAnnotation->Put($peg, $annotationID);                          $loadIsTargetOfAnnotation->Put($peg, $annotationID);
1144                          $loadMadeAnnotation->Put($user, $annotationID);                          $loadMadeAnnotation->Put($user, $annotationID);
1145                      } else {                      } else {
# Line 950  Line 1149 
1149                  }                  }
1150              }              }
1151          }          }
     }  
1152      # Finish the load.      # Finish the load.
1153      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
1154      return $retVal;      return $retVal;
# Line 991  Line 1189 
1189      my $fig = $self->{fig};      my $fig = $self->{fig};
1190      # Get the genome hash.      # Get the genome hash.
1191      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
1192      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
1193      my $loadComesFrom = $self->_TableLoader('ComesFrom', $genomeCount * 4);      my $loadComesFrom = $self->_TableLoader('ComesFrom', $self->PrimaryOnly);
1194      my $loadSource = $self->_TableLoader('Source', $genomeCount * 4);      my $loadSource = $self->_TableLoader('Source');
1195      my $loadSourceURL = $self->_TableLoader('SourceURL', $genomeCount * 8);      my $loadSourceURL = $self->_TableLoader('SourceURL');
1196      Trace("Beginning source data load.") if T(2);      if ($self->{options}->{loadOnly}) {
1197            Trace("Loading from existing files.") if T(2);
1198        } else {
1199            Trace("Generating annotation data.") if T(2);
1200      # Create hashes to collect the Source information.      # Create hashes to collect the Source information.
1201      my %sourceURL = ();      my %sourceURL = ();
1202      my %sourceDesc = ();      my %sourceDesc = ();
# Line 1010  Line 1210 
1210              chomp $line;              chomp $line;
1211              my($sourceID, $desc, $url) = split(/\t/,$line);              my($sourceID, $desc, $url) = split(/\t/,$line);
1212              $loadComesFrom->Put($genomeID, $sourceID);              $loadComesFrom->Put($genomeID, $sourceID);
1213              if ($url && ! exists $sourceURL{$genomeID}) {                  if ($url && ! exists $sourceURL{$sourceID}) {
1214                  $loadSourceURL->Put($sourceID, $url);                  $loadSourceURL->Put($sourceID, $url);
1215                  $sourceURL{$sourceID} = 1;                  $sourceURL{$sourceID} = 1;
1216              }              }
1217              if ($desc && ! exists $sourceDesc{$sourceID}) {                  if ($desc) {
1218                  $loadSource->Put($sourceID, $desc);                      $sourceDesc{$sourceID} = $desc;
1219                  $sourceDesc{$sourceID} = 1;                  } elsif (! exists $sourceDesc{$sourceID}) {
1220                        $sourceDesc{$sourceID} = $sourceID;
1221              }              }
1222          }          }
1223          close TMP;          close TMP;
1224      }      }
1225            # Write the source descriptions.
1226            for my $sourceID (keys %sourceDesc) {
1227                $loadSource->Put($sourceID, $sourceDesc{$sourceID});
1228            }
1229        }
1230      # Finish the load.      # Finish the load.
1231      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
1232      return $retVal;      return $retVal;
# Line 1060  Line 1266 
1266      my $fig = $self->{fig};      my $fig = $self->{fig};
1267      # Get the genome hash.      # Get the genome hash.
1268      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
1269      # Convert the genome hash. We'll get the genus and species for each genome and make      # Convert the genome hash. We'll get the genus and species for each genome and make
1270      # it the key.      # it the key.
1271      my %speciesHash = map { $fig->genus_species($_) => $_ } (keys %{$genomeHash});      my %speciesHash = map { $fig->genus_species($_) => $_ } (keys %{$genomeHash});
1272      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
1273      my $loadExternalAliasFunc = $self->_TableLoader('ExternalAliasFunc', $genomeCount * 4000);      my $loadExternalAliasFunc = $self->_TableLoader('ExternalAliasFunc');
1274      my $loadExternalAliasOrg = $self->_TableLoader('ExternalAliasOrg', $genomeCount * 4000);      my $loadExternalAliasOrg = $self->_TableLoader('ExternalAliasOrg');
1275      Trace("Beginning external data load.") if T(2);      if ($self->{options}->{loadOnly}) {
1276            Trace("Loading from existing files.") if T(2);
1277        } else {
1278            Trace("Generating external data.") if T(2);
1279      # We loop through the files one at a time. First, the organism file.      # We loop through the files one at a time. First, the organism file.
1280      Open(\*ORGS, "<$FIG_Config::global/ext_org.table");          Open(\*ORGS, "sort +0 -1 -u -t\"\t\" $FIG_Config::global/ext_org.table |");
1281      my $orgLine;      my $orgLine;
1282      while (defined($orgLine = <ORGS>)) {      while (defined($orgLine = <ORGS>)) {
1283          # Clean the input line.          # Clean the input line.
# Line 1081  Line 1289 
1289      close ORGS;      close ORGS;
1290      # Now the function file.      # Now the function file.
1291      my $funcLine;      my $funcLine;
1292      Open(\*FUNCS, "<$FIG_Config::global/ext_func.table");          Open(\*FUNCS, "sort +0 -1 -u -t\"\t\" $FIG_Config::global/ext_func.table |");
1293      while (defined($funcLine = <FUNCS>)) {      while (defined($funcLine = <FUNCS>)) {
1294          # Clean the line ending.          # Clean the line ending.
1295          chomp $funcLine;          chomp $funcLine;
# Line 1097  Line 1305 
1305              $loadExternalAliasFunc->Put(@funcFields[0,1]);              $loadExternalAliasFunc->Put(@funcFields[0,1]);
1306          }          }
1307      }      }
1308        }
1309        # Finish the load.
1310        my $retVal = $self->_FinishAll();
1311        return $retVal;
1312    }
1313    
1314    
1315    =head3 LoadReactionData
1316    
1317    C<< my $stats = $spl->LoadReactionData(); >>
1318    
1319    Load the reaction data from FIG into Sprout.
1320    
1321    Reaction data connects reactions to the compounds that participate in them.
1322    
1323    The following relations are loaded by this method.
1324    
1325        Reaction
1326        ReactionURL
1327        Compound
1328        CompoundName
1329        CompoundCAS
1330        IsAComponentOf
1331    
1332    This method proceeds reaction by reaction rather than genome by genome.
1333    
1334    =over 4
1335    
1336    =item RETURNS
1337    
1338    Returns a statistics object for the loads.
1339    
1340    =back
1341    
1342    =cut
1343    #: Return Type $%;
1344    sub LoadReactionData {
1345        # Get this object instance.
1346        my ($self) = @_;
1347        # Get the FIG object.
1348        my $fig = $self->{fig};
1349        # Create load objects for each of the tables we're loading.
1350        my $loadReaction = $self->_TableLoader('Reaction');
1351        my $loadReactionURL = $self->_TableLoader('ReactionURL', $self->PrimaryOnly);
1352        my $loadCompound = $self->_TableLoader('Compound', $self->PrimaryOnly);
1353        my $loadCompoundName = $self->_TableLoader('CompoundName', $self->PrimaryOnly);
1354        my $loadCompoundCAS = $self->_TableLoader('CompoundCAS', $self->PrimaryOnly);
1355        my $loadIsAComponentOf = $self->_TableLoader('IsAComponentOf', $self->PrimaryOnly);
1356        if ($self->{options}->{loadOnly}) {
1357            Trace("Loading from existing files.") if T(2);
1358        } else {
1359            Trace("Generating annotation data.") if T(2);
1360            # First we create the compounds.
1361            my @compounds = $fig->all_compounds();
1362            for my $cid (@compounds) {
1363                # Check for names.
1364                my @names = $fig->names_of_compound($cid);
1365                # Each name will be given a priority number, starting with 1.
1366                my $prio = 1;
1367                for my $name (@names) {
1368                    $loadCompoundName->Put($cid, $name, $prio++);
1369                }
1370                # Create the main compound record. Note that the first name
1371                # becomes the label.
1372                my $label = (@names > 0 ? $names[0] : $cid);
1373                $loadCompound->Put($cid, $label);
1374                # Check for a CAS ID.
1375                my $cas = $fig->cas($cid);
1376                if ($cas) {
1377                    $loadCompoundCAS->Put($cid, $cas);
1378                }
1379            }
1380            # All the compounds are set up, so we need to loop through the reactions next. First,
1381            # we initialize the discriminator index. This is a single integer used to insure
1382            # duplicate elements in a reaction are not accidentally collapsed.
1383            my $discrim = 0;
1384            my @reactions = $fig->all_reactions();
1385            for my $reactionID (@reactions) {
1386                # Create the reaction record.
1387                $loadReaction->Put($reactionID, $fig->reversible($reactionID));
1388                # Compute the reaction's URL.
1389                my $url = HTML::reaction_link($reactionID);
1390                # Put it in the ReactionURL table.
1391                $loadReactionURL->Put($reactionID, $url);
1392                # Now we need all of the reaction's compounds. We get these in two phases,
1393                # substrates first and then products.
1394                for my $product (0, 1) {
1395                    # Get the compounds of the current type for the current reaction. FIG will
1396                    # give us 3-tuples: [ID, stoichiometry, main-flag]. At this time we do not
1397                    # have location data in SEED, so it defaults to the empty string.
1398                    my @compounds = $fig->reaction2comp($reactionID, $product);
1399                    for my $compData (@compounds) {
1400                        # Extract the compound data from the current tuple.
1401                        my ($cid, $stoich, $main) = @{$compData};
1402                        # Link the compound to the reaction.
1403                        $loadIsAComponentOf->Put($cid, $reactionID, $discrim++, "", $main,
1404                                                 $product, $stoich);
1405                    }
1406                }
1407            }
1408        }
1409      # Finish the load.      # Finish the load.
1410      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
1411      return $retVal;      return $retVal;
# Line 1112  Line 1421 
1421    
1422      GenomeGroups      GenomeGroups
1423    
1424  There is no direct support for genome groups in FIG, so we access the SEED  Currently, we do not use groups. We used to use them for NMPDR groups,
1425    butThere is no direct support for genome groups in FIG, so we access the SEED
1426  files directly.  files directly.
1427    
1428  =over 4  =over 4
# Line 1132  Line 1442 
1442      my $fig = $self->{fig};      my $fig = $self->{fig};
1443      # Get the genome hash.      # Get the genome hash.
1444      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
1445      # Create a load object for the table we're loading.      # Create a load object for the table we're loading.
1446      my $loadGenomeGroups = $self->_TableLoader('GenomeGroups', $genomeCount * 4);      my $loadGenomeGroups = $self->_TableLoader('GenomeGroups');
1447      Trace("Beginning group data load.") if T(2);      if ($self->{options}->{loadOnly}) {
1448            Trace("Loading from existing files.") if T(2);
1449        } else {
1450            Trace("Generating group data.") if T(2);
1451            # Currently there are no groups.
1452        }
1453        # Finish the load.
1454        my $retVal = $self->_FinishAll();
1455        return $retVal;
1456    }
1457    
1458    =head3 LoadSynonymData
1459    
1460    C<< my $stats = $spl->LoadSynonymData(); >>
1461    
1462    Load the synonym groups into Sprout.
1463    
1464    The following relations are loaded by this method.
1465    
1466        SynonymGroup
1467        IsSynonymGroupFor
1468    
1469    The source information for these relations is taken from the C<maps_to_id> method
1470    of the B<FIG> object. Unfortunately, to make this work, we need to use direct
1471    SQL against the FIG database.
1472    
1473    =over 4
1474    
1475    =item RETURNS
1476    
1477    Returns a statistics object for the loads.
1478    
1479    =back
1480    
1481    =cut
1482    #: Return Type $%;
1483    sub LoadSynonymData {
1484        # Get this object instance.
1485        my ($self) = @_;
1486        # Get the FIG object.
1487        my $fig = $self->{fig};
1488        # Get the genome hash.
1489        my $genomeHash = $self->{genomes};
1490        # Create a load object for the table we're loading.
1491        my $loadSynonymGroup = $self->_TableLoader('SynonymGroup');
1492        my $loadIsSynonymGroupFor = $self->_TableLoader('IsSynonymGroupFor');
1493        if ($self->{options}->{loadOnly}) {
1494            Trace("Loading from existing files.") if T(2);
1495        } else {
1496            Trace("Generating synonym group data.") if T(2);
1497            # Get the database handle.
1498            my $dbh = $fig->db_handle();
1499            # Ask for the synonyms.
1500            my $sth = $dbh->prepare_command("SELECT maps_to, syn_id FROM peg_synonyms ORDER BY maps_to");
1501            my $result = $sth->execute();
1502            if (! defined($result)) {
1503                Confess("Database error in Synonym load: " . $sth->errstr());
1504            } else {
1505                # Remember the current synonym.
1506                my $current_syn = "";
1507                # Count the features.
1508                my $featureCount = 0;
1509                # Loop through the synonym/peg pairs.
1510                while (my @row = $sth->fetchrow()) {
1511                    # Get the synonym ID and feature ID.
1512                    my ($syn_id, $peg) = @row;
1513                    # Insure it's for one of our genomes.
1514                    my $genomeID = FIG::genome_of($peg);
1515                    if (exists $genomeHash->{$genomeID}) {
1516                        # Verify the synonym.
1517                        if ($syn_id ne $current_syn) {
1518                            # It's new, so put it in the group table.
1519                            $loadSynonymGroup->Put($syn_id);
1520                            $current_syn = $syn_id;
1521                        }
1522                        # Connect the synonym to the peg.
1523                        $loadIsSynonymGroupFor->Put($syn_id, $peg);
1524                        # Count this feature.
1525                        $featureCount++;
1526                        if ($featureCount % 1000 == 0) {
1527                            Trace("$featureCount features processed.") if T(3);
1528                        }
1529                    }
1530                }
1531            }
1532        }
1533        # Finish the load.
1534        my $retVal = $self->_FinishAll();
1535        return $retVal;
1536    }
1537    
1538    =head3 LoadFamilyData
1539    
1540    C<< my $stats = $spl->LoadFamilyData(); >>
1541    
1542    Load the protein families into Sprout.
1543    
1544    The following relations are loaded by this method.
1545    
1546        Family
1547        IsFamilyForFeature
1548    
1549    The source information for these relations is taken from the C<families_for_protein>,
1550    C<family_function>, and C<sz_family> methods of the B<FIG> object.
1551    
1552    =over 4
1553    
1554    =item RETURNS
1555    
1556    Returns a statistics object for the loads.
1557    
1558    =back
1559    
1560    =cut
1561    #: Return Type $%;
1562    sub LoadFamilyData {
1563        # Get this object instance.
1564        my ($self) = @_;
1565        # Get the FIG object.
1566        my $fig = $self->{fig};
1567        # Get the genome hash.
1568        my $genomeHash = $self->{genomes};
1569        # Create load objects for the tables we're loading.
1570        my $loadFamily = $self->_TableLoader('Family');
1571        my $loadIsFamilyForFeature = $self->_TableLoader('IsFamilyForFeature');
1572        if ($self->{options}->{loadOnly}) {
1573            Trace("Loading from existing files.") if T(2);
1574        } else {
1575            Trace("Generating family data.") if T(2);
1576            # Create a hash for the family IDs.
1577            my %familyHash = ();
1578      # Loop through the genomes.      # Loop through the genomes.
1579      my $line;          for my $genomeID (sort keys %{$genomeHash}) {
1580      for my $genomeID (keys %{$genomeHash}) {              Trace("Processing features for $genomeID.") if T(2);
1581          Trace("Processing $genomeID.") if T(3);              # Loop through this genome's PEGs.
1582          # Open the NMPDR group file for this genome.              for my $fid ($fig->all_features($genomeID, "peg")) {
1583          if (open(TMP, "<$FIG_Config::organisms/$genomeID/NMPDR") &&                  $loadIsFamilyForFeature->Add("features", 1);
1584              defined($line = <TMP>)) {                  # Get this feature's families.
1585              # Clean the line ending.                  my @families = $fig->families_for_protein($fid);
1586              chomp $line;                  # Loop through the families, connecting them to the feature.
1587              # Add the group to the table. Note that there can only be one group                  for my $family (@families) {
1588              # per genome.                      $loadIsFamilyForFeature->Put($family, $fid);
1589              $loadGenomeGroups->Put($genomeID, $line);                      # If this is a new family, create a record for it.
1590                        if (! exists $familyHash{$family}) {
1591                            $familyHash{$family} = 1;
1592                            $loadFamily->Add("families", 1);
1593                            my $size = $fig->sz_family($family);
1594                            my $func = $fig->family_function($family);
1595                            $loadFamily->Put($family, $size, $func);
1596                        }
1597                    }
1598                }
1599          }          }
         close TMP;  
1600      }      }
1601      # Finish the load.      # Finish the load.
1602      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
1603      return $retVal;      return $retVal;
1604  }  }
1605    
1606    =head3 LoadDrugData
1607    
1608    C<< my $stats = $spl->LoadDrugData(); >>
1609    
1610    Load the drug target data into Sprout.
1611    
1612    The following relations are loaded by this method.
1613    
1614        DrugProject
1615        ContainsTopic
1616        DrugTopic
1617        ContainsAnalysisOf
1618        PDB
1619        IncludesBound
1620        IsBoundIn
1621        BindsWith
1622        Ligand
1623        DescribesProteinForFeature
1624        FeatureConservation
1625    
1626    The source information for these relations is taken from flat files in the
1627    C<$FIG_Config::drug_directory>. The file C<master_tables.list> contains
1628    a list of drug project names paired with file names. The named file (in the
1629    same directory) contains all the data for the project.
1630    
1631    =over 4
1632    
1633    =item RETURNS
1634    
1635    Returns a statistics object for the loads.
1636    
1637    =back
1638    
1639    =cut
1640    #: Return Type $%;
1641    sub LoadDrugData {
1642        # Get this object instance.
1643        my ($self) = @_;
1644        # Get the FIG object.
1645        my $fig = $self->{fig};
1646        # Get the genome hash.
1647        my $genomeHash = $self->{genomes};
1648        # Create load objects for the tables we're loading.
1649        my $loadDrugProject = $self->_TableLoader('DrugProject');
1650        my $loadContainsTopic = $self->_TableLoader('ContainsTopic');
1651        my $loadDrugTopic = $self->_TableLoader('DrugTopic');
1652        my $loadContainsAnalysisOf = $self->_TableLoader('ContainsAnalysisOf');
1653        my $loadPDB = $self->_TableLoader('PDB');
1654        my $loadIncludesBound = $self->_TableLoader('IncludesBound');
1655        my $loadIsBoundIn = $self->_TableLoader('IsBoundIn');
1656        my $loadBindsWith = $self->_TableLoader('BindsWith');
1657        my $loadLigand = $self->_TableLoader('Ligand');
1658        my $loadDescribesProteinForFeature = $self->_TableLoader('DescribesProteinForFeature');
1659        my $loadFeatureConservation = $self->_TableLoader('FeatureConservation');
1660        if ($self->{options}->{loadOnly}) {
1661            Trace("Loading from existing files.") if T(2);
1662        } else {
1663            Trace("Generating drug target data.") if T(2);
1664            # Load the project list. The file comes in as a list of chomped lines,
1665            # and we split them on the TAB character to make the project name the
1666            # key and the file name the value of the resulting hash.
1667            my %projects = map { split /\t/, $_ } Tracer::GetFile("$FIG_Config::drug_directory/master_tables.list");
1668            # Create hashes for the derived objects: PDBs, Features, and Ligands. These objects
1669            # may occur multiple times in a single project file or even in multiple project
1670            # files.
1671            my %ligands = ();
1672            my %pdbs = ();
1673            my %features = ();
1674            my %bindings = ();
1675            # Set up a counter for drug topics. This will be used as the key.
1676            my $topicCounter = 0;
1677            # Loop through the projects. We sort the keys not because we need them sorted, but
1678            # because it makes it easier to infer our progress from trace messages.
1679            for my $project (sort keys %projects) {
1680                Trace("Processing project $project.") if T(3);
1681                # Only proceed if the download file exists.
1682                my $projectFile = "$FIG_Config::drug_directory/$projects{$project}";
1683                if (! -f $projectFile) {
1684                    Trace("Project file $projectFile not found.") if T(0);
1685                } else {
1686                    # Create the project record.
1687                    $loadDrugProject->Put($project);
1688                    # Create a hash for the topics. Each project has one or more topics. The
1689                    # topic is identified by a URL, a category, and an identifier.
1690                    my %topics = ();
1691                    # Now we can open the project file.
1692                    Trace("Reading project file $projectFile.") if T(3);
1693                    Open(\*PROJECT, "<$projectFile");
1694                    # Get the first record, which is a list of column headers. We don't use this
1695                    # for anything, but it may be useful for debugging.
1696                    my $headerLine = <PROJECT>;
1697                    # Loop through the rest of the records.
1698                    while (! eof PROJECT) {
1699                        # Get the current line of data. Note that not all lines will have all
1700                        # the fields. In particular, the CLIBE data is fairly rare.
1701                        my ($authorOrganism, $category, $tag, $refURL, $peg, $conservation,
1702                            $pdbBound, $pdbBoundEval, $pdbFree, $pdbFreeEval, $pdbFreeTitle,
1703                            $protDistInfo, $passAspInfo, $passAspFile, $passWeightInfo,
1704                            $passWeightFile, $clibeInfo, $clibeURL, $clibeTotalEnergy,
1705                            $clibeVanderwaals, $clibeHBonds, $clibeEI, $clibeSolvationE)
1706                           = Tracer::GetLine(\*PROJECT);
1707                        # The tag contains an identifier for the current line of data followed
1708                        # by a text statement that generally matches a property name in the
1709                        # main database. We split it up, since the identifier goes with
1710                        # the PDB data and the text statement is part of the topic.
1711                        my ($lineID, $topicTag) = split /\s*,\s*/, $tag;
1712                        $loadDrugProject->Add("data line");
1713                        # Check for a new topic.
1714                        my $topicData = "$category\t$topicTag\t$refURL";
1715                        if (! exists $topics{$topicData}) {
1716                            # Here we have a new topic. Compute its ID.
1717                            $topicCounter++;
1718                            $topics{$topicData} = $topicCounter;
1719                            # Create its database record.
1720                            $loadDrugTopic->Put($topicCounter, $refURL, $category, $authorOrganism,
1721                                                $topicTag);
1722                            # Connect it to the project.
1723                            $loadContainsTopic->Put($project, $topicCounter);
1724                            $loadDrugTopic->Add("topic");
1725                        }
1726                        # Now we know the topic ID exists in the hash and the topic will
1727                        # appear in the database, so we get this topic's ID.
1728                        my $topicID = $topics{$topicData};
1729                        # If the feature in this line is new, we need to save its conservation
1730                        # number.
1731                        if (! exists $features{$peg}) {
1732                            $loadFeatureConservation->Put($peg, $conservation);
1733                            $features{$peg} = 1;
1734                        }
1735                        # Now we have two PDBs to deal with-- a bound PDB and a free PDB.
1736                        # The free PDB will have data about docking points; the bound PDB
1737                        # will have data about docking. We store both types as PDBs, and
1738                        # the special data comes from relationships. First we process the
1739                        # bound PDB.
1740                        if ($pdbBound) {
1741                            $loadPDB->Add("bound line");
1742                            # Insure this PDB is in the database.
1743                            $self->CreatePDB($pdbBound, lc "$pdbFreeTitle (bound)", "bound", \%pdbs, $loadPDB);
1744                            # Connect it to this topic.
1745                            $loadIncludesBound->Put($topicID, $pdbBound);
1746                            # Check for CLIBE data.
1747                            if ($clibeInfo) {
1748                                $loadLigand->Add("clibes");
1749                                # We have CLIBE data, so we create a ligand and relate it to the PDB.
1750                                if (! exists $ligands{$clibeInfo}) {
1751                                    # This is a new ligand, so create its record.
1752                                    $loadLigand->Put($clibeInfo);
1753                                    $loadLigand->Add("ligand");
1754                                    # Make sure we know this ligand already exists.
1755                                    $ligands{$clibeInfo} = 1;
1756                                }
1757                                # Now connect the PDB to the ligand using the CLIBE data.
1758                                $loadBindsWith->Put($pdbBound, $clibeInfo, $clibeURL, $clibeHBonds, $clibeEI,
1759                                                    $clibeSolvationE, $clibeVanderwaals);
1760                            }
1761                            # Connect this PDB to the feature.
1762                            $loadDescribesProteinForFeature->Put($pdbBound, $peg, $protDistInfo, $pdbBoundEval);
1763                        }
1764                        # Next is the free PDB.
1765                        if ($pdbFree) {
1766                            $loadPDB->Add("free line");
1767                            # Insure this PDB is in the database.
1768                            $self->CreatePDB($pdbFree, lc $pdbFreeTitle, "free", \%pdbs, $loadPDB);
1769                            # Connect it to this topic.
1770                            $loadContainsAnalysisOf->Put($topicID, $pdbFree, $passAspInfo,
1771                                                         $passWeightFile, $passWeightInfo, $passAspFile);
1772                            # Connect this PDB to the feature.
1773                            $loadDescribesProteinForFeature->Put($pdbFree, $peg, $protDistInfo, $pdbFreeEval);
1774                        }
1775                        # If we have both PDBs, we may need to link them.
1776                        if ($pdbFree && $pdbBound) {
1777                            $loadIsBoundIn->Add("connection");
1778                            # Insure we only link them once.
1779                            my $bindingKey =  "$pdbFree\t$pdbBound";
1780                            if (! exists $bindings{$bindingKey}) {
1781                                $loadIsBoundIn->Add("newConnection");
1782                                $loadIsBoundIn->Put($pdbFree, $pdbBound);
1783                                $bindings{$bindingKey} = 1;
1784                            }
1785                        }
1786                    }
1787                    # Close off this project.
1788                    close PROJECT;
1789                }
1790            }
1791        }
1792        # Finish the load.
1793        my $retVal = $self->_FinishAll();
1794        return $retVal;
1795    }
1796    
1797    
1798  =head2 Internal Utility Methods  =head2 Internal Utility Methods
1799    
1800    =head3 SpecialAttribute
1801    
1802    C<< my $count = SproutLoad::SpecialAttribute($id, \@attributes, $idxMatch, \@idxValues, $pattern, $loader); >>
1803    
1804    Look for special attributes of a given type. A special attribute is found by comparing one of
1805    the columns of the incoming attribute list to a search pattern. If a match is found, then
1806    a set of columns is put into an output table connected to the specified ID.
1807    
1808    For example, when processing features, the attribute list we look at has three columns: attribute
1809    name, attribute value, and attribute value HTML. The IEDB attribute exists if the attribute name
1810    begins with C<iedb_>. The call signature is therefore
1811    
1812        my $found = SpecialAttribute($fid, \@attributeList, 0, [0,2], '^iedb_', $loadFeatureIEDB);
1813    
1814    The pattern is matched against column 0, and if we have a match, then column 2's value is put
1815    to the output along with the specified feature ID.
1816    
1817    =over 4
1818    
1819    =item id
1820    
1821    ID of the object whose special attributes are being loaded. This forms the first column of the
1822    output.
1823    
1824    =item attributes
1825    
1826    Reference to a list of tuples.
1827    
1828    =item idxMatch
1829    
1830    Index in each tuple of the column to be matched against the pattern. If the match is
1831    successful, an output record will be generated.
1832    
1833    =item idxValues
1834    
1835    Reference to a list containing the indexes in each tuple of the columns to be put as
1836    the second column of the output.
1837    
1838    =item pattern
1839    
1840    Pattern to be matched against the specified column. The match will be case-insensitive.
1841    
1842    =item loader
1843    
1844    An object to which each output record will be put. Usually this is an B<ERDBLoad> object,
1845    but technically it could be anything with a C<Put> method.
1846    
1847    =item RETURN
1848    
1849    Returns a count of the matches found.
1850    
1851    =item
1852    
1853    =back
1854    
1855    =cut
1856    
1857    sub SpecialAttribute {
1858        # Get the parameters.
1859        my ($id, $attributes, $idxMatch, $idxValues, $pattern, $loader) = @_;
1860        # Declare the return variable.
1861        my $retVal = 0;
1862        # Loop through the attribute rows.
1863        for my $row (@{$attributes}) {
1864            # Check for a match.
1865            if ($row->[$idxMatch] =~ m/$pattern/i) {
1866                # We have a match, so output a row. This is a bit tricky, since we may
1867                # be putting out multiple columns of data from the input.
1868                my $value = join(" ", map { $row->[$_] } @{$idxValues});
1869                $loader->Put($id, $value);
1870                $retVal++;
1871            }
1872        }
1873        Trace("$retVal special attributes found for $id and loader " . $loader->RelName() . ".") if T(4) && $retVal;
1874        # Return the number of matches.
1875        return $retVal;
1876    }
1877    
1878    =head3 CreatePDB
1879    
1880    C<< $loader->CreatePDB($pdbID, $title, $type, \%pdbHash); >>
1881    
1882    Insure that a PDB record exists for the identified PDB. If one does not exist, it will be
1883    created.
1884    
1885    =over 4
1886    
1887    =item pdbID
1888    
1889    ID string (usually an unqualified file name) for the desired PDB.
1890    
1891    =item title
1892    
1893    Title to use if the PDB must be created.
1894    
1895    =item type
1896    
1897    Type of PDB: C<free> or C<bound>
1898    
1899    =item pdbHash
1900    
1901    Hash containing the IDs of PDBs that have already been created.
1902    
1903    =item pdbLoader
1904    
1905    Load object for the PDB table.
1906    
1907    =back
1908    
1909    =cut
1910    
1911    sub CreatePDB {
1912        # Get the parameters.
1913        my ($self, $pdbID, $title, $type, $pdbHash, $pdbLoader) = @_;
1914        $pdbLoader->Add("PDB check");
1915        # Check to see if this is a new PDB.
1916        if (! exists $pdbHash->{$pdbID}) {
1917            # It is, so we create it.
1918            $pdbLoader->Put($pdbID, $title, $type);
1919            $pdbHash->{$pdbID} = 1;
1920            # Count it.
1921            $pdbLoader->Add("PDB-$type");
1922        }
1923    }
1924    
1925  =head3 TableLoader  =head3 TableLoader
1926    
1927  Create an ERDBLoad object for the specified table. The object is also added to  Create an ERDBLoad object for the specified table. The object is also added to
# Line 1172  Line 1936 
1936    
1937  Name of the table (relation) being loaded.  Name of the table (relation) being loaded.
1938    
1939  =item rowCount (optional)  =item ignore
1940    
1941  Estimated maximum number of rows in the table.  TRUE if the table should be ignored entirely, else FALSE.
1942    
1943  =item RETURN  =item RETURN
1944    
# Line 1186  Line 1950 
1950    
1951  sub _TableLoader {  sub _TableLoader {
1952      # Get the parameters.      # Get the parameters.
1953      my ($self, $tableName, $rowCount) = @_;      my ($self, $tableName, $ignore) = @_;
1954      # Create the load object.      # Create the load object.
1955      my $retVal = ERDBLoad->new($self->{erdb}, $tableName, $self->{loadDirectory}, $rowCount);      my $retVal = ERDBLoad->new($self->{erdb}, $tableName, $self->{loadDirectory}, $self->LoadOnly,
1956                                   $ignore);
1957      # Cache it in the loader list.      # Cache it in the loader list.
1958      push @{$self->{loaders}}, $retVal;      push @{$self->{loaders}}, $retVal;
1959      # Return it to the caller.      # Return it to the caller.
# Line 1222  Line 1987 
1987      my $retVal = Stats->new();      my $retVal = Stats->new();
1988      # Get the loader list.      # Get the loader list.
1989      my $loadList = $self->{loaders};      my $loadList = $self->{loaders};
1990        # Create a hash to hold the statistics objects, keyed on relation name.
1991        my %loaderHash = ();
1992      # Loop through the list, finishing the loads. Note that if the finish fails, we die      # Loop through the list, finishing the loads. Note that if the finish fails, we die
1993      # ignominiously. At some future point, we want to make the loads restartable.      # ignominiously. At some future point, we want to make the loads more restartable.
1994      while (my $loader = pop @{$loadList}) {      while (my $loader = pop @{$loadList}) {
1995            # Get the relation name.
1996            my $relName = $loader->RelName;
1997            # Check the ignore flag.
1998            if ($loader->Ignore) {
1999                Trace("Relation $relName not loaded.") if T(2);
2000            } else {
2001                # Here we really need to finish.
2002                Trace("Finishing $relName.") if T(2);
2003          my $stats = $loader->Finish();          my $stats = $loader->Finish();
2004                $loaderHash{$relName} = $stats;
2005            }
2006        }
2007        # Now we loop through again, actually loading the tables. We want to finish before
2008        # loading so that if something goes wrong at this point, all the load files are usable
2009        # and we don't have to redo all that work.
2010        for my $relName (sort keys %loaderHash) {
2011            # Get the statistics for this relation.
2012            my $stats = $loaderHash{$relName};
2013            # Check for a database load.
2014            if ($self->{options}->{dbLoad}) {
2015                # Here we want to use the load file just created to load the database.
2016                Trace("Loading relation $relName.") if T(2);
2017                my $newStats = $self->{sprout}->LoadUpdate(1, [$relName]);
2018                # Accumulate the statistics from the DB load.
2019                $stats->Accumulate($newStats);
2020            }
2021          $retVal->Accumulate($stats);          $retVal->Accumulate($stats);
         my $relName = $loader->RelName;  
2022          Trace("Statistics for $relName:\n" . $stats->Show()) if T(2);          Trace("Statistics for $relName:\n" . $stats->Show()) if T(2);
2023      }      }
2024      # Return the load statistics.      # Return the load statistics.
2025      return $retVal;      return $retVal;
2026  }  }
2027    =head3 GetGenomeAttributes
2028    
2029    C<< my $aHashRef = GetGenomeAttributes($fig, $genomeID, \@fids); >>
2030    
2031    Return a hash of attributes keyed on feature ID. This method gets all the attributes
2032    for all the features of a genome in a single call, then organizes them into a hash.
2033    
2034    =over 4
2035    
2036    =item fig
2037    
2038    FIG-like object for accessing attributes.
2039    
2040    =item genomeID
2041    
2042    ID of the genome who's attributes are desired.
2043    
2044    =item fids
2045    
2046    Reference to a list of the feature IDs whose attributes are to be kept.
2047    
2048    =item RETURN
2049    
2050    Returns a reference to a hash. The key of the hash is the feature ID. The value is the
2051    reference to a list of the feature's attribute tuples. Each tuple contains the feature ID,
2052    the attribute key, and one or more attribute values.
2053    
2054    =back
2055    
2056    =cut
2057    
2058    sub GetGenomeAttributes {
2059        # Get the parameters.
2060        my ($fig, $genomeID, $fids) = @_;
2061        # Declare the return variable.
2062        my $retVal = {};
2063        # Get the attributes.
2064        my @aList = $fig->get_attributes("fig|$genomeID%");
2065        # Initialize the hash. This not only enables us to easily determine which FIDs to
2066        # keep, it insures that the caller sees a list reference for every known fid,
2067        # simplifying the logic.
2068        for my $fid (@{$fids}) {
2069            $retVal->{$fid} = [];
2070        }
2071        # Populate the hash.
2072        for my $aListEntry (@aList) {
2073            my $fid = $aListEntry->[0];
2074            if (exists $retVal->{$fid}) {
2075                push @{$retVal->{$fid}}, $aListEntry;
2076            }
2077        }
2078        # Return the result.
2079        return $retVal;
2080    }
2081    
2082  1;  1;

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3