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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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