[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.40, Thu Jun 8 15:37:32 2006 UTC revision 1.78, Wed Nov 15 12:15:30 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                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                  # Link it to the parent genome.                      Trace("Duplicate feature $featureID found.") if T(1);
534                  $loadHasFeature->Put($genomeID, $featureID, $type);                  } 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, and the organism name.
540                        my @keywords = ($genomeID, $featureID, $fig->genus_species($genomeID));
541                        # Get the functional assignment and aliases. This
542                        # depends on the feature type.
543                        my $assignment;
544                        if ($type eq "peg") {
545                            $assignment = $fig->function_of($featureID);
546                  # Create the aliases.                  # Create the aliases.
547                  for my $alias ($fig->feature_aliases($featureID)) {                  for my $alias ($fig->feature_aliases($featureID)) {
548                      $loadFeatureAlias->Put($featureID, $alias);                      $loadFeatureAlias->Put($featureID, $alias);
549                                push @keywords, $alias;
550                            }
551                        } else {
552                            # For other types, the assignment is the first (and ONLY) alias.
553                            ($assignment) = $fig->feature_aliases($featureID);
554                  }                  }
555                        Trace("Assignment for $featureID is: $assignment") if T(4);
556                        # Break the assignment into words and shove it onto the
557                        # keyword list.
558                        push @keywords, split(/\s+/, $assignment);
559                        # Link this feature to the parent genome.
560                        $loadHasFeature->Put($genomeID, $featureID, $type);
561                  # Get the links.                  # Get the links.
562                  my @links = $fig->fid_links($featureID);                  my @links = $fig->fid_links($featureID);
563                  for my $link (@links) {                  for my $link (@links) {
# Line 517  Line 576 
576                          $loadFeatureUpstream->Put($featureID, $upstream);                          $loadFeatureUpstream->Put($featureID, $upstream);
577                      }                      }
578                  }                  }
579                        # Now we need to find the subsystems this feature participates in.
580                        # We also add the subsystems to the keyword list. Before we do that,
581                        # we must convert underscores to spaces and tack on the classifications.
582                        my @subsystems = $fig->peg_to_subsystems($featureID);
583                        for my $subsystem (@subsystems) {
584                            # Only proceed if we like this subsystem.
585                            if (exists $subHash->{$subsystem}) {
586                                # Store the has-role link.
587                                $loadHasRoleInSubsystem->Put($featureID, $subsystem, $genomeID, $type);
588                                # Save the subsystem's keyword data.
589                                my $subKeywords = $subHash->{$subsystem};
590                                push @keywords, split /\s+/, $subKeywords;
591                                # Now we need to get this feature's role in the subsystem.
592                                my $subObject = $fig->get_subsystem($subsystem);
593                                my @roleColumns = $subObject->get_peg_roles($featureID);
594                                my @allRoles = $subObject->get_roles();
595                                for my $col (@roleColumns) {
596                                    my $role = $allRoles[$col];
597                                    push @keywords, split /\s+/, $role;
598                                    push @keywords, $subObject->get_role_abbr($col);
599                                }
600                            }
601                        }
602                        # There are three special attributes computed from property
603                        # data that we build next. If the special attribute is non-empty,
604                        # its name will be added to the keyword list. First, we get all
605                        # the attributes for this feature. They will come back as
606                        # 4-tuples: [peg, name, value, URL]. We use a 3-tuple instead:
607                        # [name, value, value with URL]. (We don't need the PEG, since
608                        # we already know it.)
609                        my @attributes = map { [$_->[1], $_->[2], Tracer::CombineURL($_->[2], $_->[3])] }
610                                             $fig->get_attributes($featureID);
611                        # Now we process each of the special attributes.
612                        if (SpecialAttribute($featureID, \@attributes,
613                                             1, [0,2], '^(essential|potential_essential)$',
614                                             $loadFeatureEssential)) {
615                            push @keywords, 'essential';
616                            $loadFeature->Add('essential');
617                        }
618                        if (SpecialAttribute($featureID, \@attributes,
619                                             0, [2], '^virulen',
620                                             $loadFeatureVirulent)) {
621                            push @keywords, 'virulent';
622                            $loadFeature->Add('virulent');
623                        }
624                        if (SpecialAttribute($featureID, \@attributes,
625                                             0, [0,2], '^iedb_',
626                                             $loadFeatureIEDB)) {
627                            push @keywords, 'iedb';
628                            $loadFeature->Add('iedb');
629                        }
630                        # Now we need to bust up hyphenated words in the keyword
631                        # list.
632                        my $keywordString = "";
633                        for my $keyword (@keywords) {
634                            if (length $keyword >= 4) {
635                                $keywordString .= " $keyword";
636                                if ($keyword =~ /-/) {
637                                    my @words = grep { length($_) >= 4 } split /-/, $keyword;
638                                    $keywordString .= join(" ", "", @words);
639                                }
640                            }
641                        }
642                        # Clean the keyword list.
643                        my $cleanWords = $sprout->CleanKeywords($keywordString);
644                        Trace("Keyword string for $featureID: $cleanWords") if T(4);
645                        # Create the feature record.
646                        $loadFeature->Put($featureID, 1, $type, $assignment, $cleanWords);
647                  # 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
648                  # 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
649                  # 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 673 
673              }              }
674          }          }
675      }      }
     # 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);  
                     }  
                 }  
             }  
         }  
