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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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