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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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