[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.19, Thu Oct 20 09:34:09 2005 UTC revision 1.81, Wed Feb 21 13:21:42 2007 UTC
# Line 30  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 80  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 94  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 119  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 129  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 153  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 162  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 171  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 198  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 216  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 268  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 308  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 340  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 376  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, 2);                              $loadUsesAsEvidence->Put($pchID, $peg4, 2);
443                            }
444                      }                      }
445                  }                  }
446              }              }
# Line 410  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 424  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                my @fids = map { $_->[0] } @featureTuples;
525                Trace("$count features found for genome $genomeID.") if T(3);
526                # Get the attributes for this genome and put them in a hash by feature ID.
527                my $attributes = GetGenomeAttributes($fig, $genomeID, \@fids);
528                # Set up for our duplicate-feature check.
529                my $oldFeatureID = "";
530          # Loop through the features.          # Loop through the features.
531          for my $featureData (@{$features}) {              for my $featureTuple (@featureTuples) {
             $loadFeature->Add("featureIn");  
532              # Split the tuple.              # Split the tuple.
533              my ($featureID, $locations, undef, $type) = @{$featureData};                  my ($featureID, $locations, undef, $type) = @{$featureTuple};
534              # Create the feature record.                  # Check for duplicates.
535              $loadFeature->Put($featureID, 1, $type);                  if ($featureID eq $oldFeatureID) {
536                        Trace("Duplicate feature $featureID found.") if T(1);
537                    } else {
538                        $oldFeatureID = $featureID;
539                        # Count this feature.
540                        $loadFeature->Add("featureIn");
541                        # Begin building the keywords. We start with the genome ID, the
542                        # feature ID, the taxonomy, and the organism name.
543                        my @keywords = ($genomeID, $featureID, $fig->genus_species($genomeID),
544                                        $fig->taxonomy_of($genomeID));
545                        # Get the functional assignment and aliases.
546                        my $assignment = $fig->function_of($featureID);
547              # Create the aliases.              # Create the aliases.
548              for my $alias ($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              # The next stuff is for a full load only.                      Trace("Assignment for $featureID is: $assignment") if T(4);
553              if (! $limited) {                      # Break the assignment into words and shove it onto the
554                        # keyword list.
555                        push @keywords, split(/\s+/, $assignment);
556                        # Link this feature to the parent genome.
557                        $loadHasFeature->Put($genomeID, $featureID, $type);
558                  # Get the links.                  # Get the links.
559                  my @links = $fig->fid_links($featureID);                  my @links = $fig->fid_links($featureID);
560                  for my $link (@links) {                  for my $link (@links) {
# Line 483  Line 573 
573                          $loadFeatureUpstream->Put($featureID, $upstream);                          $loadFeatureUpstream->Put($featureID, $upstream);
574                      }                      }
575                  }                  }
576              }                      # Now we need to find the subsystems this feature participates in.
577                        # We also add the subsystems to the keyword list. Before we do that,
578                        # we must convert underscores to spaces and tack on the classifications.
579                        my @subsystems = $fig->peg_to_subsystems($featureID);
580                        for my $subsystem (@subsystems) {
581                            # Only proceed if we like this subsystem.
582                            if (exists $subHash->{$subsystem}) {
583                                # Store the has-role link.
584                                $loadHasRoleInSubsystem->Put($featureID, $subsystem, $genomeID, $type);
585                                # Save the subsystem's keyword data.
586                                my $subKeywords = $subHash->{$subsystem};
587                                push @keywords, split /\s+/, $subKeywords;
588                                # Now we need to get this feature's role in the subsystem.
589                                my $subObject = $fig->get_subsystem($subsystem);
590                                my @roleColumns = $subObject->get_peg_roles($featureID);
591                                my @allRoles = $subObject->get_roles();
592                                for my $col (@roleColumns) {
593                                    my $role = $allRoles[$col];
594                                    push @keywords, split /\s+/, $role;
595                                    push @keywords, $subObject->get_role_abbr($col);
596                                }
597                            }
598                        }
599                        # There are three special attributes computed from property
600                        # data that we build next. If the special attribute is non-empty,
601                        # its name will be added to the keyword list. First, we get all
602                        # the attributes for this feature. They will come back as
603                        # 4-tuples: [peg, name, value, URL]. We use a 3-tuple instead:
604                        # [name, value, value with URL]. (We don't need the PEG, since
605                        # we already know it.)
606                        my @attributes = map { [$_->[1], $_->[2], Tracer::CombineURL($_->[2], $_->[3])] }
607                                             @{$attributes->{$featureID}};
608                        # Now we process each of the special attributes.
609                        if (SpecialAttribute($featureID, \@attributes,
610                                             1, [0,2], '^(essential|potential_essential)$',
611                                             $loadFeatureEssential)) {
612                            push @keywords, 'essential';
613                            $loadFeature->Add('essential');
614                        }
615                        if (SpecialAttribute($featureID, \@attributes,
616                                             0, [2], '^virulen',
617                                             $loadFeatureVirulent)) {
618                            push @keywords, 'virulent';
619                            $loadFeature->Add('virulent');
620                        }
621                        if (SpecialAttribute($featureID, \@attributes,
622                                             0, [0,2], '^iedb_',
623                                             $loadFeatureIEDB)) {
624                            push @keywords, 'iedb';
625                            $loadFeature->Add('iedb');
626                        }
627                        # Now we need to bust up hyphenated words in the keyword
628                        # list. We keep them separate and put them at the end so
629                        # the original word order is available.
630                        my $keywordString = "";
631                        my $bustedString = "";
632                        for my $keyword (@keywords) {
633                            if (length $keyword >= 3) {
634                                $keywordString .= " $keyword";
635                                if ($keyword =~ /-/) {
636                                    my @words = split /-/, $keyword;
637                                    $bustedString .= join(" ", "", @words);
638                                }
639                            }
640                        }
641                        $keywordString .= $bustedString;
642                        # Get rid of annoying punctuation.
643                        $keywordString =~ s/[();]//g;
644                        # Clean the keyword list.
645                        my $cleanWords = $sprout->CleanKeywords($keywordString);
646                        Trace("Keyword string for $featureID: $cleanWords") if T(4);
647                        # Create the feature record.
648                        $loadFeature->Put($featureID, 1, $type, $assignment, $cleanWords);
649              # This part is the roughest. We need to relate the features to contig              # This part is the roughest. We need to relate the features to contig
650              # locations, and the locations must be split so that none of them exceed              # locations, and the locations must be split so that none of them exceed
651              # the maximum segment size. This simplifies the genes_in_region processing              # the maximum segment size. This simplifies the genes_in_region processing
# Line 512  Line 674 
674              }              }
675          }          }
676      }      }
     # Finish the loads.  
     my $retVal = $self->_FinishAll();  
     return $retVal;  
 }  
   
 =head3 LoadBBHData  
   
 C<< my $stats = $spl->LoadBBHData(); >>  
   
 Load the bidirectional best hit data from FIG into Sprout.  
   
 Sprout does not store information on similarities. Instead, it has only the  
 bi-directional best hits. Even so, the BBH table is one of the largest in  
 the database.  
   
 The following relations are loaded by this method.  
   
     IsBidirectionalBestHitOf  
   
 =over 4  
   
 =item RETURNS  
   
 Returns a statistics object for the loads.  
   
 =back  
   
 =cut  
 #: Return Type $%;  
 sub LoadBBHData {  
     # Get this object instance.  
     my ($self) = @_;  
     # Get the FIG object.  
     my $fig = $self->{fig};  
     # Get the table of genome IDs.  
     my $genomeHash = $self->{genomes};  
     my $genomeCount = (keys %{$genomeHash});  
     my $featureCount = $genomeCount * 4000;  
     # Create load objects for each of the tables we're loading.  
     my $loadIsBidirectionalBestHitOf = $self->_TableLoader('IsBidirectionalBestHitOf',  
                                                            $featureCount * $genomeCount);  
     Trace("Beginning BBH load.") if T(2);  
     # Now we loop through the genomes, generating the data for each one.  
     for my $genomeID (sort keys %{$genomeHash}) {  
         $loadIsBidirectionalBestHitOf->Add("genomeIn");  
         Trace("Processing features for genome $genomeID.") if T(3);  
         # Get the feature list for this genome.  
         my $features = $fig->all_features_detailed($genomeID);  
         # Loop through the features.  
         for my $featureData (@{$features}) {  
             # Split the tuple.  
             my ($featureID, $locations, $aliases, $type) = @{$featureData};  
             # Get the bi-directional best hits.  
             my @bbhList = $fig->bbhs($featureID);  
             for my $bbhEntry (@bbhList) {  
                 # Get the target feature ID and the score.  
                 my ($targetID, $score) = @{$bbhEntry};  
                 # Check the target feature's genome.  
                 my $targetGenomeID = $fig->genome_of($targetID);  
                 # Only proceed if it's one of our genomes.  
                 if ($genomeHash->{$targetGenomeID}) {  
                     $loadIsBidirectionalBestHitOf->Put($featureID, $targetID, $targetGenomeID,  
                                                        $score);  
                 }  
             }  
677          }          }
678      }      }
679      # Finish the loads.      # Finish the loads.
# Line 599  Line 696 
696  The following relations are loaded by this method.  The following relations are loaded by this method.
697    
698      Subsystem      Subsystem
699        SubsystemClass
700      Role      Role
701      RoleEC      RoleEC
702      SSCell      SSCell
# Line 608  Line 706 
706      OccursInSubsystem      OccursInSubsystem
707      ParticipatesIn      ParticipatesIn
708      HasSSCell      HasSSCell
     Catalyzes  
     Reaction  
