[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.46, Mon Jun 26 19:13:16 2006 UTC revision 1.80, Wed Dec 20 20:04:58 2006 UTC
# Line 80  Line 80 
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 NMPDR subsystems will be  to a list of subsystem names. If nothing is specified, all NMPDR subsystems will be
82  considered trusted. (A subsystem is considered NMPDR if it has a file named C<NMPDR>  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 trusted subsystems is loaded.  in its data directory.) Only subsystem data related to the NMPDR subsystems is loaded.
84    
85  =item options  =item options
86    
# Line 120  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 136  Line 136 
136      # We only need it if load-only is NOT specified.      # We only need it if load-only is NOT specified.
137      if (! $options->{loadOnly}) {      if (! $options->{loadOnly}) {
138          if (! defined $subsysFile || $subsysFile eq '') {          if (! defined $subsysFile || $subsysFile eq '') {
139              # Here we want all the NMPDR subsystems. First we get the whole list.              # Here we want all the usable subsystems. First we get the whole list.
140              my @subs = $fig->all_subsystems();              my @subs = $fig->all_subsystems();
141              # Loop through, checking for the NMPDR file.              # Loop through, checking for the NMPDR file.
142              for my $sub (@subs) {              for my $sub (@subs) {
143                  if (-e "$FIG_Config::data/Subsystems/$sub/NMPDR") {                  if ($fig->nmpdr_subsystem($sub)) {
144                      $subsystems{$sub} = 1;                      $subsystems{$sub} = 1;
145                  }                  }
146              }              }
# Line 163  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();
# Line 266  Line 274 
274              my $extra = join " ", @extraData;              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 340  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 375  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 411  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 447  Line 468 
468      FeatureUpstream      FeatureUpstream
469      IsLocatedIn      IsLocatedIn
470      HasFeature      HasFeature
471        HasRoleInSubsystem
472        FeatureEssential
473        FeatureVirulent
474        FeatureIEDB
475    
476  =over 4  =over 4
477    
# Line 461  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 472  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');      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 486  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                my @fids = map { $_->[0] } @featureTuples;
525                Trace("$count features found for genome $genomeID.") if T(3);
526                # Get the attributes for this genome and put them in a hash by feature ID.
527                my $attributes = GetGenomeAttributes($fig, $genomeID, \@fids);
528                # Set up for our duplicate-feature check.
529                my $oldFeatureID = "";
530              # Loop through the features.              # Loop through the features.
531              for my $featureData (@{$features}) {              for my $featureTuple (@featureTuples) {
                 $loadFeature->Add("featureIn");  
532                  # Split the tuple.                  # Split the tuple.
533                  my ($featureID, $locations, undef, $type) = @{$featureData};                  my ($featureID, $locations, undef, $type) = @{$featureTuple};
534                  # Create the feature record.                  # Check for duplicates.
535                  $loadFeature->Put($featureID, 1, $type);                  if ($featureID eq $oldFeatureID) {
536                  # Link it to the parent genome.                      Trace("Duplicate feature $featureID found.") if T(1);
537                  $loadHasFeature->Put($genomeID, $featureID, $type);                  } 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 ($fig->feature_aliases($featureID)) {                  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 517  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
# Line 546  Line 682 
682              }              }
683          }          }
684      }      }
     # 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);  
                     }  
                 }  
             }  
         }  