676      }      }
677      # Finish the loads.      # Finish the loads.
678      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
# Line 634  Line 694 
694  The following relations are loaded by this method.  The following relations are loaded by this method.
695    
696      Subsystem      Subsystem
697        SubsystemClass
698      Role      Role
699      RoleEC      RoleEC
700      SSCell      SSCell
# Line 696  Line 757 
757      my $loadConsistsOfGenomes = $self->_TableLoader('ConsistsOfGenomes', $self->PrimaryOnly);      my $loadConsistsOfGenomes = $self->_TableLoader('ConsistsOfGenomes', $self->PrimaryOnly);
758      my $loadHasRoleSubset = $self->_TableLoader('HasRoleSubset', $self->PrimaryOnly);      my $loadHasRoleSubset = $self->_TableLoader('HasRoleSubset', $self->PrimaryOnly);
759      my $loadHasGenomeSubset = $self->_TableLoader('HasGenomeSubset', $self->PrimaryOnly);      my $loadHasGenomeSubset = $self->_TableLoader('HasGenomeSubset', $self->PrimaryOnly);
760        my $loadSubsystemClass = $self->_TableLoader('SubsystemClass', $self->PrimaryOnly);
761      if ($self->{options}->{loadOnly}) {      if ($self->{options}->{loadOnly}) {
762          Trace("Loading from existing files.") if T(2);          Trace("Loading from existing files.") if T(2);
763      } else {      } else {
# Line 721  Line 783 
783                  my $curator = $sub->get_curator();                  my $curator = $sub->get_curator();
784                  my $notes = $sub->get_notes();                  my $notes = $sub->get_notes();
785                  $loadSubsystem->Put($subsysID, $curator, $notes);                  $loadSubsystem->Put($subsysID, $curator, $notes);
786                    # Now for the classification string. This comes back as a list
787                    # reference and we convert it to a space-delimited string.
788                    my $classList = $fig->subsystem_classification($subsysID);
789                    my $classString = join($FIG_Config::splitter, grep { $_ } @$classList);
790                    $loadSubsystemClass->Put($subsysID, $classString);
791                  # 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.
792                  for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {                  for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {
793                      # Connect to this role.                      # Connect to this role.
# Line 785  Line 852 
852                          if ($pegCount > 0) {                          if ($pegCount > 0) {
853                              Trace("$pegCount PEGs in $cellCount cells for $genomeID.") if T(3);                              Trace("$pegCount PEGs in $cellCount cells for $genomeID.") if T(3);
854                              $loadParticipatesIn->Put($genomeID, $subsysID, $variantCode);                              $loadParticipatesIn->Put($genomeID, $subsysID, $variantCode);
                             # Partition the PEGs found into clusters.  
                             my @clusters = $fig->compute_clusters(\@pegsFound, $sub);  
855                              # Create a hash mapping PEG IDs to cluster numbers.                              # Create a hash mapping PEG IDs to cluster numbers.
856                              # We default to -1 for all of them.                              # We default to -1 for all of them.
857                              my %clusterOf = map { $_ => -1 } @pegsFound;                              my %clusterOf = map { $_ => -1 } @pegsFound;
858                                # Partition the PEGs found into clusters.
859                                my @clusters = $fig->compute_clusters([keys %clusterOf], $sub);
860                              for (my $i = 0; $i <= $#clusters; $i++) {                              for (my $i = 0; $i <= $#clusters; $i++) {
861                                  my $subList = $clusters[$i];                                  my $subList = $clusters[$i];
862                                  for my $peg (@{$subList}) {                                  for my $peg (@{$subList}) {
# Line 837  Line 904 
904                      }                      }
905                  }                  }
906              }              }
907            }
908              # 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
909              # 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
910              # in subsystems (and therefore appear in the %ecToRoles hash) are              # in subsystems (and therefore appear in the %ecToRoles hash) are
# Line 870  Line 938 
938                  }                  }
939              }              }
940          }          }
     }  
