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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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