[Bio] / FigKernelPackages / FIG.pm Repository:
ViewVC logotype

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.529 - (view) (download) (as text)

1 : olson 1.404 #
2 :     # Copyright (c) 2003-2006 University of Chicago and Fellowship
3 :     # for Interpretations of Genomes. All Rights Reserved.
4 :     #
5 :     # This file is part of the SEED Toolkit.
6 : parrello 1.518 #
7 : olson 1.404 # The SEED Toolkit is free software. You can redistribute
8 :     # it and/or modify it under the terms of the SEED Toolkit
9 : parrello 1.518 # Public License.
10 : olson 1.404 #
11 :     # You should have received a copy of the SEED Toolkit Public License
12 :     # along with this program; if not write to the University of Chicago
13 :     # at info@ci.uchicago.edu or the Fellowship for Interpretation of
14 :     # Genomes at veronika@thefig.info or download a copy from
15 :     # http://www.theseed.org/LICENSE.TXT.
16 :     #
17 :    
18 : efrank 1.1 package FIG;
19 :    
20 : olson 1.111 use strict;
21 :    
22 : overbeek 1.453 use FIG_Config;
23 :    
24 :     #
25 :     # See if we need to use fcntl-based file locking. If so, import
26 :     # the package and override the global definition of flock.
27 :     # This is in place at least initially for the GPFS-based install on
28 :     # the NMPDR cluster.
29 :     #
30 :    
31 :     use FileLocking;
32 :    
33 : overbeek 1.135 use Fcntl qw/:flock/; # import LOCK_* constants
34 :    
35 : olson 1.116 use POSIX;
36 : olson 1.158 use IPC::Open2;
37 : olson 1.329 use MIME::Base64;
38 : olson 1.330 use File::Basename;
39 : olson 1.359 use FileHandle;
40 : parrello 1.394 use File::Copy;
41 : olson 1.417 use SOAP::Lite;
42 : parrello 1.420 use File::Path;
43 : overbeek 1.484 use LWP::UserAgent;
44 : olson 1.116
45 : efrank 1.1 use DBrtns;
46 :     use Sim;
47 : olson 1.361 use Annotation;
48 : efrank 1.1 use Blast;
49 : overbeek 1.322 use FullLocation;
50 : overbeek 1.36 use tree_utilities;
51 : olson 1.93 use Subsystem;
52 : olson 1.162 use SeedDas;
53 : olson 1.183 use Construct;
54 : parrello 1.200 use FIGRules;
55 : parrello 1.210 use Tracer;
56 : olson 1.297 use GenomeIDMap;
57 : olson 1.260
58 : olson 1.356 our $haveDateParse;
59 :     eval {
60 :     require Date::Parse;
61 :     import Date::Parse;
62 :     $haveDateParse = 1;
63 :     };
64 :    
65 : olson 1.245 eval { require FigGFF; };
66 : parrello 1.390 if ($@ and T(1)) {
67 : olson 1.260 warn $@;
68 :     }
69 : olson 1.79
70 :     #
71 :     # Conditionally evaluate this in case its prerequisites are not available.
72 :     #
73 :    
74 : olson 1.356 our $ClearinghouseOK;
75 :     eval {
76 : olson 1.79 require Clearinghouse;
77 : olson 1.356 $ClearinghouseOK = 1;
78 : olson 1.79 };
79 : efrank 1.1
80 : olson 1.10 use IO::Socket;
81 :    
82 : efrank 1.1 use FileHandle;
83 :    
84 :     use Carp;
85 :     use Data::Dumper;
86 : overbeek 1.25 use Time::Local;
87 : olson 1.93 use File::Spec;
88 : olson 1.123 use File::Copy;
89 : olson 1.112 #
90 :     # Try to load the RPC stuff; it might fail on older versions of the software.
91 :     #
92 :     eval {
93 :     require FIGrpc;
94 :     };
95 :    
96 :     my $xmlrpc_available = 1;
97 : parrello 1.287 if ($@ ne "") {
98 : olson 1.112 $xmlrpc_available = 0;
99 :     }
100 :    
101 : efrank 1.1
102 : olson 1.111 use FIGAttributes;
103 :     use base 'FIGAttributes';
104 :    
105 :     use vars qw(%_FunctionAttributes);
106 :    
107 :     use Data::Dumper;
108 :    
109 : olson 1.124 #
110 :     # Force all new files to be all-writable.
111 :     #
112 :    
113 :     umask 0;
114 :    
115 : parrello 1.210 =head1 FIG Genome Annotation System
116 :    
117 :     =head2 Introduction
118 :    
119 :     This is the main object for access to the SEED data store. The data store
120 :     itself is a combination of flat files and a database. The flat files can
121 :     be moved easily between systems and the database rebuilt as needed.
122 :    
123 :     A reduced set of this object's functions are available via the B<SFXlate>
124 :     object. The SFXlate object uses a single database to represent all its
125 :     genomic information. It provides a much smaller capability for updating
126 :     the data, and eliminates all similarities except for bidirectional best
127 :     hits.
128 :    
129 :     The key to making the FIG system work is proper configuration of the
130 :     C<FIG_Config.pm> file. This file contains names and URLs for the key
131 :     directories as well as the type and login information for the database.
132 :    
133 : parrello 1.287 FIG was designed to operate as a series of peer instances. Each instance is
134 :     updated independently by its owner, and the instances can be synchronized
135 :     using a process called a I<peer-to-peer update>. The terms
136 :     I<SEED instance> and I<peer> are used more-or-less interchangeably.
137 :    
138 :     The POD documentation for this module is still in progress, and is provided
139 :     on an AS IS basis without warranty. If you have a correction and you're
140 :     not a developer, EMAIL the details to B<bruce@gigabarb.com> and I'll fold
141 :     it in.
142 :    
143 :     B<NOTE>: The usage example for each method specifies whether it is static
144 :    
145 :     FIG::something
146 :    
147 :     or dynamic
148 :    
149 :     $fig->something
150 :    
151 :     If the method is static and has no parameters (C<FIG::something()>) it can
152 : parrello 1.298 also be invoked dynamically. This is a general artifact of the
153 : parrello 1.287 way PERL implements object-oriented programming.
154 :    
155 :     =head2 Hiding/Caching in a FIG object
156 :    
157 :     We save the DB handle, cache taxonomies, and put a few other odds and ends in the
158 :     FIG object. We expect users to invoke these services using the object $fig constructed
159 :     using:
160 :    
161 :     use FIG;
162 :     my $fig = new FIG;
163 :    
164 :     $fig is then used as the basic mechanism for accessing FIG services. It is, of course,
165 :     just a hash that is used to retain/cache data. The most commonly accessed item is the
166 :     DB filehandle, which is accessed via $self->db_handle.
167 :    
168 :     We cache genus/species expansions, taxonomies, distances (very crudely estimated) estimated
169 :     between genomes, and a variety of other things.
170 :    
171 : parrello 1.210 =cut
172 :    
173 : parrello 1.287
174 : parrello 1.210 #: Constructor FIG->new();
175 :    
176 :     =head2 Public Methods
177 :    
178 :     =head3 new
179 :    
180 :     C<< my $fig = FIG->new(); >>
181 :    
182 : parrello 1.298 This is the constructor for a FIG object. It uses no parameters. If tracing
183 :     has not yet been turned on, it will be turned on here. The tracing type and
184 :     level are specified by the configuration variables C<$FIG_Config::trace_levels>
185 : parrello 1.301 and C<$FIG_Config::trace_type>. These defaults can be overridden using the
186 :     environment variables C<Trace> and C<TraceType>, respectively.
187 : parrello 1.210
188 :     =cut
189 :    
190 : efrank 1.1 sub new {
191 :     my($class) = @_;
192 :    
193 : olson 1.102 #
194 :     # Check to see if we have a FIG_URL environment variable set.
195 :     # If we do, don't actually create a FIG object, but rather
196 :     # create a FIGrpc and return that as the return from this constructor.
197 :     #
198 : parrello 1.390 if ($ENV{FIG_URL} && $xmlrpc_available) {
199 : parrello 1.210 my $figrpc = new FIGrpc($ENV{FIG_URL});
200 :     return $figrpc;
201 : olson 1.102 }
202 : parrello 1.355 Trace("Connecting to the database.") if T(2);
203 : parrello 1.287 # Connect to the database, then return ourselves.
204 : efrank 1.1 my $rdbH = new DBrtns;
205 : overbeek 1.453
206 :     my $self = {
207 : parrello 1.210 _dbf => $rdbH,
208 : overbeek 1.453 };
209 :    
210 :     #
211 :     # If we have a readonly-database defined in the config,
212 :     # create a handle for that as well.
213 :     #
214 :    
215 :     if (defined($FIG_Config::readonly_dbhost))
216 :     {
217 : parrello 1.485 my $ro = new DBrtns($FIG_Config::dbms, $FIG_Config::readonly_db, $FIG_Config::readonly_dbuser,
218 :     $FIG_Config::readonly_dbpass, $FIG_Config::readonly_dbport, $FIG_Config::readonly_dbhost,
219 :     $FIG_Config::readonly_dbsock);
220 :     $self->{_ro_dbf} = $ro;
221 : overbeek 1.453
222 : parrello 1.485 #
223 :     # Oh ick. All of the queries made go through the one dbf that a FIG holds. We want
224 :     # to redirect the select queries through this readonly object. We'll need
225 :     # to tell the main handle about the readonly one, and let it decide.
226 :     #
227 :    
228 :     $rdbH->set_readonly_handle($ro);
229 : overbeek 1.453 }
230 :    
231 :     return bless $self, $class;
232 : efrank 1.1 }
233 :    
234 : overbeek 1.454
235 : parrello 1.287 =head3 db_handle
236 :    
237 :     C<< my $dbh = $fig->db_handle; >>
238 :    
239 :     Return the handle to the internal B<DBrtns> object. This allows direct access to
240 :     the database methods.
241 :    
242 :     =cut
243 :    
244 :     sub db_handle {
245 :     my($self) = @_;
246 :     return $self->{_dbf};
247 :     }
248 :    
249 : overbeek 1.293 sub table_exists {
250 :     my($self,$table) = @_;
251 :    
252 :     my $rdbH = $self->db_handle;
253 :     return $rdbH->table_exists($table);
254 :     }
255 : parrello 1.292
256 : parrello 1.287 =head3 cached
257 :    
258 :     C<< my $x = $fig->cached($name); >>
259 :    
260 :     Return a reference to a hash containing transient data. If no hash exists with the
261 :     specified name, create an empty one under that name and return it.
262 :    
263 :     The idea behind this method is to allow clients to cache data in the FIG object for
264 :     later use. (For example, a method might cache feature data so that it can be
265 :     retrieved later without using the database.) This facility should be used sparingly,
266 :     since different clients may destroy each other's data if they use the same name.
267 :    
268 :     =over 4
269 :    
270 :     =item name
271 :    
272 :     Name assigned to the cached data.
273 :    
274 :     =item RETURN
275 :    
276 :     Returns a reference to a hash that is permanently associated with the specified name.
277 :     If no such hash exists, an empty one will be created for the purpose.
278 :    
279 :     =back
280 :    
281 :     =cut
282 :    
283 :     sub cached {
284 :     my($self,$what) = @_;
285 :    
286 :     my $x = $self->{$what};
287 :     if (! $x) {
288 :     $x = $self->{$what} = {};
289 :     }
290 :     return $x;
291 :     }
292 : parrello 1.210
293 :     =head3 get_system_name
294 :    
295 :     C<< my $name = $fig->get_system_name; >>
296 :    
297 :     Returns C<seed>, indicating that this is object is using the SEED
298 :     database. The same method on an SFXlate object will return C<sprout>.
299 :    
300 :     =cut
301 :     #: Return Type $;
302 :     sub get_system_name {
303 : olson 1.207 return "seed";
304 : olson 1.205 }
305 : parrello 1.210
306 : parrello 1.287 =head3 DESTROY
307 :    
308 :     The destructor releases the database handle.
309 :    
310 :     =cut
311 : olson 1.205
312 : parrello 1.287 sub DESTROY {
313 : efrank 1.1 my($self) = @_;
314 :     my($rdbH);
315 :    
316 : parrello 1.210 if ($rdbH = $self->db_handle) {
317 :     $rdbH->DESTROY;
318 : efrank 1.1 }
319 :     }
320 :    
321 : parrello 1.355 =head3 same_seqs
322 :    
323 :     C<< my $sameFlag = FIG::same_seqs($s1, $s2); >>
324 :    
325 :     Return TRUE if the specified protein sequences are considered equivalent and FALSE
326 :     otherwise. The sequences should be presented in I<nr-analysis> form, which is in
327 :     reverse order and upper case with the stop codon omitted.
328 :    
329 :     The sequences will be considered equivalent if the shorter matches the initial
330 :     portion of the long one and is no more than 30% smaller. Since the sequences are
331 :     in nr-analysis form, the equivalent start potions means that the sequences
332 :     have the same tail. The importance of the tail is that the stop point of a PEG
333 :     is easier to find than the start point, so a same tail means that the two
334 :     sequences are equivalent except for the choice of start point.
335 :    
336 :     =over 4
337 :    
338 :     =item s1
339 :    
340 :     First protein sequence, reversed and with the stop codon removed.
341 :    
342 :     =item s2
343 :    
344 :     Second protein sequence, reversed and with the stop codon removed.
345 :    
346 :     =item RETURN
347 :    
348 :     Returns TRUE if the two protein sequences are equivalent, else FALSE.
349 :    
350 :     =back
351 :    
352 :     =cut
353 :    
354 :     sub same_seqs {
355 :     my ($s1,$s2) = @_;
356 :    
357 :     my $ln1 = length($s1);
358 :     my $ln2 = length($s2);
359 :    
360 :     return ((abs($ln1-$ln2) < (0.3 * (($ln1 < $ln2) ? $ln1 : $ln2))) &&
361 :     ((($ln1 <= $ln2) && (index($s2,$s1) == 0)) ||
362 :     (($ln1 > $ln2) && (index($s1,$s2) == 0))));
363 :     }
364 :    
365 : overbeek 1.520 =head3 is_locked_fid
366 :    
367 :     C<< $fig->is_locked_fid($fid); >>
368 :    
369 :     returns 1 iff $fid is locked
370 :    
371 :     =cut
372 :    
373 :     sub is_locked_fid {
374 :     my($self,$fid) = @_;
375 :    
376 : overbeek 1.523 if (! $self->table_exists('fid_locks')) { return 0 }
377 : overbeek 1.520 my $rdbH = $self->db_handle;
378 :     my $relational_db_response = $rdbH->SQL("SELECT fid FROM fid_locks WHERE fid = \'$fid\' ");
379 :     return (@$relational_db_response > 0) ? 1 : 0;
380 :     }
381 :    
382 :     =head3 lock_fid
383 :    
384 :     C<< $fig->lock_fid($user,$fid); >>
385 :    
386 :     Sets a lock on annotations for $fid.
387 :    
388 :     =cut
389 :    
390 :     sub lock_fid {
391 :     my($self,$user,$fid) = @_;
392 :    
393 : overbeek 1.523 if (! $self->table_exists('fid_locks')) { return 0 }
394 : overbeek 1.521 if ((! $user) || ($fid !~ /^fig\|\d+\.\d+/)) { return 0 }
395 :    
396 : overbeek 1.520 my $func = $self->function_of($fid);
397 :     $self->add_annotation($fid,$user,"locked assignments to '$func'");
398 :    
399 :     my $rdbH = $self->db_handle;
400 :     my $relational_db_response = $rdbH->SQL("SELECT fid FROM fid_locks WHERE fid = \'$fid\' ");
401 :     if (! (@$relational_db_response > 0))
402 :     {
403 :     $rdbH->SQL("INSERT INTO fid_locks ( fid ) VALUES ( '$fid' )");
404 :     if ($fid =~ /^fig\|(\d+\.\d+)\.([^\.]+)/)
405 :     {
406 :     my $genome = $1;
407 :     my $type = $2;
408 :     if (open(TMP,">>$FIG_Config::organisms/$genome/Features/$type/locks"))
409 :     {
410 :     print TMP "$fid\t1\n";
411 :     }
412 :     close(TMP);
413 :     }
414 :     }
415 :     }
416 :    
417 :     =head3 unlock_fid
418 :    
419 :     C<< $fig->unlock_fid($user,$fid); >>
420 :    
421 :     Sets a unlock on annotations for $fid.
422 :    
423 :     =cut
424 :    
425 :     sub unlock_fid {
426 :     my($self,$user,$fid) = @_;
427 :    
428 : overbeek 1.523 if (! $self->table_exists('fid_locks')) { return 0 }
429 : overbeek 1.521 if ((! $user) || ($fid !~ /^fig\|\d+\.\d+/)) { return 0 }
430 :    
431 : overbeek 1.520 $self->add_annotation($fid,$user,"unlocked assignments");
432 :     my $rdbH = $self->db_handle;
433 :     my $relational_db_response = $rdbH->SQL("SELECT fid FROM fid_locks WHERE fid = '$fid' ");
434 :     $rdbH->SQL("DELETE FROM fid_locks WHERE ( fid = '$fid' )");
435 :     if ($fid =~ /^fig\|(\d+\.\d+)\.([^\.]+)/)
436 :     {
437 :     my $genome = $1;
438 :     my $type = $2;
439 :     if (open(TMP,">>$FIG_Config::organisms/$genome/Features/$type/locks"))
440 :     {
441 :     print TMP "$fid\t0\n";
442 :     }
443 :     close(TMP);
444 :     }
445 :     }
446 :    
447 : parrello 1.210 =head3 delete_genomes
448 :    
449 :     C<< $fig->delete_genomes(\@genomes); >>
450 :    
451 :     Delete the specified genomes from the data store. This requires making
452 :     system calls to move and delete files.
453 :    
454 :     =cut
455 :     #: Return Type ;
456 : overbeek 1.429 ################################# make damn sure that you have enough disk ######################
457 :     ### The following code represents a serious, major update. Normally, one simply "marks" deleted
458 :     ### genomes, which is quick and does not require halting the system.
459 : overbeek 1.7 sub delete_genomes {
460 :     my($self,$genomes) = @_;
461 :     my $tmpD = "$FIG_Config::temp/tmp.deleted.$$";
462 :     my $tmp_Data = "$FIG_Config::temp/Data.$$";
463 :    
464 :     my %to_del = map { $_ => 1 } @$genomes;
465 :     open(TMP,">$tmpD") || die "could not open $tmpD";
466 :    
467 :     my $genome;
468 : parrello 1.287 foreach $genome ($self->genomes) {
469 :     if (! $to_del{$genome}) {
470 :     print TMP "$genome\n";
471 :     }
472 : overbeek 1.7 }
473 :     close(TMP);
474 :    
475 :     &run("extract_genomes $tmpD $FIG_Config::data $tmp_Data");
476 : overbeek 1.429 print STDERR "Please bring the system down for a bit\n";
477 :     system "echo \"System down due to update of genomes\n\" >> $tmp_Data/Global/why_down";
478 : parrello 1.200 &run("mv $FIG_Config::data $FIG_Config::data.deleted");
479 : overbeek 1.47 &run("mv $tmp_Data $FIG_Config::data");
480 :     &run("fig load_all");
481 : overbeek 1.429 print STDERR "Now, you should think about deleting $FIG_Config::data.deleted\n";
482 :     unlink("$FIG_Config::global/why_down"); ### start allowing CGIs to run
483 :     # &run("rm -rf $FIG_Config::data.deleted");
484 :     }
485 :    
486 :     ### Mark a genome as deleted, but do not actually clean up anything. That whole event
487 :     ### requires "delete_genomes"
488 :     ###
489 :     sub mark_deleted_genomes {
490 : overbeek 1.466 my($self,$user,$genomes) = @_;
491 : overbeek 1.429 my($genome);
492 :    
493 : overbeek 1.466 foreach $genome (@$genomes)
494 :     {
495 : parrello 1.485 $self->log_update($user,$genome,$self->genus_species($genome),"Marked Deleted Genome $genome");
496 : overbeek 1.466 }
497 :     return $self->mark_deleted_genomes_body($user,$genomes);
498 :     }
499 :    
500 :     sub mark_deleted_genomes_body {
501 :     my($self,$user,$genomes) = @_;
502 :     my($genome);
503 : overbeek 1.440
504 : overbeek 1.429 my $rdbH = $self->db_handle;
505 :    
506 :     my $n = 0;
507 :     foreach $genome (@$genomes)
508 :     {
509 : parrello 1.485 if ($self->is_genome($genome) && open(DEL,">$FIG_Config::organisms/$genome/DELETED"))
510 : parrello 1.518 {
511 : parrello 1.485 print DEL "deleted\n";
512 :     $rdbH->SQL("DELETE FROM genome WHERE ( genome = '$genome' )");
513 :     $n++;
514 :     }
515 :     close(DEL);
516 : overbeek 1.429 }
517 : overbeek 1.466 $self->{_is_genome} = {};
518 : overbeek 1.429 return $n;
519 :     }
520 : parrello 1.518
521 : overbeek 1.429 sub unmark_deleted_genomes {
522 : overbeek 1.466 my($self,$user,$genomes) = @_;
523 : overbeek 1.429 my($genome);
524 :    
525 : overbeek 1.466 foreach $genome (@$genomes)
526 :     {
527 : parrello 1.485 $self->log_update($user,$genome,$self->genus_species($genome),"Unmarked Deleted Genome $genome");
528 : overbeek 1.466 }
529 :    
530 : overbeek 1.429 my $rdbH = $self->db_handle;
531 :    
532 :     my $n = 0;
533 :     foreach $genome (@$genomes)
534 :     {
535 : parrello 1.485 if (-s "$FIG_Config::organisms/$genome/DELETED")
536 :     {
537 :     unlink("$FIG_Config::organisms/$genome/DELETED");
538 :     &run("compute_genome_counts $genome");
539 :     $n++;
540 :     }
541 : overbeek 1.429 }
542 : overbeek 1.466 $self->{_is_genome} = {};
543 : overbeek 1.429 return $n;
544 : overbeek 1.7 }
545 : parrello 1.200
546 : overbeek 1.469 sub log_corr {
547 : overbeek 1.470 my($self,$user,$genome, $mapping,$msg) = @_;
548 : overbeek 1.469
549 :     my $gs = $self->genus_species($genome);
550 : overbeek 1.470 $self->log_update($user,$genome,$gs,"Logged correspondence for $genome [$msg]",$mapping);
551 : overbeek 1.469 }
552 :    
553 : overbeek 1.466 sub replace_genome {
554 :     my($self,$user,$old_genome,$genomeF, $mapping, $force, $skipnr) = @_;
555 :    
556 : parrello 1.518 ($genomeF =~ /(\d+\.\d+)$/)
557 : parrello 1.485 || die "$genomeF must have a valid genome ID as the last part of the path";
558 : overbeek 1.466 my $genome = $1;
559 :    
560 :     open(TMP,"<$genomeF/GENOME") || die "could not open $genome/GENOME";
561 :     my $gs = <TMP>;
562 :     chomp $gs;
563 :     close(TMP);
564 :    
565 :     $self->log_update($user,$genome,$gs,"Replaced genome $old_genome with $genome\n$genomeF $force $skipnr",$genomeF,$mapping);
566 : parrello 1.518
567 : overbeek 1.466 $self->mark_deleted_genomes($user,[$old_genome]);
568 :     return $self->add_genome_body($user,$genomeF,$force,$skipnr);
569 :     }
570 :    
571 : parrello 1.210 =head3 add_genome
572 :    
573 : overbeek 1.335 C<< my $ok = $fig->add_genome($genomeF, $force, $skipnr); >>
574 : parrello 1.210
575 :     Add a new genome to the data store. A genome's data is kept in a directory
576 : parrello 1.287 by itself, underneath the main organism directory. This method essentially
577 :     moves genome data from an external directory to the main directory and
578 :     performs some indexing tasks to integrate it.
579 : parrello 1.210
580 :     =over 4
581 :    
582 :     =item genomeF
583 :    
584 : parrello 1.287 Name of the directory containing the genome files. This should be a
585 :     fully-qualified directory name. The last segment of the directory
586 :     name should be the genome ID.
587 : parrello 1.210
588 : overbeek 1.331 =item force
589 :    
590 :     This will ignore errors thrown by verify_genome_directory. This is bad, and you should
591 :     never do it, but I am in the situation where I need to move a genome from one machine
592 :     to another, and although I trust the genome I can't.
593 :    
594 : overbeek 1.335 =item skipnr
595 :    
596 : olson 1.478 We don't always want to add the proteins into the nr database. For example wih a metagnome that has been called by blastx. This will just skip appending the proteins into the NR file.
597 : overbeek 1.335
598 : parrello 1.210 =item RETURN
599 :    
600 :     Returns TRUE if successful, else FALSE.
601 :    
602 :     =back
603 :    
604 :     =cut
605 :     #: Return Type $;
606 : efrank 1.1 sub add_genome {
607 : overbeek 1.466 my($self,$user,$genomeF, $force, $skipnr, $dont_mark_complete) = @_;
608 :    
609 : parrello 1.518 ($genomeF =~ /(\d+\.\d+)$/)
610 : parrello 1.485 || die "$genomeF must have a valid genome ID as the last part of the path";
611 : overbeek 1.466 my $genome = $1;
612 :    
613 :     open(TMP,"<$genomeF/GENOME") || die "could not open $genome/GENOME";
614 :     my $gs = <TMP>;
615 :     chomp $gs;
616 :     close(TMP);
617 :    
618 : olson 1.478 my $rc = $self->add_genome_body($user,$genomeF,$force,$skipnr,$dont_mark_complete);
619 : overbeek 1.466
620 : olson 1.478 if ($rc)
621 :     {
622 : parrello 1.485 $self->log_update($user,$genome,$gs,"Added genome $genome\n$genomeF $force $skipnr",$genomeF);
623 : olson 1.478 }
624 : parrello 1.518
625 : olson 1.478 return $rc;
626 : overbeek 1.466 }
627 : efrank 1.1
628 : overbeek 1.466 sub add_genome_body {
629 :     my($self,$user,$genomeF, $force, $skipnr,$dont_mark_complete) = @_;
630 : overbeek 1.440
631 : efrank 1.1 my $rc = 0;
632 : olson 1.93
633 :     my(undef, $path, $genome) = File::Spec->splitpath($genomeF);
634 :    
635 : parrello 1.287 if ($genome !~ /^\d+\.\d+$/) {
636 :     warn "Invalid genome filename $genomeF\n";
637 :     return $rc;
638 : olson 1.93 }
639 :    
640 : parrello 1.287 if (-d $FIG_Config::organisms/$genome) {
641 :     warn "Organism already exists for $genome\n";
642 :     return $rc;
643 : olson 1.93 }
644 : parrello 1.200
645 : olson 1.93
646 :     #
647 :     # We're okay, it doesn't exist.
648 :     #
649 :    
650 :     my @errors = `$FIG_Config::bin/verify_genome_directory $genomeF`;
651 :    
652 : parrello 1.287 if (@errors) {
653 : olson 1.478 print STDERR "Errors found while verifying genome directory $genomeF:\n";
654 :     print STDERR join("", @errors);
655 :    
656 :     if (!$force)
657 : parrello 1.485 {
658 :     return $rc;
659 :     }
660 : olson 1.478 else
661 : parrello 1.485 {
662 :     warn "Skipped these errors and continued. You should not do this";
663 :     }
664 : olson 1.93 }
665 : parrello 1.200
666 : olson 1.478 my $sysrc = system("cp -r $genomeF $FIG_Config::organisms");
667 :     if ($sysrc != 0)
668 :     {
669 : parrello 1.485 warn "Failure copying $genomeF to $FIG_Config::organisms\n";
670 :     return $rc;
671 : olson 1.478 }
672 :     $sysrc = system("chmod -R 777 $FIG_Config::organisms/$genome");
673 :     if ($sysrc != 0)
674 :     {
675 : parrello 1.485 warn "Command failed: chmod -R 777 $FIG_Config::organisms/$genome\n";
676 :     return $rc;
677 : olson 1.478 }
678 : parrello 1.379
679 : overbeek 1.353 if (-s "$FIG_Config::organisms/$genome/COMPLETE")
680 :     {
681 : parrello 1.485 if ($dont_mark_complete)
682 :     {
683 :     print STDERR "$genome was marked as \"complete\", but moving to WAS_MARKED_COMPLETE\n";
684 :     rename("$FIG_Config::organisms/$genome/COMPLETE", "$FIG_Config::organisms/$genome/WAS_MARKED_COMPLETE");
685 :     }
686 :     else
687 :     {
688 :     print STDERR "$genome was marked as \"complete\"\n";
689 :     }
690 : overbeek 1.353 }
691 :     else
692 :     {
693 : parrello 1.485 #
694 :     # Not marked complete; assess completeness.
695 :     #
696 : parrello 1.518
697 : olson 1.478 my $sysrc = system("assess_completeness $FIG_Config::organisms/$genome");
698 : parrello 1.485 if ($sysrc != 0)
699 :     {
700 :     warn "assess_completeness $FIG_Config::organisms/$genome failed; continuing with installation.\n";
701 :     }
702 :     else
703 :     {
704 :     if (-s "$FIG_Config::organisms/$genome/PROBABLY_COMPLETE")
705 :     {
706 :     print STDERR "Assessed $genome to be probably complete\n";
707 :     if ($dont_mark_complete)
708 :     {
709 :     print STDERR "Not copying PROBABLY_COMPLETE to COMPLETE; this will need to be done later\n";
710 :     }
711 :     else
712 :     {
713 :     my $cp = "cp -p $FIG_Config::organisms/$genome/PROBABLY_COMPLETE " .
714 :     "$FIG_Config::organisms/$genome/COMPLETE";
715 :     $sysrc = system($cp);
716 :     $sysrc == 0 or warn "Command failed, continuing: $cp\n";
717 :     }
718 :     }
719 :     else
720 :     {
721 :     print STDERR "Assessed $genome to not be probably complete\n";
722 :     }
723 :     }
724 : overbeek 1.353 }
725 : parrello 1.379
726 : olson 1.478 $sysrc = system("index_contigs $genome");
727 :     $sysrc == 0 or
728 : parrello 1.485 warn "index_contigs $genome failed; continuing with installation\n";
729 : olson 1.478
730 :     $sysrc = system("compute_genome_counts $genome");
731 :     $sysrc == 0 or
732 : parrello 1.485 warn "compute_genome_counts $genome failed; continuing with installation\n";
733 : olson 1.478
734 :     $sysrc = system("load_features $genome");
735 :     $sysrc == 0 or
736 : parrello 1.485 warn "load_features $genome failed; continuing with installation\n";
737 : parrello 1.379
738 : olson 1.93 $rc = 1;
739 : olson 1.478 if (-s "$FIG_Config::organisms/$genome/Features/peg/fasta")
740 :     {
741 : parrello 1.518
742 : parrello 1.485 $sysrc = system("index_translations $genome");
743 :     $sysrc == 0 or
744 :     warn "index_translations $genome failed; continuing with installation\n";
745 : parrello 1.518
746 : parrello 1.485 my @tmp = `cut -f1 $FIG_Config::organisms/$genome/Features/peg/tbl`;
747 :     if (@tmp == 0)
748 :     {
749 :     warn "Did not find any features in $FIG_Config::organisms/$genome/Features/peg/tbl\n";
750 :     }
751 :     chomp @tmp;
752 :     if (!$skipnr)
753 :     {
754 :     $sysrc = system("cat $FIG_Config::organisms/$genome/Features/peg/fasta >> $FIG_Config::data/Global/nr");
755 :     $sysrc == 0 or warn "error concatenating features ot NR; continuing with installation\n";
756 : parrello 1.518
757 : parrello 1.485 # &run("formatdb -i $FIG_Config::data/Global/nr -p T");
758 :     }
759 :     &enqueue_similarities(\@tmp);
760 : olson 1.93 }
761 : olson 1.478
762 : olson 1.93 if ((-s "$FIG_Config::organisms/$genome/assigned_functions") ||
763 : olson 1.478 (-d "$FIG_Config::organisms/$genome/UserModels"))
764 :     {
765 :     $sysrc = system("add_assertions_of_function $genome");
766 : parrello 1.485 $sysrc == 0 or warn "add_assertions_of_function $genome failed; continuing with installation\n";
767 : efrank 1.1 }
768 : parrello 1.200
769 : efrank 1.1 return $rc;
770 :     }
771 :    
772 : overbeek 1.466 sub get_index {
773 :     my($self,$gs) = @_;
774 :    
775 :     my($index,$max);
776 :     $gs || confess "MISSING GS";
777 :    
778 : overbeek 1.467 my $indexF = "$FIG_Config::data/Logs/GenomeLog/index";
779 : overbeek 1.466 if (open(INDEX,"<$indexF"))
780 :     {
781 : parrello 1.485 while ((! $index) && ($_ = <INDEX>))
782 :     {
783 :     if ($_ =~ /^(\d+)/)
784 :     {
785 :     $max = $1;
786 :     if (($_ =~ /^(\d+)\t(\S.*\S)/) && ($2 eq $gs))
787 :     {
788 :     $index = $1;
789 :     }
790 :     }
791 :     }
792 :     close(INDEX);
793 : overbeek 1.466 }
794 :    
795 :     if (! $index)
796 :     {
797 : parrello 1.485 open(INDEX,">>$indexF") || die "could not open $indexF";
798 :     $index = defined($max) ? $max+1 : 1;
799 :     print INDEX "$index\t$gs\n";
800 :     close(INDEX);
801 :     &verify_dir("$FIG_Config::data/Logs/GenomeLog/Entries/$index");
802 : overbeek 1.466 }
803 :     return $index;
804 :     }
805 : parrello 1.518
806 : overbeek 1.440 sub log_update {
807 : overbeek 1.466 my($self,$user,$genome,$gs,$msg,@data) = @_;
808 : overbeek 1.440
809 :     my $time_made = time;
810 : overbeek 1.471 &verify_dir("$FIG_Config::data/Logs/GenomeLog");
811 : overbeek 1.466 my $index_id = $self->get_index($gs);
812 :     $index_id || die "could not make an index entry for $gs";
813 : overbeek 1.471 my $gs_dir = "$FIG_Config::data/Logs/GenomeLog/Entries/$index_id";
814 : overbeek 1.466
815 : overbeek 1.440 my($i,$file_or_dir,@tars);
816 :     for ($i=0; ($i < @data); $i++)
817 :     {
818 : parrello 1.485 $file_or_dir = $data[$i];
819 :     my($dir,$file);
820 :     if ($file_or_dir =~ /^(.*)\/([^\/]+)$/)
821 :     {
822 :     ($dir,$file) = ($1,$2);
823 :     }
824 :     else
825 :     {
826 :     ($dir,$file) = (".",$file_or_dir);
827 :     }
828 :     my $tar = "$gs_dir/$time_made.$i.tgz";
829 :     &run("cd $dir; tar czf $tar $file");
830 :     push(@tars,$tar);
831 : overbeek 1.440 }
832 : overbeek 1.466 open(LOG,">>$gs_dir/log")
833 : parrello 1.485 || die "could not open $gs_dir/log";
834 : overbeek 1.466 print LOG "$time_made\n$user\n$genome\n$msg\n";
835 : parrello 1.518 if (@tars > 0)
836 : overbeek 1.466 {
837 : parrello 1.485 print LOG join(",",@tars),"\n";
838 : overbeek 1.466 }
839 :     print LOG "//\n";
840 : overbeek 1.440 close(LOG);
841 :     }
842 :    
843 : parrello 1.287 =head3 parse_genome_args
844 :    
845 :     C<< my ($mode, @genomes) = FIG::parse_genome_args(@args); >>
846 :    
847 :     Extract a list of genome IDs from an argument list. If the argument list is empty,
848 :     return all the genomes in the data store.
849 :    
850 :     This is a function that is performed by many of the FIG command-line utilities. The
851 :     user has the option of specifying a list of specific genome IDs or specifying none
852 :     in order to get all of them. If your command requires additional arguments in the
853 :     command line, you can still use this method if you shift them out of the argument list
854 :     before calling. The $mode return value will be C<all> if the user asked for all of
855 :     the genomes or C<some> if he specified a list of IDs. This is useful to know if,
856 :     for example, we are loading a table. If we're loading everything, we can delete the
857 :     entire table; if we're only loading some genomes, we must delete them individually.
858 :    
859 :     This method uses the genome directory rather than the database because it may be used
860 :     before the database is ready.
861 :    
862 :     =over 4
863 :    
864 :     =item args1, args2, ... argsN
865 :    
866 :     List of genome IDs. If all genome IDs are to be processed, then this list should be
867 :     empty.
868 :    
869 :     =item RETURN
870 :    
871 :     Returns a list. The first element of the list is C<all> if the user is asking for all
872 :     the genome IDs and C<some> otherwise. The remaining elements of the list are the
873 :     desired genome IDs.
874 :    
875 :     =back
876 :    
877 :     =cut
878 :    
879 :     sub parse_genome_args {
880 :     # Get the parameters.
881 :     my @args = @_;
882 :     # Check the mode.
883 :     my $mode = (@args > 0 ? 'some' : 'all');
884 :     # Build the return list.
885 :     my @retVal = ($mode);
886 :     # Process according to the mode.
887 :     if ($mode eq 'all') {
888 :     # We want all the genomes, so we get them from the organism directory.
889 :     my $orgdir = "$FIG_Config::organisms";
890 :     opendir( GENOMES, $orgdir ) || Confess("Could not open directory $orgdir");
891 :     push @retVal, grep { $_ =~ /^\d/ } readdir( GENOMES );
892 :     closedir( GENOMES );
893 :     } else {
894 :     # We want only the genomes specified by the user.
895 :     push @retVal, @args;
896 :     }
897 :     # Return the result.
898 :     return @retVal;
899 :     }
900 :    
901 :     =head3 reload_table
902 :    
903 :     C<< $fig->reload_table($mode, $table, $flds, $xflds, $fileName, $keyList, $keyName); >>
904 :    
905 :     Reload a database table from a sequential file. If I<$mode> is C<all>, the table
906 :     will be dropped and re-created. If I<$mode> is C<some>, the data for the individual
907 :     items in I<$keyList> will be deleted before the table is loaded. Thus, the load
908 :     process is optimized for the type of reload.
909 :    
910 :     =over 4
911 :    
912 :     =item mode
913 :    
914 :     C<all> if we are reloading the entire table, C<some> if we are only reloading
915 :     specific entries.
916 :    
917 :     =item table
918 :    
919 :     Name of the table to reload.
920 :    
921 :     =item flds
922 :    
923 :     String defining the table columns, in SQL format. In general, this is a
924 :     comma-delimited set of field specifiers, each specifier consisting of the
925 :     field name followed by the field type and any optional qualifiers (such as
926 :     C<NOT NULL> or C<DEFAULT>); however, it can be anything that would appear
927 :     between the parentheses in a C<CREATE TABLE> statement. The order in which
928 :     the fields are specified is important, since it is presumed that is the
929 :     order in which they are appearing in the load file.
930 :    
931 :     =item xflds
932 :    
933 :     Reference to a hash that describes the indexes. The hash is keyed by index name.
934 :     The value is the index's field list. This is a comma-delimited list of field names
935 :     in order from most significant to least significant. If a field is to be indexed
936 :     in descending order, its name should be followed by the qualifier C<DESC>. For
937 :     example, the following I<$xflds> value will create two indexes, one for name followed
938 :     by creation date in reverse chronological order, and one for ID.
939 :    
940 :     { name_index => "name, createDate DESC", id_index => "id" }
941 :    
942 :     =item fileName
943 :    
944 :     Fully-qualified name of the file containing the data to load. Each line of the
945 :     file must correspond to a record, and the fields must be arranged in order and
946 : parrello 1.298 tab-delimited. If the file name is omitted, the table is dropped and re-created
947 :     but not loaded.
948 : parrello 1.287
949 :     =item keyList
950 :    
951 :     Reference to a list of the IDs for the objects being reloaded. This parameter is
952 :     only used if I<$mode> is C<some>.
953 :    
954 :     =item keyName (optional)
955 :    
956 :     Name of the key field containing the IDs in the keylist. If omitted, C<genome> is
957 :     assumed.
958 :    
959 :     =back
960 :    
961 :     =cut
962 :    
963 :     sub reload_table {
964 : parrello 1.298 # Get the parameters.
965 :     my ($self, $mode, $table, $flds, $xflds, $fileName, $keyList, $keyName) = @_;
966 : parrello 1.287 if (!defined $keyName) {
967 :     $keyName = 'genome';
968 :     }
969 :     # Get the database handler.
970 :     my $dbf = $self->{_dbf};
971 : parrello 1.298 # Call the DBKernel method.
972 :     $dbf->reload_table($mode, $table, $flds, $xflds, $fileName, $keyList, $keyName);
973 : parrello 1.287 }
974 :    
975 : parrello 1.210 =head3 enqueue_similarities
976 : olson 1.93
977 : parrello 1.287 C<< FIG::enqueue_similarities(\@fids); >>
978 :    
979 :     Queue the passed Feature IDs for similarity computation. The actual
980 :     computation is performed by L</create_sim_askfor_pool>. The queue is a
981 :     persistent text file in the global data directory, and this method
982 :     essentially writes new IDs on the end of it.
983 :    
984 :     =over 4
985 :    
986 :     =item fids
987 :    
988 :     Reference to a list of feature IDs.
989 : olson 1.93
990 : parrello 1.287 =back
991 : olson 1.93
992 :     =cut
993 : parrello 1.210 #: Return Type ;
994 : olson 1.93 sub enqueue_similarities {
995 : olson 1.334 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
996 : efrank 1.1 my($fids) = @_;
997 :     my $fid;
998 :    
999 : olson 1.93 my $sim_q = "$FIG_Config::global/queued_similarities";
1000 :    
1001 :     open(TMP,">>$sim_q")
1002 : parrello 1.287 || die "could not open $sim_q";
1003 : olson 1.93
1004 :     #
1005 :     # We need to lock here so that if a computation is creating a snapshot of the
1006 :     # queue, we block until it's done.
1007 :     #
1008 :    
1009 :     flock(TMP, LOCK_EX) or die "Cannot lock $sim_q\n";
1010 : overbeek 1.442 seek(TMP, 0, 2);
1011 : olson 1.93
1012 : parrello 1.287 foreach $fid (@$fids) {
1013 :     print TMP "$fid\n";
1014 : efrank 1.1 }
1015 :     close(TMP);
1016 : olson 1.10 }
1017 :    
1018 : olson 1.281 =head3 export_similarity_request
1019 :    
1020 :     Creates a similarity computation request from the queued similarities and
1021 : parrello 1.287 the current NR.
1022 : olson 1.281
1023 :     We keep track of the exported requests in case one gets lost.
1024 :    
1025 :     =cut
1026 :    
1027 : parrello 1.287 sub export_similarity_request {
1028 : overbeek 1.439 my($self, $user_req_dir) = @_;
1029 :    
1030 :     my $nr_file = "$user_req_dir/nr";
1031 :     my $fasta_file = "$user_req_dir/fasta";
1032 :     my $peg_syn_file = "$user_req_dir/peg.synonyms";
1033 : olson 1.281
1034 :     my $req_dir = "$FIG_Config::fig/var/sim_requests";
1035 :     &verify_dir("$FIG_Config::fig/var");
1036 :     &verify_dir($req_dir);
1037 :    
1038 :     $req_dir = "$req_dir/" . time;
1039 :     &verify_dir($req_dir);
1040 :    
1041 :     #
1042 :     # Open all of our output files before zeroing out the sim queue, in case
1043 :     # there is a problem.
1044 :     #
1045 :    
1046 :     open(my $user_fasta_fh, ">$fasta_file") or confess "Cannot open $fasta_file for writing: $!";
1047 :     open(my $fasta_fh, ">$req_dir/fasta.in");
1048 :    
1049 :     open(my $user_nr_fh, ">$nr_file") or confess "Cannot open $nr_file for writing: $!";
1050 :     open(my $nr_fh, ">$req_dir/nr") or confess "Cannot open $req_dir/nr for writing: $!";
1051 :    
1052 : overbeek 1.439 open(my $user_peg_syn_fh, ">$peg_syn_file") or confess "Cannot open $peg_syn_file for writing: $!";
1053 :     open(my $peg_syn_fh, ">$req_dir/peg.synonyms") or confess "Cannot open $req_dir/peg.synonyms for writing: $!";
1054 :    
1055 : olson 1.281 open(my $nr_read_fh, "<$FIG_Config::data/Global/nr") or die "Cannot open $FIG_Config::data/Global/nr for reading: $!";
1056 : overbeek 1.439 open(my $peg_syn_read_fh, "<$FIG_Config::data/Global/peg.synonyms") or die "Cannot open $FIG_Config::data/Global/peg.synonyms for reading: $!";
1057 : parrello 1.287
1058 : olson 1.281 my $sim_q = "$FIG_Config::global/queued_similarities";
1059 :    
1060 :     #
1061 :     # We need to lock here so that if a computation is creating a snapshot of the
1062 :     # queue, we block until it's done.
1063 :     #
1064 :    
1065 :     open(my $sim_q_lock, ">>$sim_q") or confess "could not open $sim_q";
1066 :     flock($sim_q_lock, LOCK_EX) or confess "Cannot lock $sim_q\n";
1067 :    
1068 :     #
1069 :     # Everything open & locked, start copying.
1070 :     #
1071 : parrello 1.287
1072 : olson 1.281 copy("$sim_q", "$req_dir/q") or confess "Copy $sim_q $req_dir/q failed: $!";
1073 : overbeek 1.439 copy("$sim_q", "$user_req_dir/q") or confess "Copy $sim_q $user_req_dir/q failed: $!";
1074 : parrello 1.287
1075 : overbeek 1.442 #
1076 :     # Copy the contents of the sim queue to the "expected import" queue;
1077 :     # this is a list of pegs for which we expect sims to be computed and installed
1078 :     # at some point.
1079 :     #
1080 :     # We also lock on the pending queue file.
1081 :     #
1082 : parrello 1.518
1083 : overbeek 1.442 if (not(open(SQ, "<$sim_q")))
1084 :     {
1085 : parrello 1.485 warn "Cannot open $sim_q for reading: $!\n";
1086 : overbeek 1.442 }
1087 :     else
1088 :     {
1089 : parrello 1.485 if (open(AW, ">>$FIG_Config::global/pending_similarities"))
1090 :     {
1091 :     flock(AW, LOCK_EX);
1092 :     seek(AW, 0, 2);
1093 :    
1094 :     while (<SQ>)
1095 :     {
1096 :     print AW @_;
1097 :     }
1098 :     close(AW);
1099 :     }
1100 :     else
1101 :     {
1102 :     warn "Could not open $FIG_Config::global/pending_similarities: $!\n";
1103 :     }
1104 :     close(SQ);
1105 : overbeek 1.442 }
1106 : parrello 1.518
1107 : olson 1.281 my($buf);
1108 : parrello 1.287 while (1) {
1109 :     my $n = read($nr_read_fh, $buf, 4096);
1110 :     defined($n) or confess "Error reading nr: $!";
1111 :     last unless $n;
1112 :     syswrite($user_nr_fh, $buf) or confess "Error writing $nr_file: $!";
1113 :     syswrite($nr_fh, $buf) or confess "Error writing $req_dir/nr: $!";
1114 : olson 1.281 }
1115 :    
1116 :     close($nr_read_fh);
1117 :     close($nr_fh);
1118 :     close($user_nr_fh);
1119 :    
1120 : overbeek 1.439 while (1) {
1121 :     my $n = read($peg_syn_read_fh, $buf, 4096);
1122 :     defined($n) or confess "Error reading peg.synonyms: $!";
1123 :     last unless $n;
1124 :     syswrite($user_peg_syn_fh, $buf) or confess "Error writing $peg_syn_file: $!";
1125 :     syswrite($peg_syn_fh, $buf) or confess "Error writing $req_dir/peg.synonyms: $!";
1126 :     }
1127 :    
1128 :     close($peg_syn_read_fh);
1129 :     close($peg_syn_fh);
1130 :     close($user_peg_syn_fh);
1131 : parrello 1.518
1132 : olson 1.281 #
1133 :     # We can zero out the queue and unlock now.
1134 :     #
1135 :    
1136 :     open(F, ">$sim_q") or die "Cannot open $sim_q to truncate it: $!\n";
1137 :     close(F);
1138 : parrello 1.287
1139 : olson 1.281 close($sim_q_lock);
1140 :    
1141 :     #
1142 :     # Generate the fasta input from the queued ids.
1143 :     #
1144 :    
1145 :     open(my $q_fh, "<$req_dir/q");
1146 : parrello 1.287 while (my $id = <$q_fh>) {
1147 :     chomp $id;
1148 : olson 1.281
1149 : parrello 1.287 my $seq = $self->get_translation($id);
1150 : olson 1.281
1151 : parrello 1.287 display_id_and_seq($id, \$seq, $user_fasta_fh);
1152 :     display_id_and_seq($id, \$seq, $fasta_fh);
1153 : olson 1.281 }
1154 :     close($q_fh);
1155 :    
1156 :     close($user_fasta_fh);
1157 :     close($fasta_fh);
1158 :     }
1159 :    
1160 : parrello 1.210 =head3 create_sim_askfor_pool
1161 : olson 1.93
1162 : parrello 1.287 C<< $fig->create_sim_askfor_pool($chunk_size); >>
1163 : olson 1.93
1164 : parrello 1.287 Creates an askfor pool, which a snapshot of the current NR and similarity
1165 :     queue. This process clears the old queue.
1166 : olson 1.123
1167 :     The askfor pool needs to keep track of which sequences need to be
1168 :     calculated, which have been handed out, etc. To simplify this task we
1169 : olson 1.279 chunk the sequences into fairly small numbers (20k characters) and
1170 : olson 1.123 allocate work on a per-chunk basis. We make use of the relational
1171 :     database to keep track of chunk status as well as the seek locations
1172 :     into the file of sequence data. The initial creation of the pool
1173 :     involves indexing the sequence data with seek offsets and lengths and
1174 :     populating the sim_askfor_index table with this information and with
1175 :     initial status information.
1176 : olson 1.93
1177 : parrello 1.287 =over 4
1178 :    
1179 :     =item chunk_size
1180 :    
1181 :     Number of features to put into a processing chunk. The default is 15.
1182 :    
1183 :     =back
1184 :    
1185 : parrello 1.200 =cut
1186 : parrello 1.210 #: Return Type $;
1187 : parrello 1.287 sub create_sim_askfor_pool {
1188 : olson 1.123 my($self, $chunk_size) = @_;
1189 :    
1190 : olson 1.279 $chunk_size = 20000 unless $chunk_size =~ /^\d+$/;
1191 : olson 1.93
1192 : olson 1.279 my $pool_dir = "$FIG_Config::fig/var/sim_pools";
1193 : olson 1.93 &verify_dir($pool_dir);
1194 :    
1195 :     #
1196 :     # Lock the pool directory.
1197 :     #
1198 :     open(my $lock, ">$pool_dir/lockfile");
1199 :    
1200 :     flock($lock, LOCK_EX);
1201 :    
1202 :     my $num = 0;
1203 : parrello 1.287 if (open(my $toc, "<$pool_dir/TOC")) {
1204 :     while (<$toc>) {
1205 :     chomp;
1206 :     # print STDERR "Have toc entry $_\n";
1207 :     my ($idx, $time, $str) = split(/\s+/, $_, 3);
1208 : olson 1.93
1209 : parrello 1.287 $num = max($num, $idx);
1210 :     }
1211 :     close($toc);
1212 : olson 1.93 }
1213 :     $num++;
1214 :     open(my $toc, ">>$pool_dir/TOC") or die "Cannot write $pool_dir/TOC: $!\n";
1215 :    
1216 :     print $toc "$num ", time(), " New toc entry\n";
1217 :     close($toc);
1218 :    
1219 : olson 1.123 my $cpool_id = sprintf "%04d", $num;
1220 :     my $cpool_dir = "$pool_dir/$cpool_id";
1221 : olson 1.93
1222 :     #
1223 :     # All set, create the directory for this pool.
1224 :     #
1225 :    
1226 :     &verify_dir($cpool_dir);
1227 :    
1228 :     #
1229 :     # Now we can copy the nr and sim queue here.
1230 :     # Do this stuff inside an eval so we can clean up
1231 :     # the lockfile.
1232 :     #
1233 :    
1234 :     eval {
1235 : parrello 1.287 my $sim_q = "$FIG_Config::global/queued_similarities";
1236 : olson 1.93
1237 : parrello 1.287 copy("$sim_q", "$cpool_dir/q");
1238 :     copy("$FIG_Config::data/Global/nr", "$cpool_dir/nr");
1239 : olson 1.93
1240 : parrello 1.287 open(F, ">$sim_q") or die "Cannot open $sim_q to truncate it: $!\n";
1241 :     close(F);
1242 : olson 1.93 };
1243 : parrello 1.200
1244 : olson 1.93 unlink("$pool_dir/lockfile");
1245 :     close($lock);
1246 : olson 1.123
1247 :     #
1248 :     # We've created our pool; we can now run the formatdb and
1249 :     # extract the sequences for the blast run.
1250 :     #
1251 : parrello 1.287 my $child_pid = $self->run_in_background(
1252 :     sub {
1253 :     #
1254 :     # Need to close db or there's all sorts of trouble.
1255 :     #
1256 :    
1257 :     my $cmd = "$FIG_Config::ext_bin/formatdb -i $cpool_dir/nr -p T -l $cpool_dir/formatdb.log";
1258 :     print "Will run '$cmd'\n";
1259 :     &run($cmd);
1260 :     print "finished. Logfile:\n";
1261 :     print &FIG::file_read("$cpool_dir/formatdb.log");
1262 :     unlink("$cpool_dir/formatdb.pid");
1263 :     });
1264 : olson 1.279 warn "Running formatdb in background job $child_pid\n";
1265 : olson 1.123 open(FPID, ">$cpool_dir/formatdb.pid");
1266 :     print FPID "$child_pid\n";
1267 :     close(FPID);
1268 :    
1269 :     my $db = $self->db_handle();
1270 : parrello 1.287 if (!$db->table_exists("sim_queue")) {
1271 :     $db->create_table(tbl => "sim_queue",
1272 :     flds => "qid varchar(32), chunk_id INTEGER, seek INTEGER, len INTEGER, " .
1273 :     "assigned BOOL, finished BOOL, output_file varchar(255), " .
1274 : parrello 1.485 "worker_pid INTEGER, start_time timestamp, " .
1275 : parrello 1.287 "assignment_expires INTEGER, worker_info varchar(255)"
1276 :     );
1277 : olson 1.123 }
1278 :    
1279 :     #
1280 :     # Write the fasta input file. Keep track of how many have been written,
1281 :     # and write seek info into the database as appropriate.
1282 :     #
1283 :    
1284 :     open(my $seq_fh, ">$cpool_dir/fasta.in");
1285 :    
1286 :     my($chunk_idx, $chunk_begin, $seq_idx);
1287 :    
1288 : olson 1.279 my $cur_size = 0;
1289 :    
1290 : olson 1.123 $chunk_idx = 0;
1291 :     $chunk_begin = 0;
1292 :     $seq_idx = 0;
1293 :    
1294 : olson 1.279 my $tmpfile = "$FIG_Config::temp/simseek.$$";
1295 :     open(my $tmpfh, ">$tmpfile") or confess "Cannot open tmpfile $tmpfile: $!";
1296 :    
1297 : olson 1.123 open(my $q_fh, "<$cpool_dir/q");
1298 : parrello 1.287 while (my $id = <$q_fh>) {
1299 :     chomp $id;
1300 : olson 1.123
1301 : parrello 1.287 my $seq = $self->get_translation($id);
1302 : olson 1.123
1303 : parrello 1.287 #
1304 :     # check if we're at the beginning of a chunk
1305 :     #
1306 :    
1307 :     print $seq_fh ">$id\n$seq\n";
1308 :    
1309 :     #
1310 :     # Check if we're at the end of a chunk
1311 :     #
1312 :    
1313 :     $cur_size += length($seq);
1314 :     if ($cur_size >= $chunk_size) {
1315 :     my $chunk_end = tell($seq_fh);
1316 :     my $chunk_len = $chunk_end - $chunk_begin;
1317 :    
1318 : olson 1.430 print $tmpfh join("\t", $cpool_id, $chunk_idx, $chunk_begin, $chunk_len, 'FALSE', 'FALSE',
1319 : parrello 1.485 '\N', '\N', '\N', '\N', '\N'), "\n";
1320 : parrello 1.287 $chunk_idx++;
1321 :     $chunk_begin = $chunk_end;
1322 :     $cur_size = 0;
1323 :     }
1324 :     $seq_idx++;
1325 : olson 1.123 }
1326 :    
1327 : parrello 1.287 if ($cur_size > 0) {
1328 :     my $chunk_end = tell($seq_fh);
1329 :     my $chunk_len = $chunk_end - $chunk_begin;
1330 : olson 1.123
1331 : olson 1.430 print $tmpfh join("\t", $cpool_id, $chunk_idx, $chunk_begin, $chunk_len, 'FALSE', 'FALSE',
1332 : parrello 1.485 '\N', '\N', '\N', '\N', '\N'), "\n";
1333 : olson 1.123 }
1334 :    
1335 :     close($q_fh);
1336 :     close($seq_fh);
1337 : olson 1.279 close($tmpfh);
1338 : olson 1.123
1339 : olson 1.279 warn "Write seqs from $tmpfile\n";
1340 : olson 1.123
1341 : olson 1.279 $self->db_handle->load_table(tbl => 'sim_queue',
1342 : parrello 1.298 file => $tmpfile);
1343 : parrello 1.200
1344 : olson 1.430 # unlink($tmpfile);
1345 : parrello 1.287
1346 : olson 1.279 # for my $seek (@seeks)
1347 :     # {
1348 : parrello 1.298 # my($cpool_id, $chunk_idx, $chunk_begin, $chunk_len) = @$seek;
1349 : olson 1.279
1350 : parrello 1.298 # $db->SQL("insert into sim_queue (qid, chunk_id, seek, len, assigned, finished) " .
1351 :     # "values('$cpool_id', $chunk_idx, $chunk_begin, $chunk_len, FALSE, FALSE)");
1352 : olson 1.279 # }
1353 : parrello 1.200
1354 : olson 1.123 return $cpool_id;
1355 :     }
1356 :    
1357 : parrello 1.210 #=head3 get_sim_queue
1358 :     #
1359 :     #usage: get_sim_queue($pool_id, $all_sims)
1360 :     #
1361 :     #Returns the sims in the given pool. If $all_sims is true, return the entire queue. Otherwise,
1362 :     #just return the sims awaiting processing.
1363 :     #
1364 :     #=cut
1365 : olson 1.123
1366 : parrello 1.287 sub get_sim_queue {
1367 : olson 1.123 my($self, $pool_id, $all_sims) = @_;
1368 : olson 1.279 }
1369 :    
1370 : parrello 1.287 =head3 get_sim_work
1371 : olson 1.279
1372 : parrello 1.287 C<< my ($nrPath, $fasta) = $fig->get_sim_work(); >>
1373 : olson 1.279
1374 :     Get the next piece of sim computation work to be performed. Returned are
1375 :     the path to the NR and a string containing the fasta data.
1376 :    
1377 :     =cut
1378 :    
1379 : parrello 1.287 sub get_sim_work {
1380 :    
1381 :     my ($self) = @_;
1382 : olson 1.279
1383 :     #
1384 :     # For now, just don't care about order of data that we get back.
1385 :     #
1386 :    
1387 :     my $db = $self->db_handle();
1388 :     my $lock = FIG::SimLock->new;
1389 :    
1390 :     my $work = $db->SQL(qq(SELECT qid, chunk_id, seek, len
1391 : parrello 1.298 FROM sim_queue
1392 : olson 1.430 WHERE not finished AND not assigned
1393 : parrello 1.298 LIMIT 1));
1394 : olson 1.279 print "Got work ", Dumper($work), "\n";
1395 :    
1396 : parrello 1.287 if (not $work or @$work == 0) {
1397 :     return undef;
1398 : olson 1.279 }
1399 :    
1400 :     my($cpool_id, $chunk_id, $seek, $len) = @{$work->[0]};
1401 : parrello 1.287
1402 : olson 1.279 my $pool_dir = "$FIG_Config::fig/var/sim_pools";
1403 :     my $cpool_dir = "$pool_dir/$cpool_id";
1404 :    
1405 :     my $nr = "$cpool_dir/nr";
1406 :     open(my $fh, "<$cpool_dir/fasta.in");
1407 :     seek($fh, $seek, 0);
1408 :     my $fasta;
1409 :     read($fh, $fasta, $len);
1410 :    
1411 : olson 1.430 $db->SQL(qq(UPDATE sim_queue
1412 : parrello 1.485 SET assigned = true
1413 :     WHERE qid = ? AND chunk_id = ?), undef,
1414 :     $cpool_id, $chunk_id);
1415 : olson 1.430
1416 : olson 1.279 return($cpool_id, $chunk_id, $nr, $fasta, "$cpool_dir/out.$chunk_id");
1417 :     }
1418 :    
1419 : olson 1.430 sub sim_work_working
1420 :     {
1421 :     my($self, $pool, $chunk, $host, $pid) = @_;
1422 :    
1423 :     my $db = $self->db_handle();
1424 :     my $lock = FIG::SimLock->new;
1425 :    
1426 :     my $res = $db->SQL(qq(UPDATE sim_queue
1427 : parrello 1.485 SET worker_pid = ?, start_time = NOW(), worker_info = ?
1428 :     WHERE qid = ? AND chunk_id = ?),
1429 : parrello 1.518 undef,
1430 : parrello 1.485 $pid, $host, $pool, $chunk);
1431 : olson 1.430 }
1432 :    
1433 : olson 1.279 =head3 sim_work_done
1434 :    
1435 : parrello 1.287 C<< $fig->sim_work_done($pool_id, $chunk_id, $out_file); >>
1436 :    
1437 : olson 1.279 Declare that the work in pool_id/chunk_id has been completed, and output written
1438 :     to the pool directory (get_sim_work gave it the path).
1439 :    
1440 : parrello 1.287 =over 4
1441 :    
1442 :     =item pool_id
1443 :    
1444 :     The ID number of the pool containing the work that just completed.
1445 :    
1446 :     =item chunk_id
1447 :    
1448 :     The ID number of the chunk completed.
1449 :    
1450 :     =item out_file
1451 :    
1452 :     The file into which the work was placed.
1453 :    
1454 :     =back
1455 :    
1456 : olson 1.279 =cut
1457 :    
1458 : parrello 1.287 sub sim_work_done {
1459 :     my ($self, $pool_id, $chunk_id, $out_file) = @_;
1460 : olson 1.279
1461 : parrello 1.287 if (! -f $out_file) {
1462 :     Confess("sim_work_done: output file $out_file does not exist");
1463 : olson 1.279 }
1464 :    
1465 :     my $db = $self->db_handle();
1466 :     my $lock = FIG::SimLock->new;
1467 :    
1468 :     my $dbh = $db->{_dbh};
1469 :    
1470 :     my $rows = $dbh->do(qq(UPDATE sim_queue
1471 : parrello 1.298 SET finished = TRUE, output_file = ?
1472 :     WHERE qid = ? and chunk_id = ?), undef, $out_file, $pool_id, $chunk_id);
1473 : parrello 1.287 if ($rows != 1) {
1474 :     if ($dbh->errstr) {
1475 :     Confess("Update not able to set finished=TRUE: ", $dbh->errstr);
1476 :     } else {
1477 :     Confess("Update not able to set finished=TRUE");
1478 :     }
1479 : olson 1.279 }
1480 :     #
1481 :     # Determine if this was the last piece of work for this pool. If so, we can
1482 : parrello 1.287 # schedule the postprocessing work.
1483 : olson 1.279 #
1484 :     # Note we're still holding the lock.
1485 :     #
1486 :    
1487 :     my $out = $db->SQL(qq(SELECT chunk_id
1488 : parrello 1.298 FROM sim_queue
1489 :     WHERE qid = ? AND not finished), undef, $pool_id);
1490 : parrello 1.287 if (@$out == 0) {
1491 :     #
1492 :     # Pool is done.
1493 :     #
1494 :     $self->schedule_sim_pool_postprocessing($pool_id);
1495 : olson 1.279 }
1496 : olson 1.123 }
1497 :    
1498 : olson 1.279 =head3 schedule_sim_pool_postprocessing
1499 :    
1500 : parrello 1.287 C<< $fig->schedule_sim_pool_postprocessing($pool_id); >>
1501 :    
1502 :     Schedule a job to do the similarity postprocessing for the specified pool.
1503 :    
1504 :     =over 4
1505 :    
1506 :     =item pool_id
1507 :    
1508 :     ID of the pool whose similarity postprocessing needs to be scheduled.
1509 : olson 1.279
1510 : parrello 1.287 =back
1511 : olson 1.279
1512 :     =cut
1513 :    
1514 : parrello 1.287 sub schedule_sim_pool_postprocessing {
1515 :    
1516 : olson 1.279 my($self, $pool_id) = @_;
1517 :    
1518 :     my $pool_dir = "$FIG_Config::fig/var/sim_pools";
1519 :     my $cpool_dir = "$pool_dir/$pool_id";
1520 :    
1521 :     my $js = JobScheduler->new();
1522 :     my $job = $js->job_create();
1523 :    
1524 :     my $spath = $job->get_script_path();
1525 :     open(my $sfh, ">$spath");
1526 :     print $sfh <<END;
1527 :     #!/bin/sh
1528 :     . $FIG_Config::fig_disk/config/fig-user-env.sh
1529 :     $FIG_Config::bin/postprocess_computed_sims $pool_id
1530 :     END
1531 :    
1532 :     close($sfh);
1533 :     chmod(0775, $spath);
1534 :    
1535 :     #
1536 :     # Write the job ID to the subsystem queue dir.
1537 :     #
1538 :    
1539 :     open(J, ">$cpool_dir/postprocess_jobid");
1540 :     print J $job->get_id(), "\n";
1541 :     close(J);
1542 :    
1543 :     $job->enqueue();
1544 :     }
1545 :    
1546 :     =head3 postprocess_computed_sims
1547 :    
1548 : parrello 1.287 C<< $fig->postprocess_computed_sims($pool_id); >>
1549 :    
1550 :     Set up to reduce, reformat, and split the similarities in a given pool. We build
1551 :     a pipe to this pipeline:
1552 : olson 1.279
1553 :     reduce_sims peg.synonyms 300 | reformat_sims nr | split_sims dest prefix
1554 :    
1555 : parrello 1.287 Then we put the new sims in the pool directory, and then copy to NewSims.
1556 :    
1557 :     =over 4
1558 :    
1559 :     =item pool_id
1560 :    
1561 :     ID of the pool whose similarities are to be post-processed.
1562 :    
1563 :     =back
1564 : olson 1.279
1565 :     =cut
1566 :    
1567 : parrello 1.287 sub postprocess_computed_sims {
1568 : olson 1.279 my($self, $pool_id) = @_;
1569 :    
1570 :     #
1571 :     # We don't lock here because the job is already done, and we
1572 :     # shouldn't (ha, ha) ever postprocess twice.
1573 :     #
1574 :    
1575 :     my $pool_dir = "$FIG_Config::fig/var/sim_pools";
1576 :     my $cpool_dir = "$pool_dir/$pool_id";
1577 :    
1578 :     my $sim_dir = "$cpool_dir/NewSims";
1579 :     &verify_dir($sim_dir);
1580 :    
1581 :     #
1582 :     # Open the processing pipeline.
1583 :     #
1584 :    
1585 :     my $reduce = "$FIG_Config::bin/reduce_sims $FIG_Config::global/peg.synonyms 300";
1586 :     my $reformat = "$FIG_Config::bin/reformat_sims $cpool_dir/nr";
1587 :     my $split = "$FIG_Config::bin/split_sims $sim_dir sims.$pool_id";
1588 :     open(my $process, "| $reduce | $reformat | $split");
1589 :    
1590 :     #
1591 :     # Iterate over all the sims files, taken from the database.
1592 :     #
1593 :    
1594 :     my $dbh = $self->db_handle()->{_dbh};
1595 :     my $files = $dbh->selectcol_arrayref(qq(SELECT output_file
1596 : parrello 1.298 FROM sim_queue
1597 :     WHERE qid = ? and output_file IS NOT NULL
1598 :     ORDER BY chunk_id), undef, $pool_id);
1599 : parrello 1.287 for my $file (@$files) {
1600 :     my $buf;
1601 :     open(my $fh, "<$file") or confess "Cannot sim input file $file: $!";
1602 :     while (read($fh, $buf, 4096)) {
1603 :     print $process $buf;
1604 :     }
1605 :     close($fh);
1606 : olson 1.279 }
1607 :     my $res = close($process);
1608 : parrello 1.287 if (!$res) {
1609 :     if ($!) {
1610 :     confess "Error closing process pipeline: $!";
1611 :     } else {
1612 :     confess "Process pipeline exited with status $?";
1613 :     }
1614 : olson 1.279 }
1615 :    
1616 :     #
1617 :     # If we got here, it worked. Copy the new sims files over to NewSims.
1618 :     #
1619 :    
1620 :     opendir(my $simdh, $sim_dir) or confess "Cannot open $sim_dir: $!";
1621 :     my @new_sims = grep { $_ !~ /^\./ } readdir($simdh);
1622 :     closedir($simdh);
1623 :    
1624 :     &verify_dir("$FIG_Config::data/NewSims");
1625 :    
1626 : parrello 1.287 for my $sim_file (@new_sims) {
1627 :     my $target = "$FIG_Config::data/NewSims/$sim_file";
1628 :     if (-s $target) {
1629 :     Confess("$target already exists");
1630 :     }
1631 :     print "copying sim file $sim_file\n";
1632 :     &FIG::run("cp $sim_dir/$sim_file $target");
1633 :     &FIG::run("$FIG_Config::bin/index_sims $target");
1634 : olson 1.279 }
1635 :     }
1636 :    
1637 : parrello 1.210 =head3 get_active_sim_pools
1638 : olson 1.123
1639 : parrello 1.287 C<< @pools = $fig->get_active_sim_pools(); >>
1640 : olson 1.123
1641 : parrello 1.287 Return a list of the pool IDs for the sim processing queues that have
1642 :     entries awaiting computation.
1643 : olson 1.123
1644 :     =cut
1645 : parrello 1.210 #: Return Type @;
1646 : parrello 1.287 sub get_active_sim_pools {
1647 : olson 1.123 my($self) = @_;
1648 :    
1649 :     my $dbh = $self->db_handle();
1650 :    
1651 :     my $res = $dbh->SQL("select distinct qid from sim_queue where not finished");
1652 :     return undef unless $res;
1653 :    
1654 :     return map { $_->[0] } @$res;
1655 :     }
1656 :    
1657 : parrello 1.376 =head3 compute_clusters
1658 :    
1659 :     C<< my @clusterList = $fig->compute_clusters(\@pegList, $subsystem, $distance); >>
1660 :    
1661 :     Partition a list of PEGs into sections that are clustered close together on
1662 :     the genome. The basic algorithm used builds a graph connecting PEGs to
1663 :     other PEGs close by them on the genome. Each connected subsection of the graph
1664 :     is then separated into a cluster. Singleton clusters are thrown away, and
1665 :     the remaining ones are sorted by length. All PEGs in the incoming list
1666 :     should belong to the same genome, but this is not a requirement. PEGs on
1667 :     different genomes will simply find themselves in different clusters.
1668 :    
1669 :     =over 4
1670 :    
1671 :     =item pegList
1672 :    
1673 :     Reference to a list of PEG IDs.
1674 :    
1675 :     =item subsystem
1676 :    
1677 :     Subsystem object for the relevant subsystem. This parameter is not used, but is
1678 :     required for compatability with Sprout.
1679 :    
1680 :     =item distance (optional)
1681 :    
1682 :     The maximum distance between PEGs that makes them considered close. If omitted,
1683 :     the distance is 5000 bases.
1684 :    
1685 :     =item RETURN
1686 :    
1687 :     Returns a list of lists. Each sub-list is a cluster of PEGs.
1688 :    
1689 :     =back
1690 :    
1691 :     =cut
1692 :    
1693 :     sub compute_clusters {
1694 :     # Get the parameters.
1695 :     my ($self, $pegList, $subsystem, $distance) = @_;
1696 :     if (! defined $distance) {
1697 :     $distance = 5000;
1698 :     }
1699 : overbeek 1.434
1700 :     my($peg,%by_contig);
1701 :     foreach $peg (@$pegList)
1702 :     {
1703 : parrello 1.485 my $loc;
1704 :     if ($loc = $self->feature_location($peg))
1705 :     {
1706 : parrello 1.488 my ($contig,$beg,$end) = $self->boundaries_of($loc);
1707 : parrello 1.485 my $genome = &FIG::genome_of($peg);
1708 :     push(@{$by_contig{"$genome\t$contig"}},[($beg+$end)/2,$peg]);
1709 :     }
1710 : overbeek 1.434 }
1711 :    
1712 : parrello 1.376 my @clusters = ();
1713 : overbeek 1.434 foreach my $tuple (keys(%by_contig))
1714 :     {
1715 : parrello 1.485 my $x = $by_contig{$tuple};
1716 :     my @pegs = sort { $a->[0] <=> $b->[0] } @$x;
1717 :     while ($x = shift @pegs)
1718 :     {
1719 :     my $clust = [$x->[1]];
1720 :     while ((@pegs > 0) && (abs($pegs[0]->[0] - $x->[0]) <= $distance))
1721 :     {
1722 :     $x = shift @pegs;
1723 :     push(@$clust,$x->[1]);
1724 :     }
1725 : parrello 1.518
1726 : parrello 1.485 if (@$clust > 1)
1727 :     {
1728 :     push(@clusters,$clust);
1729 :     }
1730 :     }
1731 : parrello 1.376 }
1732 : overbeek 1.434 return sort { @$b <=> @$a } @clusters;
1733 : parrello 1.376 }
1734 :    
1735 : parrello 1.210 =head3 get_sim_pool_info
1736 : olson 1.123
1737 : parrello 1.287 C<< my ($total_entries, $n_finished, $n_assigned, $n_unassigned) = $fig->get_sim_pool_info($pool_id); >>
1738 :    
1739 :     Return information about the given sim pool.
1740 :    
1741 :     =over 4
1742 :    
1743 :     =item pool_id
1744 :    
1745 :     Pool ID of the similarity processing queue whose information is desired.
1746 :    
1747 :     =item RETURN
1748 :    
1749 :     Returns a four-element list. The first is the number of features in the
1750 :     queue; the second is the number of features that have been processed; the
1751 :     third is the number of features that have been assigned to a
1752 :     processor, and the fourth is the number of features left over.
1753 : olson 1.123
1754 : parrello 1.287 =back
1755 : olson 1.123
1756 :     =cut
1757 : parrello 1.210 #: Return Type @;
1758 : parrello 1.287 sub get_sim_pool_info {
1759 :    
1760 : olson 1.123 my($self, $pool_id) = @_;
1761 :     my($dbh, $res, $total_entries, $n_finished, $n_assigned, $n_unassigned);
1762 :    
1763 :     $dbh = $self->db_handle();
1764 :    
1765 :     $res = $dbh->SQL("select count(chunk_id) from sim_queue where qid = '$pool_id'");
1766 : parrello 1.200 $total_entries = $res->[0]->[0];
1767 : olson 1.123
1768 :     $res = $dbh->SQL("select count(chunk_id) from sim_queue where qid = '$pool_id' and finished");
1769 :     $n_finished = $res->[0]->[0];
1770 :    
1771 :     $res = $dbh->SQL("select count(chunk_id) from sim_queue where qid = '$pool_id' and assigned and not finished");
1772 :     $n_assigned = $res->[0]->[0];
1773 :    
1774 :     $res = $dbh->SQL("select count(chunk_id) from sim_queue where qid = '$pool_id' and not finished and not assigned");
1775 :     $n_unassigned = $res->[0]->[0];
1776 :    
1777 :     return ($total_entries, $n_finished, $n_assigned, $n_unassigned);
1778 : olson 1.93 }
1779 :    
1780 : parrello 1.210 #=head3 get_sim_chunk
1781 :     #
1782 :     #usage: get_sim_chunk($n_seqs, $worker_id)
1783 :     #
1784 :     #Returns a chunk of $n_seqs of work.
1785 :     #
1786 :     #From Ross, about how sims are processed:
1787 :     #
1788 :     #Here is how I process them:
1789 :     #
1790 :     #
1791 :     # bash$ cd /Volumes/seed/olson/Sims/June22.out
1792 :     # bash$ for i in really*
1793 :     # > do
1794 :     # > cat < $i >> /Volumes/laptop/new.sims
1795 :     # > done
1796 :     #
1797 :     #
1798 :     #Then, I need to "reformat" them by adding to columns to each one
1799 :     # and split the result into files of about 3M each This I do using
1800 :     #
1801 :     #reduce_sims /Volumes/laptop/NR/NewNR/peg.synonyms.june21 300 < /Volumes/laptop/new.sims |
1802 :     # reformat_sims /Volumes/laptop/NR/NewNR/checked.nr.june21 > /Volumes/laptop/reformated.sims
1803 :     #rm /Volumes/laptop/new.sims
1804 :     #split_sims /Volumes/laptop/NewSims sims.june24 reformated.sims
1805 :     #rm reformatted.sims
1806 :     #
1807 :     #=cut
1808 : olson 1.93
1809 : parrello 1.287 sub get_sim_chunk {
1810 : parrello 1.210 my($self, $n_seqs, $worker_id) = @_;
1811 :     }
1812 : olson 1.123
1813 : parrello 1.210 =head3 get_local_hostname
1814 : parrello 1.200
1815 : parrello 1.287 C<< my $result = FIG::get_local_hostname(); >>
1816 :    
1817 :     Return the local host name for the current processor. The name may be
1818 :     stored in a configuration file, or we may have to get it from the
1819 :     operating system.
1820 : olson 1.123
1821 : olson 1.93 =cut
1822 : parrello 1.213 #: Return Type $;
1823 : olson 1.10 sub get_local_hostname {
1824 : olson 1.52
1825 :     #
1826 :     # See if there is a FIGdisk/config/hostname file. If there
1827 :     # is, force the hostname to be that.
1828 :     #
1829 :    
1830 :     my $hostfile = "$FIG_Config::fig_disk/config/hostname";
1831 : parrello 1.287 if (-f $hostfile) {
1832 :     my $fh;
1833 :     if (open($fh, $hostfile)) {
1834 :     my $hostname = <$fh>;
1835 :     chomp($hostname);
1836 :     return $hostname;
1837 :     }
1838 : olson 1.52 }
1839 : parrello 1.200
1840 : olson 1.10 #
1841 :     # First check to see if we our hostname is correct.
1842 :     #
1843 :     # Map it to an IP address, and try to bind to that ip.
1844 :     #
1845 :    
1846 : overbeek 1.435 local $/ = "\n";
1847 :    
1848 : olson 1.10 my $tcp = getprotobyname('tcp');
1849 : parrello 1.200
1850 : olson 1.10 my $hostname = `hostname`;
1851 : overbeek 1.435 chomp $hostname;
1852 : olson 1.10
1853 :     my @hostent = gethostbyname($hostname);
1854 :    
1855 : parrello 1.287 if (@hostent > 0) {
1856 :     my $sock;
1857 :     my $ip = $hostent[4];
1858 :    
1859 :     socket($sock, PF_INET, SOCK_STREAM, $tcp);
1860 :     if (bind($sock, sockaddr_in(0, $ip))) {
1861 :     #
1862 :     # It worked. Reverse-map back to a hopefully fqdn.
1863 :     #
1864 :    
1865 :     my @rev = gethostbyaddr($ip, AF_INET);
1866 :     if (@rev > 0) {
1867 :     my $host = $rev[0];
1868 :     #
1869 :     # Check to see if we have a FQDN.
1870 :     #
1871 :    
1872 :     if ($host =~ /\./) {
1873 :     #
1874 :     # Good.
1875 :     #
1876 :     return $host;
1877 :     } else {
1878 :     #
1879 :     # We didn't get a fqdn; bail and return the IP address.
1880 :     #
1881 :     return get_hostname_by_adapter()
1882 :     }
1883 :     } else {
1884 :     return inet_ntoa($ip);
1885 :     }
1886 :     } else {
1887 :     #
1888 :     # Our hostname must be wrong; we can't bind to the IP
1889 :     # address it maps to.
1890 :     # Return the name associated with the adapter.
1891 :     #
1892 :     return get_hostname_by_adapter()
1893 :     }
1894 :     } else {
1895 :     #
1896 :     # Our hostname isn't known to DNS. This isn't good.
1897 :     # Return the name associated with the adapter.
1898 :     #
1899 :     return get_hostname_by_adapter()
1900 :     }
1901 :     }
1902 :    
1903 :     =head3 get_hostname_by_adapter
1904 : parrello 1.200
1905 : parrello 1.287 C<< my $name = FIG::get_hostname_by_adapter(); >>
1906 : olson 1.10
1907 : parrello 1.287 Return the local host name for the current network environment.
1908 : parrello 1.213
1909 :     =cut
1910 :     #: Return Type $;
1911 : olson 1.10 sub get_hostname_by_adapter {
1912 :     #
1913 :     # Attempt to determine our local hostname based on the
1914 :     # network environment.
1915 :     #
1916 :     # This implementation reads the routing table for the default route.
1917 :     # We then look at the interface config for the interface that holds the default.
1918 :     #
1919 :     #
1920 :     # Linux routing table:
1921 :     # [olson@yips 0.0.0]$ netstat -rn
1922 :     # Kernel IP routing table
1923 :     # Destination Gateway Genmask Flags MSS Window irtt Iface
1924 :     # 140.221.34.32 0.0.0.0 255.255.255.224 U 0 0 0 eth0
1925 :     # 169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth0
1926 :     # 127.0.0.0 0.0.0.0 255.0.0.0 U 0 0 0 lo
1927 :     # 0.0.0.0 140.221.34.61 0.0.0.0 UG 0 0 0 eth0
1928 : parrello 1.200 #
1929 : olson 1.10 # Mac routing table:
1930 : parrello 1.200 #
1931 : olson 1.10 # bash-2.05a$ netstat -rn
1932 :     # Routing tables
1933 : parrello 1.200 #
1934 : olson 1.10 # Internet:
1935 :     # Destination Gateway Flags Refs Use Netif Expire
1936 :     # default 140.221.11.253 UGSc 12 120 en0
1937 :     # 127.0.0.1 127.0.0.1 UH 16 8415486 lo0
1938 :     # 140.221.8/22 link#4 UCS 12 0 en0
1939 :     # 140.221.8.78 0:6:5b:f:51:c4 UHLW 0 183 en0 408
1940 :     # 140.221.8.191 0:3:93:84:ab:e8 UHLW 0 92 en0 622
1941 :     # 140.221.8.198 0:e0:98:8e:36:e2 UHLW 0 5 en0 691
1942 :     # 140.221.9.6 0:6:5b:f:51:d6 UHLW 1 63 en0 1197
1943 :     # 140.221.10.135 0:d0:59:34:26:34 UHLW 2 2134 en0 1199
1944 :     # 140.221.10.152 0:30:1b:b0:ec:dd UHLW 1 137 en0 1122
1945 :     # 140.221.10.153 127.0.0.1 UHS 0 0 lo0
1946 :     # 140.221.11.37 0:9:6b:53:4e:4b UHLW 1 624 en0 1136
1947 :     # 140.221.11.103 0:30:48:22:59:e6 UHLW 3 973 en0 1016
1948 :     # 140.221.11.224 0:a:95:6f:7:10 UHLW 1 1 en0 605
1949 :     # 140.221.11.237 0:1:30:b8:80:c0 UHLW 0 0 en0 1158
1950 :     # 140.221.11.250 0:1:30:3:1:0 UHLW 0 0 en0 1141
1951 :     # 140.221.11.253 0:d0:3:e:70:a UHLW 13 0 en0 1199
1952 :     # 169.254 link#4 UCS 0 0 en0
1953 : parrello 1.200 #
1954 : olson 1.10 # Internet6:
1955 :     # Destination Gateway Flags Netif Expire
1956 :     # UH lo0
1957 :     # fe80::%lo0/64 Uc lo0
1958 :     # link#1 UHL lo0
1959 :     # fe80::%en0/64 link#4 UC en0
1960 :     # 0:a:95:a8:26:68 UHL lo0
1961 :     # ff01::/32 U lo0
1962 :     # ff02::%lo0/32 UC lo0
1963 :     # ff02::%en0/32 link#4 UC en0
1964 :    
1965 :     my($fh);
1966 :    
1967 : parrello 1.287 if (!open($fh, "netstat -rn |")) {
1968 :     warn "Cannot run netstat to determine local IP address\n";
1969 :     return "localhost";
1970 : olson 1.10 }
1971 :    
1972 :     my $interface_name;
1973 : parrello 1.200
1974 : parrello 1.287 while (<$fh>) {
1975 :     my @cols = split();
1976 : olson 1.10
1977 : parrello 1.287 if ($cols[0] eq "default" || $cols[0] eq "0.0.0.0") {
1978 :     $interface_name = $cols[$#cols];
1979 :     }
1980 : olson 1.10 }
1981 :     close($fh);
1982 : parrello 1.200
1983 : olson 1.11 # print "Default route on $interface_name\n";
1984 : olson 1.10
1985 :     #
1986 :     # Find ifconfig.
1987 :     #
1988 :    
1989 :     my $ifconfig;
1990 :    
1991 : parrello 1.287 for my $dir ((split(":", $ENV{PATH}), "/sbin", "/usr/sbin")) {
1992 :     if (-x "$dir/ifconfig") {
1993 :     $ifconfig = "$dir/ifconfig";
1994 :     last;
1995 :     }
1996 : olson 1.10 }
1997 :    
1998 : parrello 1.287 if ($ifconfig eq "") {
1999 :     warn "Ifconfig not found\n";
2000 :     return "localhost";
2001 : olson 1.10 }
2002 : olson 1.11 # print "Foudn $ifconfig\n";
2003 : olson 1.10
2004 : parrello 1.287 if (!open($fh, "$ifconfig $interface_name |")) {
2005 :     warn "Could not run $ifconfig: $!\n";
2006 :     return "localhost";
2007 : olson 1.10 }
2008 :    
2009 :     my $ip;
2010 : parrello 1.287 while (<$fh>) {
2011 :     #
2012 :     # Mac:
2013 :     # inet 140.221.10.153 netmask 0xfffffc00 broadcast 140.221.11.255
2014 :     # Linux:
2015 :     # inet addr:140.221.34.37 Bcast:140.221.34.63 Mask:255.255.255.224
2016 :     #
2017 :    
2018 :     chomp;
2019 :     s/^\s*//;
2020 :    
2021 :     # print "Have '$_'\n";
2022 :     if (/inet\s+addr:(\d+\.\d+\.\d+\.\d+)\s+/) {
2023 :     #
2024 :     # Linux hit.
2025 :     #
2026 :     $ip = $1;
2027 :     # print "Got linux $ip\n";
2028 :     last;
2029 :     } elsif (/inet\s+(\d+\.\d+\.\d+\.\d+)\s+/) {
2030 :     #
2031 :     # Mac hit.
2032 :     #
2033 :     $ip = $1;
2034 :     # print "Got mac $ip\n";
2035 :     last;
2036 :     }
2037 : olson 1.10 }
2038 :     close($fh);
2039 :    
2040 : parrello 1.287 if ($ip eq "") {
2041 :     warn "Didn't find an IP\n";
2042 :     return "localhost";
2043 : olson 1.10 }
2044 :    
2045 :     return $ip;
2046 : efrank 1.1 }
2047 :    
2048 : parrello 1.213 =head3 get_seed_id
2049 :    
2050 : parrello 1.287 C<< my $id = FIG::get_seed_id(); >>
2051 :    
2052 :     Return the Universally Unique ID for this SEED instance. If one
2053 :     does not exist, it will be created.
2054 : parrello 1.213
2055 :     =cut
2056 :     #: Return type $;
2057 : olson 1.38 sub get_seed_id {
2058 :     #
2059 :     # Retrieve the seed identifer from FIGdisk/config/seed_id.
2060 :     #
2061 :     # If it's not there, create one, and make it readonly.
2062 :     #
2063 :     my $id;
2064 :     my $id_file = "$FIG_Config::fig_disk/config/seed_id";
2065 : parrello 1.287 if (! -f $id_file) {
2066 :     my $newid = `uuidgen`;
2067 :     if (!$newid) {
2068 :     die "Cannot run uuidgen: $!";
2069 :     }
2070 : olson 1.38
2071 : parrello 1.287 chomp($newid);
2072 :     my $fh = new FileHandle(">$id_file");
2073 :     if (!$fh) {
2074 :     die "error creating $id_file: $!";
2075 :     }
2076 :     print $fh "$newid\n";
2077 :     $fh->close();
2078 :     chmod(0444, $id_file);
2079 : olson 1.38 }
2080 :     my $fh = new FileHandle("<$id_file");
2081 :     $id = <$fh>;
2082 :     chomp($id);
2083 :     return $id;
2084 :     }
2085 :    
2086 : parrello 1.287 =head3 get_release_info
2087 : olson 1.155
2088 : parrello 1.287 C<< my ($name, $id, $inst, $email, $parent_id, $description) = FIG::get_release_info(); >>
2089 : olson 1.155
2090 : parrello 1.287 Return the current data release information..
2091 : olson 1.195
2092 :     The release info comes from the file FIG/Data/RELEASE. It is formatted as:
2093 :    
2094 : parrello 1.287 <release-name>
2095 :     <unique id>
2096 :     <institution>
2097 :     <contact email>
2098 :     <unique id of data release this release derived from>
2099 :     <description>
2100 : olson 1.195
2101 :     For instance:
2102 :    
2103 : parrello 1.287 -----
2104 :     SEED Data Release, 09/15/2004.
2105 :     4148208C-1DF2-11D9-8417-000A95D52EF6
2106 :     ANL/FIG
2107 :     olson@mcs.anl.gov
2108 :    
2109 :     Test release.
2110 :     -----
2111 : olson 1.195
2112 :     If no RELEASE file exists, this routine will create one with a new unique ID. This
2113 :     lets a peer optimize the data transfer by being able to cache ID translations
2114 :     from this instance.
2115 : olson 1.155
2116 :     =cut
2117 : parrello 1.213 #: Return Type @;
2118 : parrello 1.287 sub get_release_info {
2119 : olson 1.196 my($fig, $no_create) = @_;
2120 : olson 1.195
2121 :     my $rel_file = "$FIG_Config::data/RELEASE";
2122 :    
2123 : parrello 1.287 if (! -f $rel_file and !$no_create) {
2124 : parrello 1.298 #
2125 :     # Create a new one.
2126 :     #
2127 : olson 1.195
2128 : parrello 1.287 my $newid = `uuidgen`;
2129 :     if (!$newid) {
2130 :     die "Cannot run uuidgen: $!";
2131 :     }
2132 : olson 1.195
2133 : parrello 1.287 chomp($newid);
2134 : olson 1.195
2135 : parrello 1.287 my $relinfo = "Automatically generated release info " . localtime();
2136 :     my $inst = "Unknown";
2137 :     my $contact = "Unknown";
2138 :     my $parent = "";
2139 :     my( $a, $b, $e, $v, $env ) = $fig->genome_counts;
2140 :     my $description = "Automatically generated release info\n";
2141 :     $description .= "Contains $a archaeal, $b bacterial, $e eukaryal, $v viral and $env environmental genomes.\n";
2142 :    
2143 :     my $fh = new FileHandle(">$rel_file");
2144 :     if (!$fh) {
2145 :     warn "error creating $rel_file: $!";
2146 :     return undef;
2147 :     }
2148 :     print $fh "$relinfo\n";
2149 :     print $fh "$newid\n";
2150 :     print $fh "$inst\n";
2151 :     print $fh "$contact\n";
2152 :     print $fh "$parent\n";
2153 :     print $fh $description;
2154 :     $fh->close();
2155 :     chmod(0444, $rel_file);
2156 : olson 1.195 }
2157 :    
2158 : parrello 1.287 if (open(my $fh, $rel_file)) {
2159 :     my(@lines) = <$fh>;
2160 :     close($fh);
2161 : parrello 1.200
2162 : parrello 1.287 chomp(@lines);
2163 : parrello 1.200
2164 : parrello 1.287 my($info, $id, $inst, $contact, $parent, @desc) = @lines;
2165 : olson 1.195
2166 : parrello 1.287 return ($info, $id, $inst, $contact, $parent, join("\n", @desc));
2167 : olson 1.195 }
2168 : olson 1.155
2169 :     return undef;
2170 :     }
2171 :    
2172 : parrello 1.406 =head3 Title
2173 :    
2174 :     C<< my $title = $fig->Title(); >>
2175 :    
2176 :     Return the title of this database. For SEED, this will return SEED, for Sprout
2177 :     it will return NMPDR, and so forth.
2178 :    
2179 :     =cut
2180 :    
2181 :     sub Title {
2182 :     return "SEED";
2183 :     }
2184 :    
2185 : parrello 1.376 =head3 FIG
2186 :    
2187 :     C<< my $realFig = $fig->FIG(); >>
2188 :    
2189 :     Return this object. This method is provided for compatability with SFXlate.
2190 :    
2191 :     =cut
2192 :    
2193 :     sub FIG {
2194 :     my ($self) = @_;
2195 :     return $self;
2196 :     }
2197 :    
2198 : parrello 1.287 =head3 get_peer_last_update
2199 : olson 1.155
2200 : parrello 1.287 C<< my $date = $fig->get_peer_last_update($peer_id); >>
2201 : parrello 1.213
2202 : olson 1.155 Return the timestamp from the last successful peer-to-peer update with
2203 : parrello 1.287 the given peer. If the specified peer has made updates, comparing this
2204 :     timestamp to the timestamp of the updates can tell you whether or not
2205 :     the updates have been integrated into your SEED data store.
2206 : olson 1.155
2207 :     We store this information in FIG/Data/Global/Peers/<peer-id>.
2208 :    
2209 : parrello 1.287 =over 4
2210 :    
2211 :     =item peer_id
2212 :    
2213 :     Universally Unique ID for the desired peer.
2214 :    
2215 :     =item RETURN
2216 :    
2217 :     Returns the date/time stamp for the last peer-to-peer updated performed
2218 :     with the identified SEED instance.
2219 :    
2220 :     =back
2221 :    
2222 : olson 1.155 =cut
2223 : parrello 1.213 #: Return Type $;
2224 : parrello 1.287 sub get_peer_last_update {
2225 : olson 1.155 my($self, $peer_id) = @_;
2226 :    
2227 :     my $dir = "$FIG_Config::data/Global/Peers";
2228 :     &verify_dir($dir);
2229 :     $dir .= "/$peer_id";
2230 :     &verify_dir($dir);
2231 :    
2232 :     my $update_file = "$dir/last_update";
2233 : parrello 1.287 if (-f $update_file) {
2234 :     my $time = file_head($update_file, 1);
2235 :     chomp $time;
2236 :     return $time;
2237 :     } else {
2238 :     return undef;
2239 : olson 1.155 }
2240 :     }
2241 :    
2242 : parrello 1.287 =head3 set_peer_last_update
2243 : parrello 1.213
2244 : parrello 1.287 C<< $fig->set_peer_last_update($peer_id, $time); >>
2245 : parrello 1.213
2246 : parrello 1.287 Manually set the update timestamp for a specified peer. This informs
2247 :     the SEED that you have all of the assignments and updates from a
2248 :     particular SEED instance as of a certain date.
2249 : parrello 1.213
2250 :     =cut
2251 :     #: Return Type ;
2252 :    
2253 : parrello 1.287 sub set_peer_last_update {
2254 : olson 1.155 my($self, $peer_id, $time) = @_;
2255 :    
2256 :     my $dir = "$FIG_Config::data/Global/Peers";
2257 :     &verify_dir($dir);
2258 :     $dir .= "/$peer_id";
2259 :     &verify_dir($dir);
2260 :    
2261 :     my $update_file = "$dir/last_update";
2262 :     open(F, ">$update_file");
2263 :     print F "$time\n";
2264 :     close(F);
2265 :     }
2266 :    
2267 : redwards 1.302 =head3 clean_spaces
2268 :    
2269 : parrello 1.320 Remove any extra spaces from input fields. This will (currently) remove ^\s, \s$, and concatenate multiple spaces into one.
2270 : redwards 1.302
2271 :     my $input=$fig->clean_spaces($cgi->param('input'));
2272 :    
2273 :     =cut
2274 :    
2275 :     sub clean_spaces
2276 :     {
2277 :     my ($self, $s)=@_;
2278 :     # note at the moment I do not use \s because that recognizes \t and \n too. This should only remove multiple spaces.
2279 : parrello 1.320 $s =~ s/^ +//;
2280 : redwards 1.302 $s =~ s/ +$//;
2281 :     $s =~ s/ +/ /g;
2282 :     return $s;
2283 :     }
2284 :    
2285 :    
2286 :    
2287 : parrello 1.213 =head3 cgi_url
2288 :    
2289 : parrello 1.287 C<< my $url = FIG::$fig->cgi_url(); >>
2290 :    
2291 :     Return the URL for the CGI script directory.
2292 : parrello 1.213
2293 :     =cut
2294 :     #: Return Type $;
2295 : efrank 1.1 sub cgi_url {
2296 : overbeek 1.377 # return &plug_url($FIG_Config::cgi_url);
2297 :    
2298 :     #
2299 :     # In order to globally make relative references work properly, return ".".
2300 :     # This might break some stuff in p2p, but this will get us most of the way there.
2301 :     # The things that break we can repair by inspecting the value of $ENV{SCRIPT_NAME}
2302 :     #
2303 :     return ".";
2304 : efrank 1.1 }
2305 : parrello 1.200
2306 : overbeek 1.382 =head3 top_link
2307 :    
2308 :     C<< my $url = FIG::top_link(); >>
2309 :    
2310 :     Return the relative URL for the top of the CGI script directory.
2311 :    
2312 :     We determine this based on the SCRIPT_NAME environment variable, falling
2313 :     back to FIG_Config::cgi_base if necessary.
2314 :    
2315 :     =cut
2316 :    
2317 :     sub top_link
2318 :     {
2319 : parrello 1.518
2320 : overbeek 1.382 #
2321 :     # Determine if this is a toplevel cgi or one in one of the subdirs (currently
2322 :     # just /p2p).
2323 :     #
2324 :    
2325 :     my @parts = split(/\//, $ENV{SCRIPT_NAME});
2326 :     my $top;
2327 :     if ($parts[-2] eq 'FIG')
2328 :     {
2329 : parrello 1.485 $top = '.';
2330 :     # warn "toplevel @parts\n";
2331 : overbeek 1.382 }
2332 :     elsif ($parts[-3] eq 'FIG')
2333 :     {
2334 : parrello 1.485 $top = '..';
2335 :     # warn "subdir @parts\n";
2336 : overbeek 1.382 }
2337 :     else
2338 :     {
2339 : parrello 1.485 $top = $FIG_Config::cgi_base;
2340 :     # warn "other @parts\n";
2341 : overbeek 1.382 }
2342 :    
2343 :     return $top;
2344 :     }
2345 :    
2346 : parrello 1.213 =head3 temp_url
2347 :    
2348 : parrello 1.287 C<< my $url = FIG::temp_url(); >>
2349 :    
2350 :     Return the URL of the temporary file directory.
2351 : parrello 1.213
2352 :     =cut
2353 :     #: Return Type $;
2354 : efrank 1.1 sub temp_url {
2355 : overbeek 1.377 # return &plug_url($FIG_Config::temp_url);
2356 :    
2357 :     #
2358 :     # Similarly, make this relative.
2359 :     #
2360 :     return "../FIG-Tmp";
2361 : efrank 1.1 }
2362 : parrello 1.200
2363 : parrello 1.213 =head3 plug_url
2364 :    
2365 : parrello 1.287 C<< my $url2 = $fig->plug_url($url); >>
2366 :    
2367 :     or
2368 :    
2369 :     C<< my $url2 = $fig->plug_url($url); >>
2370 :    
2371 :     Change the domain portion of a URL to point to the current domain. This essentially
2372 :     relocates URLs into the current environment.
2373 :    
2374 :     =over 4
2375 :    
2376 :     =item url
2377 :    
2378 :     URL to relocate.
2379 :    
2380 :     =item RETURN
2381 :    
2382 :     Returns a new URL with the base portion converted to the current operating host.
2383 :     If the URL does not begin with C<http://>, the URL will be returned unmodified.
2384 :    
2385 :     =back
2386 : parrello 1.213
2387 :     =cut
2388 :     #: Return Type $;
2389 : efrank 1.1 sub plug_url {
2390 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2391 : efrank 1.1 my($url) = @_;
2392 :    
2393 : golsen 1.44 my $name;
2394 :    
2395 :     # Revised by GJO
2396 :     # First try to get url from the current http request
2397 :    
2398 :     if ( defined( $ENV{ 'HTTP_HOST' } ) # This is where $cgi->url gets its value
2399 :     && ( $name = $ENV{ 'HTTP_HOST' } )
2400 :     && ( $url =~ s~^http://[^/]*~http://$name~ ) # ~ is delimiter
2401 :     ) {}
2402 :    
2403 :     # Otherwise resort to alternative sources
2404 :    
2405 :     elsif ( ( $name = &get_local_hostname )
2406 :     && ( $url =~ s~^http://[^/]*~http://$name~ ) # ~ is delimiter
2407 :     ) {}
2408 :    
2409 : efrank 1.1 return $url;
2410 :     }
2411 :    
2412 : parrello 1.213 =head3 file_read
2413 :    
2414 : parrello 1.287 C<< my $text = $fig->file_read($fileName); >>
2415 :    
2416 :     or
2417 :    
2418 :     C<< my @lines = $fig->file_read($fileName); >>
2419 :    
2420 :     or
2421 :    
2422 :     C<< my $text = FIG::file_read($fileName); >>
2423 :    
2424 :     or
2425 :    
2426 :     C<< my @lines = FIG::file_read($fileName); >>
2427 :    
2428 :     Read an entire file into memory. In a scalar context, the file is returned
2429 :     as a single text string with line delimiters included. In a list context, the
2430 :     file is returned as a list of lines, each line terminated by a line
2431 :     delimiter. (For a method that automatically strips the line delimiters,
2432 :     use C<Tracer::GetFile>.)
2433 :    
2434 :     =over 4
2435 :    
2436 :     =item fileName
2437 :    
2438 :     Fully-qualified name of the file to read.
2439 :    
2440 :     =item RETURN
2441 :    
2442 :     In a list context, returns a list of the file lines. In a scalar context, returns
2443 :     a string containing all the lines of the file with delimiters included.
2444 : parrello 1.213
2445 : parrello 1.287 =back
2446 : parrello 1.213
2447 :     =cut
2448 :     #: Return Type $;
2449 :     #: Return Type @;
2450 : parrello 1.287 sub file_read {
2451 :    
2452 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2453 : parrello 1.287 my($fileName) = @_;
2454 :     return file_head($fileName, '*');
2455 : olson 1.90
2456 :     }
2457 :    
2458 :    
2459 : parrello 1.213 =head3 file_head
2460 :    
2461 : parrello 1.287 C<< my $text = $fig->file_head($fileName, $count); >>
2462 :    
2463 :     or
2464 :    
2465 :     C<< my @lines = $fig->file_head($fileName, $count); >>
2466 : parrello 1.213
2467 : parrello 1.287 or
2468 : parrello 1.213
2469 : parrello 1.287 C<< my $text = FIG::file_head($fileName, $count); >>
2470 : olson 1.90
2471 : parrello 1.287 or
2472 : olson 1.90
2473 : parrello 1.287 C<< my @lines = FIG::file_head($fileName, $count); >>
2474 : olson 1.90
2475 : parrello 1.287 Read a portion of a file into memory. In a scalar context, the file portion is
2476 :     returned as a single text string with line delimiters included. In a list
2477 :     context, the file portion is returned as a list of lines, each line terminated
2478 :     by a line delimiter.
2479 : olson 1.155
2480 : parrello 1.287 =over 4
2481 : olson 1.90
2482 : parrello 1.287 =item fileName
2483 : olson 1.90
2484 : parrello 1.287 Fully-qualified name of the file to read.
2485 : efrank 1.1
2486 : parrello 1.287 =item count (optional)
2487 : efrank 1.1
2488 : parrello 1.287 Number of lines to read from the file. If omitted, C<1> is assumed. If the
2489 :     non-numeric string C<*> is specified, the entire file will be read.
2490 : efrank 1.1
2491 : parrello 1.287 =item RETURN
2492 : efrank 1.1
2493 : parrello 1.287 In a list context, returns a list of the desired file lines. In a scalar context, returns
2494 :     a string containing the desired lines of the file with delimiters included.
2495 : efrank 1.1
2496 : parrello 1.287 =back
2497 : efrank 1.1
2498 :     =cut
2499 : parrello 1.287 #: Return Type $;
2500 :     #: Return Type @;
2501 :     sub file_head {
2502 : efrank 1.1
2503 : parrello 1.287 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2504 :     my($file, $count) = @_;
2505 : efrank 1.1
2506 : parrello 1.287 my ($n, $allFlag);
2507 :     if ($count eq '*') {
2508 : olson 1.304 Trace("Full file read for \"$file\".") if T(3);
2509 : parrello 1.287 $allFlag = 1;
2510 :     $n = 0;
2511 :     } else {
2512 :     $allFlag = 0;
2513 :     $n = (!$count ? 1 : $count);
2514 : olson 1.304 Trace("Reading $n record(s) from \"$file\".") if T(3);
2515 : parrello 1.287 }
2516 : efrank 1.1
2517 : parrello 1.287 if (open(my $fh, "<$file")) {
2518 : parrello 1.298 my(@ret, $i);
2519 : parrello 1.287 $i = 0;
2520 :     while (<$fh>) {
2521 :     push(@ret, $_);
2522 :     $i++;
2523 :     last if !$allFlag && $i >= $n;
2524 :     }
2525 :     close($fh);
2526 :     if (wantarray) {
2527 :     return @ret;
2528 :     } else {
2529 :     return join("", @ret);
2530 :     }
2531 : efrank 1.1 }
2532 :     }
2533 :    
2534 :     ################ Basic Routines [ existed since WIT ] ##########################
2535 :    
2536 : parrello 1.287 =head3 min
2537 :    
2538 :     C<< my $min = FIG::min(@x); >>
2539 :    
2540 :     or
2541 :    
2542 :     C<< my $min = $fig->min(@x); >>
2543 :    
2544 :     Return the minimum numeric value from a list.
2545 :    
2546 :     =over 4
2547 :    
2548 :     =item x1, x2, ... xN
2549 : efrank 1.1
2550 : parrello 1.287 List of numbers to process.
2551 : efrank 1.1
2552 : parrello 1.287 =item RETURN
2553 : efrank 1.1
2554 : parrello 1.287 Returns the numeric value of the list entry possessing the lowest value. Returns
2555 :     C<undef> if the list is empty.
2556 : efrank 1.1
2557 : parrello 1.287 =back
2558 : efrank 1.1
2559 :     =cut
2560 : parrello 1.213 #: Return Type $;
2561 : efrank 1.1 sub min {
2562 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2563 : efrank 1.1 my(@x) = @_;
2564 :     my($min,$i);
2565 :    
2566 :     (@x > 0) || return undef;
2567 :     $min = $x[0];
2568 : parrello 1.287 for ($i=1; ($i < @x); $i++) {
2569 :     $min = ($min > $x[$i]) ? $x[$i] : $min;
2570 : efrank 1.1 }
2571 :     return $min;
2572 :     }
2573 :    
2574 : parrello 1.287 =head3 max
2575 :    
2576 :     C<< my $max = FIG::max(@x); >>
2577 :    
2578 :     or
2579 :    
2580 :     C<< my $max = $fig->max(@x); >>
2581 : efrank 1.1
2582 : parrello 1.287 Return the maximum numeric value from a list.
2583 : efrank 1.1
2584 : parrello 1.287 =over 4
2585 :    
2586 :     =item x1, x2, ... xN
2587 :    
2588 :     List of numbers to process.
2589 :    
2590 :     =item RETURN
2591 :    
2592 :     Returns the numeric value of t/he list entry possessing the highest value. Returns
2593 :     C<undef> if the list is empty.
2594 : efrank 1.1
2595 : parrello 1.287 =back
2596 : efrank 1.1
2597 :     =cut
2598 : parrello 1.213 #: Return Type $;
2599 : efrank 1.1 sub max {
2600 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2601 : efrank 1.1 my(@x) = @_;
2602 :     my($max,$i);
2603 :    
2604 :     (@x > 0) || return undef;
2605 :     $max = $x[0];
2606 : parrello 1.287 for ($i=1; ($i < @x); $i++) {
2607 :     $max = ($max < $x[$i]) ? $x[$i] : $max;
2608 : efrank 1.1 }
2609 :     return $max;
2610 :     }
2611 :    
2612 : parrello 1.287 =head3 between
2613 : efrank 1.1
2614 : parrello 1.287 C<< my $flag = FIG::between($x, $y, $z); >>
2615 : efrank 1.1
2616 : parrello 1.287 or
2617 :    
2618 :     C<< my $flag = $fig->between($x, $y, $z); >>
2619 :    
2620 :     Determine whether or not $y is between $x and $z.
2621 :    
2622 :     =over 4
2623 :    
2624 :     =item x
2625 :    
2626 :     First edge number.
2627 :    
2628 :     =item y
2629 : efrank 1.1
2630 : parrello 1.287 Number to examine.
2631 :    
2632 :     =item z
2633 :    
2634 :     Second edge number.
2635 :    
2636 :     =item RETURN
2637 :    
2638 :     Return TRUE if the number I<$y> is between the numbers I<$x> and I<$z>. The check
2639 :     is inclusive (that is, if I<$y> is equal to I<$x> or I<$z> the function returns
2640 :     TRUE), and the order of I<$x> and I<$z> does not matter. If I<$x> is lower than
2641 :     I<$z>, then the return is TRUE if I<$x> <= I<$y> <= I<$z>. If I<$z> is lower,
2642 :     then the return is TRUE if I<$x> >= I$<$y> >= I<$z>.
2643 :    
2644 :     =back
2645 : efrank 1.1
2646 :     =cut
2647 : parrello 1.213 #: Return Type $;
2648 : efrank 1.1 sub between {
2649 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2650 : efrank 1.1 my($x,$y,$z) = @_;
2651 :    
2652 : parrello 1.287 if ($x < $z) {
2653 :     return (($x <= $y) && ($y <= $z));
2654 :     } else {
2655 :     return (($x >= $y) && ($y >= $z));
2656 : efrank 1.1 }
2657 :     }
2658 :    
2659 : parrello 1.287 =head3 standard_genetic_code
2660 : efrank 1.1
2661 : parrello 1.287 C<< my $code = FIG::standard_genetic_code(); >>
2662 : efrank 1.1
2663 : parrello 1.287 Return a hash containing the standard translation of nucleotide triples to proteins.
2664 :     Methods such as L</translate> can take a translation scheme as a parameter. This method
2665 :     returns the default translation scheme. The scheme is implemented as a reference to a
2666 :     hash that contains nucleotide triplets as keys and has protein letters as values.
2667 : efrank 1.1
2668 :     =cut
2669 : parrello 1.213 #: Return Type $;
2670 : efrank 1.1 sub standard_genetic_code {
2671 : parrello 1.200
2672 : efrank 1.1 my $code = {};
2673 :    
2674 :     $code->{"AAA"} = "K";
2675 :     $code->{"AAC"} = "N";
2676 :     $code->{"AAG"} = "K";
2677 :     $code->{"AAT"} = "N";
2678 :     $code->{"ACA"} = "T";
2679 :     $code->{"ACC"} = "T";
2680 :     $code->{"ACG"} = "T";
2681 :     $code->{"ACT"} = "T";
2682 :     $code->{"AGA"} = "R";
2683 :     $code->{"AGC"} = "S";
2684 :     $code->{"AGG"} = "R";
2685 :     $code->{"AGT"} = "S";
2686 :     $code->{"ATA"} = "I";
2687 :     $code->{"ATC"} = "I";
2688 :     $code->{"ATG"} = "M";
2689 :     $code->{"ATT"} = "I";
2690 :     $code->{"CAA"} = "Q";
2691 :     $code->{"CAC"} = "H";
2692 :     $code->{"CAG"} = "Q";
2693 :     $code->{"CAT"} = "H";
2694 :     $code->{"CCA"} = "P";
2695 :     $code->{"CCC"} = "P";
2696 :     $code->{"CCG"} = "P";
2697 :     $code->{"CCT"} = "P";
2698 :     $code->{"CGA"} = "R";
2699 :     $code->{"CGC"} = "R";
2700 :     $code->{"CGG"} = "R";
2701 :     $code->{"CGT"} = "R";
2702 :     $code->{"CTA"} = "L";
2703 :     $code->{"CTC"} = "L";
2704 :     $code->{"CTG"} = "L";
2705 :     $code->{"CTT"} = "L";
2706 :     $code->{"GAA"} = "E";
2707 :     $code->{"GAC"} = "D";
2708 :     $code->{"GAG"} = "E";
2709 :     $code->{"GAT"} = "D";
2710 :     $code->{"GCA"} = "A";
2711 :     $code->{"GCC"} = "A";
2712 :     $code->{"GCG"} = "A";
2713 :     $code->{"GCT"} = "A";
2714 :     $code->{"GGA"} = "G";
2715 :     $code->{"GGC"} = "G";
2716 :     $code->{"GGG"} = "G";
2717 :     $code->{"GGT"} = "G";
2718 :     $code->{"GTA"} = "V";
2719 :     $code->{"GTC"} = "V";
2720 :     $code->{"GTG"} = "V";
2721 :     $code->{"GTT"} = "V";
2722 :     $code->{"TAA"} = "*";
2723 :     $code->{"TAC"} = "Y";
2724 :     $code->{"TAG"} = "*";
2725 :     $code->{"TAT"} = "Y";
2726 :     $code->{"TCA"} = "S";
2727 :     $code->{"TCC"} = "S";
2728 :     $code->{"TCG"} = "S";
2729 :     $code->{"TCT"} = "S";
2730 :     $code->{"TGA"} = "*";
2731 :     $code->{"TGC"} = "C";
2732 :     $code->{"TGG"} = "W";
2733 :     $code->{"TGT"} = "C";
2734 :     $code->{"TTA"} = "L";
2735 :     $code->{"TTC"} = "F";
2736 :     $code->{"TTG"} = "L";
2737 :     $code->{"TTT"} = "F";
2738 : parrello 1.200
2739 : efrank 1.1 return $code;
2740 :     }
2741 :    
2742 : parrello 1.287 =head3 translate
2743 :    
2744 :     C<< my $aa_seq = &FIG::translate($dna_seq, $code, $fix_start); >>
2745 :    
2746 :     Translate a DNA sequence to a protein sequence using the specified genetic code.
2747 :     If I<$fix_start> is TRUE, will translate an initial C<TTG> or C<GTG> code to
2748 :     C<M>. (In the standard genetic code, these two combinations normally translate
2749 :     to C<V> and C<L>, respectively.)
2750 :    
2751 :     =over 4
2752 : efrank 1.1
2753 : parrello 1.287 =item dna_seq
2754 : efrank 1.1
2755 : parrello 1.287 DNA sequence to translate. Note that the DNA sequence can only contain
2756 :     known nucleotides.
2757 : efrank 1.1
2758 : parrello 1.287 =item code
2759 : efrank 1.1
2760 : parrello 1.287 Reference to a hash specifying the translation code. The hash is keyed by
2761 :     nucleotide triples, and the value for each key is the corresponding protein
2762 :     letter. If this parameter is omitted, the L</standard_genetic_code> will be
2763 :     used.
2764 : efrank 1.1
2765 : parrello 1.287 =item fix_start
2766 :    
2767 :     TRUE if the first triple is to get special treatment, else FALSE. If TRUE,
2768 :     then a value of C<TTG> or C<GTG> in the first position will be translated to
2769 :     C<M> instead of the value specified in the translation code.
2770 :    
2771 :     =item RETURN
2772 :    
2773 :     Returns a string resulting from translating each nucleotide triple into a
2774 :     protein letter.
2775 :    
2776 :     =back
2777 :    
2778 :     =cut
2779 :     #: Return Type $;
2780 :     sub translate {
2781 :     shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2782 :    
2783 :     my( $dna,$code,$start ) = @_;
2784 :     my( $i,$j,$ln );
2785 :     my( $x,$y );
2786 :     my( $prot );
2787 :    
2788 :     if (! defined($code)) {
2789 :     $code = &FIG::standard_genetic_code;
2790 : efrank 1.1 }
2791 :     $ln = length($dna);
2792 :     $prot = "X" x ($ln/3);
2793 :     $dna =~ tr/a-z/A-Z/;
2794 :    
2795 : parrello 1.287 for ($i=0,$j=0; ($i < ($ln-2)); $i += 3,$j++) {
2796 :     $x = substr($dna,$i,3);
2797 :     if ($y = $code->{$x}) {
2798 :     substr($prot,$j,1) = $y;
2799 : efrank 1.1 }
2800 :     }
2801 : parrello 1.200
2802 : parrello 1.287 if (($start) && ($ln >= 3) && (substr($dna,0,3) =~ /^[GT]TG$/)) {
2803 :     substr($prot,0,1) = 'M';
2804 : efrank 1.1 }
2805 :     return $prot;
2806 :     }
2807 :    
2808 : parrello 1.287 =head3 reverse_comp
2809 :    
2810 :     C<< my $dnaR = FIG::reverse_comp($dna); >>
2811 :    
2812 :     or
2813 :    
2814 :     C<< my $dnaR = $fig->reverse_comp($dna); >>
2815 :    
2816 :     Return the reverse complement os the specified DNA sequence.
2817 : efrank 1.1
2818 : parrello 1.287 NOTE: for extremely long DNA strings, use L</rev_comp>, which allows you to
2819 :     pass the strings around in the form of pointers.
2820 : efrank 1.1
2821 : parrello 1.287 =over 4
2822 :    
2823 :     =item dna
2824 : efrank 1.1
2825 : parrello 1.287 DNA sequence whose reverse complement is desired.
2826 :    
2827 :     =item RETURN
2828 :    
2829 :     Returns the reverse complement of the incoming DNA sequence.
2830 :    
2831 :     =back
2832 : efrank 1.1
2833 :     =cut
2834 : parrello 1.213 #: Return Type $;
2835 : efrank 1.1 sub reverse_comp {
2836 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2837 : efrank 1.1 my($seq) = @_;
2838 :    
2839 :     return ${&rev_comp(\$seq)};
2840 :     }
2841 :    
2842 : parrello 1.287 =head3 rev_comp
2843 :    
2844 :     C<< my $dnaRP = FIG::rev_comp(\$dna); >>
2845 :    
2846 :     or
2847 :    
2848 :     C<< my $dnaRP = $fig->rev_comp(\$dna); >>
2849 :    
2850 :     Return the reverse complement of the specified DNA sequence. The DNA sequence
2851 :     is passed in as a string reference rather than a raw string for performance
2852 :     reasons. If this is unnecessary, use L</reverse_comp>, which processes strings
2853 :     instead of references to strings.
2854 :    
2855 :     =over 4
2856 :    
2857 :     =item dna
2858 :    
2859 :     Reference to the DNA sequence whose reverse complement is desired.
2860 :    
2861 :     =item RETURN
2862 :    
2863 :     Returns a reference to the reverse complement of the incoming DNA sequence.
2864 :    
2865 :     =back
2866 : parrello 1.213
2867 :     =cut
2868 :     #: Return Type $;
2869 : efrank 1.1 sub rev_comp {
2870 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2871 : efrank 1.1 my( $seqP ) = @_;
2872 :     my( $rev );
2873 :    
2874 :     $rev = reverse( $$seqP );
2875 : overbeek 1.317 $rev =~ tr/A-Z/a-z/;
2876 :     $rev =~ tr/acgtumrwsykbdhv/tgcaakywsrmvhdb/;
2877 : efrank 1.1 return \$rev;
2878 :     }
2879 :    
2880 : overbeek 1.454 sub verify_external_tool {
2881 :     my(@progs) = @_;
2882 :    
2883 :     my $prog;
2884 :     foreach $prog (@progs)
2885 :     {
2886 :     my @tmp = `which $prog`;
2887 :     if ($tmp[0] =~ /^no $prog/)
2888 :     {
2889 :     print STDERR $tmp[0];
2890 :     exit(1);
2891 :     }
2892 :     }
2893 :     }
2894 :    
2895 : parrello 1.287 =head3 verify_dir
2896 :    
2897 :     C<< FIG::verify_dir($dir); >>
2898 : efrank 1.1
2899 : parrello 1.287 or
2900 : efrank 1.1
2901 : parrello 1.287 C<< $fig->verify_dir($dir); >>
2902 : efrank 1.1
2903 : parrello 1.287 Insure that the specified directory exists. If it must be created, the permissions will
2904 :     be set to C<0777>.
2905 : efrank 1.1
2906 :     =cut
2907 :    
2908 :     sub verify_dir {
2909 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2910 : efrank 1.1 my($dir) = @_;
2911 :    
2912 : olson 1.416 if (!defined($dir))
2913 :     {
2914 : parrello 1.485 Confess("FIG::verify_dir: missing \$dir argument\n");
2915 : olson 1.416 }
2916 :     if ($dir eq "")
2917 :     {
2918 : parrello 1.485 confess("FIG::verify_dir: refusing to create a directory named ''\n");
2919 : olson 1.416 }
2920 :    
2921 : parrello 1.287 if (-d $dir) {
2922 :     return
2923 :     }
2924 : olson 1.416 if ($dir =~ /^(.*)\/[^\/]+$/ and $1 ne '') {
2925 : parrello 1.287 &verify_dir($1);
2926 : efrank 1.1 }
2927 : overbeek 1.522 mkdir($dir,0777) || confess "Could not make directory $dir: $!";
2928 : efrank 1.1 }
2929 :    
2930 : parrello 1.287 =head3 run
2931 : efrank 1.1
2932 : parrello 1.287 C<< FIG::run($cmd); >>
2933 : overbeek 1.283
2934 : parrello 1.287 or
2935 :    
2936 :     C<< $fig->run($cmd); >>
2937 : overbeek 1.283
2938 : parrello 1.287 Run a command. If the command fails, the error will be traced.
2939 : overbeek 1.283
2940 :     =cut
2941 :    
2942 : parrello 1.287 sub run {
2943 :     shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2944 :     my($cmd) = @_;
2945 :    
2946 : overbeek 1.363 if ($ENV{FIG_VERBOSE}) {
2947 : parrello 1.287 my @tmp = `date`;
2948 :     chomp @tmp;
2949 :     print STDERR "$tmp[0]: running $cmd\n";
2950 :     }
2951 :     Trace("Running command: $cmd") if T(3);
2952 :     (system($cmd) == 0) || Confess("FAILED: $cmd");
2953 :     }
2954 :    
2955 : olson 1.388 =head3 run_gathering_output
2956 :    
2957 :     C<< FIG::run_gathering_output($cmd, @args); >>
2958 :    
2959 :     or
2960 :    
2961 :     C<< $fig->run_gathering_output($cmd, @args); >>
2962 :    
2963 :     Run a command, gathering the output. This is similar to the backtick
2964 :     operator, but it does not invoke the shell. Note that the argument list
2965 : parrello 1.518 must be explicitly passed one command line argument per argument to
2966 : olson 1.388 run_gathering_output.
2967 :    
2968 :     If the command fails, the error will be traced.
2969 :    
2970 :     =cut
2971 :    
2972 :     sub run_gathering_output {
2973 :     shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2974 :     my($cmd, @args) = @_;
2975 :    
2976 :     #
2977 :     # Run the command in a safe fork-with-pipe/exec.
2978 :     #
2979 :    
2980 :     my $pid = open(PROC_READ, "-|");
2981 :    
2982 :     if ($pid == 0)
2983 :     {
2984 : parrello 1.485 exec { $cmd } $cmd, @args;
2985 :     die "could not execute $cmd @args: $!\n";
2986 : olson 1.388 }
2987 :    
2988 :     if (wantarray)
2989 :     {
2990 : parrello 1.485 my @out;
2991 :     while (<PROC_READ>)
2992 :     {
2993 :     push(@out, $_);
2994 :     }
2995 :     if (!close(PROC_READ))
2996 :     {
2997 :     Confess("FAILED: $cmd @args with error return $?");
2998 :     }
2999 :     return @out;
3000 : olson 1.388 }
3001 :     else
3002 :     {
3003 : parrello 1.485 my $out = '';
3004 : parrello 1.518
3005 : parrello 1.485 while (<PROC_READ>)
3006 :     {
3007 :     $out .= $_;
3008 :     }
3009 :     if (!close(PROC_READ))
3010 :     {
3011 :     Confess("FAILED: $cmd @args with error return $?");
3012 :     }
3013 :     return $out;
3014 : olson 1.388 }
3015 :     }
3016 :    
3017 : parrello 1.287 =head3 augment_path
3018 :    
3019 :     C<< FIG::augment_path($dirName); >>
3020 : overbeek 1.283
3021 : parrello 1.287 Add a directory to the system path.
3022 : overbeek 1.283
3023 : parrello 1.287 This method adds a new directory to the front of the system path. It looks in the
3024 :     configuration file to determine whether this is Windows or Unix, and uses the
3025 :     appropriate separator.
3026 : efrank 1.1
3027 : parrello 1.287 =over 4
3028 : efrank 1.1
3029 : parrello 1.287 =item dirName
3030 :    
3031 :     Name of the directory to add to the path.
3032 :    
3033 :     =back
3034 : efrank 1.1
3035 :     =cut
3036 :    
3037 : parrello 1.287 sub augment_path {
3038 :     my ($dirName) = @_;
3039 :     if ($FIG_Config::win_mode) {
3040 :     $ENV{PATH} = "$dirName;$ENV{PATH}";
3041 :     } else {
3042 :     $ENV{PATH} = "$dirName:$ENV{PATH}";
3043 : overbeek 1.278 }
3044 : efrank 1.1 }
3045 :    
3046 : parrello 1.287 =head3 read_fasta_record
3047 : gdpusch 1.45
3048 : parrello 1.287 C<< my ($seq_id, $seq_pointer, $comment) = FIG::read_fasta_record(\*FILEHANDLE); >>
3049 : gdpusch 1.45
3050 : parrello 1.287 or
3051 : gdpusch 1.45
3052 : parrello 1.287 C<< my ($seq_id, $seq_pointer, $comment) = $fig->read_fasta_record(\*FILEHANDLE); >>
3053 : gdpusch 1.45
3054 : parrello 1.287 Read and parse the next logical record of a FASTA file. A FASTA logical record
3055 :     consists of multiple lines of text. The first line begins with a C<< > >> symbol
3056 :     and contains the sequence ID followed by an optional comment. (NOTE: comments
3057 :     are currently deprecated, because not all tools handle them properly.) The
3058 :     remaining lines contain the sequence data.
3059 :    
3060 :     This method uses a trick to smooth its operation: the line terminator character
3061 :     is temporarily changed to C<< \n> >> so that a single read operation brings in
3062 :     the entire logical record.
3063 : gdpusch 1.45
3064 : parrello 1.287 =over 4
3065 : gdpusch 1.45
3066 : parrello 1.287 =item FILEHANDLE
3067 : gdpusch 1.45
3068 : parrello 1.287 Open handle of the FASTA file. If not specified, C<STDIN> is assumed.
3069 :    
3070 :     =item RETURN
3071 :    
3072 :     If we are at the end of the file, returns C<undef>. Otherwise, returns a
3073 :     three-element list. The first element is the sequence ID, the second is
3074 :     a pointer to the sequence data (that is, a string reference as opposed to
3075 :     as string), and the third is the comment.
3076 :    
3077 :     =back
3078 : gdpusch 1.45
3079 :     =cut
3080 : parrello 1.213 #: Return Type @;
3081 : parrello 1.287 sub read_fasta_record {
3082 :    
3083 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3084 : gdpusch 1.45 my ($file_handle) = @_;
3085 : parrello 1.287 my ($old_end_of_record, $fasta_record, @lines, $head, $sequence, $seq_id, $comment, @parsed_fasta_record);
3086 : parrello 1.200
3087 : gdpusch 1.45 if (not defined($file_handle)) { $file_handle = \*STDIN; }
3088 : parrello 1.200
3089 : gdpusch 1.45 $old_end_of_record = $/;
3090 :     $/ = "\n>";
3091 : parrello 1.200
3092 : parrello 1.287 if (defined($fasta_record = <$file_handle>)) {
3093 :     chomp $fasta_record;
3094 :     @lines = split( /\n/, $fasta_record );
3095 :     $head = shift @lines;
3096 :     $head =~ s/^>?//;
3097 :     $head =~ m/^(\S+)/;
3098 :     $seq_id = $1;
3099 :     if ($head =~ m/^\S+\s+(.*)$/) { $comment = $1; } else { $comment = ""; }
3100 :     $sequence = join( "", @lines );
3101 :     @parsed_fasta_record = ( $seq_id, \$sequence, $comment );
3102 :     } else {
3103 :     @parsed_fasta_record = ();
3104 : gdpusch 1.45 }
3105 : parrello 1.200
3106 : gdpusch 1.45 $/ = $old_end_of_record;
3107 : parrello 1.200
3108 : gdpusch 1.45 return @parsed_fasta_record;
3109 :     }
3110 :    
3111 : parrello 1.287 =head3 display_id_and_seq
3112 :    
3113 :     C<< FIG::display_id_and_seq($id_and_comment, $seqP, $fh); >>
3114 :    
3115 :     or
3116 :    
3117 : parrello 1.355 C<< $fig->display_id_and_seq($id_and_comment, \$seqP, $fh); >>
3118 : parrello 1.287
3119 :     Display a fasta ID and sequence to the specified open file. This method is designed
3120 :     to work well with L</read_fasta_sequence> and L</rev_comp>, because it takes as
3121 :     input a string pointer rather than a string. If the file handle is omitted it
3122 :     defaults to STDOUT.
3123 :    
3124 :     The output is formatted into a FASTA record. The first line of the output is
3125 :     preceded by a C<< > >> symbol, and the sequence is split into 60-character
3126 :     chunks displayed one per line. Thus, this method can be used to produce
3127 :     FASTA files from data gathered by the rest of the system.
3128 :    
3129 :     =over 4
3130 :    
3131 :     =item id_and_comment
3132 :    
3133 :     The sequence ID and (optionally) the comment from the sequence's FASTA record.
3134 :     The ID
3135 : gdpusch 1.45
3136 : parrello 1.287 =item seqP
3137 : efrank 1.1
3138 : parrello 1.287 Reference to a string containing the sequence. The sequence is automatically
3139 :     formatted into 60-character chunks displayed one per line.
3140 : efrank 1.1
3141 : parrello 1.287 =item fh
3142 : efrank 1.1
3143 : parrello 1.287 Open file handle to which the ID and sequence should be output. If omitted,
3144 : parrello 1.355 C<\*STDOUT> is assumed.
3145 : parrello 1.287
3146 :     =back
3147 : efrank 1.1
3148 :     =cut
3149 :    
3150 : parrello 1.287 sub display_id_and_seq {
3151 : mkubal 1.53
3152 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3153 : parrello 1.287
3154 : overbeek 1.326 my( $id, $seqP, $fh ) = @_;
3155 : parrello 1.200
3156 : efrank 1.1 if (! defined($fh) ) { $fh = \*STDOUT; }
3157 : parrello 1.200
3158 : efrank 1.1 print $fh ">$id\n";
3159 : overbeek 1.326 &display_seq($seqP, $fh);
3160 : efrank 1.1 }
3161 :    
3162 : parrello 1.355 =head3 display_seq
3163 : parrello 1.287
3164 : parrello 1.355 C<< FIG::display_seq(\$seqP, $fh); >>
3165 : parrello 1.287
3166 :     or
3167 :    
3168 : parrello 1.355 C<< $fig->display_seq(\$seqP, $fh); >>
3169 : parrello 1.287
3170 :     Display a fasta sequence to the specified open file. This method is designed
3171 :     to work well with L</read_fasta_sequence> and L</rev_comp>, because it takes as
3172 :     input a string pointer rather than a string. If the file handle is omitted it
3173 :     defaults to STDOUT.
3174 :    
3175 :     The sequence is split into 60-character chunks displayed one per line for
3176 :     readability.
3177 :    
3178 :     =over 4
3179 :    
3180 :     =item seqP
3181 :    
3182 :     Reference to a string containing the sequence.
3183 :    
3184 :     =item fh
3185 :    
3186 :     Open file handle to which the sequence should be output. If omitted,
3187 :     C<STDOUT> is assumed.
3188 :    
3189 :     =back
3190 :    
3191 :     =cut
3192 :    
3193 : efrank 1.1 sub display_seq {
3194 : parrello 1.287
3195 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3196 : parrello 1.287
3197 : overbeek 1.326 my ( $seqP, $fh ) = @_;
3198 : efrank 1.1 my ( $i, $n, $ln );
3199 : parrello 1.200
3200 : efrank 1.1 if (! defined($fh) ) { $fh = \*STDOUT; }
3201 :    
3202 : overbeek 1.326 $n = length($$seqP);
3203 : efrank 1.1 # confess "zero-length sequence ???" if ( (! defined($n)) || ($n == 0) );
3204 : parrello 1.287 for ($i=0; ($i < $n); $i += 60) {
3205 :     if (($i + 60) <= $n) {
3206 : overbeek 1.326 $ln = substr($$seqP,$i,60);
3207 : parrello 1.287 } else {
3208 : overbeek 1.326 $ln = substr($$seqP,$i,($n-$i));
3209 : parrello 1.287 }
3210 :     print $fh "$ln\n";
3211 : efrank 1.1 }
3212 :     }
3213 :    
3214 : overbeek 1.529
3215 :     =head3 flatten_dumper
3216 :    
3217 :     C<< FIG::flatten_dumper( $perl_ref_or_object_1, ... ); >>
3218 :    
3219 :     C<< $fig->flatten_dumper( $perl_ref_or_object_1, ... ); >>
3220 :    
3221 :     Takes a list of perl references or objects, and "flattens" their Data::Dumper() output
3222 :     so that it can be printed on a single line.
3223 :    
3224 :     =cut
3225 :    
3226 :     sub flatten_dumper {
3227 :     my @x = @_;
3228 :     my $x;
3229 :    
3230 :     foreach $x (@x)
3231 :     {
3232 :     $x = Dumper($x);
3233 :    
3234 :     $x =~ s/\$VAR\d+\s+\=\s+//o;
3235 :     $x =~ s/\n//gso;
3236 :     $x =~ s/\s+/ /go;
3237 :     $x =~ s/\'//go;
3238 :     # $x =~ s/^[^\(\[\{]+//o;
3239 :     # $x =~ s/[^\)\]\}]+$//o;
3240 :     }
3241 :    
3242 :     return @x;
3243 :     }
3244 :    
3245 :    
3246 : efrank 1.1 ########## I commented the pods on the following routines out, since they should not
3247 :     ########## be part of the SOAP/WSTL interface
3248 :     #=pod
3249 :     #
3250 : parrello 1.287 #=head3 file2N
3251 : efrank 1.1 #
3252 :     #usage: $n = $fig->file2N($file)
3253 :     #
3254 :     #In some of the databases I need to store filenames, which can waste a lot of
3255 :     #space. Hence, I maintain a database for converting filenames to/from integers.
3256 :     #
3257 :     #=cut
3258 :     #
3259 : parrello 1.328 sub file2N :Scalar {
3260 : efrank 1.1 my($self,$file) = @_;
3261 :     my($relational_db_response);
3262 :    
3263 :     my $rdbH = $self->db_handle;
3264 :    
3265 : olson 1.403 #
3266 :     # Strip the figdisk path from the file. N2file replaces it if the path
3267 :     # in the database is relative.
3268 :     #
3269 :     $file =~ s,^$FIG_Config::fig_disk/,,;
3270 :    
3271 : efrank 1.1 if (($relational_db_response = $rdbH->SQL("SELECT fileno FROM file_table WHERE ( file = \'$file\')")) &&
3272 : parrello 1.298 (@$relational_db_response == 1)) {
3273 : parrello 1.287 return $relational_db_response->[0]->[0];
3274 :     } elsif (($relational_db_response = $rdbH->SQL("SELECT MAX(fileno) FROM file_table ")) && (@$relational_db_response == 1) && ($relational_db_response->[0]->[0])) {
3275 :     my $fileno = $relational_db_response->[0]->[0] + 1;
3276 :     if ($rdbH->SQL("INSERT INTO file_table ( file, fileno ) VALUES ( \'$file\', $fileno )")) {
3277 :     return $fileno;
3278 :     }
3279 :     } elsif ($rdbH->SQL("INSERT INTO file_table ( file, fileno ) VALUES ( \'$file\', 1 )")) {
3280 :     return 1;
3281 : efrank 1.1 }
3282 :     return undef;
3283 :     }
3284 :    
3285 :     #=pod
3286 :     #
3287 : parrello 1.287 #=head3 N2file
3288 : efrank 1.1 #
3289 :     #usage: $filename = $fig->N2file($n)
3290 :     #
3291 :     #In some of the databases I need to store filenames, which can waste a lot of
3292 :     #space. Hence, I maintain a database for converting filenames to/from integers.
3293 :     #
3294 :     #=cut
3295 :     #
3296 : overbeek 1.364 sub N2file :Scalar
3297 :     {
3298 : efrank 1.1 my($self,$fileno) = @_;
3299 : overbeek 1.364
3300 :     #
3301 :     # Cache outputs. This results in a huge savings of time when files are
3302 :     # accessed multiple times (as in when a bunch of sims are requested).
3303 :     #
3304 :    
3305 :     my $fcache = $self->cached("_n2file");
3306 : parrello 1.379
3307 : overbeek 1.364 my $fname;
3308 :     if (defined($fname = $fcache->{$fileno}))
3309 :     {
3310 : parrello 1.365 return $fname;
3311 : overbeek 1.364 }
3312 : efrank 1.1
3313 :     my $rdbH = $self->db_handle;
3314 : parrello 1.379
3315 : overbeek 1.364 my $relational_db_response = $rdbH->SQL("SELECT file FROM file_table WHERE ( fileno = $fileno )");
3316 : efrank 1.1
3317 : overbeek 1.364 if ($relational_db_response and @$relational_db_response == 1)
3318 :     {
3319 : parrello 1.365 $fname = $relational_db_response->[0]->[0];
3320 : olson 1.403
3321 : parrello 1.420 #
3322 :     # If $fname is relative, prepend the base of the fig_disk.
3323 :     # (Updated to use PERL's system-independent filename utilities.
3324 :     #
3325 : parrello 1.518
3326 : parrello 1.420 $fname = File::Spec->rel2abs($fname, $FIG_Config::fig_disk);
3327 : parrello 1.518
3328 : parrello 1.365 $fcache->{$fileno} = $fname;
3329 :     return $fname;
3330 : efrank 1.1 }
3331 :     return undef;
3332 :     }
3333 :    
3334 :    
3335 :     #=pod
3336 :     #
3337 : parrello 1.287 #=head3 openF
3338 : efrank 1.1 #
3339 :     #usage: $fig->openF($filename)
3340 :     #
3341 :     #Parts of the system rely on accessing numerous different files. The most obvious case is
3342 :     #the situation with similarities. It is important that the system be able to run in cases in
3343 :     #which an arbitrary number of files cannot be open simultaneously. This routine (with closeF) is
3344 :     #a hack to handle this. I should probably just pitch them and insist that the OS handle several
3345 :     #hundred open filehandles.
3346 :     #
3347 :     #=cut
3348 :     #
3349 :     sub openF {
3350 :     my($self,$file) = @_;
3351 :     my($fxs,$x,@fxs,$fh);
3352 :    
3353 :     $fxs = $self->cached('_openF');
3354 : parrello 1.287 if ($x = $fxs->{$file}) {
3355 :     $x->[1] = time();
3356 :     return $x->[0];
3357 : efrank 1.1 }
3358 : parrello 1.200
3359 : efrank 1.1 @fxs = keys(%$fxs);
3360 : parrello 1.287 if (defined($fh = new FileHandle "<$file")) {
3361 :     if (@fxs >= 50) {
3362 :     @fxs = sort { $fxs->{$a}->[1] <=> $fxs->{$b}->[1] } @fxs;
3363 :     $x = $fxs->{$fxs[0]};
3364 :     undef $x->[0];
3365 :     delete $fxs->{$fxs[0]};
3366 :     }
3367 :     $fxs->{$file} = [$fh,time()];
3368 :     return $fh;
3369 : efrank 1.1 }
3370 :     return undef;
3371 :     }
3372 :    
3373 :     #=pod
3374 :     #
3375 : parrello 1.287 #=head3 closeF
3376 : efrank 1.1 #
3377 :     #usage: $fig->closeF($filename)
3378 :     #
3379 :     #Parts of the system rely on accessing numerous different files. The most obvious case is
3380 :     #the situation with similarities. It is important that the system be able to run in cases in
3381 :     #which an arbitrary number of files cannot be open simultaneously. This routine (with openF) is
3382 :     #a hack to handle this. I should probably just pitch them and insist that the OS handle several
3383 :     #hundred open filehandles.
3384 :     #
3385 :     #=cut
3386 :     #
3387 :     sub closeF {
3388 :     my($self,$file) = @_;
3389 :     my($fxs,$x);
3390 :    
3391 : parrello 1.287 if (($fxs = $self->{_openF}) && ($x = $fxs->{$file})) {
3392 :     undef $x->[0];
3393 :     delete $fxs->{$file};
3394 : efrank 1.1 }
3395 :     }
3396 :    
3397 : parrello 1.287 =head3 ec_name
3398 :    
3399 :     C<< my $enzymatic_function = $fig->ec_name($ec); >>
3400 : efrank 1.1
3401 : parrello 1.287 Returns the enzymatic name corresponding to the specified enzyme code.
3402 : efrank 1.1
3403 : parrello 1.287 =over 4
3404 :    
3405 :     =item ec
3406 : efrank 1.1
3407 : parrello 1.287 Code number for the enzyme whose name is desired. The code number is actually
3408 :     a string of digits and periods (e.g. C<1.2.50.6>).
3409 :    
3410 :     =item RETURN
3411 :    
3412 :     Returns the name of the enzyme specified by the indicated code, or a null string
3413 :     if the code is not found in the database.
3414 :    
3415 :     =back
3416 : efrank 1.1
3417 :     =cut
3418 :    
3419 :     sub ec_name {
3420 :     my($self,$ec) = @_;
3421 :    
3422 :     ($ec =~ /^\d+\.\d+\.\d+\.\d+$/) || return "";
3423 :     my $rdbH = $self->db_handle;
3424 :     my $relational_db_response = $rdbH->SQL("SELECT name FROM ec_names WHERE ( ec = \'$ec\' )");
3425 :    
3426 :     return (@$relational_db_response == 1) ? $relational_db_response->[0]->[0] : "";
3427 :     return "";
3428 :     }
3429 :    
3430 : parrello 1.287 =head3 all_roles
3431 : efrank 1.1
3432 : parrello 1.287 C<< my @roles = $fig->all_roles; >>
3433 : efrank 1.1
3434 : parrello 1.287 Return a list of the known roles. Currently, this is a list of the enzyme codes and names.
3435 : efrank 1.1
3436 : parrello 1.287 The return value is a list of list references. Each element of the big list contains an
3437 :     enzyme code (EC) followed by the enzymatic name.
3438 : efrank 1.1
3439 :     =cut
3440 :    
3441 :     sub all_roles {
3442 :     my($self) = @_;
3443 :    
3444 :     my $rdbH = $self->db_handle;
3445 :     my $relational_db_response = $rdbH->SQL("SELECT ec,name FROM ec_names");
3446 :    
3447 :     return @$relational_db_response;
3448 :     }
3449 :    
3450 : parrello 1.287 =head3 expand_ec
3451 : efrank 1.1
3452 : parrello 1.287 C<< my $expanded_ec = $fig->expand_ec($ec); >>
3453 : efrank 1.1
3454 :     Expands "1.1.1.1" to "1.1.1.1 - alcohol dehydrogenase" or something like that.
3455 :    
3456 :     =cut
3457 :    
3458 :     sub expand_ec {
3459 :     my($self,$ec) = @_;
3460 :     my($name);
3461 :    
3462 :     return ($name = $self->ec_name($ec)) ? "$ec - $name" : $ec;
3463 :     }
3464 :    
3465 : parrello 1.287 =head3 clean_tmp
3466 : efrank 1.1
3467 : parrello 1.287 C<< FIG::clean_tmp(); >>
3468 : efrank 1.1
3469 : parrello 1.287 Delete temporary files more than two days old.
3470 : efrank 1.1
3471 :     We store temporary files in $FIG_Config::temp. There are specific classes of files
3472 :     that are created and should be saved for at least a few days. This routine can be
3473 :     invoked to clean out those that are over two days old.
3474 :    
3475 :     =cut
3476 :    
3477 :     sub clean_tmp {
3478 :    
3479 :     my($file);
3480 : parrello 1.287 if (opendir(TMP,"$FIG_Config::temp")) {
3481 :     # change the pattern to pick up other files that need to be cleaned up
3482 :     my @temp = grep { $_ =~ /^(Geno|tmp)/ } readdir(TMP);
3483 :     foreach $file (@temp) {
3484 :     if (-M "$FIG_Config::temp/$file" > 2) {
3485 :     unlink("$FIG_Config::temp/$file");
3486 :     }
3487 :     }
3488 : efrank 1.1 }
3489 :     }
3490 :    
3491 :     ################ Routines to process genomes and genome IDs ##########################
3492 :    
3493 :    
3494 : parrello 1.287 =head3 genomes
3495 : efrank 1.1
3496 : parrello 1.287 C<< my @genome_ids = $fig->genomes($complete, $restrictions, $domain); >>
3497 : efrank 1.1
3498 : parrello 1.287 Return a list of genome IDs. If called with no parameters, all genome IDs
3499 :     in the database will be returned.
3500 : efrank 1.1
3501 :     Genomes are assigned ids of the form X.Y where X is the taxonomic id maintained by
3502 :     NCBI for the species (not the specific strain), and Y is a sequence digit assigned to
3503 :     this particular genome (as one of a set with the same genus/species). Genomes also
3504 :     have versions, but that is a separate issue.
3505 :    
3506 : parrello 1.287 =over 4
3507 :    
3508 :     =item complete
3509 :    
3510 :     TRUE if only complete genomes should be returned, else FALSE.
3511 :    
3512 :     =item restrictions
3513 :    
3514 :     TRUE if only restriction genomes should be returned, else FALSE.
3515 :    
3516 :     =item domain
3517 :    
3518 :     Name of the domain from which the genomes should be returned. Possible values are
3519 :     C<Bacteria>, C<Virus>, C<Eukaryota>, C<unknown>, C<Archaea>, and
3520 :     C<Environmental Sample>. If no domain is specified, all domains will be
3521 :     eligible.
3522 :    
3523 :     =item RETURN
3524 :    
3525 :     Returns a list of all the genome IDs with the specified characteristics.
3526 :    
3527 :     =back
3528 :    
3529 : efrank 1.1 =cut
3530 : parrello 1.320 #: Return Type @;
3531 : parrello 1.328 sub genomes :Remote :List {
3532 : golsen 1.150 my( $self, $complete, $restrictions, $domain ) = @_;
3533 : overbeek 1.13
3534 :     my $rdbH = $self->db_handle;
3535 :    
3536 :     my @where = ();
3537 : parrello 1.287 if ($complete) {
3538 :     push(@where, "( complete = \'1\' )")
3539 : overbeek 1.13 }
3540 :    
3541 : parrello 1.287 if ($restrictions) {
3542 :     push(@where, "( restrictions = \'1\' )")
3543 : overbeek 1.13 }
3544 : golsen 1.150
3545 : parrello 1.287 if ($domain) {
3546 :     push( @where, "( maindomain = '$domain' )" )
3547 : golsen 1.150 }
3548 :    
3549 : overbeek 1.13 my $relational_db_response;
3550 : parrello 1.287 if (@where > 0) {
3551 :     my $where = join(" AND ",@where);
3552 :     $relational_db_response = $rdbH->SQL("SELECT genome FROM genome where $where");
3553 :     } else {
3554 :     $relational_db_response = $rdbH->SQL("SELECT genome FROM genome");
3555 : overbeek 1.13 }
3556 :     my @genomes = sort { $a <=> $b } map { $_->[0] } @$relational_db_response;
3557 : efrank 1.1 return @genomes;
3558 :     }
3559 :    
3560 : parrello 1.287 =head3 is_complete
3561 :    
3562 :     C<< my $flag = $fig->is_complete($genome); >>
3563 :    
3564 :     Return TRUE if the genome with the specified ID is complete, else FALSE.
3565 :    
3566 :     =over 4
3567 :    
3568 :     =item genome
3569 :    
3570 :     ID of the relevant genome.
3571 :    
3572 :     =item RETURN
3573 :    
3574 :     Returns TRUE if there is a complete genome in the database with the specified ID,
3575 :     else FALSE.
3576 :    
3577 :     =back
3578 :    
3579 :     =cut
3580 :    
3581 : overbeek 1.180 sub is_complete {
3582 :     my($self,$genome) = @_;
3583 :    
3584 :     my $rdbH = $self->db_handle;
3585 :     my $relational_db_response = $rdbH->SQL("SELECT genome FROM genome where (genome = '$genome') AND (complete = '1')");
3586 :     return (@$relational_db_response == 1)
3587 : parrello 1.287 }
3588 :    
3589 : parrello 1.490 =head3 is_genome
3590 :    
3591 :     C<< my $flag = $fig->is_genome($genome); >>
3592 :    
3593 :     Return TRUE if the specified genome exists, else FALSE.
3594 :    
3595 :     =over 4
3596 :    
3597 :     =item genome
3598 :    
3599 :     ID of the genome to test.
3600 :    
3601 :     =item RETURN
3602 :    
3603 :     Returns TRUE if a genome with the specified ID exists in the data store, else FALSE.
3604 :    
3605 :     =back
3606 :    
3607 :     =cut
3608 :    
3609 : overbeek 1.421 sub is_genome {
3610 :     my($self,$genome) = @_;
3611 :     my($x,$y);
3612 :    
3613 :     if (! ($x = $self->{_is_genome}))
3614 :     {
3615 :     $x = $self->{_is_genome} = {};
3616 :     }
3617 :    
3618 :     if (defined($y = $x->{$genome})) { return $y }
3619 :     my $rdbH = $self->db_handle;
3620 :     my $relational_db_response = $rdbH->SQL("SELECT genome FROM genome where (genome = '$genome')");
3621 :     $y = (@$relational_db_response == 1);
3622 :     $x->{$genome} = $y;
3623 :     return $y;
3624 :     }
3625 :    
3626 : parrello 1.287 =head3 genome_counts
3627 :    
3628 :     C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $fig->genome_counts($complete); >>
3629 :    
3630 :     Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
3631 :     genomes will be included in the counts.
3632 :    
3633 :     =over 4
3634 :    
3635 :     =item complete
3636 :    
3637 :     TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
3638 :     counted
3639 :    
3640 :     =item RETURN
3641 :    
3642 :     A six-element list containing the number of genomes in each of six categories--
3643 :     Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
3644 :    
3645 :     =back
3646 :    
3647 :     =cut
3648 : golsen 1.150
3649 : efrank 1.2 sub genome_counts {
3650 : overbeek 1.13 my($self,$complete) = @_;
3651 :     my($x,$relational_db_response);
3652 : efrank 1.2
3653 : overbeek 1.13 my $rdbH = $self->db_handle;
3654 :    
3655 : parrello 1.287 if ($complete) {
3656 :     $relational_db_response = $rdbH->SQL("SELECT genome, maindomain FROM genome where complete = '1'");
3657 :     } else {
3658 :     $relational_db_response = $rdbH->SQL("SELECT genome,maindomain FROM genome");
3659 : overbeek 1.13 }
3660 :    
3661 : gdpusch 1.107 my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
3662 : parrello 1.287 if (@$relational_db_response > 0) {
3663 :     foreach $x (@$relational_db_response) {
3664 :     if ($x->[1] =~ /^archaea/i) { ++$arch }
3665 :     elsif ($x->[1] =~ /^bacter/i) { ++$bact }
3666 :     elsif ($x->[1] =~ /^eukar/i) { ++$euk }
3667 :     elsif ($x->[1] =~ /^vir/i) { ++$vir }
3668 :     elsif ($x->[1] =~ /^env/i) { ++$env }
3669 :     else { ++$unk }
3670 : parrello 1.298 }
3671 : efrank 1.2 }
3672 : parrello 1.200
3673 : gdpusch 1.107 return ($arch, $bact, $euk, $vir, $env, $unk);
3674 :     }
3675 :    
3676 :    
3677 : parrello 1.287 =head3 genome_domain
3678 :    
3679 :     C<< my $domain = $fig->genome_domain($genome_id); >>
3680 :    
3681 :     Find the domain of a genome.
3682 : gdpusch 1.107
3683 : parrello 1.287 =over 4
3684 :    
3685 :     =item genome_id
3686 : gdpusch 1.107
3687 : parrello 1.287 ID of the genome whose domain is desired.
3688 : gdpusch 1.107
3689 : parrello 1.287 =item RETURN
3690 :    
3691 :     Returns the name of the genome's domain (archaea, bacteria, etc.), or C<undef> if
3692 :     the genome is not in the database.
3693 : gdpusch 1.107
3694 : parrello 1.292 =back
3695 :    
3696 : gdpusch 1.107 =cut
3697 :    
3698 :     sub genome_domain {
3699 :     my($self,$genome) = @_;
3700 :     my $relational_db_response;
3701 :     my $rdbH = $self->db_handle;
3702 : parrello 1.200
3703 : parrello 1.287 if ($genome) {
3704 :     if (($relational_db_response = $rdbH->SQL("SELECT genome,maindomain FROM genome WHERE ( genome = \'$genome\' )"))
3705 :     && (@$relational_db_response == 1)) {
3706 :     # die Dumper($relational_db_response);
3707 :     return $relational_db_response->[0]->[1];
3708 :     }
3709 : gdpusch 1.107 }
3710 :     return undef;
3711 : efrank 1.2 }
3712 :    
3713 : gdpusch 1.92
3714 : parrello 1.287 =head3 genome_pegs
3715 : gdpusch 1.92
3716 : parrello 1.287 C<< my $num_pegs = $fig->genome_pegs($genome_id); >>
3717 : gdpusch 1.92
3718 : parrello 1.287 Return the number of protein-encoding genes (PEGs) for a specified
3719 :     genome.
3720 : gdpusch 1.92
3721 : parrello 1.287 =over 4
3722 :    
3723 :     =item genome_id
3724 :    
3725 :     ID of the genome whose PEG count is desired.
3726 :    
3727 :     =item RETURN
3728 :    
3729 :     Returns the number of PEGs for the specified genome, or C<undef> if the genome
3730 :     is not indexed in the database.
3731 :    
3732 :     =back
3733 : gdpusch 1.92
3734 :     =cut
3735 :    
3736 :     sub genome_pegs {
3737 :     my($self,$genome) = @_;
3738 :     my $relational_db_response;
3739 :     my $rdbH = $self->db_handle;
3740 : parrello 1.200
3741 : parrello 1.287 if ($genome) {
3742 :     if (($relational_db_response = $rdbH->SQL("SELECT pegs FROM genome WHERE ( genome = \'$genome\' )"))
3743 :     && (@$relational_db_response == 1)) {
3744 :     return $relational_db_response->[0]->[0];
3745 :     }
3746 : gdpusch 1.92 }
3747 :     return undef;
3748 :     }
3749 :    
3750 :    
3751 : parrello 1.287 =head3 genome_rnas
3752 :    
3753 :     C<< my $num_rnas = $fig->genome_rnas($genome_id); >>
3754 :    
3755 :     Return the number of RNA-encoding genes for a genome.
3756 :     "$genome_id" is indexed in the "genome" database, and 'undef' otherwise.
3757 : efrank 1.1
3758 : parrello 1.287 =over 4
3759 :    
3760 :     =item genome_id
3761 :    
3762 :     ID of the genome whose RNA count is desired.
3763 :    
3764 :     =item RETURN
3765 : gdpusch 1.92
3766 : parrello 1.287 Returns the number of RNAs for the specified genome, or C<undef> if the genome
3767 :     is not indexed in the database.
3768 : gdpusch 1.92
3769 : parrello 1.287 =back
3770 : gdpusch 1.92
3771 :     =cut
3772 :    
3773 :     sub genome_rnas {
3774 :     my($self,$genome) = @_;
3775 :     my $relational_db_response;
3776 :     my $rdbH = $self->db_handle;
3777 : parrello 1.200
3778 : parrello 1.287 if ($genome) {
3779 :     if (($relational_db_response = $rdbH->SQL("SELECT rnas FROM genome WHERE ( genome = \'$genome\' )"))
3780 :     && (@$relational_db_response == 1)) {
3781 :     return $relational_db_response->[0]->[0];
3782 :     }
3783 : gdpusch 1.92 }
3784 :     return undef;
3785 :     }
3786 :    
3787 :    
3788 : parrello 1.287 =head3 genome_szdna
3789 :    
3790 :     usage: $szdna = $fig->genome_szdna($genome_id);
3791 :    
3792 :     Return the number of DNA base-pairs in a genome's contigs.
3793 :    
3794 :     =over 4
3795 :    
3796 :     =item genome_id
3797 :    
3798 :     ID of the genome whose base-pair count is desired.
3799 : gdpusch 1.92
3800 : parrello 1.287 =item RETURN
3801 : efrank 1.1
3802 : parrello 1.287 Returns the number of base pairs in the specified genome's contigs, or C<undef>
3803 :     if the genome is not indexed in the database.
3804 : gdpusch 1.91
3805 : parrello 1.287 =back
3806 : gdpusch 1.91
3807 :     =cut
3808 :    
3809 : gdpusch 1.92 sub genome_szdna {
3810 : gdpusch 1.91 my($self,$genome) = @_;
3811 :     my $relational_db_response;
3812 :     my $rdbH = $self->db_handle;
3813 : parrello 1.200
3814 : parrello 1.287 if ($genome) {
3815 :     if (($relational_db_response =
3816 :     $rdbH->SQL("SELECT szdna FROM genome WHERE ( genome = \'$genome\' )"))
3817 :     && (@$relational_db_response == 1)) {
3818 :    
3819 :     return $relational_db_response->[0]->[0];
3820 :    
3821 :     }
3822 : gdpusch 1.91 }
3823 :     return undef;
3824 :     }
3825 :    
3826 : parrello 1.287 =head3 genome_version
3827 : gdpusch 1.91
3828 : parrello 1.287 C<< my $version = $fig->genome_version($genome_id); >>
3829 : gdpusch 1.91
3830 : parrello 1.287 Return the version number of the specified genome.
3831 : efrank 1.1
3832 :     Versions are incremented for major updates. They are put in as major
3833 :     updates of the form 1.0, 2.0, ...
3834 :    
3835 :     Users may do local "editing" of the DNA for a genome, but when they do,
3836 :     they increment the digits to the right of the decimal. Two genomes remain
3837 : parrello 1.200 comparable only if the versions match identically. Hence, minor updating should be
3838 : efrank 1.1 committed only by the person/group responsible for updating that genome.
3839 :    
3840 :     We can, of course, identify which genes are identical between any two genomes (by matching
3841 :     the DNA or amino acid sequences). However, the basic intent of the system is to
3842 :     support editing by the main group issuing periodic major updates.
3843 :    
3844 : parrello 1.287 =over 4
3845 :    
3846 :     =item genome_id
3847 :    
3848 :     ID of the genome whose version is desired.
3849 :    
3850 :     =item RETURN
3851 :    
3852 :     Returns the version number of the specified genome, or C<undef> if the genome is not in
3853 :     the data store or no version number has been assigned.
3854 :    
3855 :     =back
3856 :    
3857 : efrank 1.1 =cut
3858 :    
3859 : parrello 1.328 sub genome_version :Scalar {
3860 : efrank 1.1 my($self,$genome) = @_;
3861 :    
3862 :     my(@tmp);
3863 :     if ((-s "$FIG_Config::organisms/$genome/VERSION") &&
3864 : parrello 1.298 (@tmp = `cat $FIG_Config::organisms/$genome/VERSION`) &&
3865 :     ($tmp[0] =~ /^(\S+)$/)) {
3866 :     return $1;
3867 : efrank 1.1 }
3868 :     return undef;
3869 :     }
3870 :    
3871 : parrello 1.287 =head3 genome_md5sum
3872 : olson 1.236
3873 : parrello 1.287 C<< my $md5sum = $fig->genome_md5sum($genome_id); >>
3874 : olson 1.236
3875 : parrello 1.287 Returns the MD5 checksum of the specified genome.
3876 : olson 1.236
3877 :     The checksum of a genome is defined as the checksum of its signature file. The signature
3878 :     file consists of tab-separated lines, one for each contig, ordered by the contig id.
3879 : parrello 1.287 Each line contains the contig ID, the length of the contig in nucleotides, and the
3880 : olson 1.236 MD5 checksum of the nucleotide data, with uppercase letters forced to lower case.
3881 :    
3882 : parrello 1.287 The checksum is indexed in the database. If you know a genome's checksum, you can use
3883 :     the L</genome_with_md5sum> method to find its ID in the database.
3884 :    
3885 :     =over 4
3886 :    
3887 :     =item genome
3888 :    
3889 :     ID of the genome whose checksum is desired.
3890 :    
3891 :     =item RETURN
3892 :    
3893 :     Returns the specified genome's checksum, or C<undef> if the genome is not in the
3894 :     database.
3895 :    
3896 :     =back
3897 : olson 1.236
3898 :     =cut
3899 :    
3900 : parrello 1.328 sub genome_md5sum :Scalar {
3901 : olson 1.236 my($self,$genome) = @_;
3902 :     my $relational_db_response;
3903 :     my $rdbH = $self->db_handle;
3904 :    
3905 : parrello 1.287 if ($genome) {
3906 :     if (($relational_db_response =
3907 :     $rdbH->SQL("SELECT md5sum FROM genome_md5sum WHERE ( genome = \'$genome\' )"))
3908 :     && (@$relational_db_response == 1)) {
3909 :     return $relational_db_response->[0]->[0];
3910 :     }
3911 : olson 1.236 }
3912 :     return undef;
3913 :     }
3914 :    
3915 : parrello 1.287 =head3 genome_with_md5sum
3916 :    
3917 :     C<< my $genome = $fig->genome_with_md5sum($cksum); >>
3918 :    
3919 :     Find a genome with the specified checksum.
3920 :    
3921 :     The MD5 checksum is computed from the content of the genome (see L</genome_md5sum>). This method
3922 :     can be used to determine if a genome already exists for a specified content.
3923 :    
3924 :     =over 4
3925 :    
3926 :     =item cksum
3927 :    
3928 :     Checksum to use for searching the genome table.
3929 : olson 1.260
3930 : parrello 1.287 =item RETURN
3931 :    
3932 :     The ID of a genome with the specified checksum, or C<undef> if no such genome exists.
3933 : olson 1.260
3934 : parrello 1.287 =back
3935 : olson 1.260
3936 :     =cut
3937 :    
3938 : parrello 1.328 sub genome_with_md5sum :Scalar {
3939 : olson 1.260 my($self,$cksum) = @_;
3940 :     my $relational_db_response;
3941 :     my $rdbH = $self->db_handle;
3942 :    
3943 : parrello 1.287 if (($relational_db_response =
3944 :     $rdbH->SQL("SELECT genome FROM genome_md5sum WHERE ( md5sum = \'$cksum\' )"))
3945 : parrello 1.298 && (@$relational_db_response == 1)) {
3946 :     return $relational_db_response->[0]->[0];
3947 : olson 1.260 }
3948 :    
3949 :     return undef;
3950 :     }
3951 :    
3952 : parrello 1.287 =head3 contig_md5sum
3953 :    
3954 :     C<< my $cksum = $fig->contig_md5sum($genome, $contig); >>
3955 :    
3956 :     Return the MD5 checksum for a contig. The MD5 checksum is computed from the content
3957 :     of the contig. This method retrieves the checksum stored in the database. The checksum
3958 :     can be compared to the checksum of an external contig as a cheap way of seeing if they
3959 :     match.
3960 :    
3961 :     =over 4
3962 :    
3963 :     =item genome
3964 :    
3965 :     ID of the genome containing the contig.
3966 :    
3967 :     =item contig
3968 :    
3969 :     ID of the relevant contig.
3970 :    
3971 :     =item RETURN
3972 :    
3973 :     Returns the checksum of the specified contig, or C<undef> if the contig is not in the
3974 :     database.
3975 :    
3976 :     =back
3977 :    
3978 :     =cut
3979 :    
3980 : parrello 1.328 sub contig_md5sum :Scalar {
3981 : olson 1.237 my($self, $genome, $contig) = @_;
3982 :     my $relational_db_response;
3983 :     my $rdbH = $self->db_handle;
3984 :    
3985 : parrello 1.287 if ($genome) {
3986 :     if (($relational_db_response =
3987 :     $rdbH->SQL(qq(SELECT md5 FROM contig_md5sums WHERE (genome = ? AND contig = ?)), undef, $genome, $contig))
3988 :     && (@$relational_db_response == 1)) {
3989 :     return $relational_db_response->[0]->[0];
3990 :     }
3991 : olson 1.237 }
3992 :     return undef;
3993 :     }
3994 :    
3995 : parrello 1.287 =head3 genus_species
3996 :    
3997 :     C<< my $gs = $fig->genus_species($genome_id); >>
3998 :    
3999 :     Return the genus, species, and possibly also the strain of a specified genome.
4000 :    
4001 :     This method converts a genome ID into a more recognizble species name. The species name
4002 :     is stored directly in the genome table of the database. Essentially, if the strain is
4003 :     present in the database, it will be returned by this method, and if it's not present,
4004 :     it won't.
4005 : efrank 1.1
4006 : parrello 1.287 =over 4
4007 :    
4008 :     =item genome_id
4009 :    
4010 :     ID of the genome whose name is desired.
4011 : efrank 1.1
4012 : parrello 1.287 =item RETURN
4013 :    
4014 :     Returns the scientific species name associated with the specified ID, or C<undef> if the
4015 :     ID is not in the database.
4016 : efrank 1.1
4017 : parrello 1.287 =back
4018 : efrank 1.1
4019 :     =cut
4020 : parrello 1.320 #: Return Type $;
4021 : parrello 1.328 sub genus_species :Scalar {
4022 : efrank 1.1 my ($self,$genome) = @_;
4023 : overbeek 1.13 my $ans;
4024 : efrank 1.1
4025 :     my $genus_species = $self->cached('_genus_species');
4026 : parrello 1.287 if (! ($ans = $genus_species->{$genome})) {
4027 :     my $rdbH = $self->db_handle;
4028 :     my $relational_db_response = $rdbH->SQL("SELECT genome,gname FROM genome");
4029 :     my $pair;
4030 :     foreach $pair (@$relational_db_response) {
4031 :     $genus_species->{$pair->[0]} = $pair->[1];
4032 :     }
4033 :     $ans = $genus_species->{$genome};
4034 : parrello 1.485 if ((! $ans) && open(GEN,"<$FIG_Config::organisms/$genome/GENOME"))
4035 :     {
4036 :     $ans = <GEN>;
4037 :     close(GEN);
4038 :     chomp $ans;
4039 :     $genus_species->{$genome} = $ans;
4040 :     }
4041 : efrank 1.1 }
4042 :     return $ans;
4043 :     }
4044 :    
4045 : parrello 1.287 =head3 org_of
4046 :    
4047 :     C<< my $org = $fig->org_of($prot_id); >>
4048 :    
4049 :     Return the genus/species name of the organism containing a protein. Note that in this context
4050 :     I<protein> is not a certain string of amino acids but a protein encoding region on a specific
4051 :     contig.
4052 :    
4053 :     For a FIG protein ID (e.g. C<fig|134537.1.peg.123>), the organism and strain
4054 :     information is always available. In the case of external proteins, we can usually
4055 :     determine an organism, but not anything more precise than genus/species (and
4056 :     often not that). When the organism name is not present, a null string is returned.
4057 :    
4058 :     =over 4
4059 :    
4060 :     =item prot_id
4061 : efrank 1.1
4062 : parrello 1.287 Protein or feature ID.
4063 : efrank 1.1
4064 : parrello 1.287 =item RETURN
4065 :    
4066 :     Returns the displayable scientific name (genus, species, and strain) of the organism containing
4067 :     the identified PEG. If the name is not available, returns a null string. If the PEG is not found,
4068 :     returns C<undef>.
4069 : efrank 1.1
4070 : parrello 1.287 =back
4071 : efrank 1.1
4072 :     =cut
4073 :    
4074 :     sub org_of {
4075 :     my($self,$prot_id) = @_;
4076 :     my $relational_db_response;
4077 :     my $rdbH = $self->db_handle;
4078 :    
4079 : parrello 1.287 if ($prot_id =~ /^fig\|/) {
4080 :     return $self->is_deleted_fid( $prot_id) ? undef
4081 :     : $self->genus_species( $self->genome_of( $prot_id ) ) || "";
4082 : efrank 1.1 }
4083 :    
4084 : parrello 1.287 if (($relational_db_response =
4085 :     $rdbH->SQL("SELECT org FROM external_orgs WHERE ( prot = \'$prot_id\' )")) &&
4086 :     (@$relational_db_response >= 1)) {
4087 :     $relational_db_response->[0]->[0] =~ s/^\d+://;
4088 :     return $relational_db_response->[0]->[0];
4089 : efrank 1.1 }
4090 :     return "";
4091 :     }
4092 :    
4093 : parrello 1.287 =head3 genus_species_domain
4094 :    
4095 :     C<< my ($gs, $domain) = $fig->genus_species_domain($genome_id); >>
4096 :    
4097 :     Returns a genome's genus and species (and strain if that has been properly
4098 :     recorded) in a printable form, along with its domain. This method is similar
4099 :     to L</genus_species>, except it also returns the domain name (archaea,
4100 :     bacteria, etc.).
4101 :    
4102 :     =over 4
4103 :    
4104 :     =item genome_id
4105 :    
4106 :     ID of the genome whose species and domain information is desired.
4107 : golsen 1.130
4108 : parrello 1.287 =item RETURN
4109 : golsen 1.130
4110 : parrello 1.287 Returns a two-element list. The first element is the species name and the
4111 :     second is the domain name.
4112 : golsen 1.130
4113 : parrello 1.287 =back
4114 : golsen 1.130
4115 :     =cut
4116 :    
4117 :     sub genus_species_domain {
4118 :     my ($self, $genome) = @_;
4119 :    
4120 :     my $genus_species_domain = $self->cached('_genus_species_domain');
4121 : parrello 1.287 if ( ! $genus_species_domain->{ $genome } ) {
4122 :     my $rdbH = $self->db_handle;
4123 :     my $relational_db_response = $rdbH->SQL("SELECT genome,gname,maindomain FROM genome");
4124 :     my $triple;
4125 :     foreach $triple ( @$relational_db_response ) {
4126 :     $genus_species_domain->{ $triple->[0] } = [ $triple->[1], $triple->[2] ];
4127 :     }
4128 : golsen 1.130 }
4129 :     my $gsdref = $genus_species_domain->{ $genome };
4130 :     return $gsdref ? @$gsdref : ( "", "" );
4131 :     }
4132 :    
4133 : parrello 1.287 =head3 domain_color
4134 :    
4135 :     C<< my $web_color = FIG::domain_color($domain); >>
4136 :    
4137 :     Return the web color string associated with a specified domain. The colors are
4138 :     extremely subtle (86% luminance), so they absolutely require a black background.
4139 :     Archaea are slightly cyan, bacteria are slightly magenta, eukaryota are slightly
4140 :     yellow, viruses are slightly silver, environmental samples are slightly gray,
4141 :     and unknown or invalid domains are pure white.
4142 :    
4143 :     =over 4
4144 :    
4145 :     =item domain
4146 :    
4147 :     Name of the domain whose color is desired.
4148 :    
4149 :     =item RETURN
4150 :    
4151 :     Returns a web color string for the specified domain (e.g. C<#FFDDFF> for
4152 :     bacteria).
4153 :    
4154 :     =back
4155 :    
4156 :     =cut
4157 : golsen 1.130
4158 :     my %domain_color = ( AR => "#DDFFFF", BA => "#FFDDFF", EU => "#FFFFDD",
4159 :     VI => "#DDDDDD", EN => "#BBBBBB" );
4160 :    
4161 :     sub domain_color {
4162 :     my ($domain) = @_;
4163 :     defined $domain || return "#FFFFFF";
4164 :     return $domain_color{ uc substr($domain, 0, 2) } || "#FFFFFF";
4165 :     }
4166 :    
4167 : parrello 1.287 =head3 org_and_color_of
4168 : golsen 1.130
4169 : parrello 1.287 C<< my ($org, $color) = $fig->org_and_domain_of($prot_id); >>
4170 : golsen 1.130
4171 : parrello 1.287 Return the best guess organism and domain html color string of an organism.
4172 :     In the case of external proteins, we can usually determine an organism, but not
4173 :     anything more precise than genus/species (and often not that).
4174 :    
4175 :     =over 4
4176 :    
4177 :     =item prot_id
4178 :    
4179 :     Relevant protein or feature ID.
4180 :    
4181 :     =item RETURN
4182 : golsen 1.130
4183 : parrello 1.287 Returns a two-element list. The first element is the displayable organism name, and the second
4184 :     is an HTML color string based on the domain (see L</domain_color>).
4185 : golsen 1.130
4186 : parrello 1.287 =back
4187 : golsen 1.130
4188 :     =cut
4189 :    
4190 :     sub org_and_color_of {
4191 :     my($self,$prot_id) = @_;
4192 :     my $relational_db_response;
4193 :     my $rdbH = $self->db_handle;
4194 :    
4195 : parrello 1.287 if ($prot_id =~ /^fig\|/) {
4196 :     my( $gs, $domain ) = $self->genus_species_domain($self->genome_of($prot_id));
4197 :     return ( $gs, domain_color( $domain ) );
4198 : golsen 1.130 }
4199 :    
4200 : parrello 1.287 if (($relational_db_response =
4201 :     $rdbH->SQL("SELECT org FROM external_orgs WHERE ( prot = \'$prot_id\' )")) &&
4202 :     (@$relational_db_response >= 1)) {
4203 :     return ($relational_db_response->[0]->[0], "#FFFFFF");
4204 : golsen 1.130 }
4205 :     return ("", "#FFFFFF");
4206 :     }
4207 :    
4208 : redwards 1.310 =head3 partial_genus_matching
4209 :    
4210 :     Return a list of genome IDs that match a partial genus.
4211 :    
4212 : redwards 1.311 For example partial_genus_matching("Listeria") will return all genome IDs that begin with Listeria, and this can also be restricted to complete genomes with another argument like this partial_genus_matching("Listeria", 1)
4213 : redwards 1.310
4214 :     =cut
4215 :    
4216 :     sub partial_genus_matching {
4217 : redwards 1.311 my ($self, $gen, $complete)=@_;
4218 :     return grep {$self->genus_species($_) =~ /$gen/i} $self->genomes($complete);
4219 : redwards 1.310 }
4220 :    
4221 :    
4222 : parrello 1.287 =head3 abbrev