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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3