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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3