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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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