[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.26, Mon Jan 30 21:57:02 2006 UTC revision 1.79, Sat Nov 18 20:38:45 2006 UTC
# Line 30  Line 30 
30      $stats->Accumulate($spl->LoadFeatureData());      $stats->Accumulate($spl->LoadFeatureData());
31      print $stats->Show();      print $stats->Show();
32    
 This module makes use of the internal Sprout property C<_erdb>.  
   
33  It is worth noting that the FIG object does not need to be a real one. Any object  It is worth noting that the FIG object does not need to be a real one. Any object
34  that implements the FIG methods for data retrieval could be used. So, for example,  that implements the FIG methods for data retrieval could be used. So, for example,
35  this object could be used to copy data from one Sprout database to another, or  this object could be used to copy data from one Sprout database to another, or
# Line 80  Line 78 
78  =item subsysFile  =item subsysFile
79    
80  Either the name of the file containing the list of trusted subsystems or a reference  Either the name of the file containing the list of trusted subsystems or a reference
81  to a list of subsystem names. If nothing is specified, all known subsystems will be  to a list of subsystem names. If nothing is specified, all NMPDR subsystems will be
82  considered trusted. Only subsystem data related to the trusted subsystems is loaded.  considered trusted. (A subsystem is considered NMPDR if it has a file named C<NMPDR>
83    in its data directory.) Only subsystem data related to the NMPDR subsystems is loaded.
84    
85  =item options  =item options
86    
# Line 94  Line 93 
93  sub new {  sub new {
94      # Get the parameters.      # Get the parameters.
95      my ($class, $sprout, $fig, $genomeFile, $subsysFile, $options) = @_;      my ($class, $sprout, $fig, $genomeFile, $subsysFile, $options) = @_;
96      # Load the list of genomes into a hash.      # Create the genome hash.
97      my %genomes;      my %genomes = ();
98        # We only need it if load-only is NOT specified.
99        if (! $options->{loadOnly}) {
100      if (! defined($genomeFile) || $genomeFile eq '') {      if (! defined($genomeFile) || $genomeFile eq '') {
101          # Here we want all the complete genomes and an access code of 1.          # Here we want all the complete genomes and an access code of 1.
102          my @genomeList = $fig->genomes(1);          my @genomeList = $fig->genomes(1);
# Line 119  Line 120 
120                  # an omitted access code can be defaulted to 1.                  # an omitted access code can be defaulted to 1.
121                  for my $genomeLine (@genomeList) {                  for my $genomeLine (@genomeList) {
122                      my ($genomeID, $accessCode) = split("\t", $genomeLine);                      my ($genomeID, $accessCode) = split("\t", $genomeLine);
123                      if (undef $accessCode) {                          if (! defined($accessCode)) {
124                          $accessCode = 1;                          $accessCode = 1;
125                      }                      }
126                      $genomes{$genomeID} = $accessCode;                      $genomes{$genomeID} = $accessCode;
# Line 129  Line 130 
130              Confess("Invalid genome parameter ($type) in SproutLoad constructor.");              Confess("Invalid genome parameter ($type) in SproutLoad constructor.");
131          }          }
132      }      }
133        }
134      # Load the list of trusted subsystems.      # Load the list of trusted subsystems.
135      my %subsystems = ();      my %subsystems = ();
136        # We only need it if load-only is NOT specified.
137        if (! $options->{loadOnly}) {
138      if (! defined $subsysFile || $subsysFile eq '') {      if (! defined $subsysFile || $subsysFile eq '') {
139          # Here we want all the subsystems.              # Here we want all the usable subsystems. First we get the whole list.
140          %subsystems = map { $_ => 1 } $fig->all_subsystems();              my @subs = $fig->all_subsystems();
141                # Loop through, checking for the NMPDR file.
142                for my $sub (@subs) {
143                    if ($fig->nmpdr_subsystem($sub)) {
144                        $subsystems{$sub} = 1;
145                    }
146                }
147      } else {      } else {
148          my $type = ref $subsysFile;          my $type = ref $subsysFile;
149          if ($type eq 'ARRAY') {          if ($type eq 'ARRAY') {
# Line 153  Line 163 
163              Confess("Invalid subsystem parameter in SproutLoad constructor.");              Confess("Invalid subsystem parameter in SproutLoad constructor.");
164          }          }
165      }      }
166            # Go through the subsys hash again, creating the keyword list for each subsystem.
167            for my $subsystem (keys %subsystems) {
168                my $name = $subsystem;
169                $name =~ s/_/ /g;
170                my $classes = $fig->subsystem_classification($subsystem);
171                $name .= " " . join(" ", @{$classes});
172                $subsystems{$subsystem} = $name;
173            }
174        }
175      # Get the data directory from the Sprout object.      # Get the data directory from the Sprout object.
176      my ($directory) = $sprout->LoadInfo();      my ($directory) = $sprout->LoadInfo();
177      # Create the Sprout load object.      # Create the Sprout load object.
# Line 162  Line 181 
181                    subsystems => \%subsystems,                    subsystems => \%subsystems,
182                    sprout => $sprout,                    sprout => $sprout,
183                    loadDirectory => $directory,                    loadDirectory => $directory,
184                    erdb => $sprout->{_erdb},                    erdb => $sprout,
185                    loaders => [],                    loaders => [],
186                    options => $options                    options => $options
187                   };                   };
# Line 250  Line 269 
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 330  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');      my $loadCoupling = $self->_TableLoader('Coupling');
366      my $loadIsEvidencedBy = $self->_TableLoader('IsEvidencedBy', $self->PrimaryOnly);      my $loadIsEvidencedBy = $self->_TableLoader('IsEvidencedBy', $self->PrimaryOnly);
# Line 365  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 401  Line 430 
430                              }                              }
431                          }                          }
432                          for my $evidenceID (keys %evidenceMap) {                          for my $evidenceID (keys %evidenceMap) {
433                                # Get the ID for this evidence.
434                                $pchID++;
435                              # Create the evidence record.                              # Create the evidence record.
436                              my ($peg3, $peg4, $usage) = @{$evidenceMap{$evidenceID}};                              my ($peg3, $peg4, $usage) = @{$evidenceMap{$evidenceID}};
437                              $loadPCH->Put($evidenceID, $usage);                              $loadPCH->Put($pchID, $usage);
438                              # Connect it to the coupling.                              # Connect it to the coupling.
439                              $loadIsEvidencedBy->Put($coupleID, $evidenceID);                              $loadIsEvidencedBy->Put($coupleID, $pchID);
440                              # Connect it to the features.                              # Connect it to the features.
441                              $loadUsesAsEvidence->Put($evidenceID, $peg3, 1);                              $loadUsesAsEvidence->Put($pchID, $peg3, 1);
442                              $loadUsesAsEvidence->Put($evidenceID, $peg4, 2);                              $loadUsesAsEvidence->Put($pchID, $peg4, 2);
443                          }                          }
444                      }                      }
445                  }                  }
# Line 436  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 450  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};
494      # Create load objects for each of the tables we're loading.      # Create load objects for each of the tables we're loading.
# Line 461  Line 498 
498      my $loadFeatureLink = $self->_TableLoader('FeatureLink');      my $loadFeatureLink = $self->_TableLoader('FeatureLink');
499      my $loadFeatureTranslation = $self->_TableLoader('FeatureTranslation');      my $loadFeatureTranslation = $self->_TableLoader('FeatureTranslation');
500      my $loadFeatureUpstream = $self->_TableLoader('FeatureUpstream');      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();
# Line 474  Line 518 
518              $loadFeature->Add("genomeIn");              $loadFeature->Add("genomeIn");
519              # Get the feature list for this genome.              # Get the feature list for this genome.
520              my $features = $fig->all_features_detailed($genomeID);              my $features = $fig->all_features_detailed($genomeID);
521                # Sort and count the list.
522                my @featureTuples = sort { $a->[0] cmp $b->[0] } @{$features};
523                my $count = scalar @featureTuples;
524                Trace("$count features found for genome $genomeID.") if T(3);
525                # Set up for our duplicate-feature check.
526                my $oldFeatureID = "";
527              # Loop through the features.              # Loop through the features.
528              for my $featureData (@{$features}) {              for my $featureTuple (@featureTuples) {
                 $loadFeature->Add("featureIn");  
529                  # Split the tuple.                  # Split the tuple.
530                  my ($featureID, $locations, undef, $type) = @{$featureData};                  my ($featureID, $locations, undef, $type) = @{$featureTuple};
531                  # Create the feature record.                  # Check for duplicates.
532                  $loadFeature->Put($featureID, 1, $type);                  if ($featureID eq $oldFeatureID) {
533                        Trace("Duplicate feature $featureID found.") if T(1);
534                    } else {
535                        $oldFeatureID = $featureID;
536                        # Count this feature.
537                        $loadFeature->Add("featureIn");
538                        # Begin building the keywords. We start with the genome ID, the
539                        # feature ID, the taxonomy, and the organism name.
540                        my @keywords = ($genomeID, $featureID, $fig->genus_species($genomeID),
541                                        $fig->taxonomy_of($genomeID));
542                        # Get the functional assignment and aliases. This
543                        # depends on the feature type.
544                        my $assignment;
545                        if ($type eq "peg") {
546                            $assignment = $fig->function_of($featureID);
547                  # Create the aliases.                  # Create the aliases.
548                  for my $alias ($fig->feature_aliases($featureID)) {                  for my $alias ($fig->feature_aliases($featureID)) {
549                      $loadFeatureAlias->Put($featureID, $alias);                      $loadFeatureAlias->Put($featureID, $alias);
550                                push @keywords, $alias;
551                            }
552                        } else {
553                            # For other types, the assignment is the first (and ONLY) alias.
554                            ($assignment) = $fig->feature_aliases($featureID);
555                  }                  }
556                        Trace("Assignment for $featureID is: $assignment") if T(4);
557                        # Break the assignment into words and shove it onto the
558                        # keyword list.
559                        push @keywords, split(/\s+/, $assignment);
560                        # Link this feature to the parent genome.
561                        $loadHasFeature->Put($genomeID, $featureID, $type);
562                  # Get the links.                  # Get the links.
563                  my @links = $fig->fid_links($featureID);                  my @links = $fig->fid_links($featureID);
564                  for my $link (@links) {                  for my $link (@links) {
# Line 503  Line 577 
577                          $loadFeatureUpstream->Put($featureID, $upstream);                          $loadFeatureUpstream->Put($featureID, $upstream);
578                      }                      }
579                  }                  }
580                        # Now we need to find the subsystems this feature participates in.
581                        # We also add the subsystems to the keyword list. Before we do that,
582                        # we must convert underscores to spaces and tack on the classifications.
583                        my @subsystems = $fig->peg_to_subsystems($featureID);
584                        for my $subsystem (@subsystems) {
585                            # Only proceed if we like this subsystem.
586                            if (exists $subHash->{$subsystem}) {
587                                # Store the has-role link.
588                                $loadHasRoleInSubsystem->Put($featureID, $subsystem, $genomeID, $type);
589                                # Save the subsystem's keyword data.
590                                my $subKeywords = $subHash->{$subsystem};
591                                push @keywords, split /\s+/, $subKeywords;
592                                # Now we need to get this feature's role in the subsystem.
593                                my $subObject = $fig->get_subsystem($subsystem);
594                                my @roleColumns = $subObject->get_peg_roles($featureID);
595                                my @allRoles = $subObject->get_roles();
596                                for my $col (@roleColumns) {
597                                    my $role = $allRoles[$col];
598                                    push @keywords, split /\s+/, $role;
599                                    push @keywords, $subObject->get_role_abbr($col);
600                                }
601                            }
602                        }
603                        # There are three special attributes computed from property
604                        # data that we build next. If the special attribute is non-empty,
605                        # its name will be added to the keyword list. First, we get all
606                        # the attributes for this feature. They will come back as
607                        # 4-tuples: [peg, name, value, URL]. We use a 3-tuple instead:
608                        # [name, value, value with URL]. (We don't need the PEG, since
609                        # we already know it.)
610                        my @attributes = map { [$_->[1], $_->[2], Tracer::CombineURL($_->[2], $_->[3])] }
611                                             $fig->get_attributes($featureID);
612                        # Now we process each of the special attributes.
613                        if (SpecialAttribute($featureID, \@attributes,
614                                             1, [0,2], '^(essential|potential_essential)$',
615                                             $loadFeatureEssential)) {
616                            push @keywords, 'essential';
617                            $loadFeature->Add('essential');
618                        }
619                        if (SpecialAttribute($featureID, \@attributes,
620                                             0, [2], '^virulen',
621                                             $loadFeatureVirulent)) {
622                            push @keywords, 'virulent';
623                            $loadFeature->Add('virulent');
624                        }
625                        if (SpecialAttribute($featureID, \@attributes,
626                                             0, [0,2], '^iedb_',
627                                             $loadFeatureIEDB)) {
628                            push @keywords, 'iedb';
629                            $loadFeature->Add('iedb');
630                        }
631                        # Now we need to bust up hyphenated words in the keyword
632                        # list. We keep them separate and put them at the end so
633                        # the original word order is available.
634                        my $keywordString = "";
635                        my $bustedString = "";
636                        for my $keyword (@keywords) {
637                            if (length $keyword >= 4) {
638                                $keywordString .= " $keyword";
639                                if ($keyword =~ /-/) {
640                                    my @words = grep { length($_) >= 4 } split /-/, $keyword;
641                                    $bustedString .= join(" ", "", @words);
642                                }
643                            }
644                        }
645                        $keywordString .= $bustedString;
646                        # Get rid of annoying punctuation.
647                        $keywordString =~ s/[();]//g;
648                        # Clean the keyword list.
649                        my $cleanWords = $sprout->CleanKeywords($keywordString);
650                        Trace("Keyword string for $featureID: $cleanWords") if T(4);
651                        # Create the feature record.
652                        $loadFeature->Put($featureID, 1, $type, $assignment, $cleanWords);
653                  # This part is the roughest. We need to relate the features to contig                  # This part is the roughest. We need to relate the features to contig
654                  # locations, and the locations must be split so that none of them exceed                  # locations, and the locations must be split so that none of them exceed
655                  # the maximum segment size. This simplifies the genes_in_region processing                  # the maximum segment size. This simplifies the genes_in_region processing
# Line 532  Line 679 
679              }              }
680          }          }
681      }      }
     # 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};  
     # Create load objects for each of the tables we're loading.  
     my $loadIsBidirectionalBestHitOf = $self->_TableLoader('IsBidirectionalBestHitOf');  
     if ($self->{options}->{loadOnly}) {  
         Trace("Loading from existing files.") if T(2);  
     } else {  
         Trace("Generating BBH data.") 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);  
                     }  
                 }  
             }  
         }  
