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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3