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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.84 - (view) (download) (as text)

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3