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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3