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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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