685      }      }
686      # Finish the loads.      # Finish the loads.
687      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
# Line 723  Line 792 
792                  my $curator = $sub->get_curator();                  my $curator = $sub->get_curator();
793                  my $notes = $sub->get_notes();                  my $notes = $sub->get_notes();
794                  $loadSubsystem->Put($subsysID, $curator, $notes);                  $loadSubsystem->Put($subsysID, $curator, $notes);
795                  my $class = $fig->subsystem_classification($subsysID);                  # Now for the classification string. This comes back as a list
796                  if ($class) {                  # reference and we convert it to a space-delimited string.
797                      $loadSubsystemClass->Put($subsysID, $class);                  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.                  # 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++) {                  for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {
802                      # Connect to this role.                      # Connect to this role.
# Line 843  Line 913 
913                      }                      }
914                  }                  }
915              }              }
916            }
917              # 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
918              # 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
919              # in subsystems (and therefore appear in the %ecToRoles hash) are              # in subsystems (and therefore appear in the %ecToRoles hash) are
# Line 876  Line 947 
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 929  Line 999 
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);              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
# Line 938  Line 1008 
1008              my @features = map { $_->[0] } @{$fig->all_features_detailed($genomeID)};              my @features = map { $_->[0] } @{$fig->all_features_detailed($genomeID)};
1009              my $featureCount = 0;              my $featureCount = 0;
1010              my $propertyCount = 0;              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) {
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) {                  if (scalar @attributeList) {
1020                      $featureCount++;                      $featureCount++;
1021                  }                  }
# Line 1211  Line 1284 
1284      } else {      } else {
1285          Trace("Generating external data.") if T(2);          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 1223  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 1355  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 1381  Line 1455 
1455          Trace("Loading from existing files.") if T(2);          Trace("Loading from existing files.") if T(2);
1456      } else {      } else {
1457          Trace("Generating group data.") if T(2);          Trace("Generating group data.") if T(2);
1458          # Loop through the genomes.          # Currently there are no groups.
         my $line;  
         for my $genomeID (keys %{$genomeHash}) {  
             Trace("Processing $genomeID.") if T(3);  
             # Open the NMPDR group file for this genome.  
             if (open(TMP, "<$FIG_Config::organisms/$genomeID/NMPDR") &&  
                 defined($line = <TMP>)) {  
                 # Clean the line ending.  
                 chomp $line;  
                 # Add the group to the table. Note that there can only be one group  
                 # per genome.  
                 $loadGenomeGroups->Put($genomeID, $line);  
             }  
             close TMP;  
         }  
1459      }      }
1460      # Finish the load.      # Finish the load.
1461      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
# Line 1414  Line 1474 
1474      IsSynonymGroupFor      IsSynonymGroupFor
1475    
1476  The source information for these relations is taken from the C<maps_to_id> method  The source information for these relations is taken from the C<maps_to_id> method
1477  of the B<FIG> object. The process starts from the features, so it is possible  of the B<FIG> object. Unfortunately, to make this work, we need to use direct
1478  that there will be duplicates in the SynonymGroup load file, since the relationship  SQL against the FIG database.
 is one-to-many toward the features. The automatic sort on primary entity relations  
 will fix this for us.  
1479    
1480  =over 4  =over 4
1481    
# Line 1443  Line 1501 
1501          Trace("Loading from existing files.") if T(2);          Trace("Loading from existing files.") if T(2);
1502      } else {      } else {
1503          Trace("Generating synonym group data.") if T(2);          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          for my $genomeID (sort keys %{$genomeHash}) {          for my $genomeID (sort keys %{$genomeHash}) {
1587              Trace("Processing $genomeID.") if T(3);              Trace("Processing features for $genomeID.") if T(2);
1588              # Get all of the features for this genome. The only method that does this is              # Loop through this genome's PEGs.
1589              # all_features_detailed, which returns extra baggage that we discard.              for my $fid ($fig->all_features($genomeID, "peg")) {
1590              my $featureData = $fig->all_features_detailed($genomeID);                  $loadIsFamilyForFeature->Add("features", 1);
1591              my @fids = map { $_->[0] } @{$featureData};                  # Get this feature's families.
1592              Trace(scalar(@fids) . " features found for genome $genomeID.") if T(3);                  my @families = $fig->families_for_protein($fid);
1593              # Loop through the feature IDs.                  # Loop through the families, connecting them to the feature.
1594              for my $fid (@fids) {                  for my $family (@families) {
1595                  # Get the group for this feature.                      $loadIsFamilyForFeature->Put($family, $fid);
1596                  my $synonym = $fig->maps_to_id($fid);                      # If this is a new family, create a record for it.
1597                  # Only proceed if the synonym is a real group.                      if (! exists $familyHash{$family}) {
1598                  if ($synonym ne $fid) {                          $familyHash{$family} = 1;
1599                      $loadSynonymGroup->Put($synonym);                          $loadFamily->Add("families", 1);
1600                      $loadIsSynonymGroupFor->Put($synonym, $fid);                          my $size = $fig->sz_family($family);
1601                            my $func = $fig->family_function($family);
1602                            $loadFamily->Put($family, $size, $func);
1603                        }
1604                  }                  }
1605              }              }
1606          }          }
# Line 1468  Line 1610 
1610      return $retVal;      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            }
1798        }
1799        # Finish the load.
1800        my $retVal = $self->_FinishAll();
1801        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 1536  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.          # Get the relation name.
2003          my $relName = $loader->RelName;          my $relName = $loader->RelName;
# Line 1548  Line 2008 
2008              # Here we really need to finish.              # Here we really need to finish.
2009              Trace("Finishing $relName.") if T(2);              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}) {              if ($self->{options}->{dbLoad}) {
2022                  # 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.
2023                  Trace("Loading relation $relName.") if T(2);                  Trace("Loading relation $relName.") if T(2);
# Line 1558  Line 2028 
2028              $retVal->Accumulate($stats);              $retVal->Accumulate($stats);
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.46  
changed lines
  Added in v.1.80

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3