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

Annotation of /Sprout/SproutLoad.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3