[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.14, Fri Sep 16 02:38:49 2005 UTC revision 1.79, Sat Nov 18 20:38:45 2006 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 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  =item options
86    
# Line 93  Line 93 
93  sub new {  sub new {
94      # Get the parameters.      # Get the parameters.
95      my ($class, $sprout, $fig, $genomeFile, $subsysFile, $options) = @_;      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 118  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 128  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 152  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 161  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                    options => $options
187                   };                   };
# Line 170  Line 190 
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 197  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 215  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 267  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 307  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 339  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 367  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 375  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 409  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 423  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      # Find out if this is a limited run.      my $sprout = $self->{sprout};
     my $limited = $self->{options}->{limitedFeatures};  
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 $loadIsLocatedIn = $self->_TableLoader('IsLocatedIn', $featureCount);      my $loadIsLocatedIn = $self->_TableLoader('IsLocatedIn', $self->PrimaryOnly);
497      my $loadFeatureAlias = $self->_TableLoader('FeatureAlias', $featureCount * 6);      my $loadFeatureAlias = $self->_TableLoader('FeatureAlias');
498      my ($loadFeatureLink, $loadFeatureTranslation, $loadFeatureUpstream);      my $loadFeatureLink = $self->_TableLoader('FeatureLink');
499      if (! $limited) {      my $loadFeatureTranslation = $self->_TableLoader('FeatureTranslation');
500          $loadFeatureLink = $self->_TableLoader('FeatureLink', $featureCount * 10);      my $loadFeatureUpstream = $self->_TableLoader('FeatureUpstream');
501          $loadFeatureTranslation = $self->_TableLoader('FeatureTranslation', $featureCount);      my $loadHasFeature = $self->_TableLoader('HasFeature', $self->PrimaryOnly);
502          $loadFeatureUpstream = $self->_TableLoader('FeatureUpstream', $featureCount);      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                Trace("$count features found for genome $genomeID.") if T(3);
525                # Set up for our duplicate-feature check.
526                my $oldFeatureID = "";
527          # Loop through the features.          # Loop through the features.
528          for my $featureData (@{$features}) {              for my $featureTuple (@featureTuples) {
             $loadFeature->Add("featureIn");  
529              # Split the tuple.              # Split the tuple.
530              my ($featureID, $locations, undef, $type) = @{$featureData};                  my ($featureID, $locations, undef, $type) = @{$featureTuple};
531              # Create the feature record.                  # Check for duplicates.
532              $loadFeature->Put($featureID, 1, $type);                  if ($featureID eq $oldFeatureID) {
533                        Trace("Duplicate feature $featureID found.") if T(1);
534                    } else {
535                        $oldFeatureID = $featureID;
536                        # Count this feature.
537                        $loadFeature->Add("featureIn");
538                        # Begin building the keywords. We start with the genome ID, the
539                        # feature ID, the taxonomy, and the organism name.
540                        my @keywords = ($genomeID, $featureID, $fig->genus_species($genomeID),
541                                        $fig->taxonomy_of($genomeID));
542                        # Get the functional assignment and aliases. This
543                        # depends on the feature type.
544                        my $assignment;
545                        if ($type eq "peg") {
546                            $assignment = $fig->function_of($featureID);
547              # Create the aliases.              # Create the aliases.
548              for my $alias ($fig->feature_aliases($featureID)) {              for my $alias ($fig->feature_aliases($featureID)) {
549                  $loadFeatureAlias->Put($featureID, $alias);                  $loadFeatureAlias->Put($featureID, $alias);
550                                push @keywords, $alias;
551                            }
552                        } else {
553                            # For other types, the assignment is the first (and ONLY) alias.
554                            ($assignment) = $fig->feature_aliases($featureID);
555              }              }
556              # The next stuff is for a full load only.                      Trace("Assignment for $featureID is: $assignment") if T(4);
557              if (! $limited) {                      # Break the assignment into words and shove it onto the
558                        # keyword list.
559                        push @keywords, split(/\s+/, $assignment);
560                        # Link this feature to the parent genome.
561                        $loadHasFeature->Put($genomeID, $featureID, $type);
562                  # Get the links.                  # Get the links.
563                  my @links = $fig->fid_links($featureID);                  my @links = $fig->fid_links($featureID);
564                  for my $link (@links) {                  for my $link (@links) {
# Line 482  Line 577 
577                          $loadFeatureUpstream->Put($featureID, $upstream);                          $loadFeatureUpstream->Put($featureID, $upstream);
578                      }                      }
579                  }                  }
580              }                      # Now we need to find the subsystems this feature participates in.
581                        # We also add the subsystems to the keyword list. Before we do that,
582                        # we must convert underscores to spaces and tack on the classifications.
583                        my @subsystems = $fig->peg_to_subsystems($featureID);
584                        for my $subsystem (@subsystems) {
585                            # Only proceed if we like this subsystem.
586                            if (exists $subHash->{$subsystem}) {
587                                # Store the has-role link.
588                                $loadHasRoleInSubsystem->Put($featureID, $subsystem, $genomeID, $type);
589                                # Save the subsystem's keyword data.
590                                my $subKeywords = $subHash->{$subsystem};
591                                push @keywords, split /\s+/, $subKeywords;
592                                # Now we need to get this feature's role in the subsystem.
593                                my $subObject = $fig->get_subsystem($subsystem);
594                                my @roleColumns = $subObject->get_peg_roles($featureID);
595                                my @allRoles = $subObject->get_roles();
596                                for my $col (@roleColumns) {
597                                    my $role = $allRoles[$col];
598                                    push @keywords, split /\s+/, $role;
599                                    push @keywords, $subObject->get_role_abbr($col);
600                                }
601                            }
602                        }
603                        # There are three special attributes computed from property
604                        # data that we build next. If the special attribute is non-empty,
605                        # its name will be added to the keyword list. First, we get all
606                        # the attributes for this feature. They will come back as
607                        # 4-tuples: [peg, name, value, URL]. We use a 3-tuple instead:
608                        # [name, value, value with URL]. (We don't need the PEG, since
609                        # we already know it.)
610                        my @attributes = map { [$_->[1], $_->[2], Tracer::CombineURL($_->[2], $_->[3])] }
611                                             $fig->get_attributes($featureID);
612                        # Now we process each of the special attributes.
613                        if (SpecialAttribute($featureID, \@attributes,
614                                             1, [0,2], '^(essential|potential_essential)$',
615                                             $loadFeatureEssential)) {
616                            push @keywords, 'essential';
617                            $loadFeature->Add('essential');
618                        }
619                        if (SpecialAttribute($featureID, \@attributes,
620                                             0, [2], '^virulen',
621                                             $loadFeatureVirulent)) {
622                            push @keywords, 'virulent';
623                            $loadFeature->Add('virulent');
624                        }
625                        if (SpecialAttribute($featureID, \@attributes,
626                                             0, [0,2], '^iedb_',
627                                             $loadFeatureIEDB)) {
628                            push @keywords, 'iedb';
629                            $loadFeature->Add('iedb');
630                        }
631                        # Now we need to bust up hyphenated words in the keyword
632                        # list. We keep them separate and put them at the end so
633                        # the original word order is available.
634                        my $keywordString = "";
635                        my $bustedString = "";
636                        for my $keyword (@keywords) {
637                            if (length $keyword >= 4) {
638                                $keywordString .= " $keyword";
639                                if ($keyword =~ /-/) {
640                                    my @words = grep { length($_) >= 4 } split /-/, $keyword;
641                                    $bustedString .= join(" ", "", @words);
642                                }
643                            }
644                        }
645                        $keywordString .= $bustedString;
646                        # Get rid of annoying punctuation.
647                        $keywordString =~ s/[();]//g;
648                        # Clean the keyword list.
649                        my $cleanWords = $sprout->CleanKeywords($keywordString);
650                        Trace("Keyword string for $featureID: $cleanWords") if T(4);
651                        # Create the feature record.
652                        $loadFeature->Put($featureID, 1, $type, $assignment, $cleanWords);
653              # 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
654              # 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
655              # the maximum segment size. This simplifies the genes_in_region processing              # the maximum segment size. This simplifies the genes_in_region processing
# Line 511  Line 678 
678              }              }
679          }          }
680      }      }
     # 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);  
                 }  
             }  
