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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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