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

Diff of /Sprout/SproutLoad.pm

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

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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3