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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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