681          }          }
682      }      }
683      # Finish the loads.      # Finish the loads.
# Line 598  Line 700 
700  The following relations are loaded by this method.  The following relations are loaded by this method.
701    
702      Subsystem      Subsystem
703        SubsystemClass
704      Role      Role
705        RoleEC
706      SSCell      SSCell
707      ContainsFeature      ContainsFeature
708      IsGenomeOf      IsGenomeOf
# Line 606  Line 710 
710      OccursInSubsystem      OccursInSubsystem
711      ParticipatesIn      ParticipatesIn
712      HasSSCell      HasSSCell
713        ConsistsOfRoles
714        RoleSubset
715        HasRoleSubset
716        ConsistsOfGenomes
717        GenomeSubset
718        HasGenomeSubset
719        Catalyzes
720        Diagram
721        RoleOccursIn
722    
723  =over 4  =over 4
724    
# Line 615  Line 728 
728    
729  =back  =back
730    
 B<TO DO>  
   
 Generate RoleName table?  
   
731  =cut  =cut
732  #: Return Type $%;  #: Return Type $%;
733  sub LoadSubsystemData {  sub LoadSubsystemData {
# Line 629  Line 738 
738      # Get the genome hash. We'll use it to filter the genomes in each      # Get the genome hash. We'll use it to filter the genomes in each
739      # spreadsheet.      # spreadsheet.
740      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my @genomes = sort keys %{$genomeHash};  
741      # Get the subsystem hash. This lists the subsystems we'll process.      # Get the subsystem hash. This lists the subsystems we'll process.
742      my $subsysHash = $self->{subsystems};      my $subsysHash = $self->{subsystems};
743      my @subsysIDs = sort keys %{$subsysHash};      my @subsysIDs = sort keys %{$subsysHash};
744      my $subsysCount = @subsysIDs;      # Get the map list.
745      my $genomeCount = (keys %{$genomeHash});      my @maps = $fig->all_maps;
     my $featureCount = $genomeCount * 4000;  
746      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
747      my $loadSubsystem = $self->_TableLoader('Subsystem', $subsysCount);      my $loadDiagram = $self->_TableLoader('Diagram', $self->PrimaryOnly);
748      my $loadRole = $self->_TableLoader('Role', $featureCount * 6);      my $loadRoleOccursIn = $self->_TableLoader('RoleOccursIn', $self->PrimaryOnly);
749      my $loadSSCell = $self->_TableLoader('SSCell', $featureCount * $genomeCount);      my $loadSubsystem = $self->_TableLoader('Subsystem');
750      my $loadContainsFeature = $self->_TableLoader('ContainsFeature', $featureCount * $subsysCount);      my $loadRole = $self->_TableLoader('Role', $self->PrimaryOnly);
751      my $loadIsGenomeOf = $self->_TableLoader('IsGenomeOf', $featureCount * $genomeCount);      my $loadRoleEC = $self->_TableLoader('RoleEC', $self->PrimaryOnly);
752      my $loadIsRoleOf = $self->_TableLoader('IsRoleOf', $featureCount * $genomeCount);      my $loadCatalyzes = $self->_TableLoader('Catalyzes', $self->PrimaryOnly);
753      my $loadOccursInSubsystem = $self->_TableLoader('OccursInSubsystem', $featureCount * 6);      my $loadSSCell = $self->_TableLoader('SSCell', $self->PrimaryOnly);
754      my $loadParticipatesIn = $self->_TableLoader('ParticipatesIn', $subsysCount * $genomeCount);      my $loadContainsFeature = $self->_TableLoader('ContainsFeature', $self->PrimaryOnly);
755      my $loadHasSSCell = $self->_TableLoader('HasSSCell', $featureCount * $genomeCount);      my $loadIsGenomeOf = $self->_TableLoader('IsGenomeOf', $self->PrimaryOnly);
756      Trace("Beginning subsystem data load.") if T(2);      my $loadIsRoleOf = $self->_TableLoader('IsRoleOf', $self->PrimaryOnly);
757        my $loadOccursInSubsystem = $self->_TableLoader('OccursInSubsystem', $self->PrimaryOnly);
758        my $loadParticipatesIn = $self->_TableLoader('ParticipatesIn', $self->PrimaryOnly);
759        my $loadHasSSCell = $self->_TableLoader('HasSSCell', $self->PrimaryOnly);
760        my $loadRoleSubset = $self->_TableLoader('RoleSubset', $self->PrimaryOnly);
761        my $loadGenomeSubset = $self->_TableLoader('GenomeSubset', $self->PrimaryOnly);
762        my $loadConsistsOfRoles = $self->_TableLoader('ConsistsOfRoles', $self->PrimaryOnly);
763        my $loadConsistsOfGenomes = $self->_TableLoader('ConsistsOfGenomes', $self->PrimaryOnly);
764        my $loadHasRoleSubset = $self->_TableLoader('HasRoleSubset', $self->PrimaryOnly);
765        my $loadHasGenomeSubset = $self->_TableLoader('HasGenomeSubset', $self->PrimaryOnly);
766        my $loadSubsystemClass = $self->_TableLoader('SubsystemClass', $self->PrimaryOnly);
767        if ($self->{options}->{loadOnly}) {
768            Trace("Loading from existing files.") if T(2);
769        } else {
770            Trace("Generating subsystem data.") if T(2);
771            # This hash will contain the role for each EC. When we're done, this
772            # information will be used to generate the Catalyzes table.
773            my %ecToRoles = ();
774      # Loop through the subsystems. Our first task will be to create the      # Loop through the subsystems. Our first task will be to create the
775      # roles. We do this by looping through the subsystems and creating a      # roles. We do this by looping through the subsystems and creating a
776      # 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
777      # duplicates. As we move along, we'll connect the roles and subsystems.          # duplicates. As we move along, we'll connect the roles and subsystems
778            # and memorize up the reactions.
779            my ($genomeID, $roleID);
780      my %roleData = ();      my %roleData = ();
781      for my $subsysID (@subsysIDs) {      for my $subsysID (@subsysIDs) {
782                # Get the subsystem object.
783                my $sub = $fig->get_subsystem($subsysID);
784                # Only proceed if the subsystem has a spreadsheet.
785                if (! $sub->{empty_ss}) {
786          Trace("Creating subsystem $subsysID.") if T(3);          Trace("Creating subsystem $subsysID.") if T(3);
787          $loadSubsystem->Add("subsystemIn");          $loadSubsystem->Add("subsystemIn");
788          # Create the subsystem record.          # Create the subsystem record.
789          $loadSubsystem->Put($subsysID);                  my $curator = $sub->get_curator();
790          # Get the subsystem's roles.                  my $notes = $sub->get_notes();
791          my @roles = $fig->subsystem_to_roles($subsysID);                  $loadSubsystem->Put($subsysID, $curator, $notes);
792          # Connect the roles to the subsystem. If a role is new, we create                  # Now for the classification string. This comes back as a list
793          # a role record for it.                  # reference and we convert it to a space-delimited string.
794          for my $roleID (@roles) {                  my $classList = $fig->subsystem_classification($subsysID);
795                    my $classString = join($FIG_Config::splitter, grep { $_ } @$classList);
796                    $loadSubsystemClass->Put($subsysID, $classString);
797                    # Connect it to its roles. Each role is a column in the subsystem spreadsheet.
798                    for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {
799                        # Connect to this role.
800              $loadOccursInSubsystem->Add("roleIn");              $loadOccursInSubsystem->Add("roleIn");
801              $loadOccursInSubsystem->Put($roleID, $subsysID);                      $loadOccursInSubsystem->Put($roleID, $subsysID, $col);
802                        # If it's a new role, add it to the role table.
803              if (! exists $roleData{$roleID}) {              if (! exists $roleData{$roleID}) {
804                  $loadRole->Put($roleID);                          # Get the role's abbreviation.
805                            my $abbr = $sub->get_role_abbr($col);
806                            # Add the role.
807                            $loadRole->Put($roleID, $abbr);
808                  $roleData{$roleID} = 1;                  $roleData{$roleID} = 1;
809                            # Check for an EC number.
810                            if ($roleID =~ /\(EC ([^.]+\.[^.]+\.[^.]+\.[^)]+)\)\s*$/) {
811                                my $ec = $1;
812                                $loadRoleEC->Put($roleID, $ec);
813                                $ecToRoles{$ec} = $roleID;
814                            }
815              }              }
816          }          }
817          # 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
818          # spreadsheet by matching roles to genomes.                  # genomes. Each genome is a row and each role is a column. We may need
819                    # to actually create the roles as we find them.
820          Trace("Creating subsystem $subsysID spreadsheet.") if T(3);          Trace("Creating subsystem $subsysID spreadsheet.") if T(3);
821          for my $genomeID (@genomes) {                  for (my $row = 0; defined($genomeID = $sub->get_genome($row)); $row++) {
822                        # Only proceed if this is one of our genomes.
823                        if (exists $genomeHash->{$genomeID}) {
824              # Count the PEGs and cells found for verification purposes.              # Count the PEGs and cells found for verification purposes.
825              my $pegCount = 0;              my $pegCount = 0;
826              my $cellCount = 0;              my $cellCount = 0;
827                            # Create a list for the PEGs we find. This list will be used
828                            # to generate cluster numbers.
829                            my @pegsFound = ();
830                            # Create a hash that maps spreadsheet IDs to PEGs. We will
831                            # use this to generate the ContainsFeature data after we have
832                            # the cluster numbers.
833                            my %cellPegs = ();
834                            # Get the genome's variant code for this subsystem.
835                            my $variantCode = $sub->get_variant_code($row);
836              # 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
837              # part of the spreadsheet cell ID.              # part of the spreadsheet cell ID.
838              for (my $i = 0; $i <= $#roles; $i++) {                          for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {
                 my $role = $roles[$i];  
839                  # Get the features in the spreadsheet cell for this genome and role.                  # Get the features in the spreadsheet cell for this genome and role.
840                  my @pegs = $fig->pegs_in_subsystem_cell($subsysID, $genomeID, $i);                              my @pegs = grep { !$fig->is_deleted_fid($_) } $sub->get_pegs_from_cell($row, $col);
841                  # Only proceed if features exist.                  # Only proceed if features exist.
842                  if (@pegs > 0) {                  if (@pegs > 0) {
843                      # Create the spreadsheet cell.                      # Create the spreadsheet cell.
844                      $cellCount++;                      $cellCount++;
845                      my $cellID = "$subsysID:$genomeID:$i";                                  my $cellID = "$subsysID:$genomeID:$col";
846                      $loadSSCell->Put($cellID);                      $loadSSCell->Put($cellID);
847                      $loadIsGenomeOf->Put($genomeID, $cellID);                      $loadIsGenomeOf->Put($genomeID, $cellID);
848                      $loadIsRoleOf->Put($role, $cellID);                                  $loadIsRoleOf->Put($roleID, $cellID);
849                      $loadHasSSCell->Put($subsysID, $cellID);                      $loadHasSSCell->Put($subsysID, $cellID);
850                      # Attach the features to it.                                  # Remember its features.
851                      for my $pegID (@pegs) {                                  push @pegsFound, @pegs;
852                          $loadContainsFeature->Put($cellID, $pegID);                                  $cellPegs{$cellID} = \@pegs;
853                          $pegCount++;                                  $pegCount += @pegs;
854                      }                      }
855                  }                  }
856              }                          # If we found some cells for this genome, we need to compute clusters and
857              # If we found some cells for this genome, denote it participates in the                          # denote it participates in the subsystem.
             # subsystem.  
858              if ($pegCount > 0) {              if ($pegCount > 0) {
859                  Trace("$pegCount PEGs in $cellCount cells for $genomeID.") if T(3);                  Trace("$pegCount PEGs in $cellCount cells for $genomeID.") if T(3);
860                  $loadParticipatesIn->Put($genomeID, $subsysID);                              $loadParticipatesIn->Put($genomeID, $subsysID, $variantCode);
861                                # Create a hash mapping PEG IDs to cluster numbers.
862                                # We default to -1 for all of them.
863                                my %clusterOf = map { $_ => -1 } @pegsFound;
864                                # Partition the PEGs found into clusters.
865                                my @clusters = $fig->compute_clusters([keys %clusterOf], $sub);
866                                for (my $i = 0; $i <= $#clusters; $i++) {
867                                    my $subList = $clusters[$i];
868                                    for my $peg (@{$subList}) {
869                                        $clusterOf{$peg} = $i;
870                                    }
871                                }
872                                # Create the ContainsFeature data.
873                                for my $cellID (keys %cellPegs) {
874                                    my $cellList = $cellPegs{$cellID};
875                                    for my $cellPeg (@$cellList) {
876                                        $loadContainsFeature->Put($cellID, $cellPeg, $clusterOf{$cellPeg});
877              }              }
878          }          }
879      }      }
     # Finish the load.  
     my $retVal = $self->_FinishAll();  
     return $retVal;  
880  }  }
881                    }
882  =head3 LoadDiagramData                  # Now we need to generate the subsets. The subset names must be concatenated to
883                    # the subsystem name to make them unique keys. There are two types of subsets:
884  C<< my $stats = $spl->LoadDiagramData(); >>                  # genome subsets and role subsets. We do the role subsets first.
885                    my @subsetNames = $sub->get_subset_names();
886  Load the diagram data from FIG into Sprout.                  for my $subsetID (@subsetNames) {
887                        # Create the subset record.
888  Diagrams are used to organize functional roles. The diagram shows the                      my $actualID = "$subsysID:$subsetID";
889  connections between chemicals that interact with a subsystem.                      $loadRoleSubset->Put($actualID);
890                        # Connect the subset to the subsystem.
891  The following relations are loaded by this method.                      $loadHasRoleSubset->Put($subsysID, $actualID);
892                        # Connect the subset to its roles.
893      Diagram                      my @roles = $sub->get_subsetC_roles($subsetID);
894      RoleOccursIn                      for my $roleID (@roles) {
895                            $loadConsistsOfRoles->Put($actualID, $roleID);
896  =over 4                      }
897                    }
898  =item RETURNS                  # Next the genome subsets.
899                    @subsetNames = $sub->get_subset_namesR();
900  Returns a statistics object for the loads.                  for my $subsetID (@subsetNames) {
901                        # Create the subset record.
902  =back                      my $actualID = "$subsysID:$subsetID";
903                        $loadGenomeSubset->Put($actualID);
904  =cut                      # Connect the subset to the subsystem.
905  #: Return Type $%;                      $loadHasGenomeSubset->Put($subsysID, $actualID);
906  sub LoadDiagramData {                      # Connect the subset to its genomes.
907      # Get this object instance.                      my @genomes = $sub->get_subsetR($subsetID);
908      my ($self) = @_;                      for my $genomeID (@genomes) {
909      # Get the FIG object.                          $loadConsistsOfGenomes->Put($actualID, $genomeID);
910      my $fig = $self->{fig};                      }
911      # Get the map list.                  }
912      my @maps = $fig->all_maps;              }
913      my $mapCount = @maps;          }
914      my $genomeCount = (keys %{$self->{genomes}});          # Now we loop through the diagrams. We need to create the diagram records
915      my $featureCount = $genomeCount * 4000;          # and link each diagram to its roles. Note that only roles which occur
916      # Create load objects for each of the tables we're loading.          # in subsystems (and therefore appear in the %ecToRoles hash) are
917      my $loadDiagram = $self->_TableLoader('Diagram', $mapCount);          # included.
918      my $loadRoleOccursIn = $self->_TableLoader('RoleOccursIn', $featureCount * 6);          for my $map (@maps) {
     Trace("Beginning diagram data load.") if T(2);  
     # Loop through the diagrams.  
     for my $map ($fig->all_maps) {  
919          Trace("Loading diagram $map.") if T(3);          Trace("Loading diagram $map.") if T(3);
920          # Get the diagram's descriptive name.          # Get the diagram's descriptive name.
921          my $name = $fig->map_name($map);          my $name = $fig->map_name($map);
# Line 759  Line 924 
924          # A hash is used to prevent duplicates.          # A hash is used to prevent duplicates.
925          my %roleHash = ();          my %roleHash = ();
926          for my $role ($fig->map_to_ecs($map)) {          for my $role ($fig->map_to_ecs($map)) {
927              if (! $roleHash{$role}) {                  if (exists $ecToRoles{$role} && ! $roleHash{$role}) {
928                  $loadRoleOccursIn->Put($role, $map);                      $loadRoleOccursIn->Put($ecToRoles{$role}, $map);
929                  $roleHash{$role} = 1;                  $roleHash{$role} = 1;
930              }              }
931          }          }
932      }      }
933            # Before we leave, we must create the Catalyzes table. We start with the reactions,
934            # then use the "ecToRoles" table to convert EC numbers to role IDs.
935            my @reactions = $fig->all_reactions();
936            for my $reactionID (@reactions) {
937                # Get this reaction's list of roles. The results will be EC numbers.
938                my @roles = $fig->catalyzed_by($reactionID);
939                # Loop through the roles, creating catalyzation records.
940                for my $thisRole (@roles) {
941                    if (exists $ecToRoles{$thisRole}) {
942                        $loadCatalyzes->Put($ecToRoles{$thisRole}, $reactionID);
943                    }
944                }
945            }
946        }
947      # Finish the load.      # Finish the load.
948      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
949      return $retVal;      return $retVal;
# Line 806  Line 985 
985      my $fig = $self->{fig};      my $fig = $self->{fig};
986      # Get the genome hash.      # Get the genome hash.
987      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
988      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
989      my $loadProperty = $self->_TableLoader('Property', $genomeCount * 1500);      my $loadProperty = $self->_TableLoader('Property');
990      my $loadHasProperty = $self->_TableLoader('HasProperty', $genomeCount * 1500);      my $loadHasProperty = $self->_TableLoader('HasProperty', $self->PrimaryOnly);
991      Trace("Beginning property data load.") if T(2);      if ($self->{options}->{loadOnly}) {
992            Trace("Loading from existing files.") if T(2);
993        } else {
994            Trace("Generating property data.") if T(2);
995      # Create a hash for storing property IDs.      # Create a hash for storing property IDs.
996      my %propertyKeys = ();      my %propertyKeys = ();
997      my $nextID = 1;      my $nextID = 1;
998      # Loop through the genomes.      # Loop through the genomes.
999      for my $genomeID (keys %{$genomeHash}) {          for my $genomeID (sort keys %{$genomeHash}) {
1000          $loadProperty->Add("genomeIn");          $loadProperty->Add("genomeIn");
1001                Trace("Generating properties for $genomeID.") if T(3);
1002          # 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
1003          # tuples returned by "all_features_detailed". We use "all_features_detailed"          # tuples returned by "all_features_detailed". We use "all_features_detailed"
1004          # rather than "all_features" because we want all features regardless of type.          # rather than "all_features" because we want all features regardless of type.
1005          my @features = map { $_->[0] } @{$fig->all_features_detailed($genomeID)};          my @features = map { $_->[0] } @{$fig->all_features_detailed($genomeID)};
1006                my $featureCount = 0;
1007                my $propertyCount = 0;
1008          # Loop through the features, creating HasProperty records.          # Loop through the features, creating HasProperty records.
1009          for my $fid (@features) {          for my $fid (@features) {
             $loadProperty->Add("featureIn");  
1010              # 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
1011              # to insure we do not get any genome attributes.              # to insure we do not get any genome attributes.
1012              my @attributeList = $fig->get_attributes($fid, '', '', '');                  my @attributeList = $fig->get_attributes($fid);
1013                    # Add essentiality and virulence attributes.
1014                    if ($fig->essential($fid)) {
1015                        push @attributeList, [$fid, 'essential', 1, ''];
1016                    }
1017                    if ($fig->virulent($fid)) {
1018                        push @attributeList, [$fid, 'virulent', 1, ''];
1019                    }
1020                    if (scalar @attributeList) {
1021                        $featureCount++;
1022                    }
1023              # Loop through the attributes.              # Loop through the attributes.
1024              for my $tuple (@attributeList) {              for my $tuple (@attributeList) {
1025                        $propertyCount++;
1026                  # 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,
1027                  # since it will always be the same as the value if "$fid".                  # since it will always be the same as the value if "$fid".
1028                  my (undef, $key, $value, $url) = @{$tuple};                  my (undef, $key, $value, $url) = @{$tuple};
# Line 850  Line 1044 
1044                  $loadHasProperty->Put($fid, $propertyID, $url);                  $loadHasProperty->Put($fid, $propertyID, $url);
1045              }              }
1046          }          }
1047                # Update the statistics.
1048                Trace("$propertyCount attributes processed for $featureCount features.") if T(3);
1049                $loadHasProperty->Add("featuresIn", $featureCount);
1050                $loadHasProperty->Add("propertiesIn", $propertyCount);
1051            }
1052      }      }
1053      # Finish the load.      # Finish the load.
1054      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
# Line 890  Line 1089 
1089      my $fig = $self->{fig};      my $fig = $self->{fig};
1090      # Get the genome hash.      # Get the genome hash.
1091      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
1092      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
1093      my $loadAnnotation = $self->_TableLoader('Annotation', $genomeCount * 4000);      my $loadAnnotation = $self->_TableLoader('Annotation');
1094      my $loadIsTargetOfAnnotation = $self->_TableLoader('IsTargetOfAnnotation', $genomeCount * 4000);      my $loadIsTargetOfAnnotation = $self->_TableLoader('IsTargetOfAnnotation', $self->PrimaryOnly);
1095      my $loadSproutUser = $self->_TableLoader('SproutUser', 100);      my $loadSproutUser = $self->_TableLoader('SproutUser', $self->PrimaryOnly);
1096      my $loadUserAccess = $self->_TableLoader('UserAccess', 1000);      my $loadUserAccess = $self->_TableLoader('UserAccess', $self->PrimaryOnly);
1097      my $loadMadeAnnotation = $self->_TableLoader('MadeAnnotation', $genomeCount * 4000);      my $loadMadeAnnotation = $self->_TableLoader('MadeAnnotation', $self->PrimaryOnly);
1098      Trace("Beginning annotation data load.") if T(2);      if ($self->{options}->{loadOnly}) {
1099            Trace("Loading from existing files.") if T(2);
1100        } else {
1101            Trace("Generating annotation data.") if T(2);
1102      # 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
1103      # user records.      # user records.
1104      my %users = ( FIG => 1, master => 1 );      my %users = ( FIG => 1, master => 1 );
# Line 911  Line 1112 
1112      # Loop through the genomes.      # Loop through the genomes.
1113      for my $genomeID (sort keys %{$genomeHash}) {      for my $genomeID (sort keys %{$genomeHash}) {
1114          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);  
1115              # 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
1116              # from showing up for a single PEG's annotations.              # from showing up for a single PEG's annotations.
1117              my %seenTimestamps = ();              my %seenTimestamps = ();
1118              # Check for a functional assignment.              # Get the genome's annotations.
1119              my $func = $fig->function_of($peg);              my @annotations = $fig->read_all_annotations($genomeID);
1120              if ($func) {              Trace("Processing annotations.") if T(2);
1121                  # If this is NOT a hypothetical assignment, we create an              for my $tuple (@annotations) {
1122                  # assignment annotation for it.                  # Get the annotation tuple.
1123                  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};  
1124                      # Here we fix up the annotation text. "\r" is removed,                      # Here we fix up the annotation text. "\r" is removed,
1125                      # and "\t" and "\n" are escaped. Note we use the "s"                  # and "\t" and "\n" are escaped. Note we use the "gs"
1126                      # modifier so that new-lines inside the text do not                      # modifier so that new-lines inside the text do not
1127                      # stop the substitution search.                      # stop the substitution search.
1128                      $text =~ s/\r//gs;                      $text =~ s/\r//gs;
# Line 946  Line 1132 
1132                      $text =~ s/Set master function/Set FIG function/s;                      $text =~ s/Set master function/Set FIG function/s;
1133                      # Insure the time stamp is valid.                      # Insure the time stamp is valid.
1134                      if ($timestamp =~ /^\d+$/) {                      if ($timestamp =~ /^\d+$/) {
1135                          # 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
1136                          while ($seenTimestamps{$timestamp}) {                      # the key is unique.
1137                              $timestamp++;                      my $keyStamp = $timestamp;
1138                        while ($seenTimestamps{"$peg:$keyStamp"}) {
1139                            $keyStamp++;
1140                          }                          }
1141                          $seenTimestamps{$timestamp} = 1;                      my $annotationID = "$peg:$keyStamp";
1142                          my $annotationID = "$peg:$timestamp";                      $seenTimestamps{$annotationID} = 1;
1143                          # Insure the user exists.                          # Insure the user exists.
1144                          if (! $users{$user}) {                          if (! $users{$user}) {
1145                              $loadSproutUser->Put($user, "SEED user");                              $loadSproutUser->Put($user, "SEED user");
# Line 959  Line 1147 
1147                              $users{$user} = 1;                              $users{$user} = 1;
1148                          }                          }
1149                          # Generate the annotation.                          # Generate the annotation.
1150                          $loadAnnotation->Put($annotationID, $timestamp, "$user\\n$text");                      $loadAnnotation->Put($annotationID, $timestamp, $text);
1151                          $loadIsTargetOfAnnotation->Put($peg, $annotationID);                          $loadIsTargetOfAnnotation->Put($peg, $annotationID);
1152                          $loadMadeAnnotation->Put($user, $annotationID);                          $loadMadeAnnotation->Put($user, $annotationID);
1153                      } else {                      } else {
# Line 969  Line 1157 
1157                  }                  }
1158              }              }
1159          }          }
     }  
