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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.24 - (view) (download) (as text)

1 : parrello 1.1 #!/usr/bin/perl -w
2 :    
3 :     package SproutLoad;
4 :    
5 :     use strict;
6 :     use Tracer;
7 :     use PageBuilder;
8 :     use ERDBLoad;
9 :     use FIG;
10 :     use Sprout;
11 :     use Stats;
12 :     use BasicLocation;
13 : parrello 1.18 use HTML;
14 : parrello 1.1
15 :     =head1 Sprout Load Methods
16 :    
17 :     =head2 Introduction
18 :    
19 :     This object contains the methods needed to copy data from the FIG data store to the
20 :     Sprout database. It makes heavy use of the ERDBLoad object to manage the load into
21 :     individual tables. The client can create an instance of this object and then
22 :     call methods for each group of tables to load. For example, the following code will
23 :     load the Genome- and Feature-related tables. (It is presumed the first command line
24 :     parameter contains the name of a file specifying the genomes.)
25 :    
26 :     my $fig = FIG->new();
27 :     my $sprout = SFXlate->new_sprout_only();
28 :     my $spl = SproutLoad->new($sprout, $fig, $ARGV[0]);
29 :     my $stats = $spl->LoadGenomeData();
30 :     $stats->Accumulate($spl->LoadFeatureData());
31 :     print $stats->Show();
32 :    
33 :     This module makes use of the internal Sprout property C<_erdb>.
34 :    
35 :     It is worth noting that the FIG object does not need to be a real one. Any object
36 :     that implements the FIG methods for data retrieval could be used. So, for example,
37 :     this object could be used to copy data from one Sprout database to another, or
38 :     from any FIG-compliant data story implemented in the future.
39 :    
40 :     To insure that this is possible, each time the FIG object is used, it will be via
41 :     a variable called C<$fig>. This makes it fairly straightforward to determine which
42 :     FIG methods are required to load the Sprout database.
43 :    
44 : parrello 1.5 This object creates the load files; however, the tables are not created until it
45 :     is time to actually do the load from the files into the target database.
46 :    
47 : parrello 1.1 =cut
48 :    
49 :     #: Constructor SproutLoad->new();
50 :    
51 :     =head2 Public Methods
52 :    
53 :     =head3 new
54 :    
55 : parrello 1.8 C<< my $spl = SproutLoad->new($sprout, $fig, $genomeFile, $subsysFile, $options); >>
56 : parrello 1.1
57 :     Construct a new Sprout Loader object, specifying the two participating databases and
58 :     the name of the files containing the list of genomes and subsystems to use.
59 :    
60 :     =over 4
61 :    
62 :     =item sprout
63 :    
64 :     Sprout object representing the target database. This also specifies the directory to
65 :     be used for creating the load files.
66 :    
67 :     =item fig
68 :    
69 :     FIG object representing the source data store from which the data is to be taken.
70 :    
71 :     =item genomeFile
72 :    
73 :     Either the name of the file containing the list of genomes to load or a reference to
74 :     a hash of genome IDs to access codes. If nothing is specified, all complete genomes
75 :     will be loaded and the access code will default to 1. The genome list is presumed
76 :     to be all-inclusive. In other words, all existing data in the target database will
77 :     be deleted and replaced with the data on the specified genes. If a file is specified,
78 :     it should contain one genome ID and access code per line, tab-separated.
79 :    
80 :     =item subsysFile
81 :    
82 :     Either the name of the file containing the list of trusted subsystems or a reference
83 :     to a list of subsystem names. If nothing is specified, all known subsystems will be
84 :     considered trusted. Only subsystem data related to the trusted subsystems is loaded.
85 :    
86 : parrello 1.8 =item options
87 :    
88 :     Reference to a hash of command-line options.
89 :    
90 : parrello 1.1 =back
91 :    
92 :     =cut
93 :    
94 :     sub new {
95 :     # Get the parameters.
96 : parrello 1.8 my ($class, $sprout, $fig, $genomeFile, $subsysFile, $options) = @_;
97 : parrello 1.1 # Load the list of genomes into a hash.
98 :     my %genomes;
99 :     if (! defined($genomeFile) || $genomeFile eq '') {
100 :     # Here we want all the complete genomes and an access code of 1.
101 :     my @genomeList = $fig->genomes(1);
102 :     %genomes = map { $_ => 1 } @genomeList;
103 : parrello 1.3 } else {
104 :     my $type = ref $genomeFile;
105 :     Trace("Genome file parameter type is \"$type\".") if T(3);
106 :     if ($type eq 'HASH') {
107 :     # Here the user specified a hash of genome IDs to access codes, which is
108 :     # exactly what we want.
109 :     %genomes = %{$genomeFile};
110 :     } elsif (! $type || $type eq 'SCALAR' ) {
111 :     # The caller specified a file, so read the genomes from the file. (Note
112 :     # that some PERLs return an empty string rather than SCALAR.)
113 :     my @genomeList = Tracer::GetFile($genomeFile);
114 :     if (! @genomeList) {
115 :     # It's an error if the genome file is empty or not found.
116 :     Confess("No genomes found in file \"$genomeFile\".");
117 :     } else {
118 :     # We build the genome Hash using a loop rather than "map" so that
119 :     # an omitted access code can be defaulted to 1.
120 :     for my $genomeLine (@genomeList) {
121 :     my ($genomeID, $accessCode) = split("\t", $genomeLine);
122 :     if (undef $accessCode) {
123 :     $accessCode = 1;
124 :     }
125 :     $genomes{$genomeID} = $accessCode;
126 : parrello 1.1 }
127 :     }
128 : parrello 1.3 } else {
129 :     Confess("Invalid genome parameter ($type) in SproutLoad constructor.");
130 : parrello 1.1 }
131 :     }
132 :     # Load the list of trusted subsystems.
133 :     my %subsystems = ();
134 :     if (! defined $subsysFile || $subsysFile eq '') {
135 :     # Here we want all the subsystems.
136 :     %subsystems = map { $_ => 1 } $fig->all_subsystems();
137 : parrello 1.4 } else {
138 :     my $type = ref $subsysFile;
139 :     if ($type eq 'ARRAY') {
140 :     # Here the user passed in a list of subsystems.
141 :     %subsystems = map { $_ => 1 } @{$subsysFile};
142 :     } elsif (! $type || $type eq 'SCALAR') {
143 :     # Here the list of subsystems is in a file.
144 :     if (! -e $subsysFile) {
145 :     # It's an error if the file does not exist.
146 :     Confess("Trusted subsystem file not found.");
147 :     } else {
148 :     # GetFile automatically chomps end-of-line characters, so this
149 :     # is an easy task.
150 :     %subsystems = map { $_ => 1 } Tracer::GetFile($subsysFile);
151 :     }
152 : parrello 1.1 } else {
153 : parrello 1.4 Confess("Invalid subsystem parameter in SproutLoad constructor.");
154 : parrello 1.1 }
155 :     }
156 :     # Get the data directory from the Sprout object.
157 :     my ($directory) = $sprout->LoadInfo();
158 :     # Create the Sprout load object.
159 :     my $retVal = {
160 :     fig => $fig,
161 :     genomes => \%genomes,
162 :     subsystems => \%subsystems,
163 :     sprout => $sprout,
164 :     loadDirectory => $directory,
165 :     erdb => $sprout->{_erdb},
166 : parrello 1.8 loaders => [],
167 :     options => $options
168 : parrello 1.1 };
169 :     # Bless and return it.
170 :     bless $retVal, $class;
171 :     return $retVal;
172 :     }
173 :    
174 : parrello 1.23 =head3 LoadOnly
175 :    
176 :     C<< my $flag = $spl->LoadOnly; >>
177 :    
178 :     Return TRUE if we are in load-only mode, else FALSE.
179 :    
180 :     =cut
181 :    
182 :     sub LoadOnly {
183 :     my ($self) = @_;
184 :     return $self->{options}->{loadOnly};
185 :     }
186 :    
187 : parrello 1.1 =head3 LoadGenomeData
188 :    
189 :     C<< my $stats = $spl->LoadGenomeData(); >>
190 :    
191 :     Load the Genome, Contig, and Sequence data from FIG into Sprout.
192 :    
193 :     The Sequence table is the largest single relation in the Sprout database, so this
194 :     method is expected to be slow and clumsy. At some point we will need to make it
195 :     restartable, since an error 10 gigabytes through a 20-gigabyte load is bound to be
196 :     very annoying otherwise.
197 :    
198 :     The following relations are loaded by this method.
199 :    
200 :     Genome
201 :     HasContig
202 :     Contig
203 :     IsMadeUpOf
204 :     Sequence
205 :    
206 :     =over 4
207 :    
208 :     =item RETURNS
209 :    
210 :     Returns a statistics object for the loads.
211 :    
212 :     =back
213 :    
214 :     B<TO DO>
215 :    
216 :     Real quality vectors instead of C<unknown> for everything.
217 :    
218 :     GenomeGroup relation. (The original script took group information from the C<NMPDR> file
219 :     in each genome's main directory, but no such file exists anywhere in my version of the
220 :     data store.)
221 :    
222 :     =cut
223 :     #: Return Type $%;
224 :     sub LoadGenomeData {
225 :     # Get this object instance.
226 :     my ($self) = @_;
227 :     # Get the FIG object.
228 :     my $fig = $self->{fig};
229 :     # Get the genome count.
230 :     my $genomeHash = $self->{genomes};
231 :     my $genomeCount = (keys %{$genomeHash});
232 :     # Create load objects for each of the tables we're loading.
233 : parrello 1.23 my $loadGenome = $self->_TableLoader('Genome');
234 :     my $loadHasContig = $self->_TableLoader('HasContig');
235 :     my $loadContig = $self->_TableLoader('Contig');
236 :     my $loadIsMadeUpOf = $self->_TableLoader('IsMadeUpOf');
237 :     my $loadSequence = $self->_TableLoader('Sequence');
238 :     if ($self->{options}->{loadOnly}) {
239 :     Trace("Loading from existing files.") if T(2);
240 :     } else {
241 :     Trace("Generating genome data.") if T(2);
242 :     # Now we loop through the genomes, generating the data for each one.
243 :     for my $genomeID (sort keys %{$genomeHash}) {
244 :     Trace("Generating data for genome $genomeID.") if T(3);
245 :     $loadGenome->Add("genomeIn");
246 :     # The access code comes in via the genome hash.
247 :     my $accessCode = $genomeHash->{$genomeID};
248 :     # Get the genus, species, and strain from the scientific name. Note that we append
249 :     # the genome ID to the strain. In some cases this is the totality of the strain name.
250 :     my ($genus, $species, @extraData) = split / /, $self->{fig}->genus_species($genomeID);
251 :     my $extra = join " ", @extraData, "[$genomeID]";
252 :     # Get the full taxonomy.
253 :     my $taxonomy = $fig->taxonomy_of($genomeID);
254 :     # Output the genome record.
255 :     $loadGenome->Put($genomeID, $accessCode, $fig->is_complete($genomeID), $genus,
256 :     $species, $extra, $taxonomy);
257 :     # Now we loop through each of the genome's contigs.
258 :     my @contigs = $fig->all_contigs($genomeID);
259 :     for my $contigID (@contigs) {
260 :     Trace("Processing contig $contigID for $genomeID.") if T(4);
261 :     $loadContig->Add("contigIn");
262 :     $loadSequence->Add("contigIn");
263 :     # Create the contig ID.
264 :     my $sproutContigID = "$genomeID:$contigID";
265 :     # Create the contig record and relate it to the genome.
266 :     $loadContig->Put($sproutContigID);
267 :     $loadHasContig->Put($genomeID, $sproutContigID);
268 :     # Now we need to split the contig into sequences. The maximum sequence size is
269 :     # a property of the Sprout object.
270 :     my $chunkSize = $self->{sprout}->MaxSequence();
271 :     # Now we get the sequence a chunk at a time.
272 :     my $contigLen = $fig->contig_ln($genomeID, $contigID);
273 :     for (my $i = 1; $i <= $contigLen; $i += $chunkSize) {
274 :     $loadSequence->Add("chunkIn");
275 :     # Compute the endpoint of this chunk.
276 :     my $end = FIG::min($i + $chunkSize - 1, $contigLen);
277 :     # Get the actual DNA.
278 :     my $dna = $fig->get_dna($genomeID, $contigID, $i, $end);
279 :     # Compute the sequenceID.
280 :     my $seqID = "$sproutContigID.$i";
281 :     # Write out the data. For now, the quality vector is always "unknown".
282 :     $loadIsMadeUpOf->Put($sproutContigID, $seqID, $end + 1 - $i, $i);
283 :     $loadSequence->Put($seqID, "unknown", $dna);
284 :     }
285 : parrello 1.1 }
286 :     }
287 :     }
288 :     # Finish the loads.
289 :     my $retVal = $self->_FinishAll();
290 :     # Return the result.
291 :     return $retVal;
292 :     }
293 :    
294 :     =head3 LoadCouplingData
295 :    
296 :     C<< my $stats = $spl->LoadCouplingData(); >>
297 :    
298 :     Load the coupling and evidence data from FIG into Sprout.
299 :    
300 :     The coupling data specifies which genome features are functionally coupled. The
301 :     evidence data explains why the coupling is functional.
302 :    
303 :     The following relations are loaded by this method.
304 :    
305 :     Coupling
306 :     IsEvidencedBy
307 :     PCH
308 :     ParticipatesInCoupling
309 :     UsesAsEvidence
310 :    
311 :     =over 4
312 :    
313 :     =item RETURNS
314 :    
315 :     Returns a statistics object for the loads.
316 :    
317 :     =back
318 :    
319 :     =cut
320 :     #: Return Type $%;
321 :     sub LoadCouplingData {
322 :     # Get this object instance.
323 :     my ($self) = @_;
324 :     # Get the FIG object.
325 :     my $fig = $self->{fig};
326 :     # Get the genome hash.
327 :     my $genomeFilter = $self->{genomes};
328 :     my $genomeCount = (keys %{$genomeFilter});
329 :     my $featureCount = $genomeCount * 4000;
330 :     # Start the loads.
331 : parrello 1.23 my $loadCoupling = $self->_TableLoader('Coupling');
332 :     my $loadIsEvidencedBy = $self->_TableLoader('IsEvidencedBy');
333 :     my $loadPCH = $self->_TableLoader('PCH');
334 :     my $loadParticipatesInCoupling = $self->_TableLoader('ParticipatesInCoupling');
335 :     my $loadUsesAsEvidence = $self->_TableLoader('UsesAsEvidence');
336 :     if ($self->{options}->{loadOnly}) {
337 :     Trace("Loading from existing files.") if T(2);
338 :     } else {
339 :     Trace("Generating coupling data.") if T(2);
340 :     # Loop through the genomes found.
341 :     for my $genome (sort keys %{$genomeFilter}) {
342 :     Trace("Generating coupling data for $genome.") if T(3);
343 :     $loadCoupling->Add("genomeIn");
344 :     # Create a hash table for holding coupled pairs. We use this to prevent
345 :     # duplicates. For example, if A is coupled to B, we don't want to also
346 :     # assert that B is coupled to A, because we already know it. Fortunately,
347 :     # all couplings occur within a genome, so we can keep the hash table
348 :     # size reasonably small.
349 :     my %dupHash = ();
350 :     # Get all of the genome's PEGs.
351 :     my @pegs = $fig->pegs_of($genome);
352 :     # Loop through the PEGs.
353 :     for my $peg1 (@pegs) {
354 :     $loadCoupling->Add("pegIn");
355 :     Trace("Processing PEG $peg1 for $genome.") if T(4);
356 :     # Get a list of the coupled PEGs.
357 :     my @couplings = $fig->coupled_to($peg1);
358 :     # For each coupled PEG, we need to verify that a coupling already
359 :     # exists. If not, we have to create one.
360 :     for my $coupleData (@couplings) {
361 :     my ($peg2, $score) = @{$coupleData};
362 :     # Compute the coupling ID.
363 :     my $coupleID = Sprout::CouplingID($peg1, $peg2);
364 :     if (! exists $dupHash{$coupleID}) {
365 :     $loadCoupling->Add("couplingIn");
366 :     # Here we have a new coupling to store in the load files.
367 :     Trace("Storing coupling ($coupleID) with score $score.") if T(4);
368 :     # Ensure we don't do this again.
369 :     $dupHash{$coupleID} = $score;
370 :     # Write the coupling record.
371 :     $loadCoupling->Put($coupleID, $score);
372 :     # Connect it to the coupled PEGs.
373 :     $loadParticipatesInCoupling->Put($peg1, $coupleID, 1);
374 :     $loadParticipatesInCoupling->Put($peg2, $coupleID, 2);
375 :     # Get the evidence for this coupling.
376 :     my @evidence = $fig->coupling_evidence($peg1, $peg2);
377 :     # Organize the evidence into a hash table.
378 :     my %evidenceMap = ();
379 :     # Process each evidence item.
380 :     for my $evidenceData (@evidence) {
381 :     $loadPCH->Add("evidenceIn");
382 :     my ($peg3, $peg4, $usage) = @{$evidenceData};
383 :     # Only proceed if the evidence is from a Sprout
384 :     # genome.
385 :     if ($genomeFilter->{$fig->genome_of($peg3)}) {
386 :     $loadUsesAsEvidence->Add("evidenceChosen");
387 :     my $evidenceKey = "$coupleID $peg3 $peg4";
388 :     # We store this evidence in the hash if the usage
389 :     # is nonzero or no prior evidence has been found. This
390 :     # insures that if there is duplicate evidence, we
391 :     # at least keep the meaningful ones. Only evidence in
392 :     # the hash makes it to the output.
393 :     if ($usage || ! exists $evidenceMap{$evidenceKey}) {
394 :     $evidenceMap{$evidenceKey} = $evidenceData;
395 :     }
396 : parrello 1.1 }
397 :     }
398 : parrello 1.23 for my $evidenceID (keys %evidenceMap) {
399 :     # Create the evidence record.
400 :     my ($peg3, $peg4, $usage) = @{$evidenceMap{$evidenceID}};
401 :     $loadPCH->Put($evidenceID, $usage);
402 :     # Connect it to the coupling.
403 :     $loadIsEvidencedBy->Put($coupleID, $evidenceID);
404 :     # Connect it to the features.
405 :     $loadUsesAsEvidence->Put($evidenceID, $peg3, 1);
406 :     $loadUsesAsEvidence->Put($evidenceID, $peg4, 2);
407 :     }
408 : parrello 1.1 }
409 :     }
410 :     }
411 :     }
412 :     }
413 :     # All done. Finish the load.
414 :     my $retVal = $self->_FinishAll();
415 :     return $retVal;
416 :     }
417 :    
418 :     =head3 LoadFeatureData
419 :    
420 :     C<< my $stats = $spl->LoadFeatureData(); >>
421 :    
422 :     Load the feature data from FIG into Sprout.
423 :    
424 :     Features represent annotated genes, and are therefore the heart of the data store.
425 :    
426 :     The following relations are loaded by this method.
427 :    
428 :     Feature
429 :     FeatureAlias
430 :     FeatureLink
431 :     FeatureTranslation
432 :     FeatureUpstream
433 :     IsLocatedIn
434 :    
435 :     =over 4
436 :    
437 :     =item RETURNS
438 :    
439 :     Returns a statistics object for the loads.
440 :    
441 :     =back
442 :    
443 :     =cut
444 :     #: Return Type $%;
445 :     sub LoadFeatureData {
446 :     # Get this object instance.
447 :     my ($self) = @_;
448 :     # Get the FIG object.
449 :     my $fig = $self->{fig};
450 :     # Get the table of genome IDs.
451 :     my $genomeHash = $self->{genomes};
452 :     # Create load objects for each of the tables we're loading.
453 : parrello 1.23 my $loadFeature = $self->_TableLoader('Feature');
454 :     my $loadIsLocatedIn = $self->_TableLoader('IsLocatedIn');
455 :     my $loadFeatureAlias = $self->_TableLoader('FeatureAlias');
456 :     my $loadFeatureLink = $self->_TableLoader('FeatureLink');
457 :     my $loadFeatureTranslation = $self->_TableLoader('FeatureTranslation');
458 :     my $loadFeatureUpstream = $self->_TableLoader('FeatureUpstream');
459 : parrello 1.1 # Get the maximum sequence size. We need this later for splitting up the
460 :     # locations.
461 :     my $chunkSize = $self->{sprout}->MaxSegment();
462 : parrello 1.23 if ($self->{options}->{loadOnly}) {
463 :     Trace("Loading from existing files.") if T(2);
464 :     } else {
465 :     Trace("Generating feature data.") if T(2);
466 :     # Now we loop through the genomes, generating the data for each one.
467 :     for my $genomeID (sort keys %{$genomeHash}) {
468 :     Trace("Loading features for genome $genomeID.") if T(3);
469 :     $loadFeature->Add("genomeIn");
470 :     # Get the feature list for this genome.
471 :     my $features = $fig->all_features_detailed($genomeID);
472 :     # Loop through the features.
473 :     for my $featureData (@{$features}) {
474 :     $loadFeature->Add("featureIn");
475 :     # Split the tuple.
476 :     my ($featureID, $locations, undef, $type) = @{$featureData};
477 :     # Create the feature record.
478 :     $loadFeature->Put($featureID, 1, $type);
479 :     # Create the aliases.
480 :     for my $alias ($fig->feature_aliases($featureID)) {
481 :     $loadFeatureAlias->Put($featureID, $alias);
482 :     }
483 : parrello 1.8 # Get the links.
484 :     my @links = $fig->fid_links($featureID);
485 :     for my $link (@links) {
486 :     $loadFeatureLink->Put($featureID, $link);
487 : parrello 1.1 }
488 : parrello 1.8 # If this is a peg, generate the translation and the upstream.
489 :     if ($type eq 'peg') {
490 :     $loadFeatureTranslation->Add("pegIn");
491 :     my $translation = $fig->get_translation($featureID);
492 :     if ($translation) {
493 :     $loadFeatureTranslation->Put($featureID, $translation);
494 :     }
495 :     # We use the default upstream values of u=200 and c=100.
496 :     my $upstream = $fig->upstream_of($featureID, 200, 100);
497 :     if ($upstream) {
498 :     $loadFeatureUpstream->Put($featureID, $upstream);
499 :     }
500 : parrello 1.1 }
501 : parrello 1.23 # This part is the roughest. We need to relate the features to contig
502 :     # locations, and the locations must be split so that none of them exceed
503 :     # the maximum segment size. This simplifies the genes_in_region processing
504 :     # for Sprout.
505 :     my @locationList = split /\s*,\s*/, $locations;
506 :     # Create the location position indicator.
507 :     my $i = 1;
508 :     # Loop through the locations.
509 :     for my $location (@locationList) {
510 :     # Parse the location.
511 :     my $locObject = BasicLocation->new("$genomeID:$location");
512 :     # Split it into a list of chunks.
513 :     my @locOList = ();
514 :     while (my $peeling = $locObject->Peel($chunkSize)) {
515 :     $loadIsLocatedIn->Add("peeling");
516 :     push @locOList, $peeling;
517 :     }
518 :     push @locOList, $locObject;
519 :     # Loop through the chunks, creating IsLocatedIn records. The variable
520 :     # "$i" will be used to keep the location index.
521 :     for my $locChunk (@locOList) {
522 :     $loadIsLocatedIn->Put($featureID, $locChunk->Contig, $locChunk->Left,
523 :     $locChunk->Dir, $locChunk->Length, $i);
524 :     $i++;
525 :     }
526 : parrello 1.1 }
527 :     }
528 :     }
529 :     }
530 :     # Finish the loads.
531 :     my $retVal = $self->_FinishAll();
532 :     return $retVal;
533 :     }
534 :    
535 :     =head3 LoadBBHData
536 :    
537 :     C<< my $stats = $spl->LoadBBHData(); >>
538 :    
539 :     Load the bidirectional best hit data from FIG into Sprout.
540 :    
541 :     Sprout does not store information on similarities. Instead, it has only the
542 :     bi-directional best hits. Even so, the BBH table is one of the largest in
543 :     the database.
544 :    
545 :     The following relations are loaded by this method.
546 :    
547 :     IsBidirectionalBestHitOf
548 :    
549 :     =over 4
550 :    
551 :     =item RETURNS
552 :    
553 :     Returns a statistics object for the loads.
554 :    
555 :     =back
556 :    
557 :     =cut
558 :     #: Return Type $%;
559 : parrello 1.2 sub LoadBBHData {
560 : parrello 1.1 # Get this object instance.
561 :     my ($self) = @_;
562 :     # Get the FIG object.
563 :     my $fig = $self->{fig};
564 :     # Get the table of genome IDs.
565 :     my $genomeHash = $self->{genomes};
566 :     # Create load objects for each of the tables we're loading.
567 : parrello 1.23 my $loadIsBidirectionalBestHitOf = $self->_TableLoader('IsBidirectionalBestHitOf');
568 :     if ($self->{options}->{loadOnly}) {
569 :     Trace("Loading from existing files.") if T(2);
570 :     } else {
571 :     Trace("Generating BBH data.") if T(2);
572 :     # Now we loop through the genomes, generating the data for each one.
573 :     for my $genomeID (sort keys %{$genomeHash}) {
574 :     $loadIsBidirectionalBestHitOf->Add("genomeIn");
575 :     Trace("Processing features for genome $genomeID.") if T(3);
576 :     # Get the feature list for this genome.
577 :     my $features = $fig->all_features_detailed($genomeID);
578 :     # Loop through the features.
579 :     for my $featureData (@{$features}) {
580 :     # Split the tuple.
581 :     my ($featureID, $locations, $aliases, $type) = @{$featureData};
582 :     # Get the bi-directional best hits.
583 :     my @bbhList = $fig->bbhs($featureID);
584 :     for my $bbhEntry (@bbhList) {
585 :     # Get the target feature ID and the score.
586 :     my ($targetID, $score) = @{$bbhEntry};
587 :     # Check the target feature's genome.
588 :     my $targetGenomeID = $fig->genome_of($targetID);
589 :     # Only proceed if it's one of our genomes.
590 :     if ($genomeHash->{$targetGenomeID}) {
591 :     $loadIsBidirectionalBestHitOf->Put($featureID, $targetID, $targetGenomeID,
592 :     $score);
593 :     }
594 : parrello 1.1 }
595 :     }
596 :     }
597 :     }
598 :     # Finish the loads.
599 :     my $retVal = $self->_FinishAll();
600 :     return $retVal;
601 :     }
602 :    
603 :     =head3 LoadSubsystemData
604 :    
605 :     C<< my $stats = $spl->LoadSubsystemData(); >>
606 :    
607 :     Load the subsystem data from FIG into Sprout.
608 :    
609 :     Subsystems are groupings of genetic roles that work together to effect a specific
610 :     chemical reaction. Similar organisms require similar subsystems. To curate a subsystem,
611 :     a spreadsheet is created with genomes on one axis and subsystem roles on the other
612 :     axis. Similar features are then mapped into the cells, allowing the annotation of one
613 :     genome's roles to be used to assist in the annotation of others.
614 :    
615 :     The following relations are loaded by this method.
616 :    
617 :     Subsystem
618 :     Role
619 : parrello 1.19 RoleEC
620 : parrello 1.1 SSCell
621 :     ContainsFeature
622 :     IsGenomeOf
623 :     IsRoleOf
624 :     OccursInSubsystem
625 :     ParticipatesIn
626 :     HasSSCell
627 : parrello 1.18 ConsistsOfRoles
628 :     RoleSubset
629 :     HasRoleSubset
630 :     ConsistsOfGenomes
631 :     GenomeSubset
632 :     HasGenomeSubset
633 : parrello 1.20 Catalyzes
634 : parrello 1.21 Diagram
635 :     RoleOccursIn
636 : parrello 1.1
637 :     =over 4
638 :    
639 :     =item RETURNS
640 :    
641 :     Returns a statistics object for the loads.
642 :    
643 :     =back
644 :    
645 :     =cut
646 :     #: Return Type $%;
647 :     sub LoadSubsystemData {
648 :     # Get this object instance.
649 :     my ($self) = @_;
650 :     # Get the FIG object.
651 :     my $fig = $self->{fig};
652 :     # Get the genome hash. We'll use it to filter the genomes in each
653 :     # spreadsheet.
654 :     my $genomeHash = $self->{genomes};
655 :     # Get the subsystem hash. This lists the subsystems we'll process.
656 :     my $subsysHash = $self->{subsystems};
657 :     my @subsysIDs = sort keys %{$subsysHash};
658 : parrello 1.21 # Get the map list.
659 :     my @maps = $fig->all_maps;
660 : parrello 1.1 # Create load objects for each of the tables we're loading.
661 : parrello 1.23 my $loadDiagram = $self->_TableLoader('Diagram');
662 :     my $loadRoleOccursIn = $self->_TableLoader('RoleOccursIn');
663 :     my $loadSubsystem = $self->_TableLoader('Subsystem');
664 :     my $loadRole = $self->_TableLoader('Role');
665 :     my $loadRoleEC = $self->_TableLoader('RoleEC');
666 :     my $loadCatalyzes = $self->_TableLoader('Catalyzes');
667 :     my $loadSSCell = $self->_TableLoader('SSCell');
668 :     my $loadContainsFeature = $self->_TableLoader('ContainsFeature');
669 :     my $loadIsGenomeOf = $self->_TableLoader('IsGenomeOf');
670 :     my $loadIsRoleOf = $self->_TableLoader('IsRoleOf');
671 :     my $loadOccursInSubsystem = $self->_TableLoader('OccursInSubsystem');
672 :     my $loadParticipatesIn = $self->_TableLoader('ParticipatesIn');
673 :     my $loadHasSSCell = $self->_TableLoader('HasSSCell');
674 :     my $loadRoleSubset = $self->_TableLoader('RoleSubset');
675 :     my $loadGenomeSubset = $self->_TableLoader('GenomeSubset');
676 :     my $loadConsistsOfRoles = $self->_TableLoader('ConsistsOfRoles');
677 :     my $loadConsistsOfGenomes = $self->_TableLoader('ConsistsOfGenomes');
678 :     my $loadHasRoleSubset = $self->_TableLoader('HasRoleSubset');
679 :     my $loadHasGenomeSubset = $self->_TableLoader('HasGenomeSubset');
680 :     if ($self->{options}->{loadOnly}) {
681 :     Trace("Loading from existing files.") if T(2);
682 :     } else {
683 :     Trace("Generating subsystem data.") if T(2);
684 :     # This hash will contain the role for each EC. When we're done, this
685 :     # information will be used to generate the Catalyzes table.
686 :     my %ecToRoles = ();
687 :     # Loop through the subsystems. Our first task will be to create the
688 :     # roles. We do this by looping through the subsystems and creating a
689 :     # role hash. The hash tracks each role ID so that we don't create
690 :     # duplicates. As we move along, we'll connect the roles and subsystems
691 :     # and memorize up the reactions.
692 :     my ($genomeID, $roleID);
693 :     my %roleData = ();
694 :     for my $subsysID (@subsysIDs) {
695 :     Trace("Creating subsystem $subsysID.") if T(3);
696 :     $loadSubsystem->Add("subsystemIn");
697 :     # Get the subsystem object.
698 :     my $sub = $fig->get_subsystem($subsysID);
699 :     # Create the subsystem record.
700 :     my $curator = $sub->get_curator();
701 :     my $notes = $sub->get_notes();
702 :     $loadSubsystem->Put($subsysID, $curator, $notes);
703 :     # Connect it to its roles. Each role is a column in the subsystem spreadsheet.
704 :     for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {
705 :     # Connect to this role.
706 :     $loadOccursInSubsystem->Add("roleIn");
707 :     $loadOccursInSubsystem->Put($roleID, $subsysID, $col);
708 :     # If it's a new role, add it to the role table.
709 :     if (! exists $roleData{$roleID}) {
710 :     # Get the role's abbreviation.
711 :     my $abbr = $sub->get_role_abbr($col);
712 :     # Add the role.
713 :     $loadRole->Put($roleID, $abbr);
714 :     $roleData{$roleID} = 1;
715 :     # Check for an EC number.
716 :     if ($roleID =~ /\(EC ([^.]+\.[^.]+\.[^.]+\.[^)]+)\)\s*$/) {
717 :     my $ec = $1;
718 :     $loadRoleEC->Put($roleID, $ec);
719 :     $ecToRoles{$ec} = $roleID;
720 :     }
721 : parrello 1.18 }
722 : parrello 1.1 }
723 : parrello 1.23 # Now we create the spreadsheet for the subsystem by matching roles to
724 :     # genomes. Each genome is a row and each role is a column. We may need
725 :     # to actually create the roles as we find them.
726 :     Trace("Creating subsystem $subsysID spreadsheet.") if T(3);
727 :     for (my $row = 0; defined($genomeID = $sub->get_genome($row)); $row++) {
728 :     # Only proceed if this is one of our genomes.
729 :     if (exists $genomeHash->{$genomeID}) {
730 :     # Count the PEGs and cells found for verification purposes.
731 :     my $pegCount = 0;
732 :     my $cellCount = 0;
733 :     # Create a list for the PEGs we find. This list will be used
734 :     # to generate cluster numbers.
735 :     my @pegsFound = ();
736 :     # Create a hash that maps spreadsheet IDs to PEGs. We will
737 :     # use this to generate the ContainsFeature data after we have
738 :     # the cluster numbers.
739 :     my %cellPegs = ();
740 :     # Get the genome's variant code for this subsystem.
741 :     my $variantCode = $sub->get_variant_code($row);
742 :     # Loop through the subsystem's roles. We use an index because it is
743 :     # part of the spreadsheet cell ID.
744 :     for (my $col = 0; defined($roleID = $sub->get_role($col)); $col++) {
745 :     # Get the features in the spreadsheet cell for this genome and role.
746 :     my @pegs = $sub->get_pegs_from_cell($row, $col);
747 :     # Only proceed if features exist.
748 :     if (@pegs > 0) {
749 :     # Create the spreadsheet cell.
750 :     $cellCount++;
751 :     my $cellID = "$subsysID:$genomeID:$col";
752 :     $loadSSCell->Put($cellID);
753 :     $loadIsGenomeOf->Put($genomeID, $cellID);
754 :     $loadIsRoleOf->Put($roleID, $cellID);
755 :     $loadHasSSCell->Put($subsysID, $cellID);
756 :     # Remember its features.
757 :     push @pegsFound, @pegs;
758 :     $cellPegs{$cellID} = \@pegs;
759 :     $pegCount += @pegs;
760 :     }
761 : parrello 1.1 }
762 : parrello 1.23 # If we found some cells for this genome, we need to compute clusters and
763 :     # denote it participates in the subsystem.
764 :     if ($pegCount > 0) {
765 :     Trace("$pegCount PEGs in $cellCount cells for $genomeID.") if T(3);
766 :     $loadParticipatesIn->Put($genomeID, $subsysID, $variantCode);
767 :     # Partition the PEGs found into clusters.
768 :     my @clusters = $fig->compute_clusters(\@pegsFound, $sub);
769 :     # Create a hash mapping PEG IDs to cluster numbers.
770 :     # We default to -1 for all of them.
771 :     my %clusterOf = map { $_ => -1 } @pegsFound;
772 :     for (my $i = 0; $i <= $#clusters; $i++) {
773 :     my $subList = $clusters[$i];
774 :     for my $peg (@{$subList}) {
775 :     $clusterOf{$peg} = $i;
776 :     }
777 : parrello 1.18 }
778 : parrello 1.23 # Create the ContainsFeature data.
779 :     for my $cellID (keys %cellPegs) {
780 :     my $cellList = $cellPegs{$cellID};
781 :     for my $cellPeg (@$cellList) {
782 :     $loadContainsFeature->Put($cellID, $cellPeg, $clusterOf{$cellPeg});
783 :     }
784 : parrello 1.18 }
785 :     }
786 : parrello 1.15 }
787 : parrello 1.1 }
788 : parrello 1.23 # Now we need to generate the subsets. The subset names must be concatenated to
789 :     # the subsystem name to make them unique keys. There are two types of subsets:
790 :     # genome subsets and role subsets. We do the role subsets first.
791 :     my @subsetNames = $sub->get_subset_names();
792 :     for my $subsetID (@subsetNames) {
793 :     # Create the subset record.
794 :     my $actualID = "$subsysID:$subsetID";
795 :     $loadRoleSubset->Put($actualID);
796 :     # Connect the subset to the subsystem.
797 :     $loadHasRoleSubset->Put($subsysID, $actualID);
798 :     # Connect the subset to its roles.
799 :     my @roles = $sub->get_subset($subsetID);
800 :     for my $roleID (@roles) {
801 :     $loadConsistsOfRoles->Put($actualID, $roleID);
802 :     }
803 : parrello 1.18 }
804 : parrello 1.23 # Next the genome subsets.
805 :     @subsetNames = $sub->get_subset_namesR();
806 :     for my $subsetID (@subsetNames) {
807 :     # Create the subset record.
808 :     my $actualID = "$subsysID:$subsetID";
809 :     $loadGenomeSubset->Put($actualID);
810 :     # Connect the subset to the subsystem.
811 :     $loadHasGenomeSubset->Put($subsysID, $actualID);
812 :     # Connect the subset to its genomes.
813 :     my @genomes = $sub->get_subsetR($subsetID);
814 :     for my $genomeID (@genomes) {
815 :     $loadConsistsOfGenomes->Put($actualID, $genomeID);
816 :     }
817 : parrello 1.18 }
818 :     }
819 : parrello 1.23 # Now we loop through the diagrams. We need to create the diagram records
820 :     # and link each diagram to its roles. Note that only roles which occur
821 :     # in subsystems (and therefore appear in the %ecToRoles hash) are
822 :     # included.
823 :     for my $map (@maps) {
824 :     Trace("Loading diagram $map.") if T(3);
825 :     # Get the diagram's descriptive name.
826 :     my $name = $fig->map_name($map);
827 :     $loadDiagram->Put($map, $name);
828 :     # Now we need to link all the map's roles to it.
829 :     # A hash is used to prevent duplicates.
830 :     my %roleHash = ();
831 :     for my $role ($fig->map_to_ecs($map)) {
832 :     if (exists $ecToRoles{$role} && ! $roleHash{$role}) {
833 :     $loadRoleOccursIn->Put($ecToRoles{$role}, $map);
834 :     $roleHash{$role} = 1;
835 :     }
836 : parrello 1.21 }
837 :     }
838 : parrello 1.23 # Before we leave, we must create the Catalyzes table. We start with the reactions,
839 :     # then use the "ecToRoles" table to convert EC numbers to role IDs.
840 :     my @reactions = $fig->all_reactions();
841 :     for my $reactionID (@reactions) {
842 :     # Get this reaction's list of roles. The results will be EC numbers.
843 :     my @roles = $fig->catalyzed_by($reactionID);
844 :     # Loop through the roles, creating catalyzation records.
845 :     for my $thisRole (@roles) {
846 :     if (exists $ecToRoles{$thisRole}) {
847 :     $loadCatalyzes->Put($ecToRoles{$thisRole}, $reactionID);
848 :     }
849 : parrello 1.18 }
850 :     }
851 : parrello 1.1 }
852 :     # Finish the load.
853 :     my $retVal = $self->_FinishAll();
854 :     return $retVal;
855 :     }
856 :    
857 :     =head3 LoadPropertyData
858 :    
859 :     C<< my $stats = $spl->LoadPropertyData(); >>
860 :    
861 :     Load the attribute data from FIG into Sprout.
862 :    
863 :     Attribute data in FIG corresponds to the Sprout concept of Property. As currently
864 :     implemented, each key-value attribute combination in the SEED corresponds to a
865 :     record in the B<Property> table. The B<HasProperty> relationship links the
866 :     features to the properties.
867 :    
868 :     The SEED also allows attributes to be assigned to genomes, but this is not yet
869 :     supported by Sprout.
870 :    
871 :     The following relations are loaded by this method.
872 :    
873 :     HasProperty
874 :     Property
875 :    
876 :     =over 4
877 :    
878 :     =item RETURNS
879 :    
880 :     Returns a statistics object for the loads.
881 :    
882 :     =back
883 :    
884 :     =cut
885 :     #: Return Type $%;
886 :     sub LoadPropertyData {
887 :     # Get this object instance.
888 :     my ($self) = @_;
889 :     # Get the FIG object.
890 :     my $fig = $self->{fig};
891 :     # Get the genome hash.
892 :     my $genomeHash = $self->{genomes};
893 :     # Create load objects for each of the tables we're loading.
894 : parrello 1.23 my $loadProperty = $self->_TableLoader('Property');
895 :     my $loadHasProperty = $self->_TableLoader('HasProperty');
896 :     if ($self->{options}->{loadOnly}) {
897 :     Trace("Loading from existing files.") if T(2);
898 :     } else {
899 :     Trace("Generating property data.") if T(2);
900 :     # Create a hash for storing property IDs.
901 :     my %propertyKeys = ();
902 :     my $nextID = 1;
903 :     # Loop through the genomes.
904 :     for my $genomeID (keys %{$genomeHash}) {
905 :     $loadProperty->Add("genomeIn");
906 : parrello 1.24 Trace("Generating properties for $genomeID.") if T(3);
907 : parrello 1.23 # Get the genome's features. The feature ID is the first field in the
908 :     # tuples returned by "all_features_detailed". We use "all_features_detailed"
909 :     # rather than "all_features" because we want all features regardless of type.
910 :     my @features = map { $_->[0] } @{$fig->all_features_detailed($genomeID)};
911 : parrello 1.24 my $featureCount = 0;
912 :     my $propertyCount = 0;
913 : parrello 1.23 # Loop through the features, creating HasProperty records.
914 :     for my $fid (@features) {
915 :     # Get all attributes for this feature. We do this one feature at a time
916 :     # to insure we do not get any genome attributes.
917 :     my @attributeList = $fig->get_attributes($fid, '', '', '');
918 : parrello 1.24 if (scalar @attributeList) {
919 :     $featureCount++;
920 :     }
921 : parrello 1.23 # Loop through the attributes.
922 :     for my $tuple (@attributeList) {
923 : parrello 1.24 $propertyCount++;
924 : parrello 1.23 # Get this attribute value's data. Note that we throw away the FID,
925 :     # since it will always be the same as the value if "$fid".
926 :     my (undef, $key, $value, $url) = @{$tuple};
927 :     # Concatenate the key and value and check the "propertyKeys" hash to
928 :     # see if we already have an ID for it. We use a tab for the separator
929 :     # character.
930 :     my $propertyKey = "$key\t$value";
931 :     # Use the concatenated value to check for an ID. If no ID exists, we
932 :     # create one.
933 :     my $propertyID = $propertyKeys{$propertyKey};
934 :     if (! $propertyID) {
935 :     # Here we need to create a new property ID for this key/value pair.
936 :     $propertyKeys{$propertyKey} = $nextID;
937 :     $propertyID = $nextID;
938 :     $nextID++;
939 :     $loadProperty->Put($propertyID, $key, $value);
940 :     }
941 :     # Create the HasProperty entry for this feature/property association.
942 :     $loadHasProperty->Put($fid, $propertyID, $url);
943 : parrello 1.1 }
944 :     }
945 : parrello 1.24 # Update the statistics.
946 :     Trace("$propertyCount attributes processed for $featureCount features.") if T(3);
947 :     $loadHasProperty->Add("featuresIn", $featureCount);
948 :     $loadHasProperty->Add("propertiesIn", $propertyCount);
949 : parrello 1.1 }
950 :     }
951 :     # Finish the load.
952 :     my $retVal = $self->_FinishAll();
953 :     return $retVal;
954 :     }
955 :    
956 :     =head3 LoadAnnotationData
957 :    
958 :     C<< my $stats = $spl->LoadAnnotationData(); >>
959 :    
960 :     Load the annotation data from FIG into Sprout.
961 :    
962 :     Sprout annotations encompass both the assignments and the annotations in SEED.
963 :     These describe the function performed by a PEG as well as any other useful
964 :     information that may aid in identifying its purpose.
965 :    
966 :     The following relations are loaded by this method.
967 :    
968 :     Annotation
969 :     IsTargetOfAnnotation
970 :     SproutUser
971 :     MadeAnnotation
972 :    
973 :     =over 4
974 :    
975 :     =item RETURNS
976 :    
977 :     Returns a statistics object for the loads.
978 :    
979 :     =back
980 :    
981 :     =cut
982 :     #: Return Type $%;
983 :     sub LoadAnnotationData {
984 :     # Get this object instance.
985 :     my ($self) = @_;
986 :     # Get the FIG object.
987 :     my $fig = $self->{fig};
988 :     # Get the genome hash.
989 :     my $genomeHash = $self->{genomes};
990 :     # Create load objects for each of the tables we're loading.
991 : parrello 1.23 my $loadAnnotation = $self->_TableLoader('Annotation');
992 :     my $loadIsTargetOfAnnotation = $self->_TableLoader('IsTargetOfAnnotation');
993 :     my $loadSproutUser = $self->_TableLoader('SproutUser');
994 :     my $loadUserAccess = $self->_TableLoader('UserAccess');
995 :     my $loadMadeAnnotation = $self->_TableLoader('MadeAnnotation');
996 :     if ($self->{options}->{loadOnly}) {
997 :     Trace("Loading from existing files.") if T(2);
998 :     } else {
999 :     Trace("Generating annotation data.") if T(2);
1000 :     # Create a hash of user names. We'll use this to prevent us from generating duplicate
1001 :     # user records.
1002 :     my %users = ( FIG => 1, master => 1 );
1003 :     # Put in FIG and "master".
1004 :     $loadSproutUser->Put("FIG", "Fellowship for Interpretation of Genomes");
1005 :     $loadUserAccess->Put("FIG", 1);
1006 :     $loadSproutUser->Put("master", "Master User");
1007 :     $loadUserAccess->Put("master", 1);
1008 :     # Get the current time.
1009 :     my $time = time();
1010 :     # Loop through the genomes.
1011 :     for my $genomeID (sort keys %{$genomeHash}) {
1012 :     Trace("Processing $genomeID.") if T(3);
1013 :     # Get the genome's PEGs.
1014 :     my @pegs = $fig->pegs_of($genomeID);
1015 :     for my $peg (@pegs) {
1016 :     Trace("Processing $peg.") if T(4);
1017 :     # Create a hash of timestamps. We use this to prevent duplicate time stamps
1018 :     # from showing up for a single PEG's annotations.
1019 :     my %seenTimestamps = ();
1020 :     # Loop through the annotations.
1021 :     for my $tuple ($fig->feature_annotations($peg, "raw")) {
1022 :     my ($fid, $timestamp, $user, $text) = @{$tuple};
1023 :     # Here we fix up the annotation text. "\r" is removed,
1024 :     # and "\t" and "\n" are escaped. Note we use the "s"
1025 :     # modifier so that new-lines inside the text do not
1026 :     # stop the substitution search.
1027 :     $text =~ s/\r//gs;
1028 :     $text =~ s/\t/\\t/gs;
1029 :     $text =~ s/\n/\\n/gs;
1030 :     # Change assignments by the master user to FIG assignments.
1031 :     $text =~ s/Set master function/Set FIG function/s;
1032 :     # Insure the time stamp is valid.
1033 :     if ($timestamp =~ /^\d+$/) {
1034 :     # Here it's a number. We need to insure the one we use to form
1035 :     # the key is unique.
1036 :     my $keyStamp = $timestamp;
1037 :     while ($seenTimestamps{$keyStamp}) {
1038 :     $keyStamp++;
1039 :     }
1040 :     $seenTimestamps{$keyStamp} = 1;
1041 :     my $annotationID = "$peg:$keyStamp";
1042 :     # Insure the user exists.
1043 :     if (! $users{$user}) {
1044 :     $loadSproutUser->Put($user, "SEED user");
1045 :     $loadUserAccess->Put($user, 1);
1046 :     $users{$user} = 1;
1047 :     }
1048 :     # Generate the annotation.
1049 :     $loadAnnotation->Put($annotationID, $timestamp, $text);
1050 :     $loadIsTargetOfAnnotation->Put($peg, $annotationID);
1051 :     $loadMadeAnnotation->Put($user, $annotationID);
1052 :     } else {
1053 :     # Here we have an invalid time stamp.
1054 :     Trace("Invalid time stamp \"$timestamp\" in annotations for $peg.") if T(1);
1055 : parrello 1.1 }
1056 :     }
1057 :     }
1058 :     }
1059 :     }
1060 :     # Finish the load.
1061 :     my $retVal = $self->_FinishAll();
1062 :     return $retVal;
1063 :     }
1064 :    
1065 : parrello 1.5 =head3 LoadSourceData
1066 :    
1067 :     C<< my $stats = $spl->LoadSourceData(); >>
1068 :    
1069 :     Load the source data from FIG into Sprout.
1070 :    
1071 :     Source data links genomes to information about the organizations that
1072 :     mapped it.
1073 :    
1074 :     The following relations are loaded by this method.
1075 :    
1076 :     ComesFrom
1077 :     Source
1078 :     SourceURL
1079 :    
1080 :     There is no direct support for source attribution in FIG, so we access the SEED
1081 :     files directly.
1082 :    
1083 :     =over 4
1084 :    
1085 :     =item RETURNS
1086 :    
1087 :     Returns a statistics object for the loads.
1088 :    
1089 :     =back
1090 :    
1091 :     =cut
1092 :     #: Return Type $%;
1093 :     sub LoadSourceData {
1094 :     # Get this object instance.
1095 :     my ($self) = @_;
1096 :     # Get the FIG object.
1097 :     my $fig = $self->{fig};
1098 :     # Get the genome hash.
1099 :     my $genomeHash = $self->{genomes};
1100 :     # Create load objects for each of the tables we're loading.
1101 : parrello 1.23 my $loadComesFrom = $self->_TableLoader('ComesFrom');
1102 :     my $loadSource = $self->_TableLoader('Source');
1103 :     my $loadSourceURL = $self->_TableLoader('SourceURL');
1104 :     if ($self->{options}->{loadOnly}) {
1105 :     Trace("Loading from existing files.") if T(2);
1106 :     } else {
1107 :     Trace("Generating annotation data.") if T(2);
1108 :     # Create hashes to collect the Source information.
1109 :     my %sourceURL = ();
1110 :     my %sourceDesc = ();
1111 :     # Loop through the genomes.
1112 :     my $line;
1113 :     for my $genomeID (sort keys %{$genomeHash}) {
1114 :     Trace("Processing $genomeID.") if T(3);
1115 :     # Open the project file.
1116 :     if ((open(TMP, "<$FIG_Config::organisms/$genomeID/PROJECT")) &&
1117 :     defined($line = <TMP>)) {
1118 :     chomp $line;
1119 :     my($sourceID, $desc, $url) = split(/\t/,$line);
1120 :     $loadComesFrom->Put($genomeID, $sourceID);
1121 :     if ($url && ! exists $sourceURL{$sourceID}) {
1122 :     $loadSourceURL->Put($sourceID, $url);
1123 :     $sourceURL{$sourceID} = 1;
1124 :     }
1125 :     if ($desc) {
1126 :     $sourceDesc{$sourceID} = $desc;
1127 :     } elsif (! exists $sourceDesc{$sourceID}) {
1128 :     $sourceDesc{$sourceID} = $sourceID;
1129 :     }
1130 : parrello 1.5 }
1131 : parrello 1.23 close TMP;
1132 :     }
1133 :     # Write the source descriptions.
1134 :     for my $sourceID (keys %sourceDesc) {
1135 :     $loadSource->Put($sourceID, $sourceDesc{$sourceID});
1136 : parrello 1.5 }
1137 : parrello 1.16 }
1138 : parrello 1.5 # Finish the load.
1139 :     my $retVal = $self->_FinishAll();
1140 :     return $retVal;
1141 :     }
1142 :    
1143 : parrello 1.6 =head3 LoadExternalData
1144 :    
1145 :     C<< my $stats = $spl->LoadExternalData(); >>
1146 :    
1147 :     Load the external data from FIG into Sprout.
1148 :    
1149 :     External data contains information about external feature IDs.
1150 :    
1151 :     The following relations are loaded by this method.
1152 :    
1153 :     ExternalAliasFunc
1154 :     ExternalAliasOrg
1155 :    
1156 :     The support for external IDs in FIG is hidden beneath layers of other data, so
1157 :     we access the SEED files directly to create these tables. This is also one of
1158 :     the few load methods that does not proceed genome by genome.
1159 :    
1160 :     =over 4
1161 :    
1162 :     =item RETURNS
1163 :    
1164 :     Returns a statistics object for the loads.
1165 :    
1166 :     =back
1167 :    
1168 :     =cut
1169 :     #: Return Type $%;
1170 :     sub LoadExternalData {
1171 :     # Get this object instance.
1172 :     my ($self) = @_;
1173 :     # Get the FIG object.
1174 :     my $fig = $self->{fig};
1175 :     # Get the genome hash.
1176 :     my $genomeHash = $self->{genomes};
1177 :     # Convert the genome hash. We'll get the genus and species for each genome and make
1178 :     # it the key.
1179 :     my %speciesHash = map { $fig->genus_species($_) => $_ } (keys %{$genomeHash});
1180 :     # Create load objects for each of the tables we're loading.
1181 : parrello 1.23 my $loadExternalAliasFunc = $self->_TableLoader('ExternalAliasFunc');
1182 :     my $loadExternalAliasOrg = $self->_TableLoader('ExternalAliasOrg');
1183 :     if ($self->{options}->{loadOnly}) {
1184 :     Trace("Loading from existing files.") if T(2);
1185 :     } else {
1186 :     Trace("Generating external data.") if T(2);
1187 :     # We loop through the files one at a time. First, the organism file.
1188 :     Open(\*ORGS, "<$FIG_Config::global/ext_org.table");
1189 :     my $orgLine;
1190 :     while (defined($orgLine = <ORGS>)) {
1191 :     # Clean the input line.
1192 :     chomp $orgLine;
1193 :     # Parse the organism name.
1194 :     my ($protID, $name) = split /\s*\t\s*/, $orgLine;
1195 :     $loadExternalAliasOrg->Put($protID, $name);
1196 :     }
1197 :     close ORGS;
1198 :     # Now the function file.
1199 :     my $funcLine;
1200 :     Open(\*FUNCS, "<$FIG_Config::global/ext_func.table");
1201 :     while (defined($funcLine = <FUNCS>)) {
1202 :     # Clean the line ending.
1203 :     chomp $funcLine;
1204 :     # Only proceed if the line is non-blank.
1205 :     if ($funcLine) {
1206 :     # Split it into fields.
1207 :     my @funcFields = split /\s*\t\s*/, $funcLine;
1208 :     # If there's an EC number, append it to the description.
1209 :     if ($#funcFields >= 2 && $funcFields[2] =~ /^(EC .*\S)/) {
1210 :     $funcFields[1] .= " $1";
1211 :     }
1212 :     # Output the function line.
1213 :     $loadExternalAliasFunc->Put(@funcFields[0,1]);
1214 : parrello 1.6 }
1215 :     }
1216 :     }
1217 :     # Finish the load.
1218 :     my $retVal = $self->_FinishAll();
1219 :     return $retVal;
1220 :     }
1221 : parrello 1.5
1222 : parrello 1.18
1223 :     =head3 LoadReactionData
1224 :    
1225 :     C<< my $stats = $spl->LoadReactionData(); >>
1226 :    
1227 :     Load the reaction data from FIG into Sprout.
1228 :    
1229 :     Reaction data connects reactions to the compounds that participate in them.
1230 :    
1231 :     The following relations are loaded by this method.
1232 :    
1233 : parrello 1.20 Reaction
1234 : parrello 1.18 ReactionURL
1235 :     Compound
1236 :     CompoundName
1237 :     CompoundCAS
1238 :     IsAComponentOf
1239 :    
1240 :     This method proceeds reaction by reaction rather than genome by genome.
1241 :    
1242 :     =over 4
1243 :    
1244 :     =item RETURNS
1245 :    
1246 :     Returns a statistics object for the loads.
1247 :    
1248 :     =back
1249 :    
1250 :     =cut
1251 :     #: Return Type $%;
1252 :     sub LoadReactionData {
1253 :     # Get this object instance.
1254 :     my ($self) = @_;
1255 :     # Get the FIG object.
1256 :     my $fig = $self->{fig};
1257 :     # Create load objects for each of the tables we're loading.
1258 : parrello 1.23 my $loadReaction = $self->_TableLoader('Reaction');
1259 :     my $loadReactionURL = $self->_TableLoader('ReactionURL');
1260 :     my $loadCompound = $self->_TableLoader('Compound');
1261 :     my $loadCompoundName = $self->_TableLoader('CompoundName');
1262 :     my $loadCompoundCAS = $self->_TableLoader('CompoundCAS');
1263 :     my $loadIsAComponentOf = $self->_TableLoader('IsAComponentOf');
1264 :     if ($self->{options}->{loadOnly}) {
1265 :     Trace("Loading from existing files.") if T(2);
1266 :     } else {
1267 :     Trace("Generating annotation data.") if T(2);
1268 :     # First we create the compounds.
1269 :     my @compounds = $fig->all_compounds();
1270 :     for my $cid (@compounds) {
1271 :     # Check for names.
1272 :     my @names = $fig->names_of_compound($cid);
1273 :     # Each name will be given a priority number, starting with 1.
1274 :     my $prio = 1;
1275 :     for my $name (@names) {
1276 :     $loadCompoundName->Put($cid, $name, $prio++);
1277 :     }
1278 :     # Create the main compound record. Note that the first name
1279 :     # becomes the label.
1280 :     my $label = (@names > 0 ? $names[0] : $cid);
1281 :     $loadCompound->Put($cid, $label);
1282 :     # Check for a CAS ID.
1283 :     my $cas = $fig->cas($cid);
1284 :     if ($cas) {
1285 :     $loadCompoundCAS->Put($cid, $cas);
1286 :     }
1287 : parrello 1.20 }
1288 : parrello 1.23 # All the compounds are set up, so we need to loop through the reactions next. First,
1289 :     # we initialize the discriminator index. This is a single integer used to insure
1290 :     # duplicate elements in a reaction are not accidentally collapsed.
1291 :     my $discrim = 0;
1292 :     my @reactions = $fig->all_reactions();
1293 :     for my $reactionID (@reactions) {
1294 :     # Create the reaction record.
1295 :     $loadReaction->Put($reactionID, $fig->reversible($reactionID));
1296 :     # Compute the reaction's URL.
1297 :     my $url = HTML::reaction_link($reactionID);
1298 :     # Put it in the ReactionURL table.
1299 :     $loadReactionURL->Put($reactionID, $url);
1300 :     # Now we need all of the reaction's compounds. We get these in two phases,
1301 :     # substrates first and then products.
1302 :     for my $product (0, 1) {
1303 :     # Get the compounds of the current type for the current reaction. FIG will
1304 :     # give us 3-tuples: [ID, stoichiometry, main-flag]. At this time we do not
1305 :     # have location data in SEED, so it defaults to the empty string.
1306 :     my @compounds = $fig->reaction2comp($reactionID, $product);
1307 :     for my $compData (@compounds) {
1308 :     # Extract the compound data from the current tuple.
1309 :     my ($cid, $stoich, $main) = @{$compData};
1310 :     # Link the compound to the reaction.
1311 :     $loadIsAComponentOf->Put($cid, $reactionID, $discrim++, "", $main,
1312 :     $product, $stoich);
1313 :     }
1314 : parrello 1.18 }
1315 :     }
1316 :     }
1317 :     # Finish the load.
1318 :     my $retVal = $self->_FinishAll();
1319 :     return $retVal;
1320 :     }
1321 :    
1322 : parrello 1.5 =head3 LoadGroupData
1323 :    
1324 :     C<< my $stats = $spl->LoadGroupData(); >>
1325 :    
1326 :     Load the genome Groups into Sprout.
1327 :    
1328 :     The following relations are loaded by this method.
1329 :    
1330 :     GenomeGroups
1331 :    
1332 :     There is no direct support for genome groups in FIG, so we access the SEED
1333 :     files directly.
1334 :    
1335 :     =over 4
1336 :    
1337 :     =item RETURNS
1338 :    
1339 :     Returns a statistics object for the loads.
1340 :    
1341 :     =back
1342 :    
1343 :     =cut
1344 :     #: Return Type $%;
1345 :     sub LoadGroupData {
1346 :     # Get this object instance.
1347 :     my ($self) = @_;
1348 :     # Get the FIG object.
1349 :     my $fig = $self->{fig};
1350 :     # Get the genome hash.
1351 :     my $genomeHash = $self->{genomes};
1352 :     # Create a load object for the table we're loading.
1353 : parrello 1.23 my $loadGenomeGroups = $self->_TableLoader('GenomeGroups');
1354 :     if ($self->{options}->{loadOnly}) {
1355 :     Trace("Loading from existing files.") if T(2);
1356 :     } else {
1357 :     Trace("Generating group data.") if T(2);
1358 :     # Loop through the genomes.
1359 :     my $line;
1360 :     for my $genomeID (keys %{$genomeHash}) {
1361 :     Trace("Processing $genomeID.") if T(3);
1362 :     # Open the NMPDR group file for this genome.
1363 :     if (open(TMP, "<$FIG_Config::organisms/$genomeID/NMPDR") &&
1364 :     defined($line = <TMP>)) {
1365 :     # Clean the line ending.
1366 :     chomp $line;
1367 :     # Add the group to the table. Note that there can only be one group
1368 :     # per genome.
1369 :     $loadGenomeGroups->Put($genomeID, $line);
1370 :     }
1371 :     close TMP;
1372 : parrello 1.5 }
1373 :     }
1374 :     # Finish the load.
1375 :     my $retVal = $self->_FinishAll();
1376 :     return $retVal;
1377 :     }
1378 :    
1379 : parrello 1.1 =head2 Internal Utility Methods
1380 :    
1381 :     =head3 TableLoader
1382 :    
1383 :     Create an ERDBLoad object for the specified table. The object is also added to
1384 :     the internal list in the C<loaders> property of this object. That enables the
1385 :     L</FinishAll> method to terminate all the active loads.
1386 :    
1387 :     This is an instance method.
1388 :    
1389 :     =over 4
1390 :    
1391 :     =item tableName
1392 :    
1393 :     Name of the table (relation) being loaded.
1394 :    
1395 :     =item RETURN
1396 :    
1397 :     Returns an ERDBLoad object for loading the specified table.
1398 :    
1399 :     =back
1400 :    
1401 :     =cut
1402 :    
1403 :     sub _TableLoader {
1404 :     # Get the parameters.
1405 : parrello 1.23 my ($self, $tableName, $loadOnly) = @_;
1406 : parrello 1.1 # Create the load object.
1407 : parrello 1.23 my $retVal = ERDBLoad->new($self->{erdb}, $tableName, $self->{loadDirectory}, $self->LoadOnly);
1408 : parrello 1.1 # Cache it in the loader list.
1409 :     push @{$self->{loaders}}, $retVal;
1410 :     # Return it to the caller.
1411 :     return $retVal;
1412 :     }
1413 :    
1414 :     =head3 FinishAll
1415 :    
1416 :     Finish all the active loads on this object.
1417 :    
1418 :     When a load is started by L</TableLoader>, the controlling B<ERDBLoad> object is cached in
1419 :     the list pointed to be the C<loaders> property of this object. This method pops the loaders
1420 :     off the list and finishes them to flush out any accumulated residue.
1421 :    
1422 :     This is an instance method.
1423 :    
1424 :     =over 4
1425 :    
1426 :     =item RETURN
1427 :    
1428 :     Returns a statistics object containing the accumulated statistics for the load.
1429 :    
1430 :     =back
1431 :    
1432 :     =cut
1433 :    
1434 :     sub _FinishAll {
1435 :     # Get this object instance.
1436 :     my ($self) = @_;
1437 :     # Create the statistics object.
1438 :     my $retVal = Stats->new();
1439 :     # Get the loader list.
1440 :     my $loadList = $self->{loaders};
1441 :     # Loop through the list, finishing the loads. Note that if the finish fails, we die
1442 :     # ignominiously. At some future point, we want to make the loads restartable.
1443 :     while (my $loader = pop @{$loadList}) {
1444 : parrello 1.19 # Trace the fact that we're cleaning up.
1445 :     my $relName = $loader->RelName;
1446 : parrello 1.23 Trace("Finishing $relName.") if T(2);
1447 : parrello 1.1 my $stats = $loader->Finish();
1448 : parrello 1.19 if ($self->{options}->{dbLoad}) {
1449 :     # Here we want to use the load file just created to load the database.
1450 :     Trace("Loading relation $relName.") if T(2);
1451 :     my $newStats = $self->{sprout}->LoadUpdate(1, [$relName]);
1452 :     # Accumulate the statistics from the DB load.
1453 :     $stats->Accumulate($newStats);
1454 :     }
1455 : parrello 1.1 $retVal->Accumulate($stats);
1456 :     Trace("Statistics for $relName:\n" . $stats->Show()) if T(2);
1457 :     }
1458 :     # Return the load statistics.
1459 :     return $retVal;
1460 :     }
1461 :    
1462 :     1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3