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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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