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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3