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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3