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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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