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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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