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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3