941      # Finish the load.      # Finish the load.
942      my $retVal = $self->_FinishAll();      my $retVal = $self->_FinishAll();
943      return $retVal;      return $retVal;
# Line 923  Line 990 
990          my %propertyKeys = ();          my %propertyKeys = ();
991          my $nextID = 1;          my $nextID = 1;
992          # Loop through the genomes.          # Loop through the genomes.
993          for my $genomeID (keys %{$genomeHash}) {          for my $genomeID (sort keys %{$genomeHash}) {
994              $loadProperty->Add("genomeIn");              $loadProperty->Add("genomeIn");
995              Trace("Generating properties for $genomeID.") if T(3);              Trace("Generating properties for $genomeID.") if T(3);
996              # 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 936  Line 1003 
1003              for my $fid (@features) {              for my $fid (@features) {
1004                  # 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
1005                  # to insure we do not get any genome attributes.                  # to insure we do not get any genome attributes.
1006                  my @attributeList = $fig->get_attributes($fid, '', '', '');                  my @attributeList = $fig->get_attributes($fid);
1007                    # Add essentiality and virulence attributes.
1008                    if ($fig->essential($fid)) {
1009                        push @attributeList, [$fid, 'essential', 1, ''];
1010                    }
1011                    if ($fig->virulent($fid)) {
1012                        push @attributeList, [$fid, 'virulent', 1, ''];
1013                    }
1014                  if (scalar @attributeList) {                  if (scalar @attributeList) {
1015                      $featureCount++;                      $featureCount++;
1016                  }                  }
# Line 1042  Line 1116 
1116                  # Get the annotation tuple.                  # Get the annotation tuple.
1117                  my ($peg, $timestamp, $user, $text) = @{$tuple};                  my ($peg, $timestamp, $user, $text) = @{$tuple};
1118                  # Here we fix up the annotation text. "\r" is removed,                  # Here we fix up the annotation text. "\r" is removed,
1119                  # and "\t" and "\n" are escaped. Note we use the "s"                  # and "\t" and "\n" are escaped. Note we use the "gs"
1120                  # modifier so that new-lines inside the text do not                  # modifier so that new-lines inside the text do not
1121                  # stop the substitution search.                  # stop the substitution search.
1122                  $text =~ s/\r//gs;                  $text =~ s/\r//gs;
# Line 1205  Line 1279 
1279      } else {      } else {
1280          Trace("Generating external data.") if T(2);          Trace("Generating external data.") if T(2);
1281          # 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.
1282          Open(\*ORGS, "<$FIG_Config::global/ext_org.table");          Open(\*ORGS, "sort +0 -1 -u -t\"\t\" $FIG_Config::global/ext_org.table |");
1283          my $orgLine;          my $orgLine;
1284          while (defined($orgLine = <ORGS>)) {          while (defined($orgLine = <ORGS>)) {
1285              # Clean the input line.              # Clean the input line.
# Line 1217  Line 1291 
1291          close ORGS;          close ORGS;
1292          # Now the function file.          # Now the function file.
1293          my $funcLine;          my $funcLine;
1294          Open(\*FUNCS, "<$FIG_Config::global/ext_func.table");          Open(\*FUNCS, "sort +0 -1 -u -t\"\t\" $FIG_Config::global/ext_func.table |");
1295          while (defined($funcLine = <FUNCS>)) {          while (defined($funcLine = <FUNCS>)) {
1296              # Clean the line ending.              # Clean the line ending.
1297              chomp $funcLine;              chomp $funcLine;
# Line 1349  Line 1423 
1423    
1424      GenomeGroups      GenomeGroups
1425    
1426  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,
1427    butThere is no direct support for genome groups in FIG, so we access the SEED
1428  files directly.  files directly.
1429    
1430  =over 4  =over 4
# Line 1375  Line 1450 
1450          Trace("Loading from existing files.") if T(2);          Trace("Loading from existing files.") if T(2);
1451      } else {      } else {
1452          Trace("Generating group data.") if T(2);          Trace("Generating group data.") if T(2);
1453            # Currently there are no groups.
1454        }
1455        # Finish the load.
1456        my $retVal = $self->_FinishAll();
1457        return $retVal;
1458    }
1459    
1460    =head3 LoadSynonymData
1461    
1462    C<< my $stats = $spl->LoadSynonymData(); >>
1463    
1464    Load the synonym groups into Sprout.
1465    
1466    The following relations are loaded by this method.
1467    
1468        SynonymGroup
1469        IsSynonymGroupFor
1470    
1471    The source information for these relations is taken from the C<maps_to_id> method
1472    of the B<FIG> object. Unfortunately, to make this work, we need to use direct
1473    SQL against the FIG database.
1474    
1475    =over 4
1476    
1477    =item RETURNS
1478    
1479    Returns a statistics object for the loads.
1480    
1481    =back
1482    
1483    =cut
1484    #: Return Type $%;
1485    sub LoadSynonymData {
1486        # Get this object instance.
1487        my ($self) = @_;
1488        # Get the FIG object.
1489        my $fig = $self->{fig};
1490        # Get the genome hash.
1491        my $genomeHash = $self->{genomes};
1492        # Create a load object for the table we're loading.
1493        my $loadSynonymGroup = $self->_TableLoader('SynonymGroup');
1494        my $loadIsSynonymGroupFor = $self->_TableLoader('IsSynonymGroupFor');
1495        if ($self->{options}->{loadOnly}) {
1496            Trace("Loading from existing files.") if T(2);
1497        } else {
1498            Trace("Generating synonym group data.") if T(2);
1499            # Get the database handle.
1500            my $dbh = $fig->db_handle();
1501            # Ask for the synonyms.
1502            my $sth = $dbh->prepare_command("SELECT maps_to, syn_id FROM peg_synonyms ORDER BY maps_to");
1503            my $result = $sth->execute();
1504            if (! defined($result)) {
1505                Confess("Database error in Synonym load: " . $sth->errstr());
1506            } else {
1507                # Remember the current synonym.
1508                my $current_syn = "";
1509                # Count the features.
1510                my $featureCount = 0;
1511                # Loop through the synonym/peg pairs.
1512                while (my @row = $sth->fetchrow()) {
1513                    # Get the synonym ID and feature ID.
1514                    my ($syn_id, $peg) = @row;
1515                    # Insure it's for one of our genomes.
1516                    my $genomeID = FIG::genome_of($peg);
1517                    if (exists $genomeHash->{$genomeID}) {
1518                        # Verify the synonym.
1519                        if ($syn_id ne $current_syn) {
1520                            # It's new, so put it in the group table.
1521                            $loadSynonymGroup->Put($syn_id);
1522                            $current_syn = $syn_id;
1523                        }
1524                        # Connect the synonym to the peg.
1525                        $loadIsSynonymGroupFor->Put($syn_id, $peg);
1526                        # Count this feature.
1527                        $featureCount++;
1528                        if ($featureCount % 1000 == 0) {
1529                            Trace("$featureCount features processed.") if T(3);
1530                        }
1531                    }
1532                }
1533            }
1534        }
1535        # Finish the load.
1536        my $retVal = $self->_FinishAll();
1537        return $retVal;
1538    }
1539    
1540    =head3 LoadFamilyData
1541    
1542    C<< my $stats = $spl->LoadFamilyData(); >>
1543    
1544    Load the protein families into Sprout.
1545    
1546    The following relations are loaded by this method.
1547    
1548        Family
1549        IsFamilyForFeature
1550    
1551    The source information for these relations is taken from the C<families_for_protein>,
1552    C<family_function>, and C<sz_family> methods of the B<FIG> object.
1553    
1554    =over 4
1555    
1556    =item RETURNS
1557    
1558    Returns a statistics object for the loads.
1559    
1560    =back
1561    
1562    =cut
1563    #: Return Type $%;
1564    sub LoadFamilyData {
1565        # Get this object instance.
1566        my ($self) = @_;
1567        # Get the FIG object.
1568        my $fig = $self->{fig};
1569        # Get the genome hash.
1570        my $genomeHash = $self->{genomes};
1571        # Create load objects for the tables we're loading.
1572        my $loadFamily = $self->_TableLoader('Family');
1573        my $loadIsFamilyForFeature = $self->_TableLoader('IsFamilyForFeature');
1574        if ($self->{options}->{loadOnly}) {
1575            Trace("Loading from existing files.") if T(2);
1576        } else {
1577            Trace("Generating family data.") if T(2);
1578            # Create a hash for the family IDs.
1579            my %familyHash = ();
1580          # Loop through the genomes.          # Loop through the genomes.
1581          my $line;          for my $genomeID (sort keys %{$genomeHash}) {
1582          for my $genomeID (keys %{$genomeHash}) {              Trace("Processing features for $genomeID.") if T(2);
1583              Trace("Processing $genomeID.") if T(3);              # Loop through this genome's PEGs.
1584              # Open the NMPDR group file for this genome.              for my $fid ($fig->all_features($genomeID, "peg")) {
1585              if (open(TMP, "<$FIG_Config::organisms/$genomeID/NMPDR") &&                  $loadIsFamilyForFeature->Add("features", 1);
1586                  defined($line = <TMP>)) {                  # Get this feature's families.
1587                  # Clean the line ending.                  my @families = $fig->families_for_protein($fid);
1588                  chomp $line;                  # Loop through the families, connecting them to the feature.
1589                  # Add the group to the table. Note that there can only be one group                  for my $family (@families) {
1590                  # per genome.                      $loadIsFamilyForFeature->Put($family, $fid);
1591                  $loadGenomeGroups->Put($genomeID, $line);                      # If this is a new family, create a record for it.
1592                        if (! exists $familyHash{$family}) {
1593                            $familyHash{$family} = 1;
1594                            $loadFamily->Add("families", 1);
1595                            my $size = $fig->sz_family($family);
1596                            my $func = $fig->family_function($family);
1597                            $loadFamily->Put($family, $size, $func);
1598                        }
1599                    }
1600                }
1601            }
1602        }
1603        # Finish the load.
1604        my $retVal = $self->_FinishAll();
1605        return $retVal;
1606    }
1607    
1608    =head3 LoadDrugData
1609    
1610    C<< my $stats = $spl->LoadDrugData(); >>
1611    
1612    Load the drug target data into Sprout.
1613    
1614    The following relations are loaded by this method.
1615    
1616        DrugProject
1617        ContainsTopic
1618        DrugTopic
1619        ContainsAnalysisOf
1620        PDB
1621        IncludesBound
1622        IsBoundIn
1623        BindsWith
1624        Ligand
1625        DescribesProteinForFeature
1626        FeatureConservation
1627    
1628    The source information for these relations is taken from flat files in the
1629    C<$FIG_Config::drug_directory>. The file C<master_tables.list> contains
1630    a list of drug project names paired with file names. The named file (in the
1631    same directory) contains all the data for the project.
1632    
1633    =over 4
1634    
1635    =item RETURNS
1636    
1637    Returns a statistics object for the loads.
1638    
1639    =back
1640    
1641    =cut
1642    #: Return Type $%;
1643    sub LoadDrugData {
1644        # Get this object instance.
1645        my ($self) = @_;
1646        # Get the FIG object.
1647        my $fig = $self->{fig};
1648        # Get the genome hash.
1649        my $genomeHash = $self->{genomes};
1650        # Create load objects for the tables we're loading.
1651        my $loadDrugProject = $self->_TableLoader('DrugProject');
1652        my $loadContainsTopic = $self->_TableLoader('ContainsTopic');
1653        my $loadDrugTopic = $self->_TableLoader('DrugTopic');
1654        my $loadContainsAnalysisOf = $self->_TableLoader('ContainsAnalysisOf');
1655        my $loadPDB = $self->_TableLoader('PDB');
1656        my $loadIncludesBound = $self->_TableLoader('IncludesBound');
1657        my $loadIsBoundIn = $self->_TableLoader('IsBoundIn');
1658        my $loadBindsWith = $self->_TableLoader('BindsWith');
1659        my $loadLigand = $self->_TableLoader('Ligand');
1660        my $loadDescribesProteinForFeature = $self->_TableLoader('DescribesProteinForFeature');
1661        my $loadFeatureConservation = $self->_TableLoader('FeatureConservation');
1662        if ($self->{options}->{loadOnly}) {
1663            Trace("Loading from existing files.") if T(2);
1664        } else {
1665            Trace("Generating drug target data.") if T(2);
1666            # Load the project list. The file comes in as a list of chomped lines,
1667            # and we split them on the TAB character to make the project name the
1668            # key and the file name the value of the resulting hash.
1669            my %projects = map { split /\t/, $_ } Tracer::GetFile("$FIG_Config::drug_directory/master_tables.list");
1670            # Create hashes for the derived objects: PDBs, Features, and Ligands. These objects
1671            # may occur multiple times in a single project file or even in multiple project
1672            # files.
1673            my %ligands = ();
1674            my %pdbs = ();
1675            my %features = ();
1676            my %bindings = ();
1677            # Set up a counter for drug topics. This will be used as the key.
1678            my $topicCounter = 0;
1679            # Loop through the projects. We sort the keys not because we need them sorted, but
1680            # because it makes it easier to infer our progress from trace messages.
1681            for my $project (sort keys %projects) {
1682                Trace("Processing project $project.") if T(3);
1683                # Only proceed if the download file exists.
1684                my $projectFile = "$FIG_Config::drug_directory/$projects{$project}";
1685                if (! -f $projectFile) {
1686                    Trace("Project file $projectFile not found.") if T(0);
1687                } else {
1688                    # Create the project record.
1689                    $loadDrugProject->Put($project);
1690                    # Create a hash for the topics. Each project has one or more topics. The
1691                    # topic is identified by a URL, a category, and an identifier.
1692                    my %topics = ();
1693                    # Now we can open the project file.
1694                    Trace("Reading project file $projectFile.") if T(3);
1695                    Open(\*PROJECT, "<$projectFile");
1696                    # Get the first record, which is a list of column headers. We don't use this
1697                    # for anything, but it may be useful for debugging.
1698                    my $headerLine = <PROJECT>;
1699                    # Loop through the rest of the records.
1700                    while (! eof PROJECT) {
1701                        # Get the current line of data. Note that not all lines will have all
1702                        # the fields. In particular, the CLIBE data is fairly rare.
1703                        my ($authorOrganism, $category, $tag, $refURL, $peg, $conservation,
1704                            $pdbBound, $pdbBoundEval, $pdbFree, $pdbFreeEval, $pdbFreeTitle,
1705                            $protDistInfo, $passAspInfo, $passAspFile, $passWeightInfo,
1706                            $passWeightFile, $clibeInfo, $clibeURL, $clibeTotalEnergy,
1707                            $clibeVanderwaals, $clibeHBonds, $clibeEI, $clibeSolvationE)
1708                           = Tracer::GetLine(\*PROJECT);
1709                        # The tag contains an identifier for the current line of data followed
1710                        # by a text statement that generally matches a property name in the
1711                        # main database. We split it up, since the identifier goes with
1712                        # the PDB data and the text statement is part of the topic.
1713                        my ($lineID, $topicTag) = split /\s*,\s*/, $tag;
1714                        $loadDrugProject->Add("data line");
1715                        # Check for a new topic.
1716                        my $topicData = "$category\t$topicTag\t$refURL";
1717                        if (! exists $topics{$topicData}) {
1718                            # Here we have a new topic. Compute its ID.
1719                            $topicCounter++;
1720                            $topics{$topicData} = $topicCounter;
1721                            # Create its database record.
1722                            $loadDrugTopic->Put($topicCounter, $refURL, $category, $authorOrganism,
1723                                                $topicTag);
1724                            # Connect it to the project.
1725                            $loadContainsTopic->Put($project, $topicCounter);
1726                            $loadDrugTopic->Add("topic");
1727                        }
1728                        # Now we know the topic ID exists in the hash and the topic will
1729                        # appear in the database, so we get this topic's ID.
1730                        my $topicID = $topics{$topicData};
1731                        # If the feature in this line is new, we need to save its conservation
1732                        # number.
1733                        if (! exists $features{$peg}) {
1734                            $loadFeatureConservation->Put($peg, $conservation);
1735                            $features{$peg} = 1;
1736                        }
1737                        # Now we have two PDBs to deal with-- a bound PDB and a free PDB.
1738                        # The free PDB will have data about docking points; the bound PDB
1739                        # will have data about docking. We store both types as PDBs, and
1740                        # the special data comes from relationships. First we process the
1741                        # bound PDB.
1742                        if ($pdbBound) {
1743                            $loadPDB->Add("bound line");
1744                            # Insure this PDB is in the database.
1745                            $self->CreatePDB($pdbBound, lc "$pdbFreeTitle (bound)", "bound", \%pdbs, $loadPDB);
1746                            # Connect it to this topic.
1747                            $loadIncludesBound->Put($topicID, $pdbBound);
1748                            # Check for CLIBE data.
1749                            if ($clibeInfo) {
1750                                $loadLigand->Add("clibes");
1751                                # We have CLIBE data, so we create a ligand and relate it to the PDB.
1752                                if (! exists $ligands{$clibeInfo}) {
1753                                    # This is a new ligand, so create its record.
1754                                    $loadLigand->Put($clibeInfo);
1755                                    $loadLigand->Add("ligand");
1756                                    # Make sure we know this ligand already exists.
1757                                    $ligands{$clibeInfo} = 1;
1758                                }
1759                                # Now connect the PDB to the ligand using the CLIBE data.
1760                                $loadBindsWith->Put($pdbBound, $clibeInfo, $clibeURL, $clibeHBonds, $clibeEI,
1761                                                    $clibeSolvationE, $clibeVanderwaals);
1762                            }
1763                            # Connect this PDB to the feature.
1764                            $loadDescribesProteinForFeature->Put($pdbBound, $peg, $protDistInfo, $pdbBoundEval);
1765                        }
1766                        # Next is the free PDB.
1767                        if ($pdbFree) {
1768                            $loadPDB->Add("free line");
1769                            # Insure this PDB is in the database.
1770                            $self->CreatePDB($pdbFree, lc $pdbFreeTitle, "free", \%pdbs, $loadPDB);
1771                            # Connect it to this topic.
1772                            $loadContainsAnalysisOf->Put($topicID, $pdbFree, $passAspInfo,
1773                                                         $passWeightFile, $passWeightInfo, $passAspFile);
1774                            # Connect this PDB to the feature.
1775                            $loadDescribesProteinForFeature->Put($pdbFree, $peg, $protDistInfo, $pdbFreeEval);
1776                        }
1777                        # If we have both PDBs, we may need to link them.
1778                        if ($pdbFree && $pdbBound) {
1779                            $loadIsBoundIn->Add("connection");
1780                            # Insure we only link them once.
1781                            my $bindingKey =  "$pdbFree\t$pdbBound";
1782                            if (! exists $bindings{$bindingKey}) {
1783                                $loadIsBoundIn->Add("newConnection");
1784                                $loadIsBoundIn->Put($pdbFree, $pdbBound);
1785                                $bindings{$bindingKey} = 1;
1786                            }
1787                        }
1788                    }
1789                    # Close off this project.
1790                    close PROJECT;
1791              }              }
             close TMP;  
1792          }          }
1793      }      }
1794      # Finish the load.      # Finish the load.
# Line 1396  Line 1796 
1796      return $retVal;      return $retVal;
1797  }  }
1798    
1799    
1800  =head2 Internal Utility Methods  =head2 Internal Utility Methods
1801    
1802    =head3 SpecialAttribute
1803    
1804    C<< my $count = SproutLoad::SpecialAttribute($id, \@attributes, $idxMatch, \@idxValues, $pattern, $loader); >>
1805    
1806    Look for special attributes of a given type. A special attribute is found by comparing one of
1807    the columns of the incoming attribute list to a search pattern. If a match is found, then
1808    a set of columns is put into an output table connected to the specified ID.
1809    
1810    For example, when processing features, the attribute list we look at has three columns: attribute
1811    name, attribute value, and attribute value HTML. The IEDB attribute exists if the attribute name
1812    begins with C<iedb_>. The call signature is therefore
1813    
1814        my $found = SpecialAttribute($fid, \@attributeList, 0, [0,2], '^iedb_', $loadFeatureIEDB);
1815    
1816    The pattern is matched against column 0, and if we have a match, then column 2's value is put
1817    to the output along with the specified feature ID.
1818    
1819    =over 4
1820    
1821    =item id
1822    
1823    ID of the object whose special attributes are being loaded. This forms the first column of the
1824    output.
1825    
1826    =item attributes
1827    
1828    Reference to a list of tuples.
1829    
1830    =item idxMatch
1831    
1832    Index in each tuple of the column to be matched against the pattern. If the match is
1833    successful, an output record will be generated.
1834    
1835    =item idxValues
1836    
1837    Reference to a list containing the indexes in each tuple of the columns to be put as
1838    the second column of the output.
1839    
1840    =item pattern
1841    
1842    Pattern to be matched against the specified column. The match will be case-insensitive.
1843    
1844    =item loader
1845    
1846    An object to which each output record will be put. Usually this is an B<ERDBLoad> object,
1847    but technically it could be anything with a C<Put> method.
1848    
1849    =item RETURN
1850    
1851    Returns a count of the matches found.
1852    
1853    =item
1854    
1855    =back
1856    
1857    =cut
1858    
1859    sub SpecialAttribute {
1860        # Get the parameters.
1861        my ($id, $attributes, $idxMatch, $idxValues, $pattern, $loader) = @_;
1862        # Declare the return variable.
1863        my $retVal = 0;
1864        # Loop through the attribute rows.
1865        for my $row (@{$attributes}) {
1866            # Check for a match.
1867            if ($row->[$idxMatch] =~ m/$pattern/i) {
1868                # We have a match, so output a row. This is a bit tricky, since we may
1869                # be putting out multiple columns of data from the input.
1870                my $value = join(" ", map { $row->[$_] } @{$idxValues});
1871                $loader->Put($id, $value);
1872                $retVal++;
1873            }
1874        }
1875        Trace("$retVal special attributes found for $id and loader " . $loader->RelName() . ".") if T(4) && $retVal;
1876        # Return the number of matches.
1877        return $retVal;
1878    }
1879    
1880    =head3 CreatePDB
1881    
1882    C<< $loader->CreatePDB($pdbID, $title, $type, \%pdbHash); >>
1883    
1884    Insure that a PDB record exists for the identified PDB. If one does not exist, it will be
1885    created.
1886    
1887    =over 4
1888    
1889    =item pdbID
1890    
1891    ID string (usually an unqualified file name) for the desired PDB.
1892    
1893    =item title
1894    
1895    Title to use if the PDB must be created.
1896    
1897    =item type
1898    
1899    Type of PDB: C<free> or C<bound>
1900    
1901    =item pdbHash
1902    
1903    Hash containing the IDs of PDBs that have already been created.
1904    
1905    =item pdbLoader
1906    
1907    Load object for the PDB table.
1908    
1909    =back
1910    
1911    =cut
1912    
1913    sub CreatePDB {
1914        # Get the parameters.
1915        my ($self, $pdbID, $title, $type, $pdbHash, $pdbLoader) = @_;
1916        $pdbLoader->Add("PDB check");
1917        # Check to see if this is a new PDB.
1918        if (! exists $pdbHash->{$pdbID}) {
1919            # It is, so we create it.
1920            $pdbLoader->Put($pdbID, $title, $type);
1921            $pdbHash->{$pdbID} = 1;
1922            # Count it.
1923            $pdbLoader->Add("PDB-$type");
1924        }
1925    }
1926    
1927  =head3 TableLoader  =head3 TableLoader
1928    
1929  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 1463  Line 1989 
1989      my $retVal = Stats->new();      my $retVal = Stats->new();
1990      # Get the loader list.      # Get the loader list.
1991      my $loadList = $self->{loaders};      my $loadList = $self->{loaders};
1992        # Create a hash to hold the statistics objects, keyed on relation name.
1993        my %loaderHash = ();
1994      # 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
1995      # 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.
1996      while (my $loader = pop @{$loadList}) {      while (my $loader = pop @{$loadList}) {
1997          # Get the relation name.          # Get the relation name.
1998          my $relName = $loader->RelName;          my $relName = $loader->RelName;
# Line 1475  Line 2003 
2003              # Here we really need to finish.              # Here we really need to finish.
2004              Trace("Finishing $relName.") if T(2);              Trace("Finishing $relName.") if T(2);
2005              my $stats = $loader->Finish();              my $stats = $loader->Finish();
2006                $loaderHash{$relName} = $stats;
2007            }
2008        }
2009        # Now we loop through again, actually loading the tables. We want to finish before
2010        # loading so that if something goes wrong at this point, all the load files are usable
2011        # and we don't have to redo all that work.
2012        for my $relName (sort keys %loaderHash) {
2013            # Get the statistics for this relation.
2014            my $stats = $loaderHash{$relName};
2015            # Check for a database load.
2016              if ($self->{options}->{dbLoad}) {              if ($self->{options}->{dbLoad}) {
2017                  # 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.
2018                  Trace("Loading relation $relName.") if T(2);                  Trace("Loading relation $relName.") if T(2);
# Line 1485  Line 2023 
2023              $retVal->Accumulate($stats);              $retVal->Accumulate($stats);
2024              Trace("Statistics for $relName:\n" . $stats->Show()) if T(2);              Trace("Statistics for $relName:\n" . $stats->Show()) if T(2);
2025          }          }
     }  
2026      # Return the load statistics.      # Return the load statistics.
2027      return $retVal;      return $retVal;
2028  }  }

Legend:
Removed from v.1.40  
changed lines
  Added in v.1.78

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3