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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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