682      }      }
683      # Finish the loads.      # Finish the loads.
684      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
# Line 620  Line 700 
700  The following relations are loaded by this method.  The following relations are loaded by this method.
701    
702      Subsystem      Subsystem
703        SubsystemClass
704      Role      Role
705      RoleEC      RoleEC
706      SSCell      SSCell
# Line 682  Line 763 
763      my $loadConsistsOfGenomes = $self->_TableLoader('ConsistsOfGenomes', $self->PrimaryOnly);      my $loadConsistsOfGenomes = $self->_TableLoader('ConsistsOfGenomes', $self->PrimaryOnly);
764      my $loadHasRoleSubset = $self->_TableLoader('HasRoleSubset', $self->PrimaryOnly);      my $loadHasRoleSubset = $self->_TableLoader('HasRoleSubset', $self->PrimaryOnly);
765      my $loadHasGenomeSubset = $self->_TableLoader('HasGenomeSubset', $self->PrimaryOnly);      my $loadHasGenomeSubset = $self->_TableLoader('HasGenomeSubset', $self->PrimaryOnly);
766        my $loadSubsystemClass = $self->_TableLoader('SubsystemClass', $self->PrimaryOnly);
767      if ($self->{options}->{loadOnly}) {      if ($self->{options}->{loadOnly}) {
768          Trace("Loading from existing files.") if T(2);          Trace("Loading from existing files.") if T(2);
769      } else {      } else {
# Line 697  Line 779 
779          my ($genomeID, $roleID);          my ($genomeID, $roleID);
780          my %roleData = ();          my %roleData = ();
781          for my $subsysID (@subsysIDs) {          for my $subsysID (@subsysIDs) {
             Trace("Creating subsystem $subsysID.") if T(3);  
             $loadSubsystem->Add("subsystemIn");  
782              # Get the subsystem object.              # Get the subsystem object.
783              my $sub = $fig->get_subsystem($subsysID);              my $sub = $fig->get_subsystem($subsysID);
784                # Only proceed if the subsystem has a spreadsheet.
785                if (! $sub->{empty_ss}) {
786                    Trace("Creating subsystem $subsysID.") if T(3);
787                    $loadSubsystem->Add("subsystemIn");
788              # Create the subsystem record.              # Create the subsystem record.
789              my $curator = $sub->get_curator();              my $curator = $sub->get_curator();
790              my $notes = $sub->get_notes();              my $notes = $sub->get_notes();
791              $loadSubsystem->Put($subsysID, $curator, $notes);              $loadSubsystem->Put($subsysID, $curator, $notes);
792                    # Now for the classification string. This comes back as a list
793                    # reference and we convert it to a space-delimited string.
794                    my $classList = $fig->subsystem_classification($subsysID);
795                    my $classString = join($FIG_Config::splitter, grep { $_ } @$classList);
796                    $loadSubsystemClass->Put($subsysID, $classString);
797              # Connect it to its roles. Each role is a column in the subsystem spreadsheet.              # Connect it to its roles. Each role is a column in the subsystem spreadsheet.
798              for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {              for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {
799                  # Connect to this role.                  # Connect to this role.
# Line 748  Line 837 
837                      # part of the spreadsheet cell ID.                      # part of the spreadsheet cell ID.
838                      for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {                      for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {
839                          # Get the features in the spreadsheet cell for this genome and role.                          # Get the features in the spreadsheet cell for this genome and role.
840                          my @pegs = $sub->get_pegs_from_cell($row, $col);                              my @pegs = grep { !$fig->is_deleted_fid($_) } $sub->get_pegs_from_cell($row, $col);
841                          # Only proceed if features exist.                          # Only proceed if features exist.
842                          if (@pegs > 0) {                          if (@pegs > 0) {
843                              # Create the spreadsheet cell.                              # Create the spreadsheet cell.
# Line 769  Line 858 
858                      if ($pegCount > 0) {                      if ($pegCount > 0) {
859                          Trace("$pegCount PEGs in $cellCount cells for $genomeID.") if T(3);                          Trace("$pegCount PEGs in $cellCount cells for $genomeID.") if T(3);
860                          $loadParticipatesIn->Put($genomeID, $subsysID, $variantCode);                          $loadParticipatesIn->Put($genomeID, $subsysID, $variantCode);
                         # Partition the PEGs found into clusters.  
                         my @clusters = $fig->compute_clusters(\@pegsFound, $sub);  
861                          # Create a hash mapping PEG IDs to cluster numbers.                          # Create a hash mapping PEG IDs to cluster numbers.
862                          # We default to -1 for all of them.                          # We default to -1 for all of them.
863                          my %clusterOf = map { $_ => -1 } @pegsFound;                          my %clusterOf = map { $_ => -1 } @pegsFound;
864                                # Partition the PEGs found into clusters.
865                                my @clusters = $fig->compute_clusters([keys %clusterOf], $sub);
866                          for (my $i = 0; $i <= $#clusters; $i++) {                          for (my $i = 0; $i <= $#clusters; $i++) {
867                              my $subList = $clusters[$i];                              my $subList = $clusters[$i];
868                              for my $peg (@{$subList}) {                              for my $peg (@{$subList}) {
# Line 801  Line 890 
890                  # Connect the subset to the subsystem.                  # Connect the subset to the subsystem.
891                  $loadHasRoleSubset->Put($subsysID, $actualID);                  $loadHasRoleSubset->Put($subsysID, $actualID);
892                  # Connect the subset to its roles.                  # Connect the subset to its roles.
893                  my @roles = $sub->get_subset($subsetID);                      my @roles = $sub->get_subsetC_roles($subsetID);
894                  for my $roleID (@roles) {                  for my $roleID (@roles) {
895                      $loadConsistsOfRoles->Put($actualID, $roleID);                      $loadConsistsOfRoles->Put($actualID, $roleID);
896                  }                  }
# Line 821  Line 910 
910                  }                  }
911              }              }
912          }          }
913            }
914          # Now we loop through the diagrams. We need to create the diagram records          # Now we loop through the diagrams. We need to create the diagram records
915          # and link each diagram to its roles. Note that only roles which occur          # and link each diagram to its roles. Note that only roles which occur
916          # in subsystems (and therefore appear in the %ecToRoles hash) are          # in subsystems (and therefore appear in the %ecToRoles hash) are
# Line 906  Line 996 
996          my %propertyKeys = ();          my %propertyKeys = ();
997          my $nextID = 1;          my $nextID = 1;
998          # Loop through the genomes.          # Loop through the genomes.
999          for my $genomeID (keys %{$genomeHash}) {          for my $genomeID (sort keys %{$genomeHash}) {
1000              $loadProperty->Add("genomeIn");              $loadProperty->Add("genomeIn");
1001              Trace("Generating properties for $genomeID.") if T(3);              Trace("Generating properties for $genomeID.") if T(3);
1002              # Get the genome's features. The feature ID is the first field in the              # Get the genome's features. The feature ID is the first field in the
# Line 919  Line 1009 
1009              for my $fid (@features) {              for my $fid (@features) {
1010                  # Get all attributes for this feature. We do this one feature at a time                  # Get all attributes for this feature. We do this one feature at a time
1011                  # to insure we do not get any genome attributes.                  # to insure we do not get any genome attributes.
1012                  my @attributeList = $fig->get_attributes($fid, '', '', '');                  my @attributeList = $fig->get_attributes($fid);
1013                    # Add essentiality and virulence attributes.
1014                    if ($fig->essential($fid)) {
1015                        push @attributeList, [$fid, 'essential', 1, ''];
1016                    }
1017                    if ($fig->virulent($fid)) {
1018                        push @attributeList, [$fid, 'virulent', 1, ''];
1019                    }
1020                  if (scalar @attributeList) {                  if (scalar @attributeList) {
1021                      $featureCount++;                      $featureCount++;
1022                  }                  }
# Line 1015  Line 1112 
1112          # Loop through the genomes.          # Loop through the genomes.
1113          for my $genomeID (sort keys %{$genomeHash}) {          for my $genomeID (sort keys %{$genomeHash}) {
1114              Trace("Processing $genomeID.") if T(3);              Trace("Processing $genomeID.") if T(3);
             # Get the genome's PEGs.  
             my @pegs = $fig->pegs_of($genomeID);  
             for my $peg (@pegs) {  
                 Trace("Processing $peg.") if T(4);  
1115                  # Create a hash of timestamps. We use this to prevent duplicate time stamps                  # Create a hash of timestamps. We use this to prevent duplicate time stamps
1116                  # from showing up for a single PEG's annotations.                  # from showing up for a single PEG's annotations.
1117                  my %seenTimestamps = ();                  my %seenTimestamps = ();
1118                  # Loop through the annotations.              # Get the genome's annotations.
1119                  for my $tuple ($fig->feature_annotations($peg, "raw")) {              my @annotations = $fig->read_all_annotations($genomeID);
1120                      my ($fid, $timestamp, $user, $text) = @{$tuple};              Trace("Processing annotations.") if T(2);
1121                for my $tuple (@annotations) {
1122                    # Get the annotation tuple.
1123                    my ($peg, $timestamp, $user, $text) = @{$tuple};
1124                      # Here we fix up the annotation text. "\r" is removed,                      # Here we fix up the annotation text. "\r" is removed,
1125                      # and "\t" and "\n" are escaped. Note we use the "s"                  # and "\t" and "\n" are escaped. Note we use the "gs"
1126                      # modifier so that new-lines inside the text do not                      # modifier so that new-lines inside the text do not
1127                      # stop the substitution search.                      # stop the substitution search.
1128                      $text =~ s/\r//gs;                      $text =~ s/\r//gs;
# Line 1039  Line 1135 
1135                          # Here it's a number. We need to insure the one we use to form                          # Here it's a number. We need to insure the one we use to form
1136                          # the key is unique.                          # the key is unique.
1137                          my $keyStamp = $timestamp;                          my $keyStamp = $timestamp;
1138                          while ($seenTimestamps{$keyStamp}) {                      while ($seenTimestamps{"$peg:$keyStamp"}) {
1139                              $keyStamp++;                              $keyStamp++;
1140                          }                          }
                         $seenTimestamps{$keyStamp} = 1;  
1141                          my $annotationID = "$peg:$keyStamp";                          my $annotationID = "$peg:$keyStamp";
1142                        $seenTimestamps{$annotationID} = 1;
1143                          # Insure the user exists.                          # Insure the user exists.
1144                          if (! $users{$user}) {                          if (! $users{$user}) {
1145                              $loadSproutUser->Put($user, "SEED user");                              $loadSproutUser->Put($user, "SEED user");
# Line 1061  Line 1157 
1157                  }                  }
1158              }              }
1159          }          }
     }  
1160      # Finish the load.      # Finish the load.
1161      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
1162      return $retVal;      return $retVal;
# Line 1190  Line 1285 
1285      } else {      } else {
1286          Trace("Generating external data.") if T(2);          Trace("Generating external data.") if T(2);
1287          # We loop through the files one at a time. First, the organism file.          # We loop through the files one at a time. First, the organism file.
1288          Open(\*ORGS, "<$FIG_Config::global/ext_org.table");          Open(\*ORGS, "sort +0 -1 -u -t\"\t\" $FIG_Config::global/ext_org.table |");
1289          my $orgLine;          my $orgLine;
1290          while (defined($orgLine = <ORGS>)) {          while (defined($orgLine = <ORGS>)) {
1291              # Clean the input line.              # Clean the input line.
# Line 1202  Line 1297 
1297          close ORGS;          close ORGS;
1298          # Now the function file.          # Now the function file.
1299          my $funcLine;          my $funcLine;
1300          Open(\*FUNCS, "<$FIG_Config::global/ext_func.table");          Open(\*FUNCS, "sort +0 -1 -u -t\"\t\" $FIG_Config::global/ext_func.table |");
1301          while (defined($funcLine = <FUNCS>)) {          while (defined($funcLine = <FUNCS>)) {
1302              # Clean the line ending.              # Clean the line ending.
1303              chomp $funcLine;              chomp $funcLine;
# Line 1334  Line 1429 
1429    
1430      GenomeGroups      GenomeGroups
1431    
1432  There is no direct support for genome groups in FIG, so we access the SEED  Currently, we do not use groups. We used to use them for NMPDR groups,
1433    butThere is no direct support for genome groups in FIG, so we access the SEED
1434  files directly.  files directly.
1435    
1436  =over 4  =over 4
# Line 1360  Line 1456 
1456          Trace("Loading from existing files.") if T(2);          Trace("Loading from existing files.") if T(2);
1457      } else {      } else {
1458          Trace("Generating group data.") if T(2);          Trace("Generating group data.") if T(2);
1459            # Currently there are no groups.
1460        }
1461        # Finish the load.
1462        my $retVal = $self->_FinishAll();
1463        return $retVal;
1464    }
1465    
1466    =head3 LoadSynonymData
1467    
1468    C<< my $stats = $spl->LoadSynonymData(); >>
1469    
1470    Load the synonym groups into Sprout.
1471    
1472    The following relations are loaded by this method.
1473    
1474        SynonymGroup
1475        IsSynonymGroupFor
1476    
1477    The source information for these relations is taken from the C<maps_to_id> method
1478    of the B<FIG> object. Unfortunately, to make this work, we need to use direct
1479    SQL against the FIG database.
1480    
1481    =over 4
1482    
1483    =item RETURNS
1484    
1485    Returns a statistics object for the loads.
1486    
1487    =back
1488    
1489    =cut
1490    #: Return Type $%;
1491    sub LoadSynonymData {
1492        # Get this object instance.
1493        my ($self) = @_;
1494        # Get the FIG object.
1495        my $fig = $self->{fig};
1496        # Get the genome hash.
1497        my $genomeHash = $self->{genomes};
1498        # Create a load object for the table we're loading.
1499        my $loadSynonymGroup = $self->_TableLoader('SynonymGroup');
1500        my $loadIsSynonymGroupFor = $self->_TableLoader('IsSynonymGroupFor');
1501        if ($self->{options}->{loadOnly}) {
1502            Trace("Loading from existing files.") if T(2);
1503        } else {
1504            Trace("Generating synonym group data.") if T(2);
1505            # Get the database handle.
1506            my $dbh = $fig->db_handle();
1507            # Ask for the synonyms.
1508            my $sth = $dbh->prepare_command("SELECT maps_to, syn_id FROM peg_synonyms ORDER BY maps_to");
1509            my $result = $sth->execute();
1510            if (! defined($result)) {
1511                Confess("Database error in Synonym load: " . $sth->errstr());
1512            } else {
1513                # Remember the current synonym.
1514                my $current_syn = "";
1515                # Count the features.
1516                my $featureCount = 0;
1517                # Loop through the synonym/peg pairs.
1518                while (my @row = $sth->fetchrow()) {
1519                    # Get the synonym ID and feature ID.
1520                    my ($syn_id, $peg) = @row;
1521                    # Insure it's for one of our genomes.
1522                    my $genomeID = FIG::genome_of($peg);
1523                    if (exists $genomeHash->{$genomeID}) {
1524                        # Verify the synonym.
1525                        if ($syn_id ne $current_syn) {
1526                            # It's new, so put it in the group table.
1527                            $loadSynonymGroup->Put($syn_id);
1528                            $current_syn = $syn_id;
1529                        }
1530                        # Connect the synonym to the peg.
1531                        $loadIsSynonymGroupFor->Put($syn_id, $peg);
1532                        # Count this feature.
1533                        $featureCount++;
1534                        if ($featureCount % 1000 == 0) {
1535                            Trace("$featureCount features processed.") if T(3);
1536                        }
1537                    }
1538                }
1539            }
1540        }
1541        # Finish the load.
1542        my $retVal = $self->_FinishAll();
1543        return $retVal;
1544    }
1545    
1546    =head3 LoadFamilyData
1547    
1548    C<< my $stats = $spl->LoadFamilyData(); >>
1549    
1550    Load the protein families into Sprout.
1551    
1552    The following relations are loaded by this method.
1553    
1554        Family
1555        IsFamilyForFeature
1556    
1557    The source information for these relations is taken from the C<families_for_protein>,
1558    C<family_function>, and C<sz_family> methods of the B<FIG> object.
1559    
1560    =over 4
1561    
1562    =item RETURNS
1563    
1564    Returns a statistics object for the loads.
1565    
1566    =back
1567    
1568    =cut
1569    #: Return Type $%;
1570    sub LoadFamilyData {
1571        # Get this object instance.
1572        my ($self) = @_;
1573        # Get the FIG object.
1574        my $fig = $self->{fig};
1575        # Get the genome hash.
1576        my $genomeHash = $self->{genomes};
1577        # Create load objects for the tables we're loading.
1578        my $loadFamily = $self->_TableLoader('Family');
1579        my $loadIsFamilyForFeature = $self->_TableLoader('IsFamilyForFeature');
1580        if ($self->{options}->{loadOnly}) {
1581            Trace("Loading from existing files.") if T(2);
1582        } else {
1583            Trace("Generating family data.") if T(2);
1584            # Create a hash for the family IDs.
1585            my %familyHash = ();
1586          # Loop through the genomes.          # Loop through the genomes.
1587          my $line;          for my $genomeID (sort keys %{$genomeHash}) {
1588          for my $genomeID (keys %{$genomeHash}) {              Trace("Processing features for $genomeID.") if T(2);
1589              Trace("Processing $genomeID.") if T(3);              # Loop through this genome's PEGs.
1590              # Open the NMPDR group file for this genome.              for my $fid ($fig->all_features($genomeID, "peg")) {
1591              if (open(TMP, "<$FIG_Config::organisms/$genomeID/NMPDR") &&                  $loadIsFamilyForFeature->Add("features", 1);
1592                  defined($line = <TMP>)) {                  # Get this feature's families.
1593                  # Clean the line ending.                  my @families = $fig->families_for_protein($fid);
1594                  chomp $line;                  # Loop through the families, connecting them to the feature.
1595                  # Add the group to the table. Note that there can only be one group                  for my $family (@families) {
1596                  # per genome.                      $loadIsFamilyForFeature->Put($family, $fid);
1597                  $loadGenomeGroups->Put($genomeID, $line);                      # If this is a new family, create a record for it.
1598                        if (! exists $familyHash{$family}) {
1599                            $familyHash{$family} = 1;
1600                            $loadFamily->Add("families", 1);
1601                            my $size = $fig->sz_family($family);
1602                            my $func = $fig->family_function($family);
1603                            $loadFamily->Put($family, $size, $func);
1604                        }
1605                    }
1606              }              }
             close TMP;  
1607          }          }
1608      }      }
1609      # Finish the load.      # Finish the load.
# Line 1381  Line 1611 
1611      return $retVal;      return $retVal;
1612  }  }
1613    
1614    =head3 LoadDrugData
1615    
1616    C<< my $stats = $spl->LoadDrugData(); >>
1617    
1618    Load the drug target data into Sprout.
1619    
1620    The following relations are loaded by this method.
1621    
1622        DrugProject
1623        ContainsTopic
1624        DrugTopic
1625        ContainsAnalysisOf
1626        PDB
1627        IncludesBound
1628        IsBoundIn
1629        BindsWith
1630        Ligand
1631        DescribesProteinForFeature
1632        FeatureConservation
1633    
1634    The source information for these relations is taken from flat files in the
1635    C<$FIG_Config::drug_directory>. The file C<master_tables.list> contains
1636    a list of drug project names paired with file names. The named file (in the
1637    same directory) contains all the data for the project.
1638    
1639    =over 4
1640    
1641    =item RETURNS
1642    
1643    Returns a statistics object for the loads.
1644    
1645    =back
1646    
1647    =cut
1648    #: Return Type $%;
1649    sub LoadDrugData {
1650        # Get this object instance.
1651        my ($self) = @_;
1652        # Get the FIG object.
1653        my $fig = $self->{fig};
1654        # Get the genome hash.
1655        my $genomeHash = $self->{genomes};
1656        # Create load objects for the tables we're loading.
1657        my $loadDrugProject = $self->_TableLoader('DrugProject');
1658        my $loadContainsTopic = $self->_TableLoader('ContainsTopic');
1659        my $loadDrugTopic = $self->_TableLoader('DrugTopic');
1660        my $loadContainsAnalysisOf = $self->_TableLoader('ContainsAnalysisOf');
1661        my $loadPDB = $self->_TableLoader('PDB');
1662        my $loadIncludesBound = $self->_TableLoader('IncludesBound');
1663        my $loadIsBoundIn = $self->_TableLoader('IsBoundIn');
1664        my $loadBindsWith = $self->_TableLoader('BindsWith');
1665        my $loadLigand = $self->_TableLoader('Ligand');
1666        my $loadDescribesProteinForFeature = $self->_TableLoader('DescribesProteinForFeature');
1667        my $loadFeatureConservation = $self->_TableLoader('FeatureConservation');
1668        if ($self->{options}->{loadOnly}) {
1669            Trace("Loading from existing files.") if T(2);
1670        } else {
1671            Trace("Generating drug target data.") if T(2);
1672            # Load the project list. The file comes in as a list of chomped lines,
1673            # and we split them on the TAB character to make the project name the
1674            # key and the file name the value of the resulting hash.
1675            my %projects = map { split /\t/, $_ } Tracer::GetFile("$FIG_Config::drug_directory/master_tables.list");
1676            # Create hashes for the derived objects: PDBs, Features, and Ligands. These objects
1677            # may occur multiple times in a single project file or even in multiple project
1678            # files.
1679            my %ligands = ();
1680            my %pdbs = ();
1681            my %features = ();
1682            my %bindings = ();
1683            # Set up a counter for drug topics. This will be used as the key.
1684            my $topicCounter = 0;
1685            # Loop through the projects. We sort the keys not because we need them sorted, but
1686            # because it makes it easier to infer our progress from trace messages.
1687            for my $project (sort keys %projects) {
1688                Trace("Processing project $project.") if T(3);
1689                # Only proceed if the download file exists.
1690                my $projectFile = "$FIG_Config::drug_directory/$projects{$project}";
1691                if (! -f $projectFile) {
1692                    Trace("Project file $projectFile not found.") if T(0);
1693                } else {
1694                    # Create the project record.
1695                    $loadDrugProject->Put($project);
1696                    # Create a hash for the topics. Each project has one or more topics. The
1697                    # topic is identified by a URL, a category, and an identifier.
1698                    my %topics = ();
1699                    # Now we can open the project file.
1700                    Trace("Reading project file $projectFile.") if T(3);
1701                    Open(\*PROJECT, "<$projectFile");
1702                    # Get the first record, which is a list of column headers. We don't use this
1703                    # for anything, but it may be useful for debugging.
1704                    my $headerLine = <PROJECT>;
1705                    # Loop through the rest of the records.
1706                    while (! eof PROJECT) {
1707                        # Get the current line of data. Note that not all lines will have all
1708                        # the fields. In particular, the CLIBE data is fairly rare.
1709                        my ($authorOrganism, $category, $tag, $refURL, $peg, $conservation,
1710                            $pdbBound, $pdbBoundEval, $pdbFree, $pdbFreeEval, $pdbFreeTitle,
1711                            $protDistInfo, $passAspInfo, $passAspFile, $passWeightInfo,
1712                            $passWeightFile, $clibeInfo, $clibeURL, $clibeTotalEnergy,
1713                            $clibeVanderwaals, $clibeHBonds, $clibeEI, $clibeSolvationE)
1714                           = Tracer::GetLine(\*PROJECT);
1715                        # The tag contains an identifier for the current line of data followed
1716                        # by a text statement that generally matches a property name in the
1717                        # main database. We split it up, since the identifier goes with
1718                        # the PDB data and the text statement is part of the topic.
1719                        my ($lineID, $topicTag) = split /\s*,\s*/, $tag;
1720                        $loadDrugProject->Add("data line");
1721                        # Check for a new topic.
1722                        my $topicData = "$category\t$topicTag\t$refURL";
1723                        if (! exists $topics{$topicData}) {
1724                            # Here we have a new topic. Compute its ID.
1725                            $topicCounter++;
1726                            $topics{$topicData} = $topicCounter;
1727                            # Create its database record.
1728                            $loadDrugTopic->Put($topicCounter, $refURL, $category, $authorOrganism,
1729                                                $topicTag);
1730                            # Connect it to the project.
1731                            $loadContainsTopic->Put($project, $topicCounter);
1732                            $loadDrugTopic->Add("topic");
1733                        }
1734                        # Now we know the topic ID exists in the hash and the topic will
1735                        # appear in the database, so we get this topic's ID.
1736                        my $topicID = $topics{$topicData};
1737                        # If the feature in this line is new, we need to save its conservation
1738                        # number.
1739                        if (! exists $features{$peg}) {
1740                            $loadFeatureConservation->Put($peg, $conservation);
1741                            $features{$peg} = 1;
1742                        }
1743                        # Now we have two PDBs to deal with-- a bound PDB and a free PDB.
1744                        # The free PDB will have data about docking points; the bound PDB
1745                        # will have data about docking. We store both types as PDBs, and
1746                        # the special data comes from relationships. First we process the
1747                        # bound PDB.
1748                        if ($pdbBound) {
1749                            $loadPDB->Add("bound line");
1750                            # Insure this PDB is in the database.
1751                            $self->CreatePDB($pdbBound, lc "$pdbFreeTitle (bound)", "bound", \%pdbs, $loadPDB);
1752                            # Connect it to this topic.
1753                            $loadIncludesBound->Put($topicID, $pdbBound);
1754                            # Check for CLIBE data.
1755                            if ($clibeInfo) {
1756                                $loadLigand->Add("clibes");
1757                                # We have CLIBE data, so we create a ligand and relate it to the PDB.
1758                                if (! exists $ligands{$clibeInfo}) {
1759                                    # This is a new ligand, so create its record.
1760                                    $loadLigand->Put($clibeInfo);
1761                                    $loadLigand->Add("ligand");
1762                                    # Make sure we know this ligand already exists.
1763                                    $ligands{$clibeInfo} = 1;
1764                                }
1765                                # Now connect the PDB to the ligand using the CLIBE data.
1766                                $loadBindsWith->Put($pdbBound, $clibeInfo, $clibeURL, $clibeHBonds, $clibeEI,
1767                                                    $clibeSolvationE, $clibeVanderwaals);
1768                            }
1769                            # Connect this PDB to the feature.
1770                            $loadDescribesProteinForFeature->Put($pdbBound, $peg, $protDistInfo, $pdbBoundEval);
1771                        }
1772                        # Next is the free PDB.
1773                        if ($pdbFree) {
1774                            $loadPDB->Add("free line");
1775                            # Insure this PDB is in the database.
1776                            $self->CreatePDB($pdbFree, lc $pdbFreeTitle, "free", \%pdbs, $loadPDB);
1777                            # Connect it to this topic.
1778                            $loadContainsAnalysisOf->Put($topicID, $pdbFree, $passAspInfo,
1779                                                         $passWeightFile, $passWeightInfo, $passAspFile);
1780                            # Connect this PDB to the feature.
1781                            $loadDescribesProteinForFeature->Put($pdbFree, $peg, $protDistInfo, $pdbFreeEval);
1782                        }
1783                        # If we have both PDBs, we may need to link them.
1784                        if ($pdbFree && $pdbBound) {
1785                            $loadIsBoundIn->Add("connection");
1786                            # Insure we only link them once.
1787                            my $bindingKey =  "$pdbFree\t$pdbBound";
1788                            if (! exists $bindings{$bindingKey}) {
1789                                $loadIsBoundIn->Add("newConnection");
1790                                $loadIsBoundIn->Put($pdbFree, $pdbBound);
1791                                $bindings{$bindingKey} = 1;
1792                            }
1793                        }
1794                    }
1795                    # Close off this project.
1796                    close PROJECT;
1797                }
1798            }
1799        }
1800        # Finish the load.
1801        my $retVal = $self->_FinishAll();
1802        return $retVal;
1803    }
1804    
1805    
1806  =head2 Internal Utility Methods  =head2 Internal Utility Methods
1807    
1808    =head3 SpecialAttribute
1809    
1810    C<< my $count = SproutLoad::SpecialAttribute($id, \@attributes, $idxMatch, \@idxValues, $pattern, $loader); >>
1811    
1812    Look for special attributes of a given type. A special attribute is found by comparing one of
1813    the columns of the incoming attribute list to a search pattern. If a match is found, then
1814    a set of columns is put into an output table connected to the specified ID.
1815    
1816    For example, when processing features, the attribute list we look at has three columns: attribute
1817    name, attribute value, and attribute value HTML. The IEDB attribute exists if the attribute name
1818    begins with C<iedb_>. The call signature is therefore
1819    
1820        my $found = SpecialAttribute($fid, \@attributeList, 0, [0,2], '^iedb_', $loadFeatureIEDB);
1821    
1822    The pattern is matched against column 0, and if we have a match, then column 2's value is put
1823    to the output along with the specified feature ID.
1824    
1825    =over 4
1826    
1827    =item id
1828    
1829    ID of the object whose special attributes are being loaded. This forms the first column of the
1830    output.
1831    
1832    =item attributes
1833    
1834    Reference to a list of tuples.
1835    
1836    =item idxMatch
1837    
1838    Index in each tuple of the column to be matched against the pattern. If the match is
1839    successful, an output record will be generated.
1840    
1841    =item idxValues
1842    
1843    Reference to a list containing the indexes in each tuple of the columns to be put as
1844    the second column of the output.
1845    
1846    =item pattern
1847    
1848    Pattern to be matched against the specified column. The match will be case-insensitive.
1849    
1850    =item loader
1851    
1852    An object to which each output record will be put. Usually this is an B<ERDBLoad> object,
1853    but technically it could be anything with a C<Put> method.
1854    
1855    =item RETURN
1856    
1857    Returns a count of the matches found.
1858    
1859    =item
1860    
1861    =back
1862    
1863    =cut
1864    
1865    sub SpecialAttribute {
1866        # Get the parameters.
1867        my ($id, $attributes, $idxMatch, $idxValues, $pattern, $loader) = @_;
1868        # Declare the return variable.
1869        my $retVal = 0;
1870        # Loop through the attribute rows.
1871        for my $row (@{$attributes}) {
1872            # Check for a match.
1873            if ($row->[$idxMatch] =~ m/$pattern/i) {
1874                # We have a match, so output a row. This is a bit tricky, since we may
1875                # be putting out multiple columns of data from the input.
1876                my $value = join(" ", map { $row->[$_] } @{$idxValues});
1877                $loader->Put($id, $value);
1878                $retVal++;
1879            }
1880        }
1881        Trace("$retVal special attributes found for $id and loader " . $loader->RelName() . ".") if T(4) && $retVal;
1882        # Return the number of matches.
1883        return $retVal;
1884    }
1885    
1886    =head3 CreatePDB
1887    
1888    C<< $loader->CreatePDB($pdbID, $title, $type, \%pdbHash); >>
1889    
1890    Insure that a PDB record exists for the identified PDB. If one does not exist, it will be
1891    created.
1892    
1893    =over 4
1894    
1895    =item pdbID
1896    
1897    ID string (usually an unqualified file name) for the desired PDB.
1898    
1899    =item title
1900    
1901    Title to use if the PDB must be created.
1902    
1903    =item type
1904    
1905    Type of PDB: C<free> or C<bound>
1906    
1907    =item pdbHash
1908    
1909    Hash containing the IDs of PDBs that have already been created.
1910    
1911    =item pdbLoader
1912    
1913    Load object for the PDB table.
1914    
1915    =back
1916    
1917    =cut
1918    
1919    sub CreatePDB {
1920        # Get the parameters.
1921        my ($self, $pdbID, $title, $type, $pdbHash, $pdbLoader) = @_;
1922        $pdbLoader->Add("PDB check");
1923        # Check to see if this is a new PDB.
1924        if (! exists $pdbHash->{$pdbID}) {
1925            # It is, so we create it.
1926            $pdbLoader->Put($pdbID, $title, $type);
1927            $pdbHash->{$pdbID} = 1;
1928            # Count it.
1929            $pdbLoader->Add("PDB-$type");
1930        }
1931    }
1932    
1933  =head3 TableLoader  =head3 TableLoader
1934    
1935  Create an ERDBLoad object for the specified table. The object is also added to  Create an ERDBLoad object for the specified table. The object is also added to
# Line 1448  Line 1995 
1995      my $retVal = Stats->new();      my $retVal = Stats->new();
1996      # Get the loader list.      # Get the loader list.
1997      my $loadList = $self->{loaders};      my $loadList = $self->{loaders};
1998        # Create a hash to hold the statistics objects, keyed on relation name.
1999        my %loaderHash = ();
2000      # Loop through the list, finishing the loads. Note that if the finish fails, we die      # Loop through the list, finishing the loads. Note that if the finish fails, we die
2001      # ignominiously. At some future point, we want to make the loads restartable.      # ignominiously. At some future point, we want to make the loads more restartable.
2002      while (my $loader = pop @{$loadList}) {      while (my $loader = pop @{$loadList}) {
2003          # Get the relation name.          # Get the relation name.
2004          my $relName = $loader->RelName;          my $relName = $loader->RelName;
# Line 1460  Line 2009 
2009              # Here we really need to finish.              # Here we really need to finish.
2010              Trace("Finishing $relName.") if T(2);              Trace("Finishing $relName.") if T(2);
2011              my $stats = $loader->Finish();              my $stats = $loader->Finish();
2012              if ($self->{options}->{dbLoad} && ! $loader->Ignore) {              $loaderHash{$relName} = $stats;
2013            }
2014        }
2015        # Now we loop through again, actually loading the tables. We want to finish before
2016        # loading so that if something goes wrong at this point, all the load files are usable
2017        # and we don't have to redo all that work.
2018        for my $relName (sort keys %loaderHash) {
2019            # Get the statistics for this relation.
2020            my $stats = $loaderHash{$relName};
2021            # Check for a database load.
2022            if ($self->{options}->{dbLoad}) {
2023                  # Here we want to use the load file just created to load the database.                  # Here we want to use the load file just created to load the database.
2024                  Trace("Loading relation $relName.") if T(2);                  Trace("Loading relation $relName.") if T(2);
2025                  my $newStats = $self->{sprout}->LoadUpdate(1, [$relName]);                  my $newStats = $self->{sprout}->LoadUpdate(1, [$relName]);
# Line 1470  Line 2029 
2029              $retVal->Accumulate($stats);              $retVal->Accumulate($stats);
2030              Trace("Statistics for $relName:\n" . $stats->Show()) if T(2);              Trace("Statistics for $relName:\n" . $stats->Show()) if T(2);
2031          }          }
     }  
2032      # Return the load statistics.      # Return the load statistics.
2033      return $retVal;      return $retVal;
2034  }  }

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3