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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3