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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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