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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3