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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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