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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3