1160      # Finish the load.      # Finish the load.
1161      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
1162      return $retVal;      return $retVal;
# Line 1010  Line 1197 
1197      my $fig = $self->{fig};      my $fig = $self->{fig};
1198      # Get the genome hash.      # Get the genome hash.
1199      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
1200      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
1201      my $loadComesFrom = $self->_TableLoader('ComesFrom', $genomeCount * 4);      my $loadComesFrom = $self->_TableLoader('ComesFrom', $self->PrimaryOnly);
1202      my $loadSource = $self->_TableLoader('Source', $genomeCount * 4);      my $loadSource = $self->_TableLoader('Source');
1203      my $loadSourceURL = $self->_TableLoader('SourceURL', $genomeCount * 8);      my $loadSourceURL = $self->_TableLoader('SourceURL');
1204      Trace("Beginning source data load.") if T(2);      if ($self->{options}->{loadOnly}) {
1205            Trace("Loading from existing files.") if T(2);
1206        } else {
1207            Trace("Generating annotation data.") if T(2);
1208      # Create hashes to collect the Source information.      # Create hashes to collect the Source information.
1209      my %sourceURL = ();      my %sourceURL = ();
1210      my %sourceDesc = ();      my %sourceDesc = ();
# Line 1029  Line 1218 
1218              chomp $line;              chomp $line;
1219              my($sourceID, $desc, $url) = split(/\t/,$line);              my($sourceID, $desc, $url) = split(/\t/,$line);
1220              $loadComesFrom->Put($genomeID, $sourceID);              $loadComesFrom->Put($genomeID, $sourceID);
1221              if ($url && ! exists $sourceURL{$genomeID}) {                  if ($url && ! exists $sourceURL{$sourceID}) {
1222                  $loadSourceURL->Put($sourceID, $url);                  $loadSourceURL->Put($sourceID, $url);
1223                  $sourceURL{$sourceID} = 1;                  $sourceURL{$sourceID} = 1;
1224              }              }
1225              if ($desc && ! exists $sourceDesc{$sourceID}) {                  if ($desc) {
1226                  $loadSource->Put($sourceID, $desc);                      $sourceDesc{$sourceID} = $desc;
1227                  $sourceDesc{$sourceID} = 1;                  } elsif (! exists $sourceDesc{$sourceID}) {
1228                        $sourceDesc{$sourceID} = $sourceID;
1229              }              }
1230          }          }
1231          close TMP;          close TMP;
1232      }      }
1233            # Write the source descriptions.
1234            for my $sourceID (keys %sourceDesc) {
1235                $loadSource->Put($sourceID, $sourceDesc{$sourceID});
1236            }
1237        }
1238      # Finish the load.      # Finish the load.
1239      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
1240      return $retVal;      return $retVal;
# Line 1079  Line 1274 
1274      my $fig = $self->{fig};      my $fig = $self->{fig};
1275      # Get the genome hash.      # Get the genome hash.
1276      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
1277      # 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
1278      # it the key.      # it the key.
1279      my %speciesHash = map { $fig->genus_species($_) => $_ } (keys %{$genomeHash});      my %speciesHash = map { $fig->genus_species($_) => $_ } (keys %{$genomeHash});
1280      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
1281      my $loadExternalAliasFunc = $self->_TableLoader('ExternalAliasFunc', $genomeCount * 4000);      my $loadExternalAliasFunc = $self->_TableLoader('ExternalAliasFunc');
1282      my $loadExternalAliasOrg = $self->_TableLoader('ExternalAliasOrg', $genomeCount * 4000);      my $loadExternalAliasOrg = $self->_TableLoader('ExternalAliasOrg');
1283      Trace("Beginning external data load.") if T(2);      if ($self->{options}->{loadOnly}) {
1284            Trace("Loading from existing files.") if T(2);
1285        } else {
1286            Trace("Generating external data.") if T(2);
1287      # 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.
1288      Open(\*ORGS, "<$FIG_Config::global/ext_org.table");          Open(\*ORGS, "sort +0 -1 -u -t\"\t\" $FIG_Config::global/ext_org.table |");
1289      my $orgLine;      my $orgLine;
1290      while (defined($orgLine = <ORGS>)) {      while (defined($orgLine = <ORGS>)) {
1291          # Clean the input line.          # Clean the input line.
# Line 1100  Line 1297 
1297      close ORGS;      close ORGS;
1298      # Now the function file.      # Now the function file.
1299      my $funcLine;      my $funcLine;
1300      Open(\*FUNCS, "<$FIG_Config::global/ext_func.table");          Open(\*FUNCS, "sort +0 -1 -u -t\"\t\" $FIG_Config::global/ext_func.table |");
1301      while (defined($funcLine = <FUNCS>)) {      while (defined($funcLine = <FUNCS>)) {
1302          # Clean the line ending.          # Clean the line ending.
1303          chomp $funcLine;          chomp $funcLine;
# Line 1116  Line 1313 
1313              $loadExternalAliasFunc->Put(@funcFields[0,1]);              $loadExternalAliasFunc->Put(@funcFields[0,1]);
1314          }          }
1315      }      }
1316        }
1317        # Finish the load.
1318        my $retVal = $self->_FinishAll();
1319        return $retVal;
1320    }
1321    
1322    
1323    =head3 LoadReactionData
1324    
1325    C<< my $stats = $spl->LoadReactionData(); >>
1326    
1327    Load the reaction data from FIG into Sprout.
1328    
1329    Reaction data connects reactions to the compounds that participate in them.
1330    
1331    The following relations are loaded by this method.
1332    
1333        Reaction
1334        ReactionURL
1335        Compound
1336        CompoundName
1337        CompoundCAS
1338        IsAComponentOf
1339    
1340    This method proceeds reaction by reaction rather than genome by genome.
1341    
1342    =over 4
1343    
1344    =item RETURNS
1345    
1346    Returns a statistics object for the loads.
1347    
1348    =back
1349    
1350    =cut
1351    #: Return Type $%;
1352    sub LoadReactionData {
1353        # Get this object instance.
1354        my ($self) = @_;
1355        # Get the FIG object.
1356        my $fig = $self->{fig};
1357        # Create load objects for each of the tables we're loading.
1358        my $loadReaction = $self->_TableLoader('Reaction');
1359        my $loadReactionURL = $self->_TableLoader('ReactionURL', $self->PrimaryOnly);
1360        my $loadCompound = $self->_TableLoader('Compound', $self->PrimaryOnly);
1361        my $loadCompoundName = $self->_TableLoader('CompoundName', $self->PrimaryOnly);
1362        my $loadCompoundCAS = $self->_TableLoader('CompoundCAS', $self->PrimaryOnly);
1363        my $loadIsAComponentOf = $self->_TableLoader('IsAComponentOf', $self->PrimaryOnly);
1364        if ($self->{options}->{loadOnly}) {
1365            Trace("Loading from existing files.") if T(2);
1366        } else {
1367            Trace("Generating annotation data.") if T(2);
1368            # First we create the compounds.
1369            my @compounds = $fig->all_compounds();
1370            for my $cid (@compounds) {
1371                # Check for names.
1372                my @names = $fig->names_of_compound($cid);
1373                # Each name will be given a priority number, starting with 1.
1374                my $prio = 1;
1375                for my $name (@names) {
1376                    $loadCompoundName->Put($cid, $name, $prio++);
1377                }
1378                # Create the main compound record. Note that the first name
1379                # becomes the label.
1380                my $label = (@names > 0 ? $names[0] : $cid);
1381                $loadCompound->Put($cid, $label);
1382                # Check for a CAS ID.
1383                my $cas = $fig->cas($cid);
1384                if ($cas) {
1385                    $loadCompoundCAS->Put($cid, $cas);
1386                }
1387            }
1388            # All the compounds are set up, so we need to loop through the reactions next. First,
1389            # we initialize the discriminator index. This is a single integer used to insure
1390            # duplicate elements in a reaction are not accidentally collapsed.
1391            my $discrim = 0;
1392            my @reactions = $fig->all_reactions();
1393            for my $reactionID (@reactions) {
1394                # Create the reaction record.
1395                $loadReaction->Put($reactionID, $fig->reversible($reactionID));
1396                # Compute the reaction's URL.
1397                my $url = HTML::reaction_link($reactionID);
1398                # Put it in the ReactionURL table.
1399                $loadReactionURL->Put($reactionID, $url);
1400                # Now we need all of the reaction's compounds. We get these in two phases,
1401                # substrates first and then products.
1402                for my $product (0, 1) {
1403                    # Get the compounds of the current type for the current reaction. FIG will
1404                    # give us 3-tuples: [ID, stoichiometry, main-flag]. At this time we do not
1405                    # have location data in SEED, so it defaults to the empty string.
1406                    my @compounds = $fig->reaction2comp($reactionID, $product);
1407                    for my $compData (@compounds) {
1408                        # Extract the compound data from the current tuple.
1409                        my ($cid, $stoich, $main) = @{$compData};
1410                        # Link the compound to the reaction.
1411                        $loadIsAComponentOf->Put($cid, $reactionID, $discrim++, "", $main,
1412                                                 $product, $stoich);
1413                    }
1414                }
1415            }
1416        }
1417      # Finish the load.      # Finish the load.
1418      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
1419      return $retVal;      return $retVal;
# Line 1131  Line 1429 
1429    
1430      GenomeGroups      GenomeGroups
1431    
1432  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,
1433    butThere is no direct support for genome groups in FIG, so we access the SEED
1434  files directly.  files directly.
1435    
1436  =over 4  =over 4
# Line 1151  Line 1450 
1450      my $fig = $self->{fig};      my $fig = $self->{fig};
1451      # Get the genome hash.      # Get the genome hash.
1452      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
1453      # Create a load object for the table we're loading.      # Create a load object for the table we're loading.
1454      my $loadGenomeGroups = $self->_TableLoader('GenomeGroups', $genomeCount * 4);      my $loadGenomeGroups = $self->_TableLoader('GenomeGroups');
1455      Trace("Beginning group data load.") if T(2);      if ($self->{options}->{loadOnly}) {
1456            Trace("Loading from existing files.") if T(2);
1457        } else {
1458            Trace("Generating group data.") if T(2);
1459            # Currently there are no groups.
1460        }
1461        # Finish the load.
1462        my $retVal = $self->_FinishAll();
1463        return $retVal;
1464    }
1465    
1466    =head3 LoadSynonymData
1467    
1468    C<< my $stats = $spl->LoadSynonymData(); >>
1469    
1470    Load the synonym groups into Sprout.
1471    
1472    The following relations are loaded by this method.
1473    
1474        SynonymGroup
1475        IsSynonymGroupFor
1476    
1477    The source information for these relations is taken from the C<maps_to_id> method
1478    of the B<FIG> object. Unfortunately, to make this work, we need to use direct
1479    SQL against the FIG database.
1480    
1481    =over 4
1482    
1483    =item RETURNS
1484    
1485    Returns a statistics object for the loads.
1486    
1487    =back
1488    
1489    =cut
1490    #: Return Type $%;
1491    sub LoadSynonymData {
1492        # Get this object instance.
1493        my ($self) = @_;
1494        # Get the FIG object.
1495        my $fig = $self->{fig};
1496        # Get the genome hash.
1497        my $genomeHash = $self->{genomes};
1498        # Create a load object for the table we're loading.
1499        my $loadSynonymGroup = $self->_TableLoader('SynonymGroup');
1500        my $loadIsSynonymGroupFor = $self->_TableLoader('IsSynonymGroupFor');
1501        if ($self->{options}->{loadOnly}) {
1502            Trace("Loading from existing files.") if T(2);
1503        } else {
1504            Trace("Generating synonym group data.") if T(2);
1505            # Get the database handle.
1506            my $dbh = $fig->db_handle();
1507            # Ask for the synonyms.
1508            my $sth = $dbh->prepare_command("SELECT maps_to, syn_id FROM peg_synonyms ORDER BY maps_to");
1509            my $result = $sth->execute();
1510            if (! defined($result)) {
1511                Confess("Database error in Synonym load: " . $sth->errstr());
1512            } else {
1513                # Remember the current synonym.
1514                my $current_syn = "";
1515                # Count the features.
1516                my $featureCount = 0;
1517                # Loop through the synonym/peg pairs.
1518                while (my @row = $sth->fetchrow()) {
1519                    # Get the synonym ID and feature ID.
1520                    my ($syn_id, $peg) = @row;
1521                    # Insure it's for one of our genomes.
1522                    my $genomeID = FIG::genome_of($peg);
1523                    if (exists $genomeHash->{$genomeID}) {
1524                        # Verify the synonym.
1525                        if ($syn_id ne $current_syn) {
1526                            # It's new, so put it in the group table.
1527                            $loadSynonymGroup->Put($syn_id);
1528                            $current_syn = $syn_id;
1529                        }
1530                        # Connect the synonym to the peg.
1531                        $loadIsSynonymGroupFor->Put($syn_id, $peg);
1532                        # Count this feature.
1533                        $featureCount++;
1534                        if ($featureCount % 1000 == 0) {
1535                            Trace("$featureCount features processed.") if T(3);
1536                        }
1537                    }
1538                }
1539            }
1540        }
1541        # Finish the load.
1542        my $retVal = $self->_FinishAll();
1543        return $retVal;
1544    }
1545    
1546    =head3 LoadFamilyData
1547    
1548    C<< my $stats = $spl->LoadFamilyData(); >>
1549    
1550    Load the protein families into Sprout.
1551    
1552    The following relations are loaded by this method.
1553    
1554        Family
1555        IsFamilyForFeature
1556    
1557    The source information for these relations is taken from the C<families_for_protein>,
1558    C<family_function>, and C<sz_family> methods of the B<FIG> object.
1559    
1560    =over 4
1561    
1562    =item RETURNS
1563    
1564    Returns a statistics object for the loads.
1565    
1566    =back
1567    
1568    =cut
1569    #: Return Type $%;
1570    sub LoadFamilyData {
1571        # Get this object instance.
1572        my ($self) = @_;
1573        # Get the FIG object.
1574        my $fig = $self->{fig};
1575        # Get the genome hash.
1576        my $genomeHash = $self->{genomes};
1577        # Create load objects for the tables we're loading.
1578        my $loadFamily = $self->_TableLoader('Family');
1579        my $loadIsFamilyForFeature = $self->_TableLoader('IsFamilyForFeature');
1580        if ($self->{options}->{loadOnly}) {
1581            Trace("Loading from existing files.") if T(2);
1582        } else {
1583            Trace("Generating family data.") if T(2);
1584            # Create a hash for the family IDs.
1585            my %familyHash = ();
1586      # Loop through the genomes.      # Loop through the genomes.
1587      my $line;          for my $genomeID (sort keys %{$genomeHash}) {
1588      for my $genomeID (keys %{$genomeHash}) {              Trace("Processing features for $genomeID.") if T(2);
1589          Trace("Processing $genomeID.") if T(3);              # Loop through this genome's PEGs.
1590          # Open the NMPDR group file for this genome.              for my $fid ($fig->all_features($genomeID, "peg")) {
1591          if (open(TMP, "<$FIG_Config::organisms/$genomeID/NMPDR") &&                  $loadIsFamilyForFeature->Add("features", 1);
1592              defined($line = <TMP>)) {                  # Get this feature's families.
1593              # Clean the line ending.                  my @families = $fig->families_for_protein($fid);
1594              chomp $line;                  # Loop through the families, connecting them to the feature.
1595              # Add the group to the table. Note that there can only be one group                  for my $family (@families) {
1596              # per genome.                      $loadIsFamilyForFeature->Put($family, $fid);
1597              $loadGenomeGroups->Put($genomeID, $line);                      # If this is a new family, create a record for it.
1598                        if (! exists $familyHash{$family}) {
1599                            $familyHash{$family} = 1;
1600                            $loadFamily->Add("families", 1);
1601                            my $size = $fig->sz_family($family);
1602                            my $func = $fig->family_function($family);
1603                            $loadFamily->Put($family, $size, $func);
1604                        }
1605                    }
1606                }
1607          }          }
         close TMP;  
1608      }      }
1609      # Finish the load.      # Finish the load.
1610      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
1611      return $retVal;      return $retVal;
1612  }  }
1613    
1614    =head3 LoadDrugData
1615    
1616    C<< my $stats = $spl->LoadDrugData(); >>
1617    
1618    Load the drug target data into Sprout.
1619    
1620    The following relations are loaded by this method.
1621    
1622        DrugProject
1623        ContainsTopic
1624        DrugTopic
1625        ContainsAnalysisOf
1626        PDB
1627        IncludesBound
1628        IsBoundIn
1629        BindsWith
1630        Ligand
1631        DescribesProteinForFeature
1632        FeatureConservation
1633    
1634    The source information for these relations is taken from flat files in the
1635    C<$FIG_Config::drug_directory>. The file C<master_tables.list> contains
1636    a list of drug project names paired with file names. The named file (in the
1637    same directory) contains all the data for the project.
1638    
1639    =over 4
1640    
1641    =item RETURNS
1642    
1643    Returns a statistics object for the loads.
1644    
1645    =back
1646    
1647    =cut
1648    #: Return Type $%;
1649    sub LoadDrugData {
1650        # Get this object instance.
1651        my ($self) = @_;
1652        # Get the FIG object.
1653        my $fig = $self->{fig};
1654        # Get the genome hash.
1655        my $genomeHash = $self->{genomes};
1656        # Create load objects for the tables we're loading.
1657        my $loadDrugProject = $self->_TableLoader('DrugProject');
1658        my $loadContainsTopic = $self->_TableLoader('ContainsTopic');
1659        my $loadDrugTopic = $self->_TableLoader('DrugTopic');
1660        my $loadContainsAnalysisOf = $self->_TableLoader('ContainsAnalysisOf');
1661        my $loadPDB = $self->_TableLoader('PDB');
1662        my $loadIncludesBound = $self->_TableLoader('IncludesBound');
1663        my $loadIsBoundIn = $self->_TableLoader('IsBoundIn');
1664        my $loadBindsWith = $self->_TableLoader('BindsWith');
1665        my $loadLigand = $self->_TableLoader('Ligand');
1666        my $loadDescribesProteinForFeature = $self->_TableLoader('DescribesProteinForFeature');
1667        my $loadFeatureConservation = $self->_TableLoader('FeatureConservation');
1668        if ($self->{options}->{loadOnly}) {
1669            Trace("Loading from existing files.") if T(2);
1670        } else {
1671            Trace("Generating drug target data.") if T(2);
1672            # Load the project list. The file comes in as a list of chomped lines,
1673            # and we split them on the TAB character to make the project name the
1674            # key and the file name the value of the resulting hash.
1675            my %projects = map { split /\t/, $_ } Tracer::GetFile("$FIG_Config::drug_directory/master_tables.list");
1676            # Create hashes for the derived objects: PDBs, Features, and Ligands. These objects
1677            # may occur multiple times in a single project file or even in multiple project
1678            # files.
1679            my %ligands = ();
1680            my %pdbs = ();
1681            my %features = ();
1682            my %bindings = ();
1683            # Set up a counter for drug topics. This will be used as the key.
1684            my $topicCounter = 0;
1685            # Loop through the projects. We sort the keys not because we need them sorted, but
1686            # because it makes it easier to infer our progress from trace messages.
1687            for my $project (sort keys %projects) {
1688                Trace("Processing project $project.") if T(3);
1689                # Only proceed if the download file exists.
1690                my $projectFile = "$FIG_Config::drug_directory/$projects{$project}";
1691                if (! -f $projectFile) {
1692                    Trace("Project file $projectFile not found.") if T(0);
1693                } else {
1694                    # Create the project record.
1695                    $loadDrugProject->Put($project);
1696                    # Create a hash for the topics. Each project has one or more topics. The
1697                    # topic is identified by a URL, a category, and an identifier.
1698                    my %topics = ();
1699                    # Now we can open the project file.
1700                    Trace("Reading project file $projectFile.") if T(3);
1701                    Open(\*PROJECT, "<$projectFile");
1702                    # Get the first record, which is a list of column headers. We don't use this
1703                    # for anything, but it may be useful for debugging.
1704                    my $headerLine = <PROJECT>;
1705                    # Loop through the rest of the records.
1706                    while (! eof PROJECT) {
1707                        # Get the current line of data. Note that not all lines will have all
1708                        # the fields. In particular, the CLIBE data is fairly rare.
1709                        my ($authorOrganism, $category, $tag, $refURL, $peg, $conservation,
1710                            $pdbBound, $pdbBoundEval, $pdbFree, $pdbFreeEval, $pdbFreeTitle,
1711                            $protDistInfo, $passAspInfo, $passAspFile, $passWeightInfo,
1712                            $passWeightFile, $clibeInfo, $clibeURL, $clibeTotalEnergy,
1713                            $clibeVanderwaals, $clibeHBonds, $clibeEI, $clibeSolvationE)
1714                           = Tracer::GetLine(\*PROJECT);
1715                        # The tag contains an identifier for the current line of data followed
1716                        # by a text statement that generally matches a property name in the
1717                        # main database. We split it up, since the identifier goes with
1718                        # the PDB data and the text statement is part of the topic.
1719                        my ($lineID, $topicTag) = split /\s*,\s*/, $tag;
1720                        $loadDrugProject->Add("data line");
1721                        # Check for a new topic.
1722                        my $topicData = "$category\t$topicTag\t$refURL";
1723                        if (! exists $topics{$topicData}) {
1724                            # Here we have a new topic. Compute its ID.
1725                            $topicCounter++;
1726                            $topics{$topicData} = $topicCounter;
1727                            # Create its database record.
1728                            $loadDrugTopic->Put($topicCounter, $refURL, $category, $authorOrganism,
1729                                                $topicTag);
1730                            # Connect it to the project.
1731                            $loadContainsTopic->Put($project, $topicCounter);
1732                            $loadDrugTopic->Add("topic");
1733                        }
1734                        # Now we know the topic ID exists in the hash and the topic will
1735                        # appear in the database, so we get this topic's ID.
1736                        my $topicID = $topics{$topicData};
1737                        # If the feature in this line is new, we need to save its conservation
1738                        # number.
1739                        if (! exists $features{$peg}) {
1740                            $loadFeatureConservation->Put($peg, $conservation);
1741                            $features{$peg} = 1;
1742                        }
1743                        # Now we have two PDBs to deal with-- a bound PDB and a free PDB.
1744                        # The free PDB will have data about docking points; the bound PDB
1745                        # will have data about docking. We store both types as PDBs, and
1746                        # the special data comes from relationships. First we process the
1747                        # bound PDB.
1748                        if ($pdbBound) {
1749                            $loadPDB->Add("bound line");
1750                            # Insure this PDB is in the database.
1751                            $self->CreatePDB($pdbBound, lc "$pdbFreeTitle (bound)", "bound", \%pdbs, $loadPDB);
1752                            # Connect it to this topic.
1753                            $loadIncludesBound->Put($topicID, $pdbBound);
1754                            # Check for CLIBE data.
1755                            if ($clibeInfo) {
1756                                $loadLigand->Add("clibes");
1757                                # We have CLIBE data, so we create a ligand and relate it to the PDB.
1758                                if (! exists $ligands{$clibeInfo}) {
1759                                    # This is a new ligand, so create its record.
1760                                    $loadLigand->Put($clibeInfo);
1761                                    $loadLigand->Add("ligand");
1762                                    # Make sure we know this ligand already exists.
1763                                    $ligands{$clibeInfo} = 1;
1764                                }
1765                                # Now connect the PDB to the ligand using the CLIBE data.
1766                                $loadBindsWith->Put($pdbBound, $clibeInfo, $clibeURL, $clibeHBonds, $clibeEI,
1767                                                    $clibeSolvationE, $clibeVanderwaals);
1768                            }
1769                            # Connect this PDB to the feature.
1770                            $loadDescribesProteinForFeature->Put($pdbBound, $peg, $protDistInfo, $pdbBoundEval);
1771                        }
1772                        # Next is the free PDB.
1773                        if ($pdbFree) {
1774                            $loadPDB->Add("free line");
1775                            # Insure this PDB is in the database.
1776                            $self->CreatePDB($pdbFree, lc $pdbFreeTitle, "free", \%pdbs, $loadPDB);
1777                            # Connect it to this topic.
1778                            $loadContainsAnalysisOf->Put($topicID, $pdbFree, $passAspInfo,
1779                                                         $passWeightFile, $passWeightInfo, $passAspFile);
1780                            # Connect this PDB to the feature.
1781                            $loadDescribesProteinForFeature->Put($pdbFree, $peg, $protDistInfo, $pdbFreeEval);
1782                        }
1783                        # If we have both PDBs, we may need to link them.
1784                        if ($pdbFree && $pdbBound) {
1785                            $loadIsBoundIn->Add("connection");
1786                            # Insure we only link them once.
1787                            my $bindingKey =  "$pdbFree\t$pdbBound";
1788                            if (! exists $bindings{$bindingKey}) {
1789                                $loadIsBoundIn->Add("newConnection");
1790                                $loadIsBoundIn->Put($pdbFree, $pdbBound);
1791                                $bindings{$bindingKey} = 1;
1792                            }
1793                        }
1794                    }
1795                    # Close off this project.
1796                    close PROJECT;
1797                }
1798            }
1799        }
1800        # Finish the load.
1801        my $retVal = $self->_FinishAll();
1802        return $retVal;
1803    }
1804    
1805    
1806  =head2 Internal Utility Methods  =head2 Internal Utility Methods
1807    
1808    =head3 SpecialAttribute
1809    
1810    C<< my $count = SproutLoad::SpecialAttribute($id, \@attributes, $idxMatch, \@idxValues, $pattern, $loader); >>
1811    
1812    Look for special attributes of a given type. A special attribute is found by comparing one of
1813    the columns of the incoming attribute list to a search pattern. If a match is found, then
1814    a set of columns is put into an output table connected to the specified ID.
1815    
1816    For example, when processing features, the attribute list we look at has three columns: attribute
1817    name, attribute value, and attribute value HTML. The IEDB attribute exists if the attribute name
1818    begins with C<iedb_>. The call signature is therefore
1819    
1820        my $found = SpecialAttribute($fid, \@attributeList, 0, [0,2], '^iedb_', $loadFeatureIEDB);
1821    
1822    The pattern is matched against column 0, and if we have a match, then column 2's value is put
1823    to the output along with the specified feature ID.
1824    
1825    =over 4
1826    
1827    =item id
1828    
1829    ID of the object whose special attributes are being loaded. This forms the first column of the
1830    output.
1831    
1832    =item attributes
1833    
1834    Reference to a list of tuples.
1835    
1836    =item idxMatch
1837    
1838    Index in each tuple of the column to be matched against the pattern. If the match is
1839    successful, an output record will be generated.
1840    
1841    =item idxValues
1842    
1843    Reference to a list containing the indexes in each tuple of the columns to be put as
1844    the second column of the output.
1845    
1846    =item pattern
1847    
1848    Pattern to be matched against the specified column. The match will be case-insensitive.
1849    
1850    =item loader
1851    
1852    An object to which each output record will be put. Usually this is an B<ERDBLoad> object,
1853    but technically it could be anything with a C<Put> method.
1854    
1855    =item RETURN
1856    
1857    Returns a count of the matches found.
1858    
1859    =item
1860    
1861    =back
1862    
1863    =cut
1864    
1865    sub SpecialAttribute {
1866        # Get the parameters.
1867        my ($id, $attributes, $idxMatch, $idxValues, $pattern, $loader) = @_;
1868        # Declare the return variable.
1869        my $retVal = 0;
1870        # Loop through the attribute rows.
1871        for my $row (@{$attributes}) {
1872            # Check for a match.
1873            if ($row->[$idxMatch] =~ m/$pattern/i) {
1874                # We have a match, so output a row. This is a bit tricky, since we may
1875                # be putting out multiple columns of data from the input.
1876                my $value = join(" ", map { $row->[$_] } @{$idxValues});
1877                $loader->Put($id, $value);
1878                $retVal++;
1879            }
1880        }
1881        Trace("$retVal special attributes found for $id and loader " . $loader->RelName() . ".") if T(4) && $retVal;
1882        # Return the number of matches.
1883        return $retVal;
1884    }
1885    
1886    =head3 CreatePDB
1887    
1888    C<< $loader->CreatePDB($pdbID, $title, $type, \%pdbHash); >>
1889    
1890    Insure that a PDB record exists for the identified PDB. If one does not exist, it will be
1891    created.
1892    
1893    =over 4
1894    
1895    =item pdbID
1896    
1897    ID string (usually an unqualified file name) for the desired PDB.
1898    
1899    =item title
1900    
1901    Title to use if the PDB must be created.
1902    
1903    =item type
1904    
1905    Type of PDB: C<free> or C<bound>
1906    
1907    =item pdbHash
1908    
1909    Hash containing the IDs of PDBs that have already been created.
1910    
1911    =item pdbLoader
1912    
1913    Load object for the PDB table.
1914    
1915    =back
1916    
1917    =cut
1918    
1919    sub CreatePDB {
1920        # Get the parameters.
1921        my ($self, $pdbID, $title, $type, $pdbHash, $pdbLoader) = @_;
1922        $pdbLoader->Add("PDB check");
1923        # Check to see if this is a new PDB.
1924        if (! exists $pdbHash->{$pdbID}) {
1925            # It is, so we create it.
1926            $pdbLoader->Put($pdbID, $title, $type);
1927            $pdbHash->{$pdbID} = 1;
1928            # Count it.
1929            $pdbLoader->Add("PDB-$type");
1930        }
1931    }
1932    
1933  =head3 TableLoader  =head3 TableLoader
1934    
1935  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 1191  Line 1944 
1944    
1945  Name of the table (relation) being loaded.  Name of the table (relation) being loaded.
1946    
1947  =item rowCount (optional)  =item ignore
1948    
1949  Estimated maximum number of rows in the table.  TRUE if the table should be ignored entirely, else FALSE.
1950    
1951  =item RETURN  =item RETURN
1952    
# Line 1205  Line 1958 
1958    
1959  sub _TableLoader {  sub _TableLoader {
1960      # Get the parameters.      # Get the parameters.
1961      my ($self, $tableName, $rowCount) = @_;      my ($self, $tableName, $ignore) = @_;
1962      # Create the load object.      # Create the load object.
1963      my $retVal = ERDBLoad->new($self->{erdb}, $tableName, $self->{loadDirectory}, $rowCount);      my $retVal = ERDBLoad->new($self->{erdb}, $tableName, $self->{loadDirectory}, $self->LoadOnly,
1964                                   $ignore);
1965      # Cache it in the loader list.      # Cache it in the loader list.
1966      push @{$self->{loaders}}, $retVal;      push @{$self->{loaders}}, $retVal;
1967      # Return it to the caller.      # Return it to the caller.
# Line 1241  Line 1995 
1995      my $retVal = Stats->new();      my $retVal = Stats->new();
1996      # Get the loader list.      # Get the loader list.
1997      my $loadList = $self->{loaders};      my $loadList = $self->{loaders};
1998        # Create a hash to hold the statistics objects, keyed on relation name.
1999        my %loaderHash = ();
2000      # 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
2001      # 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.
2002      while (my $loader = pop @{$loadList}) {      while (my $loader = pop @{$loadList}) {
2003            # Get the relation name.
2004            my $relName = $loader->RelName;
2005            # Check the ignore flag.
2006            if ($loader->Ignore) {
2007                Trace("Relation $relName not loaded.") if T(2);
2008            } else {
2009                # Here we really need to finish.
2010                Trace("Finishing $relName.") if T(2);
2011          my $stats = $loader->Finish();          my $stats = $loader->Finish();
2012                $loaderHash{$relName} = $stats;
2013            }
2014        }
2015        # Now we loop through again, actually loading the tables. We want to finish before
2016        # loading so that if something goes wrong at this point, all the load files are usable
2017        # and we don't have to redo all that work.
2018        for my $relName (sort keys %loaderHash) {
2019            # Get the statistics for this relation.
2020            my $stats = $loaderHash{$relName};
2021            # Check for a database load.
2022            if ($self->{options}->{dbLoad}) {
2023                # Here we want to use the load file just created to load the database.
2024                Trace("Loading relation $relName.") if T(2);
2025                my $newStats = $self->{sprout}->LoadUpdate(1, [$relName]);
2026                # Accumulate the statistics from the DB load.
2027                $stats->Accumulate($newStats);
2028            }
2029          $retVal->Accumulate($stats);          $retVal->Accumulate($stats);
         my $relName = $loader->RelName;  
2030          Trace("Statistics for $relName:\n" . $stats->Show()) if T(2);          Trace("Statistics for $relName:\n" . $stats->Show()) if T(2);
2031      }      }
2032      # Return the load statistics.      # Return the load statistics.

Legend:
Removed from v.1.14  
changed lines
  Added in v.1.79

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3