709      ConsistsOfRoles      ConsistsOfRoles
710      RoleSubset      RoleSubset
711      HasRoleSubset      HasRoleSubset
712      ConsistsOfGenomes      ConsistsOfGenomes
713      GenomeSubset      GenomeSubset
714      HasGenomeSubset      HasGenomeSubset
715        Catalyzes
716        Diagram
717        RoleOccursIn
718    
719  =over 4  =over 4
720    
# Line 638  Line 737 
737      # Get the subsystem hash. This lists the subsystems we'll process.      # Get the subsystem hash. This lists the subsystems we'll process.
738      my $subsysHash = $self->{subsystems};      my $subsysHash = $self->{subsystems};
739      my @subsysIDs = sort keys %{$subsysHash};      my @subsysIDs = sort keys %{$subsysHash};
740      my $subsysCount = @subsysIDs;      # Get the map list.
741      my $genomeCount = (keys %{$genomeHash});      my @maps = $fig->all_maps;
     my $featureCount = $genomeCount * 4000;  
742      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
743      my $loadSubsystem = $self->_TableLoader('Subsystem', $subsysCount);      my $loadDiagram = $self->_TableLoader('Diagram', $self->PrimaryOnly);
744      my $loadRole = $self->_TableLoader('Role', $featureCount * 6);      my $loadRoleOccursIn = $self->_TableLoader('RoleOccursIn', $self->PrimaryOnly);
745      my $loadRoleEC = $self->_TableLoader('RoleEC', $featureCount * 6);      my $loadSubsystem = $self->_TableLoader('Subsystem');
746      my $loadSSCell = $self->_TableLoader('SSCell', $featureCount * $genomeCount);      my $loadRole = $self->_TableLoader('Role', $self->PrimaryOnly);
747      my $loadContainsFeature = $self->_TableLoader('ContainsFeature', $featureCount * $subsysCount);      my $loadRoleEC = $self->_TableLoader('RoleEC', $self->PrimaryOnly);
748      my $loadIsGenomeOf = $self->_TableLoader('IsGenomeOf', $featureCount * $genomeCount);      my $loadCatalyzes = $self->_TableLoader('Catalyzes', $self->PrimaryOnly);
749      my $loadIsRoleOf = $self->_TableLoader('IsRoleOf', $featureCount * $genomeCount);      my $loadSSCell = $self->_TableLoader('SSCell', $self->PrimaryOnly);
750      my $loadOccursInSubsystem = $self->_TableLoader('OccursInSubsystem', $featureCount * 6);      my $loadContainsFeature = $self->_TableLoader('ContainsFeature', $self->PrimaryOnly);
751      my $loadParticipatesIn = $self->_TableLoader('ParticipatesIn', $subsysCount * $genomeCount);      my $loadIsGenomeOf = $self->_TableLoader('IsGenomeOf', $self->PrimaryOnly);
752      my $loadHasSSCell = $self->_TableLoader('HasSSCell', $featureCount * $genomeCount);      my $loadIsRoleOf = $self->_TableLoader('IsRoleOf', $self->PrimaryOnly);
753      my $loadReaction = $self->_TableLoader('Reaction', $featureCount * $genomeCount);      my $loadOccursInSubsystem = $self->_TableLoader('OccursInSubsystem', $self->PrimaryOnly);
754      my $loadCatalyzes = $self->_TableLoader('Catalyzes', $featureCount * $genomeCount);      my $loadParticipatesIn = $self->_TableLoader('ParticipatesIn', $self->PrimaryOnly);
755      my $loadRoleSubset = $self->_TableLoader('RoleSubset', $subsysCount * 50);      my $loadHasSSCell = $self->_TableLoader('HasSSCell', $self->PrimaryOnly);
756      my $loadGenomeSubset = $self->_TableLoader('GenomeSubset', $subsysCount * 50);      my $loadRoleSubset = $self->_TableLoader('RoleSubset', $self->PrimaryOnly);
757      my $loadConsistsOfRoles = $self->_TableLoader('ConsistsOfRoles', $featureCount * $genomeCount);      my $loadGenomeSubset = $self->_TableLoader('GenomeSubset', $self->PrimaryOnly);
758      my $loadConsistsOfGenomes = $self->_TableLoader('ConsistsOfGenomes', $featureCount * $genomeCount);      my $loadConsistsOfRoles = $self->_TableLoader('ConsistsOfRoles', $self->PrimaryOnly);
759      my $loadHasRoleSubset = $self->_TableLoader('HasRoleSubset', $subsysCount * 50);      my $loadConsistsOfGenomes = $self->_TableLoader('ConsistsOfGenomes', $self->PrimaryOnly);
760      my $loadHasGenomeSubset = $self->_TableLoader('HasGenomeSubset', $subsysCount * 50);      my $loadHasRoleSubset = $self->_TableLoader('HasRoleSubset', $self->PrimaryOnly);
761      Trace("Beginning subsystem data load.") if T(2);      my $loadHasGenomeSubset = $self->_TableLoader('HasGenomeSubset', $self->PrimaryOnly);
762      # The reaction hash will contain a list of reactions for each role. When we're done,      my $loadSubsystemClass = $self->_TableLoader('SubsystemClass', $self->PrimaryOnly);
763      # a complicated sort and merge will be used to generate the Reaction and Catalyzes      if ($self->{options}->{loadOnly}) {
764      # tables.          Trace("Loading from existing files.") if T(2);
765      my %reactionsToRoles = ();      } else {
766            Trace("Generating subsystem data.") if T(2);
767            # This hash will contain the role for each EC. When we're done, this
768            # information will be used to generate the Catalyzes table.
769            my %ecToRoles = ();
770      # Loop through the subsystems. Our first task will be to create the      # Loop through the subsystems. Our first task will be to create the
771      # roles. We do this by looping through the subsystems and creating a      # roles. We do this by looping through the subsystems and creating a
772      # role hash. The hash tracks each role ID so that we don't create      # role hash. The hash tracks each role ID so that we don't create
# Line 673  Line 775 
775      my ($genomeID, $roleID);      my ($genomeID, $roleID);
776      my %roleData = ();      my %roleData = ();
777      for my $subsysID (@subsysIDs) {      for my $subsysID (@subsysIDs) {
         Trace("Creating subsystem $subsysID.") if T(3);  
         $loadSubsystem->Add("subsystemIn");  
778          # Get the subsystem object.          # Get the subsystem object.
779          my $sub = $fig->get_subsystem($subsysID);          my $sub = $fig->get_subsystem($subsysID);
780          # Get its reaction hash.              # Only proceed if the subsystem has a spreadsheet.
781          my $reactionHash = $sub->get_reactions();              if (! $sub->{empty_ss}) {
782                    Trace("Creating subsystem $subsysID.") if T(3);
783                    $loadSubsystem->Add("subsystemIn");
784          # Create the subsystem record.          # Create the subsystem record.
785          my $curator = $sub->get_curator();          my $curator = $sub->get_curator();
786          my $notes = $sub->get_notes();          my $notes = $sub->get_notes();
787          $loadSubsystem->Put($subsysID, $curator, $notes);          $loadSubsystem->Put($subsysID, $curator, $notes);
788                    # Now for the classification string. This comes back as a list
789                    # reference and we convert it to a space-delimited string.
790                    my $classList = $fig->subsystem_classification($subsysID);
791                    my $classString = join($FIG_Config::splitter, grep { $_ } @$classList);
792                    $loadSubsystemClass->Put($subsysID, $classString);
793          # Connect it to its roles. Each role is a column in the subsystem spreadsheet.          # Connect it to its roles. Each role is a column in the subsystem spreadsheet.
794          for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {          for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {
795              # Connect to this role.              # Connect to this role.
# Line 697  Line 804 
804                  $roleData{$roleID} = 1;                  $roleData{$roleID} = 1;
805                  # Check for an EC number.                  # Check for an EC number.
806                  if ($roleID =~ /\(EC ([^.]+\.[^.]+\.[^.]+\.[^)]+)\)\s*$/) {                  if ($roleID =~ /\(EC ([^.]+\.[^.]+\.[^.]+\.[^)]+)\)\s*$/) {
807                      $loadRoleEC->Put($roleID, $1);                              my $ec = $1;
808                  }                              $loadRoleEC->Put($roleID, $ec);
809                  # Add the role's reactions.                              $ecToRoles{$ec} = $roleID;
                 my $reactions = $reactionHash->{$roleID};  
                 for my $reactionID (@{$reactions}) {  
                     if (! exists $reactionsToRoles{$reactionID}) {  
                         # Here the reaction is brand-new, so we create its reaction  
                         # record.  
                         $loadReaction->Put($reactionID, $fig->reversible($reactionID));  
                         # We also create a blank list for it in the reaction hash.  
                         $reactionsToRoles{$reactionID} = [];  
                     }  
                     # Add the role to the reaction's role list.  
                     push @{$reactionsToRoles{$reactionID}}, $roleID;  
810                  }                  }
811              }              }
812          }          }
# Line 737  Line 833 
833                  # part of the spreadsheet cell ID.                  # part of the spreadsheet cell ID.
834                  for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {                  for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {
835                      # Get the features in the spreadsheet cell for this genome and role.                      # Get the features in the spreadsheet cell for this genome and role.
836                      my @pegs = $sub->get_pegs_from_cell($row, $col);                              my @pegs = grep { !$fig->is_deleted_fid($_) } $sub->get_pegs_from_cell($row, $col);
837                      # Only proceed if features exist.                      # Only proceed if features exist.
838                      if (@pegs > 0) {                      if (@pegs > 0) {
839                          # Create the spreadsheet cell.                          # Create the spreadsheet cell.
# Line 758  Line 854 
854                  if ($pegCount > 0) {                  if ($pegCount > 0) {
855                      Trace("$pegCount PEGs in $cellCount cells for $genomeID.") if T(3);                      Trace("$pegCount PEGs in $cellCount cells for $genomeID.") if T(3);
856                      $loadParticipatesIn->Put($genomeID, $subsysID, $variantCode);                      $loadParticipatesIn->Put($genomeID, $subsysID, $variantCode);
                     # Partition the PEGs found into clusters.  
                     my @clusters = $fig->compute_clusters(\@pegsFound, $sub);  
857                      # Create a hash mapping PEG IDs to cluster numbers.                      # Create a hash mapping PEG IDs to cluster numbers.
858                      # We default to -1 for all of them.                      # We default to -1 for all of them.
859                      my %clusterOf = map { $_ => -1 } @pegsFound;                      my %clusterOf = map { $_ => -1 } @pegsFound;
860                                # Partition the PEGs found into clusters.
861                                my @clusters = $fig->compute_clusters([keys %clusterOf], $sub);
862                      for (my $i = 0; $i <= $#clusters; $i++) {                      for (my $i = 0; $i <= $#clusters; $i++) {
863                          my $subList = $clusters[$i];                          my $subList = $clusters[$i];
864                          for my $peg (@{$subList}) {                          for my $peg (@{$subList}) {
# Line 790  Line 886 
886              # Connect the subset to the subsystem.              # Connect the subset to the subsystem.
887              $loadHasRoleSubset->Put($subsysID, $actualID);              $loadHasRoleSubset->Put($subsysID, $actualID);
888              # Connect the subset to its roles.              # Connect the subset to its roles.
889              my @roles = $sub->get_subset($subsetID);                      my @roles = $sub->get_subsetC_roles($subsetID);
890              for my $roleID (@roles) {              for my $roleID (@roles) {
891                  $loadConsistsOfRoles->Put($actualID, $roleID);                  $loadConsistsOfRoles->Put($actualID, $roleID);
892              }              }
# Line 810  Line 906 
906              }              }
907          }          }
908      }      }
     # Before we leave, we must create the Catalyzes table. The data is all stored in  
     # "reactionToRoles" hash.  
     for my $reactionID (keys %reactionsToRoles) {  
         # Get this reaction's list of roles. We sort it so we can merge out duplicates.  
         my @roles = sort @{$reactionsToRoles{$reactionID}};  
         my $lastRole = "";  
         # Loop through the roles, creating catalyzation records.  
         for my $thisRole (@roles) {  
             if ($thisRole ne $lastRole) {  
                 $loadCatalyzes->Put($thisRole, $reactionID);  
             }  
909          }          }
910      }          # Now we loop through the diagrams. We need to create the diagram records
911      # Finish the load.          # and link each diagram to its roles. Note that only roles which occur
912      my $retVal = $self->_FinishAll();          # in subsystems (and therefore appear in the %ecToRoles hash) are
913      return $retVal;          # included.
914  }          for my $map (@maps) {
   
 =head3 LoadDiagramData  
   
 C<< my $stats = $spl->LoadDiagramData(); >>  
   
 Load the diagram data from FIG into Sprout.  
   
 Diagrams are used to organize functional roles. The diagram shows the  
 connections between chemicals that interact with a subsystem.  
   
 The following relations are loaded by this method.  
   
     Diagram  
     RoleOccursIn  
   
 =over 4  
   
 =item RETURNS  
   
 Returns a statistics object for the loads.  
   
 =back  
   
 =cut  
 #: Return Type $%;  
 sub LoadDiagramData {  
     # Get this object instance.  
     my ($self) = @_;  
     # Get the FIG object.  
     my $fig = $self->{fig};  
     # Get the map list.  
     my @maps = $fig->all_maps;  
     my $mapCount = @maps;  
     my $genomeCount = (keys %{$self->{genomes}});  
     my $featureCount = $genomeCount * 4000;  
     # Create load objects for each of the tables we're loading.  
     my $loadDiagram = $self->_TableLoader('Diagram', $mapCount);  
     my $loadRoleOccursIn = $self->_TableLoader('RoleOccursIn', $featureCount * 6);  
     Trace("Beginning diagram data load.") if T(2);  
     # Loop through the diagrams.  
     for my $map ($fig->all_maps) {  
915          Trace("Loading diagram $map.") if T(3);          Trace("Loading diagram $map.") if T(3);
916          # Get the diagram's descriptive name.          # Get the diagram's descriptive name.
917          my $name = $fig->map_name($map);          my $name = $fig->map_name($map);
# Line 876  Line 920 
920          # A hash is used to prevent duplicates.          # A hash is used to prevent duplicates.
921          my %roleHash = ();          my %roleHash = ();
922          for my $role ($fig->map_to_ecs($map)) {          for my $role ($fig->map_to_ecs($map)) {
923              if (! $roleHash{$role}) {                  if (exists $ecToRoles{$role} && ! $roleHash{$role}) {
924                  $loadRoleOccursIn->Put($role, $map);                      $loadRoleOccursIn->Put($ecToRoles{$role}, $map);
925                  $roleHash{$role} = 1;                  $roleHash{$role} = 1;
926              }              }
927          }          }
928      }      }
929            # Before we leave, we must create the Catalyzes table. We start with the reactions,
930            # then use the "ecToRoles" table to convert EC numbers to role IDs.
931            my @reactions = $fig->all_reactions();
932            for my $reactionID (@reactions) {
933                # Get this reaction's list of roles. The results will be EC numbers.
934                my @roles = $fig->catalyzed_by($reactionID);
935                # Loop through the roles, creating catalyzation records.
936                for my $thisRole (@roles) {
937                    if (exists $ecToRoles{$thisRole}) {
938                        $loadCatalyzes->Put($ecToRoles{$thisRole}, $reactionID);
939                    }
940                }
941            }
942        }
943      # Finish the load.      # Finish the load.
944      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
945      return $retVal;      return $retVal;
# Line 923  Line 981 
981      my $fig = $self->{fig};      my $fig = $self->{fig};
982      # Get the genome hash.      # Get the genome hash.
983      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
984      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
985      my $loadProperty = $self->_TableLoader('Property', $genomeCount * 1500);      my $loadProperty = $self->_TableLoader('Property');
986      my $loadHasProperty = $self->_TableLoader('HasProperty', $genomeCount * 1500);      my $loadHasProperty = $self->_TableLoader('HasProperty', $self->PrimaryOnly);
987      Trace("Beginning property data load.") if T(2);      if ($self->{options}->{loadOnly}) {
988            Trace("Loading from existing files.") if T(2);
989        } else {
990            Trace("Generating property data.") if T(2);
991      # Create a hash for storing property IDs.      # Create a hash for storing property IDs.
992      my %propertyKeys = ();      my %propertyKeys = ();
993      my $nextID = 1;      my $nextID = 1;
994      # Loop through the genomes.      # Loop through the genomes.
995      for my $genomeID (keys %{$genomeHash}) {          for my $genomeID (sort keys %{$genomeHash}) {
996          $loadProperty->Add("genomeIn");          $loadProperty->Add("genomeIn");
997                Trace("Generating properties for $genomeID.") if T(3);
998          # Get the genome's features. The feature ID is the first field in the          # Get the genome's features. The feature ID is the first field in the
999          # tuples returned by "all_features_detailed". We use "all_features_detailed"          # tuples returned by "all_features_detailed". We use "all_features_detailed"
1000          # rather than "all_features" because we want all features regardless of type.          # rather than "all_features" because we want all features regardless of type.
1001          my @features = map { $_->[0] } @{$fig->all_features_detailed($genomeID)};          my @features = map { $_->[0] } @{$fig->all_features_detailed($genomeID)};
1002                my $featureCount = 0;
1003                my $propertyCount = 0;
1004                # Get the properties for this genome's features.
1005                my $attributes = GetGenomeAttributes($fig, $genomeID, \@features);
1006                Trace("Property hash built for $genomeID.") if T(3);
1007          # Loop through the features, creating HasProperty records.          # Loop through the features, creating HasProperty records.
1008          for my $fid (@features) {          for my $fid (@features) {
             $loadProperty->Add("featureIn");  
1009              # Get all attributes for this feature. We do this one feature at a time              # Get all attributes for this feature. We do this one feature at a time
1010              # to insure we do not get any genome attributes.              # to insure we do not get any genome attributes.
1011              my @attributeList = $fig->get_attributes($fid, '', '', '');                  my @attributeList = @{$attributes->{$fid}};
1012                    if (scalar @attributeList) {
1013                        $featureCount++;
1014                    }
1015              # Loop through the attributes.              # Loop through the attributes.
1016              for my $tuple (@attributeList) {              for my $tuple (@attributeList) {
1017                        $propertyCount++;
1018                  # Get this attribute value's data. Note that we throw away the FID,                  # Get this attribute value's data. Note that we throw away the FID,
1019                  # since it will always be the same as the value if "$fid".                  # since it will always be the same as the value if "$fid".
1020                  my (undef, $key, $value, $url) = @{$tuple};                  my (undef, $key, $value, $url) = @{$tuple};
# Line 967  Line 1036 
1036                  $loadHasProperty->Put($fid, $propertyID, $url);                  $loadHasProperty->Put($fid, $propertyID, $url);
1037              }              }
1038          }          }
1039                # Update the statistics.
1040                Trace("$propertyCount attributes processed for $featureCount features.") if T(3);
1041                $loadHasProperty->Add("featuresIn", $featureCount);
1042                $loadHasProperty->Add("propertiesIn", $propertyCount);
1043            }
1044      }      }
1045      # Finish the load.      # Finish the load.
1046      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
# Line 1007  Line 1081 
1081      my $fig = $self->{fig};      my $fig = $self->{fig};
1082      # Get the genome hash.      # Get the genome hash.
1083      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
1084      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
1085      my $loadAnnotation = $self->_TableLoader('Annotation', $genomeCount * 4000);      my $loadAnnotation = $self->_TableLoader('Annotation');
1086      my $loadIsTargetOfAnnotation = $self->_TableLoader('IsTargetOfAnnotation', $genomeCount * 4000);      my $loadIsTargetOfAnnotation = $self->_TableLoader('IsTargetOfAnnotation', $self->PrimaryOnly);
1087      my $loadSproutUser = $self->_TableLoader('SproutUser', 100);      my $loadSproutUser = $self->_TableLoader('SproutUser', $self->PrimaryOnly);
1088      my $loadUserAccess = $self->_TableLoader('UserAccess', 1000);      my $loadUserAccess = $self->_TableLoader('UserAccess', $self->PrimaryOnly);
1089      my $loadMadeAnnotation = $self->_TableLoader('MadeAnnotation', $genomeCount * 4000);      my $loadMadeAnnotation = $self->_TableLoader('MadeAnnotation', $self->PrimaryOnly);
1090      Trace("Beginning annotation data load.") if T(2);      if ($self->{options}->{loadOnly}) {
1091            Trace("Loading from existing files.") if T(2);
1092        } else {
1093            Trace("Generating annotation data.") if T(2);
1094      # Create a hash of user names. We'll use this to prevent us from generating duplicate      # Create a hash of user names. We'll use this to prevent us from generating duplicate
1095      # user records.      # user records.
1096      my %users = ( FIG => 1, master => 1 );      my %users = ( FIG => 1, master => 1 );
# Line 1028  Line 1104 
1104      # Loop through the genomes.      # Loop through the genomes.
1105      for my $genomeID (sort keys %{$genomeHash}) {      for my $genomeID (sort keys %{$genomeHash}) {
1106          Trace("Processing $genomeID.") if T(3);          Trace("Processing $genomeID.") if T(3);
         # Get the genome's PEGs.  
         my @pegs = $fig->pegs_of($genomeID);  
         for my $peg (@pegs) {  
             Trace("Processing $peg.") if T(4);  
1107              # Create a hash of timestamps. We use this to prevent duplicate time stamps              # Create a hash of timestamps. We use this to prevent duplicate time stamps
1108              # from showing up for a single PEG's annotations.              # from showing up for a single PEG's annotations.
1109              my %seenTimestamps = ();              my %seenTimestamps = ();
1110              # Check for a functional assignment.              # Get the genome's annotations.
1111              my $func = $fig->function_of($peg);              my @annotations = $fig->read_all_annotations($genomeID);
1112              if ($func) {              Trace("Processing annotations.") if T(2);
1113                  # If this is NOT a hypothetical assignment, we create an              for my $tuple (@annotations) {
1114                  # assignment annotation for it.                  # Get the annotation tuple.
1115                  if (! FIG::hypo($peg)) {                  my ($peg, $timestamp, $user, $text) = @{$tuple};
                     # Note that we double the slashes so that what goes into the database is  
                     # a new-line escape sequence rather than an actual new-line.  
                     $loadAnnotation->Put("$peg:$time", $time, "FIG\\nSet function to\\n$func");  
                     $loadIsTargetOfAnnotation->Put($peg, "$peg:$time");  
                     $loadMadeAnnotation->Put("FIG", "$peg:$time");  
                     # Denote we've seen this timestamp.  
                     $seenTimestamps{$time} = 1;  
                 }  
             }  
             # Now loop through the real annotations.  
             for my $tuple ($fig->feature_annotations($peg, "raw")) {  
                 my ($fid, $timestamp, $user, $text) = @{$tuple};  
1116                  # Here we fix up the annotation text. "\r" is removed,                  # Here we fix up the annotation text. "\r" is removed,
1117                  # and "\t" and "\n" are escaped. Note we use the "s"                  # and "\t" and "\n" are escaped. Note we use the "gs"
1118                  # modifier so that new-lines inside the text do not                  # modifier so that new-lines inside the text do not
1119                  # stop the substitution search.                  # stop the substitution search.
1120                  $text =~ s/\r//gs;                  $text =~ s/\r//gs;
# Line 1067  Line 1127 
1127                      # Here it's a number. We need to insure the one we use to form                      # Here it's a number. We need to insure the one we use to form
1128                      # the key is unique.                      # the key is unique.
1129                      my $keyStamp = $timestamp;                      my $keyStamp = $timestamp;
1130                      while ($seenTimestamps{$keyStamp}) {                      while ($seenTimestamps{"$peg:$keyStamp"}) {
1131                          $keyStamp++;                          $keyStamp++;
1132                      }                      }
                     $seenTimestamps{$keyStamp} = 1;  
1133                      my $annotationID = "$peg:$keyStamp";                      my $annotationID = "$peg:$keyStamp";
1134                        $seenTimestamps{$annotationID} = 1;
1135                      # Insure the user exists.                      # Insure the user exists.
1136                      if (! $users{$user}) {                      if (! $users{$user}) {
1137                          $loadSproutUser->Put($user, "SEED user");                          $loadSproutUser->Put($user, "SEED user");
# Line 1129  Line 1189 
1189      my $fig = $self->{fig};      my $fig = $self->{fig};
1190      # Get the genome hash.      # Get the genome hash.
1191      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
1192      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
1193      my $loadComesFrom = $self->_TableLoader('ComesFrom', $genomeCount * 4);      my $loadComesFrom = $self->_TableLoader('ComesFrom', $self->PrimaryOnly);
1194      my $loadSource = $self->_TableLoader('Source', $genomeCount * 4);      my $loadSource = $self->_TableLoader('Source');
1195      my $loadSourceURL = $self->_TableLoader('SourceURL', $genomeCount * 8);      my $loadSourceURL = $self->_TableLoader('SourceURL');
1196      Trace("Beginning source data load.") if T(2);      if ($self->{options}->{loadOnly}) {
1197            Trace("Loading from existing files.") if T(2);
1198        } else {
1199            Trace("Generating annotation data.") if T(2);
1200      # Create hashes to collect the Source information.      # Create hashes to collect the Source information.
1201      my %sourceURL = ();      my %sourceURL = ();
1202      my %sourceDesc = ();      my %sourceDesc = ();
# Line 1164  Line 1226 
1226      for my $sourceID (keys %sourceDesc) {      for my $sourceID (keys %sourceDesc) {
1227          $loadSource->Put($sourceID, $sourceDesc{$sourceID});          $loadSource->Put($sourceID, $sourceDesc{$sourceID});
1228      }      }
1229        }
1230      # Finish the load.      # Finish the load.
1231      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
1232      return $retVal;      return $retVal;
# Line 1203  Line 1266 
1266      my $fig = $self->{fig};      my $fig = $self->{fig};
1267      # Get the genome hash.      # Get the genome hash.
1268      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
1269      # Convert the genome hash. We'll get the genus and species for each genome and make      # Convert the genome hash. We'll get the genus and species for each genome and make
1270      # it the key.      # it the key.
1271      my %speciesHash = map { $fig->genus_species($_) => $_ } (keys %{$genomeHash});      my %speciesHash = map { $fig->genus_species($_) => $_ } (keys %{$genomeHash});
1272      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
1273      my $loadExternalAliasFunc = $self->_TableLoader('ExternalAliasFunc', $genomeCount * 4000);      my $loadExternalAliasFunc = $self->_TableLoader('ExternalAliasFunc');
1274      my $loadExternalAliasOrg = $self->_TableLoader('ExternalAliasOrg', $genomeCount * 4000);      my $loadExternalAliasOrg = $self->_TableLoader('ExternalAliasOrg');
1275      Trace("Beginning external data load.") if T(2);      if ($self->{options}->{loadOnly}) {
1276            Trace("Loading from existing files.") if T(2);
1277        } else {
1278            Trace("Generating external data.") if T(2);
1279      # We loop through the files one at a time. First, the organism file.      # We loop through the files one at a time. First, the organism file.
1280      Open(\*ORGS, "<$FIG_Config::global/ext_org.table");          Open(\*ORGS, "sort +0 -1 -u -t\"\t\" $FIG_Config::global/ext_org.table |");
1281      my $orgLine;      my $orgLine;
1282      while (defined($orgLine = <ORGS>)) {      while (defined($orgLine = <ORGS>)) {
1283          # Clean the input line.          # Clean the input line.
# Line 1224  Line 1289 
1289      close ORGS;      close ORGS;
1290      # Now the function file.      # Now the function file.
1291      my $funcLine;      my $funcLine;
1292      Open(\*FUNCS, "<$FIG_Config::global/ext_func.table");          Open(\*FUNCS, "sort +0 -1 -u -t\"\t\" $FIG_Config::global/ext_func.table |");
1293      while (defined($funcLine = <FUNCS>)) {      while (defined($funcLine = <FUNCS>)) {
1294          # Clean the line ending.          # Clean the line ending.
1295          chomp $funcLine;          chomp $funcLine;
# Line 1240  Line 1305 
1305              $loadExternalAliasFunc->Put(@funcFields[0,1]);              $loadExternalAliasFunc->Put(@funcFields[0,1]);
1306          }          }
1307      }      }
1308        }
1309      # Finish the load.      # Finish the load.
1310      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
1311      return $retVal;      return $retVal;
# Line 1256  Line 1322 
1322    
1323  The following relations are loaded by this method.  The following relations are loaded by this method.
1324    
1325        Reaction
1326      ReactionURL      ReactionURL
1327      Compound      Compound
1328      CompoundName      CompoundName
# Line 1279  Line 1346 
1346      my ($self) = @_;      my ($self) = @_;
1347      # Get the FIG object.      # Get the FIG object.
1348      my $fig = $self->{fig};      my $fig = $self->{fig};
     # Get the genome hash.  
     my $genomeHash = $self->{genomes};  
     my $genomeCount = (keys %{$genomeHash});  
1349      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
1350      my $loadReactionURL = $self->_TableLoader('ReactionURL', $genomeCount * 4000);      my $loadReaction = $self->_TableLoader('Reaction');
1351      my $loadCompound = $self->_TableLoader('Compound', $genomeCount * 4000);      my $loadReactionURL = $self->_TableLoader('ReactionURL', $self->PrimaryOnly);
1352      my $loadCompoundName = $self->_TableLoader('CompoundName', $genomeCount * 8000);      my $loadCompound = $self->_TableLoader('Compound', $self->PrimaryOnly);
1353      my $loadCompoundCAS = $self->_TableLoader('CompoundCAS', $genomeCount * 4000);      my $loadCompoundName = $self->_TableLoader('CompoundName', $self->PrimaryOnly);
1354      my $loadIsAComponentOf = $self->_TableLoader('IsAComponentOf', $genomeCount * 12000);      my $loadCompoundCAS = $self->_TableLoader('CompoundCAS', $self->PrimaryOnly);
1355      Trace("Beginning reaction/compound data load.") if T(2);      my $loadIsAComponentOf = $self->_TableLoader('IsAComponentOf', $self->PrimaryOnly);
1356      # Create a hash to remember the compounds we've generated in the compound table.      if ($self->{options}->{loadOnly}) {
1357      my %compoundHash = ();          Trace("Loading from existing files.") if T(2);
1358      # Loop through the reactions.      } else {
1359            Trace("Generating annotation data.") if T(2);
1360            # First we create the compounds.
1361            my @compounds = $fig->all_compounds();
1362            for my $cid (@compounds) {
1363                # Check for names.
1364                my @names = $fig->names_of_compound($cid);
1365                # Each name will be given a priority number, starting with 1.
1366                my $prio = 1;
1367                for my $name (@names) {
1368                    $loadCompoundName->Put($cid, $name, $prio++);
1369                }
1370                # Create the main compound record. Note that the first name
1371                # becomes the label.
1372                my $label = (@names > 0 ? $names[0] : $cid);
1373                $loadCompound->Put($cid, $label);
1374                # Check for a CAS ID.
1375                my $cas = $fig->cas($cid);
1376                if ($cas) {
1377                    $loadCompoundCAS->Put($cid, $cas);
1378                }
1379            }
1380            # All the compounds are set up, so we need to loop through the reactions next. First,
1381            # we initialize the discriminator index. This is a single integer used to insure
1382            # duplicate elements in a reaction are not accidentally collapsed.
1383            my $discrim = 0;
1384      my @reactions = $fig->all_reactions();      my @reactions = $fig->all_reactions();
1385      for my $reactionID (@reactions) {      for my $reactionID (@reactions) {
1386                # Create the reaction record.
1387                $loadReaction->Put($reactionID, $fig->reversible($reactionID));
1388          # Compute the reaction's URL.          # Compute the reaction's URL.
1389          my $url = HTML::reaction_link($reactionID);          my $url = HTML::reaction_link($reactionID);
1390          # Put it in the ReactionURL table.          # Put it in the ReactionURL table.
# Line 1302  Line 1393 
1393          # substrates first and then products.          # substrates first and then products.
1394          for my $product (0, 1) {          for my $product (0, 1) {
1395              # Get the compounds of the current type for the current reaction. FIG will              # Get the compounds of the current type for the current reaction. FIG will
1396              # give us 3-tuples: [ID, Stoichometry, main-flag]. At this time we do not                  # give us 3-tuples: [ID, stoichiometry, main-flag]. At this time we do not
1397              # have location data in SEED, so it defaults to the empty string.              # have location data in SEED, so it defaults to the empty string.
1398              my @compounds = $fig->reaction2comp($reactionID, $product);              my @compounds = $fig->reaction2comp($reactionID, $product);
1399              for my $compData (@compounds) {              for my $compData (@compounds) {
1400                  # Extract the compound data from the current tuple.                  # Extract the compound data from the current tuple.
1401                  my ($cid, $stoich, $main) = @{$compData};                  my ($cid, $stoich, $main) = @{$compData};
1402                  # Link the compound to the reaction.                  # Link the compound to the reaction.
1403                  $loadIsAComponentOf->Put($cid, $reactionID, "", $main, $product, $stoich);                      $loadIsAComponentOf->Put($cid, $reactionID, $discrim++, "", $main,
1404                  # If this is a new compound, we need to create its table entries.                                               $product, $stoich);
                 if (! exists $compoundHash{$cid}) {  
                     $compoundHash{$cid} = 1;  
                     # Create the main compound record and denote we've done it.  
                     $loadCompound->Put($cid);  
                     # Check for a CAS ID.  
                     my $cas = $fig->cas($cid);  
                     if ($cas) {  
                         $loadCompoundCAS->Put($cid, $cas);  
                     }  
                     # Check for names.  
                     my @names = $fig->names_of_compound($cid);  
                     # Each name will be given a priority number, starting with 1.  
                     my $prio = 0;  
                     for my $name (@names) {  
                         $loadCompoundName->Put($cid, $name, $prio++);  
                     }  
1405                  }                  }
1406              }              }
1407          }          }
# Line 1346  Line 1421 
1421    
1422      GenomeGroups      GenomeGroups
1423    
1424  There is no direct support for genome groups in FIG, so we access the SEED  Currently, we do not use groups. We used to use them for NMPDR groups,
1425    butThere is no direct support for genome groups in FIG, so we access the SEED
1426  files directly.  files directly.
1427    
1428  =over 4  =over 4
# Line 1366  Line 1442 
1442      my $fig = $self->{fig};      my $fig = $self->{fig};
1443      # Get the genome hash.      # Get the genome hash.
1444      my $genomeHash = $self->{genomes};      my $genomeHash = $self->{genomes};
     my $genomeCount = (keys %{$genomeHash});  
1445      # Create a load object for the table we're loading.      # Create a load object for the table we're loading.
1446      my $loadGenomeGroups = $self->_TableLoader('GenomeGroups', $genomeCount * 4);      my $loadGenomeGroups = $self->_TableLoader('GenomeGroups');
1447      Trace("Beginning group data load.") if T(2);      if ($self->{options}->{loadOnly}) {
1448            Trace("Loading from existing files.") if T(2);
1449        } else {
1450            Trace("Generating group data.") if T(2);
1451            # Currently there are no groups.
1452        }
1453        # Finish the load.
1454        my $retVal = $self->_FinishAll();
1455        return $retVal;
1456    }
1457    
1458    =head3 LoadSynonymData
1459    
1460    C<< my $stats = $spl->LoadSynonymData(); >>
1461    
1462    Load the synonym groups into Sprout.
1463    
1464    The following relations are loaded by this method.
1465    
1466        SynonymGroup
1467        IsSynonymGroupFor
1468    
1469    The source information for these relations is taken from the C<maps_to_id> method
1470    of the B<FIG> object. Unfortunately, to make this work, we need to use direct
1471    SQL against the FIG database.
1472    
1473    =over 4
1474    
1475    =item RETURNS
1476    
1477    Returns a statistics object for the loads.
1478    
1479    =back
1480    
1481    =cut
1482    #: Return Type $%;
1483    sub LoadSynonymData {
1484        # Get this object instance.
1485        my ($self) = @_;
1486        # Get the FIG object.
1487        my $fig = $self->{fig};
1488        # Get the genome hash.
1489        my $genomeHash = $self->{genomes};
1490        # Create a load object for the table we're loading.
1491        my $loadSynonymGroup = $self->_TableLoader('SynonymGroup');
1492        my $loadIsSynonymGroupFor = $self->_TableLoader('IsSynonymGroupFor');
1493        if ($self->{options}->{loadOnly}) {
1494            Trace("Loading from existing files.") if T(2);
1495        } else {
1496            Trace("Generating synonym group data.") if T(2);
1497            # Get the database handle.
1498            my $dbh = $fig->db_handle();
1499            # Ask for the synonyms.
1500            my $sth = $dbh->prepare_command("SELECT maps_to, syn_id FROM peg_synonyms ORDER BY maps_to");
1501            my $result = $sth->execute();
1502            if (! defined($result)) {
1503                Confess("Database error in Synonym load: " . $sth->errstr());
1504            } else {
1505                # Remember the current synonym.
1506                my $current_syn = "";
1507                # Count the features.
1508                my $featureCount = 0;
1509                # Loop through the synonym/peg pairs.
1510                while (my @row = $sth->fetchrow()) {
1511                    # Get the synonym ID and feature ID.
1512                    my ($syn_id, $peg) = @row;
1513                    # Insure it's for one of our genomes.
1514                    my $genomeID = FIG::genome_of($peg);
1515                    if (exists $genomeHash->{$genomeID}) {
1516                        # Verify the synonym.
1517                        if ($syn_id ne $current_syn) {
1518                            # It's new, so put it in the group table.
1519                            $loadSynonymGroup->Put($syn_id);
1520                            $current_syn = $syn_id;
1521                        }
1522                        # Connect the synonym to the peg.
1523                        $loadIsSynonymGroupFor->Put($syn_id, $peg);
1524                        # Count this feature.
1525                        $featureCount++;
1526                        if ($featureCount % 1000 == 0) {
1527                            Trace("$featureCount features processed.") if T(3);
1528                        }
1529                    }
1530                }
1531            }
1532        }
1533        # Finish the load.
1534        my $retVal = $self->_FinishAll();
1535        return $retVal;
1536    }
1537    
1538    =head3 LoadFamilyData
1539    
1540    C<< my $stats = $spl->LoadFamilyData(); >>
1541    
1542    Load the protein families into Sprout.
1543    
1544    The following relations are loaded by this method.
1545    
1546        Family
1547        IsFamilyForFeature
1548    
1549    The source information for these relations is taken from the C<families_for_protein>,
1550    C<family_function>, and C<sz_family> methods of the B<FIG> object.
1551    
1552    =over 4
1553    
1554    =item RETURNS
1555    
1556    Returns a statistics object for the loads.
1557    
1558    =back
1559    
1560    =cut
1561    #: Return Type $%;
1562    sub LoadFamilyData {
1563        # Get this object instance.
1564        my ($self) = @_;
1565        # Get the FIG object.
1566        my $fig = $self->{fig};
1567        # Get the genome hash.
1568        my $genomeHash = $self->{genomes};
1569        # Create load objects for the tables we're loading.
1570        my $loadFamily = $self->_TableLoader('Family');
1571        my $loadIsFamilyForFeature = $self->_TableLoader('IsFamilyForFeature');
1572        if ($self->{options}->{loadOnly}) {
1573            Trace("Loading from existing files.") if T(2);
1574        } else {
1575            Trace("Generating family data.") if T(2);
1576            # Create a hash for the family IDs.
1577            my %familyHash = ();
1578      # Loop through the genomes.      # Loop through the genomes.
1579      my $line;          for my $genomeID (sort keys %{$genomeHash}) {
1580      for my $genomeID (keys %{$genomeHash}) {              Trace("Processing features for $genomeID.") if T(2);
1581          Trace("Processing $genomeID.") if T(3);              # Loop through this genome's PEGs.
1582          # Open the NMPDR group file for this genome.              for my $fid ($fig->all_features($genomeID, "peg")) {
1583          if (open(TMP, "<$FIG_Config::organisms/$genomeID/NMPDR") &&                  $loadIsFamilyForFeature->Add("features", 1);
1584              defined($line = <TMP>)) {                  # Get this feature's families.
1585              # Clean the line ending.                  my @families = $fig->families_for_protein($fid);
1586              chomp $line;                  # Loop through the families, connecting them to the feature.
1587              # Add the group to the table. Note that there can only be one group                  for my $family (@families) {
1588              # per genome.                      $loadIsFamilyForFeature->Put($family, $fid);
1589              $loadGenomeGroups->Put($genomeID, $line);                      # If this is a new family, create a record for it.
1590                        if (! exists $familyHash{$family}) {
1591                            $familyHash{$family} = 1;
1592                            $loadFamily->Add("families", 1);
1593                            my $size = $fig->sz_family($family);
1594                            my $func = $fig->family_function($family);
1595                            $loadFamily->Put($family, $size, $func);
1596                        }
1597                    }
1598                }
1599            }
1600        }
1601        # Finish the load.
1602        my $retVal = $self->_FinishAll();
1603        return $retVal;
1604    }
1605    
1606    =head3 LoadDrugData
1607    
1608    C<< my $stats = $spl->LoadDrugData(); >>
1609    
1610    Load the drug target data into Sprout.
1611    
1612    The following relations are loaded by this method.
1613    
1614        DrugProject
1615        ContainsTopic
1616        DrugTopic
1617        ContainsAnalysisOf
1618        PDB
1619        IncludesBound
1620        IsBoundIn
1621        BindsWith
1622        Ligand
1623        DescribesProteinForFeature
1624        FeatureConservation
1625    
1626    The source information for these relations is taken from flat files in the
1627    C<$FIG_Config::drug_directory>. The file C<master_tables.list> contains
1628    a list of drug project names paired with file names. The named file (in the
1629    same directory) contains all the data for the project.
1630    
1631    =over 4
1632    
1633    =item RETURNS
1634    
1635    Returns a statistics object for the loads.
1636    
1637    =back
1638    
1639    =cut
1640    #: Return Type $%;
1641    sub LoadDrugData {
1642        # Get this object instance.
1643        my ($self) = @_;
1644        # Get the FIG object.
1645        my $fig = $self->{fig};
1646        # Get the genome hash.
1647        my $genomeHash = $self->{genomes};
1648        # Create load objects for the tables we're loading.
1649        my $loadDrugProject = $self->_TableLoader('DrugProject');
1650        my $loadContainsTopic = $self->_TableLoader('ContainsTopic');
1651        my $loadDrugTopic = $self->_TableLoader('DrugTopic');
1652        my $loadContainsAnalysisOf = $self->_TableLoader('ContainsAnalysisOf');
1653        my $loadPDB = $self->_TableLoader('PDB');
1654        my $loadIncludesBound = $self->_TableLoader('IncludesBound');
1655        my $loadIsBoundIn = $self->_TableLoader('IsBoundIn');
1656        my $loadBindsWith = $self->_TableLoader('BindsWith');
1657        my $loadLigand = $self->_TableLoader('Ligand');
1658        my $loadDescribesProteinForFeature = $self->_TableLoader('DescribesProteinForFeature');
1659        my $loadFeatureConservation = $self->_TableLoader('FeatureConservation');
1660        if ($self->{options}->{loadOnly}) {
1661            Trace("Loading from existing files.") if T(2);
1662        } else {
1663            Trace("Generating drug target data.") if T(2);
1664            # Load the project list. The file comes in as a list of chomped lines,
1665            # and we split them on the TAB character to make the project name the
1666            # key and the file name the value of the resulting hash.
1667            my %projects = map { split /\t/, $_ } Tracer::GetFile("$FIG_Config::drug_directory/master_tables.list");
1668            # Create hashes for the derived objects: PDBs, Features, and Ligands. These objects
1669            # may occur multiple times in a single project file or even in multiple project
1670            # files.
1671            my %ligands = ();
1672            my %pdbs = ();
1673            my %features = ();
1674            my %bindings = ();
1675            # Set up a counter for drug topics. This will be used as the key.
1676            my $topicCounter = 0;
1677            # Loop through the projects. We sort the keys not because we need them sorted, but
1678            # because it makes it easier to infer our progress from trace messages.
1679            for my $project (sort keys %projects) {
1680                Trace("Processing project $project.") if T(3);
1681                # Only proceed if the download file exists.
1682                my $projectFile = "$FIG_Config::drug_directory/$projects{$project}";
1683                if (! -f $projectFile) {
1684                    Trace("Project file $projectFile not found.") if T(0);
1685                } else {
1686                    # Create the project record.
1687                    $loadDrugProject->Put($project);
1688                    # Create a hash for the topics. Each project has one or more topics. The
1689                    # topic is identified by a URL, a category, and an identifier.
1690                    my %topics = ();
1691                    # Now we can open the project file.
1692                    Trace("Reading project file $projectFile.") if T(3);
1693                    Open(\*PROJECT, "<$projectFile");
1694                    # Get the first record, which is a list of column headers. We don't use this
1695                    # for anything, but it may be useful for debugging.
1696                    my $headerLine = <PROJECT>;
1697                    # Loop through the rest of the records.
1698                    while (! eof PROJECT) {
1699                        # Get the current line of data. Note that not all lines will have all
1700                        # the fields. In particular, the CLIBE data is fairly rare.
1701                        my ($authorOrganism, $category, $tag, $refURL, $peg, $conservation,
1702                            $pdbBound, $pdbBoundEval, $pdbFree, $pdbFreeEval, $pdbFreeTitle,
1703                            $protDistInfo, $passAspInfo, $passAspFile, $passWeightInfo,
1704                            $passWeightFile, $clibeInfo, $clibeURL, $clibeTotalEnergy,
1705                            $clibeVanderwaals, $clibeHBonds, $clibeEI, $clibeSolvationE)
1706                           = Tracer::GetLine(\*PROJECT);
1707                        # The tag contains an identifier for the current line of data followed
1708                        # by a text statement that generally matches a property name in the
1709                        # main database. We split it up, since the identifier goes with
1710                        # the PDB data and the text statement is part of the topic.
1711                        my ($lineID, $topicTag) = split /\s*,\s*/, $tag;
1712                        $loadDrugProject->Add("data line");
1713                        # Check for a new topic.
1714                        my $topicData = "$category\t$topicTag\t$refURL";
1715                        if (! exists $topics{$topicData}) {
1716                            # Here we have a new topic. Compute its ID.
1717                            $topicCounter++;
1718                            $topics{$topicData} = $topicCounter;
1719                            # Create its database record.
1720                            $loadDrugTopic->Put($topicCounter, $refURL, $category, $authorOrganism,
1721                                                $topicTag);
1722                            # Connect it to the project.
1723                            $loadContainsTopic->Put($project, $topicCounter);
1724                            $loadDrugTopic->Add("topic");
1725                        }
1726                        # Now we know the topic ID exists in the hash and the topic will
1727                        # appear in the database, so we get this topic's ID.
1728                        my $topicID = $topics{$topicData};
1729                        # If the feature in this line is new, we need to save its conservation
1730                        # number.
1731                        if (! exists $features{$peg}) {
1732                            $loadFeatureConservation->Put($peg, $conservation);
1733                            $features{$peg} = 1;
1734                        }
1735                        # Now we have two PDBs to deal with-- a bound PDB and a free PDB.
1736                        # The free PDB will have data about docking points; the bound PDB
1737                        # will have data about docking. We store both types as PDBs, and
1738                        # the special data comes from relationships. First we process the
1739                        # bound PDB.
1740                        if ($pdbBound) {
1741                            $loadPDB->Add("bound line");
1742                            # Insure this PDB is in the database.
1743                            $self->CreatePDB($pdbBound, lc "$pdbFreeTitle (bound)", "bound", \%pdbs, $loadPDB);
1744                            # Connect it to this topic.
1745                            $loadIncludesBound->Put($topicID, $pdbBound);
1746                            # Check for CLIBE data.
1747                            if ($clibeInfo) {
1748                                $loadLigand->Add("clibes");
1749                                # We have CLIBE data, so we create a ligand and relate it to the PDB.
1750                                if (! exists $ligands{$clibeInfo}) {
1751                                    # This is a new ligand, so create its record.
1752                                    $loadLigand->Put($clibeInfo);
1753                                    $loadLigand->Add("ligand");
1754                                    # Make sure we know this ligand already exists.
1755                                    $ligands{$clibeInfo} = 1;
1756                                }
1757                                # Now connect the PDB to the ligand using the CLIBE data.
1758                                $loadBindsWith->Put($pdbBound, $clibeInfo, $clibeURL, $clibeHBonds, $clibeEI,
1759                                                    $clibeSolvationE, $clibeVanderwaals);
1760                            }
1761                            # Connect this PDB to the feature.
1762                            $loadDescribesProteinForFeature->Put($pdbBound, $peg, $protDistInfo, $pdbBoundEval);
1763                        }
1764                        # Next is the free PDB.
1765                        if ($pdbFree) {
1766                            $loadPDB->Add("free line");
1767                            # Insure this PDB is in the database.
1768                            $self->CreatePDB($pdbFree, lc $pdbFreeTitle, "free", \%pdbs, $loadPDB);
1769                            # Connect it to this topic.
1770                            $loadContainsAnalysisOf->Put($topicID, $pdbFree, $passAspInfo,
1771                                                         $passWeightFile, $passWeightInfo, $passAspFile);
1772                            # Connect this PDB to the feature.
1773                            $loadDescribesProteinForFeature->Put($pdbFree, $peg, $protDistInfo, $pdbFreeEval);
1774                        }
1775                        # If we have both PDBs, we may need to link them.
1776                        if ($pdbFree && $pdbBound) {
1777                            $loadIsBoundIn->Add("connection");
1778                            # Insure we only link them once.
1779                            my $bindingKey =  "$pdbFree\t$pdbBound";
1780                            if (! exists $bindings{$bindingKey}) {
1781                                $loadIsBoundIn->Add("newConnection");
1782                                $loadIsBoundIn->Put($pdbFree, $pdbBound);
1783                                $bindings{$bindingKey} = 1;
1784                            }
1785                        }
1786                    }
1787                    # Close off this project.
1788                    close PROJECT;
1789                }
1790          }          }
         close TMP;  
1791      }      }
1792      # Finish the load.      # Finish the load.
1793      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
1794      return $retVal;      return $retVal;
1795  }  }
1796    
1797    
1798  =head2 Internal Utility Methods  =head2 Internal Utility Methods
1799    
1800    =head3 SpecialAttribute
1801    
1802    C<< my $count = SproutLoad::SpecialAttribute($id, \@attributes, $idxMatch, \@idxValues, $pattern, $loader); >>
1803    
1804    Look for special attributes of a given type. A special attribute is found by comparing one of
1805    the columns of the incoming attribute list to a search pattern. If a match is found, then
1806    a set of columns is put into an output table connected to the specified ID.
1807    
1808    For example, when processing features, the attribute list we look at has three columns: attribute
1809    name, attribute value, and attribute value HTML. The IEDB attribute exists if the attribute name
1810    begins with C<iedb_>. The call signature is therefore
1811    
1812        my $found = SpecialAttribute($fid, \@attributeList, 0, [0,2], '^iedb_', $loadFeatureIEDB);
1813    
1814    The pattern is matched against column 0, and if we have a match, then column 2's value is put
1815    to the output along with the specified feature ID.
1816    
1817    =over 4
1818    
1819    =item id
1820    
1821    ID of the object whose special attributes are being loaded. This forms the first column of the
1822    output.
1823    
1824    =item attributes
1825    
1826    Reference to a list of tuples.
1827    
1828    =item idxMatch
1829    
1830    Index in each tuple of the column to be matched against the pattern. If the match is
1831    successful, an output record will be generated.
1832    
1833    =item idxValues
1834    
1835    Reference to a list containing the indexes in each tuple of the columns to be put as
1836    the second column of the output.
1837    
1838    =item pattern
1839    
1840    Pattern to be matched against the specified column. The match will be case-insensitive.
1841    
1842    =item loader
1843    
1844    An object to which each output record will be put. Usually this is an B<ERDBLoad> object,
1845    but technically it could be anything with a C<Put> method.
1846    
1847    =item RETURN
1848    
1849    Returns a count of the matches found.
1850    
1851    =item
1852    
1853    =back
1854    
1855    =cut
1856    
1857    sub SpecialAttribute {
1858        # Get the parameters.
1859        my ($id, $attributes, $idxMatch, $idxValues, $pattern, $loader) = @_;
1860        # Declare the return variable.
1861        my $retVal = 0;
1862        # Loop through the attribute rows.
1863        for my $row (@{$attributes}) {
1864            # Check for a match.
1865            if ($row->[$idxMatch] =~ m/$pattern/i) {
1866                # We have a match, so output a row. This is a bit tricky, since we may
1867                # be putting out multiple columns of data from the input.
1868                my $value = join(" ", map { $row->[$_] } @{$idxValues});
1869                $loader->Put($id, $value);
1870                $retVal++;
1871            }
1872        }
1873        Trace("$retVal special attributes found for $id and loader " . $loader->RelName() . ".") if T(4) && $retVal;
1874        # Return the number of matches.
1875        return $retVal;
1876    }
1877    
1878    =head3 CreatePDB
1879    
1880    C<< $loader->CreatePDB($pdbID, $title, $type, \%pdbHash); >>
1881    
1882    Insure that a PDB record exists for the identified PDB. If one does not exist, it will be
1883    created.
1884    
1885    =over 4
1886    
1887    =item pdbID
1888    
1889    ID string (usually an unqualified file name) for the desired PDB.
1890    
1891    =item title
1892    
1893    Title to use if the PDB must be created.
1894    
1895    =item type
1896    
1897    Type of PDB: C<free> or C<bound>
1898    
1899    =item pdbHash
1900    
1901    Hash containing the IDs of PDBs that have already been created.
1902    
1903    =item pdbLoader
1904    
1905    Load object for the PDB table.
1906    
1907    =back
1908    
1909    =cut
1910    
1911    sub CreatePDB {
1912        # Get the parameters.
1913        my ($self, $pdbID, $title, $type, $pdbHash, $pdbLoader) = @_;
1914        $pdbLoader->Add("PDB check");
1915        # Check to see if this is a new PDB.
1916        if (! exists $pdbHash->{$pdbID}) {
1917            # It is, so we create it.
1918            $pdbLoader->Put($pdbID, $title, $type);
1919            $pdbHash->{$pdbID} = 1;
1920            # Count it.
1921            $pdbLoader->Add("PDB-$type");
1922        }
1923    }
1924    
1925  =head3 TableLoader  =head3 TableLoader
1926    
1927  Create an ERDBLoad object for the specified table. The object is also added to  Create an ERDBLoad object for the specified table. The object is also added to
# Line 1406  Line 1936 
1936    
1937  Name of the table (relation) being loaded.  Name of the table (relation) being loaded.
1938    
1939  =item rowCount (optional)  =item ignore
1940    
1941  Estimated maximum number of rows in the table.  TRUE if the table should be ignored entirely, else FALSE.
1942    
1943  =item RETURN  =item RETURN
1944    
# Line 1420  Line 1950 
1950    
1951  sub _TableLoader {  sub _TableLoader {
1952      # Get the parameters.      # Get the parameters.
1953      my ($self, $tableName, $rowCount) = @_;      my ($self, $tableName, $ignore) = @_;
1954      # Create the load object.      # Create the load object.
1955      my $retVal = ERDBLoad->new($self->{erdb}, $tableName, $self->{loadDirectory}, $rowCount);      my $retVal = ERDBLoad->new($self->{erdb}, $tableName, $self->{loadDirectory}, $self->LoadOnly,
1956                                   $ignore);
1957      # Cache it in the loader list.      # Cache it in the loader list.
1958      push @{$self->{loaders}}, $retVal;      push @{$self->{loaders}}, $retVal;
1959      # Return it to the caller.      # Return it to the caller.
# Line 1456  Line 1987 
1987      my $retVal = Stats->new();      my $retVal = Stats->new();
1988      # Get the loader list.      # Get the loader list.
1989      my $loadList = $self->{loaders};      my $loadList = $self->{loaders};
1990        # Create a hash to hold the statistics objects, keyed on relation name.
1991        my %loaderHash = ();
1992      # Loop through the list, finishing the loads. Note that if the finish fails, we die      # Loop through the list, finishing the loads. Note that if the finish fails, we die
1993      # ignominiously. At some future point, we want to make the loads restartable.      # ignominiously. At some future point, we want to make the loads more restartable.
1994      while (my $loader = pop @{$loadList}) {      while (my $loader = pop @{$loadList}) {
1995          # Trace the fact that we're cleaning up.          # Get the relation name.
1996          my $relName = $loader->RelName;          my $relName = $loader->RelName;
1997          Trace("Finishing load for $relName.") if T(2);          # Check the ignore flag.
1998            if ($loader->Ignore) {
1999                Trace("Relation $relName not loaded.") if T(2);
2000            } else {
2001                # Here we really need to finish.
2002                Trace("Finishing $relName.") if T(2);
2003          my $stats = $loader->Finish();          my $stats = $loader->Finish();
2004                $loaderHash{$relName} = $stats;
2005            }
2006        }
2007        # Now we loop through again, actually loading the tables. We want to finish before
2008        # loading so that if something goes wrong at this point, all the load files are usable
2009        # and we don't have to redo all that work.
2010        for my $relName (sort keys %loaderHash) {
2011            # Get the statistics for this relation.
2012            my $stats = $loaderHash{$relName};
2013            # Check for a database load.
2014          if ($self->{options}->{dbLoad}) {          if ($self->{options}->{dbLoad}) {
2015              # Here we want to use the load file just created to load the database.              # Here we want to use the load file just created to load the database.
2016              Trace("Loading relation $relName.") if T(2);              Trace("Loading relation $relName.") if T(2);
# Line 1476  Line 2024 
2024      # Return the load statistics.      # Return the load statistics.
2025      return $retVal;      return $retVal;
2026  }  }
2027    =head3 GetGenomeAttributes
2028    
2029    C<< my $aHashRef = GetGenomeAttributes($fig, $genomeID, \@fids); >>
2030    
2031    Return a hash of attributes keyed on feature ID. This method gets all the attributes
2032    for all the features of a genome in a single call, then organizes them into a hash.
2033    
2034    =over 4
2035    
2036    =item fig
2037    
2038    FIG-like object for accessing attributes.
2039    
2040    =item genomeID
2041    
2042    ID of the genome who's attributes are desired.
2043    
2044    =item fids
2045    
2046    Reference to a list of the feature IDs whose attributes are to be kept.
2047    
2048    =item RETURN
2049    
2050    Returns a reference to a hash. The key of the hash is the feature ID. The value is the
2051    reference to a list of the feature's attribute tuples. Each tuple contains the feature ID,
2052    the attribute key, and one or more attribute values.
2053    
2054    =back
2055    
2056    =cut
2057    
2058    sub GetGenomeAttributes {
2059        # Get the parameters.
2060        my ($fig, $genomeID, $fids) = @_;
2061        # Declare the return variable.
2062        my $retVal = {};
2063        # Get the attributes.
2064        my @aList = $fig->get_attributes("fig|$genomeID%");
2065        # Initialize the hash. This not only enables us to easily determine which FIDs to
2066        # keep, it insures that the caller sees a list reference for every known fid,
2067        # simplifying the logic.
2068        for my $fid (@{$fids}) {
2069            $retVal->{$fid} = [];
2070        }
2071        # Populate the hash.
2072        for my $aListEntry (@aList) {
2073            my $fid = $aListEntry->[0];
2074            if (exists $retVal->{$fid}) {
2075                push @{$retVal->{$fid}}, $aListEntry;
2076            }
2077        }
2078        # Return the result.
2079        return $retVal;
2080    }
2081    
2082  1;  1;

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3