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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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