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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3