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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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