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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3