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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.636 - (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.478 $sysrc = system("index_contigs $genome");
876 :     $sysrc == 0 or
877 : parrello 1.485 warn "index_contigs $genome failed; continuing with installation\n";
878 : olson 1.478
879 :     $sysrc = system("compute_genome_counts $genome");
880 :     $sysrc == 0 or
881 : parrello 1.485 warn "compute_genome_counts $genome failed; continuing with installation\n";
882 : olson 1.478
883 :     $sysrc = system("load_features $genome");
884 :     $sysrc == 0 or
885 : parrello 1.485 warn "load_features $genome failed; continuing with installation\n";
886 : parrello 1.379
887 : olson 1.93 $rc = 1;
888 : olson 1.617 if (-s "$genome_dir/Features/peg/fasta")
889 : olson 1.478 {
890 : parrello 1.518
891 : parrello 1.485 $sysrc = system("index_translations $genome");
892 :     $sysrc == 0 or
893 :     warn "index_translations $genome failed; continuing with installation\n";
894 : parrello 1.518
895 : olson 1.615 if (0)
896 :     {
897 :     #
898 :     # We don't do anything with the NR now; that update process is handled externally.
899 :     # The same applies to sims; we plan to optimize the genome installation process
900 :     # for genomes that were processed with the RAST server. For these, a completely
901 :     # new NR and sims set will be computed, OR the sims will be installed from the
902 :     # RAST installation and used locally from the genome direcotry (code still to be
903 :     # added).
904 :     # RDO 2007-09-06
905 :     #
906 :    
907 : olson 1.617 my @tmp = `cut -f1 $genome_dir/Features/peg/tbl`;
908 : olson 1.615 if (@tmp == 0)
909 :     {
910 : olson 1.617 warn "Did not find any features in $genome_dir/Features/peg/tbl\n";
911 : olson 1.615 }
912 :     chomp @tmp;
913 :     if (!$skipnr)
914 :     {
915 : olson 1.617 $sysrc = system("cat $genome_dir/Features/peg/fasta >> $FIG_Config::data/Global/nr");
916 : olson 1.615 $sysrc == 0 or warn "error concatenating features ot NR; continuing with installation\n";
917 :    
918 :     # &run("formatdb -i $FIG_Config::data/Global/nr -p T");
919 :     }
920 :     &enqueue_similarities(\@tmp);
921 :     }
922 : olson 1.93 }
923 : olson 1.478
924 : olson 1.617 if ((-s "$genome_dir/assigned_functions") ||
925 :     (-d "$genome_dir/UserModels"))
926 : olson 1.478 {
927 :     $sysrc = system("add_assertions_of_function $genome");
928 : parrello 1.485 $sysrc == 0 or warn "add_assertions_of_function $genome failed; continuing with installation\n";
929 : efrank 1.1 }
930 : parrello 1.200
931 : olson 1.622 if (-s "$genome_dir/annotations")
932 :     {
933 :     $sysrc = system("index_annotations $genome");
934 :     $sysrc == 0 or warn "index_annoations $genome failed; continuing with installation\n";
935 :     }
936 :    
937 : olson 1.615 #
938 :     # New support for installing precomputed data coming out of the RAST runs.
939 :     #
940 :     # PCHs are installed with install_new_coupling_data.
941 :     #
942 :    
943 : olson 1.617 my $pchs = "$genome_dir/pchs";
944 :     my $pch_scores = "$genome_dir/pchs.scored";
945 : olson 1.615
946 :     if (-f $pchs and -f $pch_scores)
947 :     {
948 :     $sysrc = system("$FIG_Config::bin/install_new_coupling_data",
949 :     $genome,
950 :     $pchs,
951 :     $pch_scores);
952 :     if ($sysrc == 0)
953 :     {
954 :     print "PCHs installed, indexing.\n";
955 :     $sysrc = system("$FIG_Config::bin/load_coupling", $genome);
956 :     if ($sysrc != 0)
957 :     {
958 :     warn "load_coupling $genome failed with rc=$sysrc\n";
959 :     }
960 :     }
961 :     else
962 :     {
963 :     warn "Error $sysrc installing coupling data";
964 :     }
965 :     }
966 :    
967 : olson 1.621 #
968 :     # If this is a RAST replacement genome, perform subsystem salvage.
969 :     #
970 :     my $replaces = &FIG::file_head("$genome_dir/REPLACES", 1);
971 :     chomp $replaces;
972 :     if (-f "$genome_dir/RAST" and $replaces ne '')
973 :     {
974 :     if (open(MAP, "$genome_dir/peg_maps"))
975 :     {
976 :     my %map;
977 :     while (<MAP>)
978 :     {
979 :     chomp;
980 :     my($f, $t) = split(/\t/);
981 :     $map{$f} = $t;
982 :     }
983 :     close(MAP);
984 :    
985 :     $self->perform_subsystem_salvage([[$replaces, $genome]], \%map);
986 :     }
987 :     else
988 :     {
989 :     warn "Genome $genome that replaces $replaces is missing a peg_maps file: $!";
990 :     }
991 :     }
992 :    
993 : olson 1.629
994 :     #
995 :     # Make sure that the features are registered for this genome. We assume here that
996 :     # the genome is already registered (as it should be if we came from RAST).
997 :     #
998 :    
999 :     my $dh = new DirHandle("$genome_dir/Features");
1000 :     for my $ftype ($dh->read())
1001 :     {
1002 :     my $path = "$genome_dir/Features/$ftype";
1003 : olson 1.630 next if $ftype =~ /^\./ or ! -d $path;
1004 : olson 1.629
1005 : olson 1.630 my $fh = new FileHandle("<$path/tbl");
1006 : olson 1.629 if (!$fh)
1007 :     {
1008 :     warn "Cannot open tbl file in feature directory $path: $!";
1009 :     next;
1010 :     }
1011 :     #
1012 :     # Find the largest feature in use.
1013 :     #
1014 :     my $max = -1;
1015 :     while (<$fh>)
1016 :     {
1017 :     chomp;
1018 :     my($fid) = split(/\t/);
1019 :     if ($fid =~ /^fig\|\d+\.\d+\.[^.]+\.(\d+)/)
1020 :     {
1021 :     $max = $1 > $max ? $1 : $max;
1022 :     }
1023 :     }
1024 :     close($fh);
1025 :    
1026 :     #
1027 :     # See what the clearinghouse has, and register features if they are not there.
1028 :     #
1029 :     my $clnext = $self->clearinghouse_next_feature_id($genome, $ftype);
1030 :     if ($clnext <= $max)
1031 :     {
1032 :     #
1033 :     # Not enough features are registered in the clearinghouse. ($clnext needs to be $max + 1)
1034 :     # Register some more.
1035 :     #
1036 :    
1037 :     my $missing = $max - $clnext + 1;
1038 :     my $start = $self->clearinghouse_register_features($genome, $ftype, $missing);
1039 :     if (defined($start))
1040 :     {
1041 :     print "Registered $missing new features of type $ftype on $genome (start=$start)\n";
1042 :     }
1043 :     }
1044 :     }
1045 :    
1046 : efrank 1.1 return $rc;
1047 :     }
1048 :    
1049 : olson 1.629
1050 :    
1051 : overbeek 1.466 sub get_index {
1052 :     my($self,$gs) = @_;
1053 :    
1054 :     my($index,$max);
1055 :     $gs || confess "MISSING GS";
1056 :    
1057 : overbeek 1.467 my $indexF = "$FIG_Config::data/Logs/GenomeLog/index";
1058 : overbeek 1.466 if (open(INDEX,"<$indexF"))
1059 :     {
1060 : parrello 1.485 while ((! $index) && ($_ = <INDEX>))
1061 :     {
1062 :     if ($_ =~ /^(\d+)/)
1063 :     {
1064 :     $max = $1;
1065 :     if (($_ =~ /^(\d+)\t(\S.*\S)/) && ($2 eq $gs))
1066 :     {
1067 :     $index = $1;
1068 :     }
1069 :     }
1070 :     }
1071 :     close(INDEX);
1072 : overbeek 1.466 }
1073 :    
1074 :     if (! $index)
1075 :     {
1076 : parrello 1.485 open(INDEX,">>$indexF") || die "could not open $indexF";
1077 :     $index = defined($max) ? $max+1 : 1;
1078 :     print INDEX "$index\t$gs\n";
1079 :     close(INDEX);
1080 :     &verify_dir("$FIG_Config::data/Logs/GenomeLog/Entries/$index");
1081 : overbeek 1.466 }
1082 :     return $index;
1083 :     }
1084 : parrello 1.518
1085 : overbeek 1.440 sub log_update {
1086 : overbeek 1.466 my($self,$user,$genome,$gs,$msg,@data) = @_;
1087 : overbeek 1.440
1088 :     my $time_made = time;
1089 : overbeek 1.471 &verify_dir("$FIG_Config::data/Logs/GenomeLog");
1090 : overbeek 1.466 my $index_id = $self->get_index($gs);
1091 :     $index_id || die "could not make an index entry for $gs";
1092 : overbeek 1.471 my $gs_dir = "$FIG_Config::data/Logs/GenomeLog/Entries/$index_id";
1093 : overbeek 1.466
1094 : overbeek 1.440 my($i,$file_or_dir,@tars);
1095 :     for ($i=0; ($i < @data); $i++)
1096 :     {
1097 : parrello 1.485 $file_or_dir = $data[$i];
1098 :     my($dir,$file);
1099 :     if ($file_or_dir =~ /^(.*)\/([^\/]+)$/)
1100 :     {
1101 :     ($dir,$file) = ($1,$2);
1102 :     }
1103 :     else
1104 :     {
1105 :     ($dir,$file) = (".",$file_or_dir);
1106 :     }
1107 :     my $tar = "$gs_dir/$time_made.$i.tgz";
1108 :     &run("cd $dir; tar czf $tar $file");
1109 :     push(@tars,$tar);
1110 : overbeek 1.440 }
1111 : overbeek 1.466 open(LOG,">>$gs_dir/log")
1112 : parrello 1.485 || die "could not open $gs_dir/log";
1113 : overbeek 1.466 print LOG "$time_made\n$user\n$genome\n$msg\n";
1114 : parrello 1.518 if (@tars > 0)
1115 : overbeek 1.466 {
1116 : parrello 1.485 print LOG join(",",@tars),"\n";
1117 : overbeek 1.466 }
1118 :     print LOG "//\n";
1119 : overbeek 1.440 close(LOG);
1120 :     }
1121 :    
1122 : parrello 1.287 =head3 parse_genome_args
1123 :    
1124 :     C<< my ($mode, @genomes) = FIG::parse_genome_args(@args); >>
1125 :    
1126 :     Extract a list of genome IDs from an argument list. If the argument list is empty,
1127 :     return all the genomes in the data store.
1128 :    
1129 :     This is a function that is performed by many of the FIG command-line utilities. The
1130 :     user has the option of specifying a list of specific genome IDs or specifying none
1131 :     in order to get all of them. If your command requires additional arguments in the
1132 :     command line, you can still use this method if you shift them out of the argument list
1133 :     before calling. The $mode return value will be C<all> if the user asked for all of
1134 :     the genomes or C<some> if he specified a list of IDs. This is useful to know if,
1135 :     for example, we are loading a table. If we're loading everything, we can delete the
1136 :     entire table; if we're only loading some genomes, we must delete them individually.
1137 :    
1138 :     This method uses the genome directory rather than the database because it may be used
1139 :     before the database is ready.
1140 :    
1141 :     =over 4
1142 :    
1143 :     =item args1, args2, ... argsN
1144 :    
1145 :     List of genome IDs. If all genome IDs are to be processed, then this list should be
1146 :     empty.
1147 :    
1148 :     =item RETURN
1149 :    
1150 :     Returns a list. The first element of the list is C<all> if the user is asking for all
1151 :     the genome IDs and C<some> otherwise. The remaining elements of the list are the
1152 :     desired genome IDs.
1153 :    
1154 :     =back
1155 :    
1156 :     =cut
1157 :    
1158 :     sub parse_genome_args {
1159 :     # Get the parameters.
1160 :     my @args = @_;
1161 :     # Check the mode.
1162 :     my $mode = (@args > 0 ? 'some' : 'all');
1163 :     # Build the return list.
1164 :     my @retVal = ($mode);
1165 :     # Process according to the mode.
1166 :     if ($mode eq 'all') {
1167 :     # We want all the genomes, so we get them from the organism directory.
1168 :     my $orgdir = "$FIG_Config::organisms";
1169 :     opendir( GENOMES, $orgdir ) || Confess("Could not open directory $orgdir");
1170 :     push @retVal, grep { $_ =~ /^\d/ } readdir( GENOMES );
1171 :     closedir( GENOMES );
1172 :     } else {
1173 :     # We want only the genomes specified by the user.
1174 :     push @retVal, @args;
1175 :     }
1176 :     # Return the result.
1177 :     return @retVal;
1178 :     }
1179 :    
1180 :     =head3 reload_table
1181 :    
1182 :     C<< $fig->reload_table($mode, $table, $flds, $xflds, $fileName, $keyList, $keyName); >>
1183 :    
1184 :     Reload a database table from a sequential file. If I<$mode> is C<all>, the table
1185 :     will be dropped and re-created. If I<$mode> is C<some>, the data for the individual
1186 :     items in I<$keyList> will be deleted before the table is loaded. Thus, the load
1187 :     process is optimized for the type of reload.
1188 :    
1189 :     =over 4
1190 :    
1191 :     =item mode
1192 :    
1193 :     C<all> if we are reloading the entire table, C<some> if we are only reloading
1194 :     specific entries.
1195 :    
1196 :     =item table
1197 :    
1198 :     Name of the table to reload.
1199 :    
1200 :     =item flds
1201 :    
1202 :     String defining the table columns, in SQL format. In general, this is a
1203 :     comma-delimited set of field specifiers, each specifier consisting of the
1204 :     field name followed by the field type and any optional qualifiers (such as
1205 :     C<NOT NULL> or C<DEFAULT>); however, it can be anything that would appear
1206 :     between the parentheses in a C<CREATE TABLE> statement. The order in which
1207 :     the fields are specified is important, since it is presumed that is the
1208 :     order in which they are appearing in the load file.
1209 :    
1210 :     =item xflds
1211 :    
1212 :     Reference to a hash that describes the indexes. The hash is keyed by index name.
1213 :     The value is the index's field list. This is a comma-delimited list of field names
1214 :     in order from most significant to least significant. If a field is to be indexed
1215 :     in descending order, its name should be followed by the qualifier C<DESC>. For
1216 :     example, the following I<$xflds> value will create two indexes, one for name followed
1217 :     by creation date in reverse chronological order, and one for ID.
1218 :    
1219 :     { name_index => "name, createDate DESC", id_index => "id" }
1220 :    
1221 :     =item fileName
1222 :    
1223 :     Fully-qualified name of the file containing the data to load. Each line of the
1224 :     file must correspond to a record, and the fields must be arranged in order and
1225 : parrello 1.298 tab-delimited. If the file name is omitted, the table is dropped and re-created
1226 :     but not loaded.
1227 : parrello 1.287
1228 :     =item keyList
1229 :    
1230 :     Reference to a list of the IDs for the objects being reloaded. This parameter is
1231 :     only used if I<$mode> is C<some>.
1232 :    
1233 :     =item keyName (optional)
1234 :    
1235 :     Name of the key field containing the IDs in the keylist. If omitted, C<genome> is
1236 :     assumed.
1237 :    
1238 :     =back
1239 :    
1240 :     =cut
1241 :    
1242 :     sub reload_table {
1243 : parrello 1.298 # Get the parameters.
1244 :     my ($self, $mode, $table, $flds, $xflds, $fileName, $keyList, $keyName) = @_;
1245 : parrello 1.287 if (!defined $keyName) {
1246 :     $keyName = 'genome';
1247 :     }
1248 :     # Get the database handler.
1249 :     my $dbf = $self->{_dbf};
1250 : parrello 1.298 # Call the DBKernel method.
1251 :     $dbf->reload_table($mode, $table, $flds, $xflds, $fileName, $keyList, $keyName);
1252 : parrello 1.287 }
1253 :    
1254 : parrello 1.210 =head3 enqueue_similarities
1255 : olson 1.93
1256 : parrello 1.287 C<< FIG::enqueue_similarities(\@fids); >>
1257 :    
1258 :     Queue the passed Feature IDs for similarity computation. The actual
1259 :     computation is performed by L</create_sim_askfor_pool>. The queue is a
1260 :     persistent text file in the global data directory, and this method
1261 :     essentially writes new IDs on the end of it.
1262 :    
1263 :     =over 4
1264 :    
1265 :     =item fids
1266 :    
1267 :     Reference to a list of feature IDs.
1268 : olson 1.93
1269 : parrello 1.287 =back
1270 : olson 1.93
1271 :     =cut
1272 : parrello 1.210 #: Return Type ;
1273 : olson 1.93 sub enqueue_similarities {
1274 : olson 1.334 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
1275 : efrank 1.1 my($fids) = @_;
1276 :     my $fid;
1277 :    
1278 : olson 1.93 my $sim_q = "$FIG_Config::global/queued_similarities";
1279 :    
1280 :     open(TMP,">>$sim_q")
1281 : parrello 1.287 || die "could not open $sim_q";
1282 : olson 1.93
1283 :     #
1284 :     # We need to lock here so that if a computation is creating a snapshot of the
1285 :     # queue, we block until it's done.
1286 :     #
1287 :    
1288 :     flock(TMP, LOCK_EX) or die "Cannot lock $sim_q\n";
1289 : overbeek 1.442 seek(TMP, 0, 2);
1290 : olson 1.93
1291 : parrello 1.287 foreach $fid (@$fids) {
1292 :     print TMP "$fid\n";
1293 : efrank 1.1 }
1294 :     close(TMP);
1295 : olson 1.10 }
1296 :    
1297 : olson 1.281 =head3 export_similarity_request
1298 :    
1299 :     Creates a similarity computation request from the queued similarities and
1300 : parrello 1.287 the current NR.
1301 : olson 1.281
1302 :     We keep track of the exported requests in case one gets lost.
1303 :    
1304 :     =cut
1305 :    
1306 : parrello 1.287 sub export_similarity_request {
1307 : overbeek 1.439 my($self, $user_req_dir) = @_;
1308 :    
1309 :     my $nr_file = "$user_req_dir/nr";
1310 :     my $fasta_file = "$user_req_dir/fasta";
1311 :     my $peg_syn_file = "$user_req_dir/peg.synonyms";
1312 : olson 1.281
1313 :     my $req_dir = "$FIG_Config::fig/var/sim_requests";
1314 :     &verify_dir("$FIG_Config::fig/var");
1315 :     &verify_dir($req_dir);
1316 :    
1317 :     $req_dir = "$req_dir/" . time;
1318 :     &verify_dir($req_dir);
1319 :    
1320 :     #
1321 :     # Open all of our output files before zeroing out the sim queue, in case
1322 :     # there is a problem.
1323 :     #
1324 :    
1325 :     open(my $user_fasta_fh, ">$fasta_file") or confess "Cannot open $fasta_file for writing: $!";
1326 :     open(my $fasta_fh, ">$req_dir/fasta.in");
1327 :    
1328 :     open(my $user_nr_fh, ">$nr_file") or confess "Cannot open $nr_file for writing: $!";
1329 :     open(my $nr_fh, ">$req_dir/nr") or confess "Cannot open $req_dir/nr for writing: $!";
1330 :    
1331 : overbeek 1.439 open(my $user_peg_syn_fh, ">$peg_syn_file") or confess "Cannot open $peg_syn_file for writing: $!";
1332 :     open(my $peg_syn_fh, ">$req_dir/peg.synonyms") or confess "Cannot open $req_dir/peg.synonyms for writing: $!";
1333 :    
1334 : olson 1.281 open(my $nr_read_fh, "<$FIG_Config::data/Global/nr") or die "Cannot open $FIG_Config::data/Global/nr for reading: $!";
1335 : 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: $!";
1336 : parrello 1.287
1337 : olson 1.281 my $sim_q = "$FIG_Config::global/queued_similarities";
1338 :    
1339 :     #
1340 :     # We need to lock here so that if a computation is creating a snapshot of the
1341 :     # queue, we block until it's done.
1342 :     #
1343 :    
1344 :     open(my $sim_q_lock, ">>$sim_q") or confess "could not open $sim_q";
1345 :     flock($sim_q_lock, LOCK_EX) or confess "Cannot lock $sim_q\n";
1346 :    
1347 :     #
1348 :     # Everything open & locked, start copying.
1349 :     #
1350 : parrello 1.287
1351 : olson 1.281 copy("$sim_q", "$req_dir/q") or confess "Copy $sim_q $req_dir/q failed: $!";
1352 : overbeek 1.439 copy("$sim_q", "$user_req_dir/q") or confess "Copy $sim_q $user_req_dir/q failed: $!";
1353 : parrello 1.287
1354 : overbeek 1.442 #
1355 :     # Copy the contents of the sim queue to the "expected import" queue;
1356 :     # this is a list of pegs for which we expect sims to be computed and installed
1357 :     # at some point.
1358 :     #
1359 :     # We also lock on the pending queue file.
1360 :     #
1361 : parrello 1.518
1362 : overbeek 1.442 if (not(open(SQ, "<$sim_q")))
1363 :     {
1364 : parrello 1.485 warn "Cannot open $sim_q for reading: $!\n";
1365 : overbeek 1.442 }
1366 :     else
1367 :     {
1368 : parrello 1.485 if (open(AW, ">>$FIG_Config::global/pending_similarities"))
1369 :     {
1370 :     flock(AW, LOCK_EX);
1371 :     seek(AW, 0, 2);
1372 :    
1373 :     while (<SQ>)
1374 :     {
1375 :     print AW @_;
1376 :     }
1377 :     close(AW);
1378 :     }
1379 :     else
1380 :     {
1381 :     warn "Could not open $FIG_Config::global/pending_similarities: $!\n";
1382 :     }
1383 :     close(SQ);
1384 : overbeek 1.442 }
1385 : parrello 1.518
1386 : olson 1.281 my($buf);
1387 : parrello 1.287 while (1) {
1388 :     my $n = read($nr_read_fh, $buf, 4096);
1389 :     defined($n) or confess "Error reading nr: $!";
1390 :     last unless $n;
1391 :     syswrite($user_nr_fh, $buf) or confess "Error writing $nr_file: $!";
1392 :     syswrite($nr_fh, $buf) or confess "Error writing $req_dir/nr: $!";
1393 : olson 1.281 }
1394 :    
1395 :     close($nr_read_fh);
1396 :     close($nr_fh);
1397 :     close($user_nr_fh);
1398 :    
1399 : overbeek 1.439 while (1) {
1400 :     my $n = read($peg_syn_read_fh, $buf, 4096);
1401 :     defined($n) or confess "Error reading peg.synonyms: $!";
1402 :     last unless $n;
1403 :     syswrite($user_peg_syn_fh, $buf) or confess "Error writing $peg_syn_file: $!";
1404 :     syswrite($peg_syn_fh, $buf) or confess "Error writing $req_dir/peg.synonyms: $!";
1405 :     }
1406 :    
1407 :     close($peg_syn_read_fh);
1408 :     close($peg_syn_fh);
1409 :     close($user_peg_syn_fh);
1410 : parrello 1.518
1411 : olson 1.281 #
1412 :     # We can zero out the queue and unlock now.
1413 :     #
1414 :    
1415 :     open(F, ">$sim_q") or die "Cannot open $sim_q to truncate it: $!\n";
1416 :     close(F);
1417 : parrello 1.287
1418 : olson 1.281 close($sim_q_lock);
1419 :    
1420 :     #
1421 :     # Generate the fasta input from the queued ids.
1422 :     #
1423 :    
1424 :     open(my $q_fh, "<$req_dir/q");
1425 : parrello 1.287 while (my $id = <$q_fh>) {
1426 :     chomp $id;
1427 : olson 1.281
1428 : parrello 1.287 my $seq = $self->get_translation($id);
1429 : olson 1.281
1430 : parrello 1.287 display_id_and_seq($id, \$seq, $user_fasta_fh);
1431 :     display_id_and_seq($id, \$seq, $fasta_fh);
1432 : olson 1.281 }
1433 :     close($q_fh);
1434 :    
1435 :     close($user_fasta_fh);
1436 :     close($fasta_fh);
1437 :     }
1438 :    
1439 : parrello 1.210 =head3 create_sim_askfor_pool
1440 : olson 1.93
1441 : parrello 1.287 C<< $fig->create_sim_askfor_pool($chunk_size); >>
1442 : olson 1.93
1443 : parrello 1.287 Creates an askfor pool, which a snapshot of the current NR and similarity
1444 :     queue. This process clears the old queue.
1445 : olson 1.123
1446 :     The askfor pool needs to keep track of which sequences need to be
1447 :     calculated, which have been handed out, etc. To simplify this task we
1448 : olson 1.279 chunk the sequences into fairly small numbers (20k characters) and
1449 : olson 1.123 allocate work on a per-chunk basis. We make use of the relational
1450 :     database to keep track of chunk status as well as the seek locations
1451 :     into the file of sequence data. The initial creation of the pool
1452 :     involves indexing the sequence data with seek offsets and lengths and
1453 :     populating the sim_askfor_index table with this information and with
1454 :     initial status information.
1455 : olson 1.93
1456 : parrello 1.287 =over 4
1457 :    
1458 :     =item chunk_size
1459 :    
1460 :     Number of features to put into a processing chunk. The default is 15.
1461 :    
1462 :     =back
1463 :    
1464 : parrello 1.200 =cut
1465 : parrello 1.210 #: Return Type $;
1466 : parrello 1.287 sub create_sim_askfor_pool {
1467 : olson 1.123 my($self, $chunk_size) = @_;
1468 :    
1469 : olson 1.279 $chunk_size = 20000 unless $chunk_size =~ /^\d+$/;
1470 : olson 1.93
1471 : olson 1.279 my $pool_dir = "$FIG_Config::fig/var/sim_pools";
1472 : olson 1.93 &verify_dir($pool_dir);
1473 :    
1474 :     #
1475 :     # Lock the pool directory.
1476 :     #
1477 :     open(my $lock, ">$pool_dir/lockfile");
1478 :    
1479 :     flock($lock, LOCK_EX);
1480 :    
1481 :     my $num = 0;
1482 : parrello 1.287 if (open(my $toc, "<$pool_dir/TOC")) {
1483 :     while (<$toc>) {
1484 :     chomp;
1485 :     # print STDERR "Have toc entry $_\n";
1486 :     my ($idx, $time, $str) = split(/\s+/, $_, 3);
1487 : olson 1.93
1488 : parrello 1.287 $num = max($num, $idx);
1489 :     }
1490 :     close($toc);
1491 : olson 1.93 }
1492 :     $num++;
1493 :     open(my $toc, ">>$pool_dir/TOC") or die "Cannot write $pool_dir/TOC: $!\n";
1494 :    
1495 :     print $toc "$num ", time(), " New toc entry\n";
1496 :     close($toc);
1497 :    
1498 : olson 1.123 my $cpool_id = sprintf "%04d", $num;
1499 :     my $cpool_dir = "$pool_dir/$cpool_id";
1500 : olson 1.93
1501 :     #
1502 :     # All set, create the directory for this pool.
1503 :     #
1504 :    
1505 :     &verify_dir($cpool_dir);
1506 :    
1507 :     #
1508 :     # Now we can copy the nr and sim queue here.
1509 :     # Do this stuff inside an eval so we can clean up
1510 :     # the lockfile.
1511 :     #
1512 :    
1513 :     eval {
1514 : parrello 1.287 my $sim_q = "$FIG_Config::global/queued_similarities";
1515 : olson 1.93
1516 : parrello 1.287 copy("$sim_q", "$cpool_dir/q");
1517 :     copy("$FIG_Config::data/Global/nr", "$cpool_dir/nr");
1518 : olson 1.93
1519 : parrello 1.287 open(F, ">$sim_q") or die "Cannot open $sim_q to truncate it: $!\n";
1520 :     close(F);
1521 : olson 1.93 };
1522 : parrello 1.200
1523 : olson 1.93 unlink("$pool_dir/lockfile");
1524 :     close($lock);
1525 : olson 1.123
1526 :     #
1527 :     # We've created our pool; we can now run the formatdb and
1528 :     # extract the sequences for the blast run.
1529 :     #
1530 : parrello 1.287 my $child_pid = $self->run_in_background(
1531 :     sub {
1532 :     #
1533 :     # Need to close db or there's all sorts of trouble.
1534 :     #
1535 :    
1536 :     my $cmd = "$FIG_Config::ext_bin/formatdb -i $cpool_dir/nr -p T -l $cpool_dir/formatdb.log";
1537 :     print "Will run '$cmd'\n";
1538 :     &run($cmd);
1539 :     print "finished. Logfile:\n";
1540 :     print &FIG::file_read("$cpool_dir/formatdb.log");
1541 :     unlink("$cpool_dir/formatdb.pid");
1542 :     });
1543 : olson 1.279 warn "Running formatdb in background job $child_pid\n";
1544 : olson 1.123 open(FPID, ">$cpool_dir/formatdb.pid");
1545 :     print FPID "$child_pid\n";
1546 :     close(FPID);
1547 :    
1548 :     my $db = $self->db_handle();
1549 : parrello 1.287 if (!$db->table_exists("sim_queue")) {
1550 :     $db->create_table(tbl => "sim_queue",
1551 :     flds => "qid varchar(32), chunk_id INTEGER, seek INTEGER, len INTEGER, " .
1552 :     "assigned BOOL, finished BOOL, output_file varchar(255), " .
1553 : parrello 1.485 "worker_pid INTEGER, start_time timestamp, " .
1554 : parrello 1.287 "assignment_expires INTEGER, worker_info varchar(255)"
1555 :     );
1556 : olson 1.123 }
1557 :    
1558 :     #
1559 :     # Write the fasta input file. Keep track of how many have been written,
1560 :     # and write seek info into the database as appropriate.
1561 :     #
1562 :    
1563 :     open(my $seq_fh, ">$cpool_dir/fasta.in");
1564 :    
1565 :     my($chunk_idx, $chunk_begin, $seq_idx);
1566 :    
1567 : olson 1.279 my $cur_size = 0;
1568 :    
1569 : olson 1.123 $chunk_idx = 0;
1570 :     $chunk_begin = 0;
1571 :     $seq_idx = 0;
1572 :    
1573 : olson 1.279 my $tmpfile = "$FIG_Config::temp/simseek.$$";
1574 :     open(my $tmpfh, ">$tmpfile") or confess "Cannot open tmpfile $tmpfile: $!";
1575 :    
1576 : olson 1.123 open(my $q_fh, "<$cpool_dir/q");
1577 : parrello 1.287 while (my $id = <$q_fh>) {
1578 :     chomp $id;
1579 : olson 1.123
1580 : parrello 1.287 my $seq = $self->get_translation($id);
1581 : olson 1.123
1582 : parrello 1.287 #
1583 :     # check if we're at the beginning of a chunk
1584 :     #
1585 :    
1586 :     print $seq_fh ">$id\n$seq\n";
1587 :    
1588 :     #
1589 :     # Check if we're at the end of a chunk
1590 :     #
1591 :    
1592 :     $cur_size += length($seq);
1593 :     if ($cur_size >= $chunk_size) {
1594 :     my $chunk_end = tell($seq_fh);
1595 :     my $chunk_len = $chunk_end - $chunk_begin;
1596 :    
1597 : olson 1.430 print $tmpfh join("\t", $cpool_id, $chunk_idx, $chunk_begin, $chunk_len, 'FALSE', 'FALSE',
1598 : parrello 1.485 '\N', '\N', '\N', '\N', '\N'), "\n";
1599 : parrello 1.287 $chunk_idx++;
1600 :     $chunk_begin = $chunk_end;
1601 :     $cur_size = 0;
1602 :     }
1603 :     $seq_idx++;
1604 : olson 1.123 }
1605 :    
1606 : parrello 1.287 if ($cur_size > 0) {
1607 :     my $chunk_end = tell($seq_fh);
1608 :     my $chunk_len = $chunk_end - $chunk_begin;
1609 : olson 1.123
1610 : olson 1.430 print $tmpfh join("\t", $cpool_id, $chunk_idx, $chunk_begin, $chunk_len, 'FALSE', 'FALSE',
1611 : parrello 1.485 '\N', '\N', '\N', '\N', '\N'), "\n";
1612 : olson 1.123 }
1613 :    
1614 :     close($q_fh);
1615 :     close($seq_fh);
1616 : olson 1.279 close($tmpfh);
1617 : olson 1.123
1618 : olson 1.279 warn "Write seqs from $tmpfile\n";
1619 : olson 1.123
1620 : olson 1.279 $self->db_handle->load_table(tbl => 'sim_queue',
1621 : parrello 1.298 file => $tmpfile);
1622 : parrello 1.200
1623 : olson 1.430 # unlink($tmpfile);
1624 : parrello 1.287
1625 : olson 1.279 # for my $seek (@seeks)
1626 :     # {
1627 : parrello 1.298 # my($cpool_id, $chunk_idx, $chunk_begin, $chunk_len) = @$seek;
1628 : olson 1.279
1629 : parrello 1.298 # $db->SQL("insert into sim_queue (qid, chunk_id, seek, len, assigned, finished) " .
1630 :     # "values('$cpool_id', $chunk_idx, $chunk_begin, $chunk_len, FALSE, FALSE)");
1631 : olson 1.279 # }
1632 : parrello 1.200
1633 : olson 1.123 return $cpool_id;
1634 :     }
1635 :    
1636 : parrello 1.210 #=head3 get_sim_queue
1637 :     #
1638 :     #usage: get_sim_queue($pool_id, $all_sims)
1639 :     #
1640 :     #Returns the sims in the given pool. If $all_sims is true, return the entire queue. Otherwise,
1641 :     #just return the sims awaiting processing.
1642 :     #
1643 :     #=cut
1644 : olson 1.123
1645 : parrello 1.287 sub get_sim_queue {
1646 : olson 1.123 my($self, $pool_id, $all_sims) = @_;
1647 : olson 1.279 }
1648 :    
1649 : parrello 1.287 =head3 get_sim_work
1650 : olson 1.279
1651 : parrello 1.287 C<< my ($nrPath, $fasta) = $fig->get_sim_work(); >>
1652 : olson 1.279
1653 :     Get the next piece of sim computation work to be performed. Returned are
1654 :     the path to the NR and a string containing the fasta data.
1655 :    
1656 :     =cut
1657 :    
1658 : parrello 1.287 sub get_sim_work {
1659 :    
1660 :     my ($self) = @_;
1661 : olson 1.279
1662 :     #
1663 :     # For now, just don't care about order of data that we get back.
1664 :     #
1665 :    
1666 :     my $db = $self->db_handle();
1667 :     my $lock = FIG::SimLock->new;
1668 :    
1669 :     my $work = $db->SQL(qq(SELECT qid, chunk_id, seek, len
1670 : parrello 1.298 FROM sim_queue
1671 : olson 1.430 WHERE not finished AND not assigned
1672 : parrello 1.298 LIMIT 1));
1673 : olson 1.279 print "Got work ", Dumper($work), "\n";
1674 :    
1675 : parrello 1.287 if (not $work or @$work == 0) {
1676 :     return undef;
1677 : olson 1.279 }
1678 :    
1679 :     my($cpool_id, $chunk_id, $seek, $len) = @{$work->[0]};
1680 : parrello 1.287
1681 : olson 1.279 my $pool_dir = "$FIG_Config::fig/var/sim_pools";
1682 :     my $cpool_dir = "$pool_dir/$cpool_id";
1683 :    
1684 :     my $nr = "$cpool_dir/nr";
1685 :     open(my $fh, "<$cpool_dir/fasta.in");
1686 :     seek($fh, $seek, 0);
1687 :     my $fasta;
1688 :     read($fh, $fasta, $len);
1689 :    
1690 : olson 1.430 $db->SQL(qq(UPDATE sim_queue
1691 : parrello 1.485 SET assigned = true
1692 :     WHERE qid = ? AND chunk_id = ?), undef,
1693 :     $cpool_id, $chunk_id);
1694 : olson 1.430
1695 : olson 1.279 return($cpool_id, $chunk_id, $nr, $fasta, "$cpool_dir/out.$chunk_id");
1696 :     }
1697 :    
1698 : olson 1.430 sub sim_work_working
1699 :     {
1700 :     my($self, $pool, $chunk, $host, $pid) = @_;
1701 :    
1702 :     my $db = $self->db_handle();
1703 :     my $lock = FIG::SimLock->new;
1704 :    
1705 :     my $res = $db->SQL(qq(UPDATE sim_queue
1706 : parrello 1.485 SET worker_pid = ?, start_time = NOW(), worker_info = ?
1707 :     WHERE qid = ? AND chunk_id = ?),
1708 : parrello 1.518 undef,
1709 : parrello 1.485 $pid, $host, $pool, $chunk);
1710 : olson 1.430 }
1711 :    
1712 : olson 1.279 =head3 sim_work_done
1713 :    
1714 : parrello 1.287 C<< $fig->sim_work_done($pool_id, $chunk_id, $out_file); >>
1715 :    
1716 : olson 1.279 Declare that the work in pool_id/chunk_id has been completed, and output written
1717 :     to the pool directory (get_sim_work gave it the path).
1718 :    
1719 : parrello 1.287 =over 4
1720 :    
1721 :     =item pool_id
1722 :    
1723 :     The ID number of the pool containing the work that just completed.
1724 :    
1725 :     =item chunk_id
1726 :    
1727 :     The ID number of the chunk completed.
1728 :    
1729 :     =item out_file
1730 :    
1731 :     The file into which the work was placed.
1732 :    
1733 :     =back
1734 :    
1735 : olson 1.279 =cut
1736 :    
1737 : parrello 1.287 sub sim_work_done {
1738 :     my ($self, $pool_id, $chunk_id, $out_file) = @_;
1739 : olson 1.279
1740 : parrello 1.287 if (! -f $out_file) {
1741 :     Confess("sim_work_done: output file $out_file does not exist");
1742 : olson 1.279 }
1743 :    
1744 :     my $db = $self->db_handle();
1745 :     my $lock = FIG::SimLock->new;
1746 :    
1747 :     my $dbh = $db->{_dbh};
1748 :    
1749 :     my $rows = $dbh->do(qq(UPDATE sim_queue
1750 : parrello 1.298 SET finished = TRUE, output_file = ?
1751 :     WHERE qid = ? and chunk_id = ?), undef, $out_file, $pool_id, $chunk_id);
1752 : parrello 1.287 if ($rows != 1) {
1753 :     if ($dbh->errstr) {
1754 :     Confess("Update not able to set finished=TRUE: ", $dbh->errstr);
1755 :     } else {
1756 :     Confess("Update not able to set finished=TRUE");
1757 :     }
1758 : olson 1.279 }
1759 :     #
1760 :     # Determine if this was the last piece of work for this pool. If so, we can
1761 : parrello 1.287 # schedule the postprocessing work.
1762 : olson 1.279 #
1763 :     # Note we're still holding the lock.
1764 :     #
1765 :    
1766 :     my $out = $db->SQL(qq(SELECT chunk_id
1767 : parrello 1.298 FROM sim_queue
1768 :     WHERE qid = ? AND not finished), undef, $pool_id);
1769 : parrello 1.287 if (@$out == 0) {
1770 :     #
1771 :     # Pool is done.
1772 :     #
1773 :     $self->schedule_sim_pool_postprocessing($pool_id);
1774 : olson 1.279 }
1775 : olson 1.123 }
1776 :    
1777 : olson 1.279 =head3 schedule_sim_pool_postprocessing
1778 :    
1779 : parrello 1.287 C<< $fig->schedule_sim_pool_postprocessing($pool_id); >>
1780 :    
1781 :     Schedule a job to do the similarity postprocessing for the specified pool.
1782 :    
1783 :     =over 4
1784 :    
1785 :     =item pool_id
1786 :    
1787 :     ID of the pool whose similarity postprocessing needs to be scheduled.
1788 : olson 1.279
1789 : parrello 1.287 =back
1790 : olson 1.279
1791 :     =cut
1792 :    
1793 : parrello 1.287 sub schedule_sim_pool_postprocessing {
1794 :    
1795 : olson 1.279 my($self, $pool_id) = @_;
1796 :    
1797 :     my $pool_dir = "$FIG_Config::fig/var/sim_pools";
1798 :     my $cpool_dir = "$pool_dir/$pool_id";
1799 :    
1800 :     my $js = JobScheduler->new();
1801 :     my $job = $js->job_create();
1802 :    
1803 :     my $spath = $job->get_script_path();
1804 :     open(my $sfh, ">$spath");
1805 :     print $sfh <<END;
1806 :     #!/bin/sh
1807 :     . $FIG_Config::fig_disk/config/fig-user-env.sh
1808 :     $FIG_Config::bin/postprocess_computed_sims $pool_id
1809 :     END
1810 :    
1811 :     close($sfh);
1812 :     chmod(0775, $spath);
1813 :    
1814 :     #
1815 :     # Write the job ID to the subsystem queue dir.
1816 :     #
1817 :    
1818 :     open(J, ">$cpool_dir/postprocess_jobid");
1819 :     print J $job->get_id(), "\n";
1820 :     close(J);
1821 :    
1822 :     $job->enqueue();
1823 :     }
1824 :    
1825 :     =head3 postprocess_computed_sims
1826 :    
1827 : parrello 1.287 C<< $fig->postprocess_computed_sims($pool_id); >>
1828 :    
1829 :     Set up to reduce, reformat, and split the similarities in a given pool. We build
1830 :     a pipe to this pipeline:
1831 : olson 1.279
1832 :     reduce_sims peg.synonyms 300 | reformat_sims nr | split_sims dest prefix
1833 :    
1834 : parrello 1.287 Then we put the new sims in the pool directory, and then copy to NewSims.
1835 :    
1836 :     =over 4
1837 :    
1838 :     =item pool_id
1839 :    
1840 :     ID of the pool whose similarities are to be post-processed.
1841 :    
1842 :     =back
1843 : olson 1.279
1844 :     =cut
1845 :    
1846 : parrello 1.287 sub postprocess_computed_sims {
1847 : olson 1.279 my($self, $pool_id) = @_;
1848 :    
1849 :     #
1850 :     # We don't lock here because the job is already done, and we
1851 :     # shouldn't (ha, ha) ever postprocess twice.
1852 :     #
1853 :    
1854 :     my $pool_dir = "$FIG_Config::fig/var/sim_pools";
1855 :     my $cpool_dir = "$pool_dir/$pool_id";
1856 :    
1857 :     my $sim_dir = "$cpool_dir/NewSims";
1858 :     &verify_dir($sim_dir);
1859 :    
1860 :     #
1861 :     # Open the processing pipeline.
1862 :     #
1863 :    
1864 :     my $reduce = "$FIG_Config::bin/reduce_sims $FIG_Config::global/peg.synonyms 300";
1865 :     my $reformat = "$FIG_Config::bin/reformat_sims $cpool_dir/nr";
1866 :     my $split = "$FIG_Config::bin/split_sims $sim_dir sims.$pool_id";
1867 :     open(my $process, "| $reduce | $reformat | $split");
1868 :    
1869 :     #
1870 :     # Iterate over all the sims files, taken from the database.
1871 :     #
1872 :    
1873 :     my $dbh = $self->db_handle()->{_dbh};
1874 :     my $files = $dbh->selectcol_arrayref(qq(SELECT output_file
1875 : parrello 1.298 FROM sim_queue
1876 :     WHERE qid = ? and output_file IS NOT NULL
1877 :     ORDER BY chunk_id), undef, $pool_id);
1878 : parrello 1.287 for my $file (@$files) {
1879 :     my $buf;
1880 :     open(my $fh, "<$file") or confess "Cannot sim input file $file: $!";
1881 :     while (read($fh, $buf, 4096)) {
1882 :     print $process $buf;
1883 :     }
1884 :     close($fh);
1885 : olson 1.279 }
1886 :     my $res = close($process);
1887 : parrello 1.287 if (!$res) {
1888 :     if ($!) {
1889 :     confess "Error closing process pipeline: $!";
1890 :     } else {
1891 :     confess "Process pipeline exited with status $?";
1892 :     }
1893 : olson 1.279 }
1894 :    
1895 :     #
1896 :     # If we got here, it worked. Copy the new sims files over to NewSims.
1897 :     #
1898 :    
1899 :     opendir(my $simdh, $sim_dir) or confess "Cannot open $sim_dir: $!";
1900 :     my @new_sims = grep { $_ !~ /^\./ } readdir($simdh);
1901 :     closedir($simdh);
1902 :    
1903 :     &verify_dir("$FIG_Config::data/NewSims");
1904 :    
1905 : parrello 1.287 for my $sim_file (@new_sims) {
1906 :     my $target = "$FIG_Config::data/NewSims/$sim_file";
1907 :     if (-s $target) {
1908 :     Confess("$target already exists");
1909 :     }
1910 :     print "copying sim file $sim_file\n";
1911 :     &FIG::run("cp $sim_dir/$sim_file $target");
1912 :     &FIG::run("$FIG_Config::bin/index_sims $target");
1913 : olson 1.279 }
1914 :     }
1915 :    
1916 : parrello 1.210 =head3 get_active_sim_pools
1917 : olson 1.123
1918 : parrello 1.287 C<< @pools = $fig->get_active_sim_pools(); >>
1919 : olson 1.123
1920 : parrello 1.287 Return a list of the pool IDs for the sim processing queues that have
1921 :     entries awaiting computation.
1922 : olson 1.123
1923 :     =cut
1924 : parrello 1.210 #: Return Type @;
1925 : parrello 1.287 sub get_active_sim_pools {
1926 : olson 1.123 my($self) = @_;
1927 :    
1928 :     my $dbh = $self->db_handle();
1929 :    
1930 :     my $res = $dbh->SQL("select distinct qid from sim_queue where not finished");
1931 :     return undef unless $res;
1932 :    
1933 :     return map { $_->[0] } @$res;
1934 :     }
1935 :    
1936 : parrello 1.376 =head3 compute_clusters
1937 :    
1938 :     C<< my @clusterList = $fig->compute_clusters(\@pegList, $subsystem, $distance); >>
1939 :    
1940 :     Partition a list of PEGs into sections that are clustered close together on
1941 :     the genome. The basic algorithm used builds a graph connecting PEGs to
1942 :     other PEGs close by them on the genome. Each connected subsection of the graph
1943 :     is then separated into a cluster. Singleton clusters are thrown away, and
1944 :     the remaining ones are sorted by length. All PEGs in the incoming list
1945 :     should belong to the same genome, but this is not a requirement. PEGs on
1946 :     different genomes will simply find themselves in different clusters.
1947 :    
1948 :     =over 4
1949 :    
1950 :     =item pegList
1951 :    
1952 :     Reference to a list of PEG IDs.
1953 :    
1954 :     =item subsystem
1955 :    
1956 :     Subsystem object for the relevant subsystem. This parameter is not used, but is
1957 :     required for compatability with Sprout.
1958 :    
1959 :     =item distance (optional)
1960 :    
1961 :     The maximum distance between PEGs that makes them considered close. If omitted,
1962 :     the distance is 5000 bases.
1963 :    
1964 :     =item RETURN
1965 :    
1966 :     Returns a list of lists. Each sub-list is a cluster of PEGs.
1967 :    
1968 :     =back
1969 :    
1970 :     =cut
1971 :    
1972 :     sub compute_clusters {
1973 :     # Get the parameters.
1974 :     my ($self, $pegList, $subsystem, $distance) = @_;
1975 :     if (! defined $distance) {
1976 :     $distance = 5000;
1977 :     }
1978 : overbeek 1.434
1979 :     my($peg,%by_contig);
1980 :     foreach $peg (@$pegList)
1981 :     {
1982 : parrello 1.485 my $loc;
1983 :     if ($loc = $self->feature_location($peg))
1984 :     {
1985 : parrello 1.488 my ($contig,$beg,$end) = $self->boundaries_of($loc);
1986 : parrello 1.485 my $genome = &FIG::genome_of($peg);
1987 :     push(@{$by_contig{"$genome\t$contig"}},[($beg+$end)/2,$peg]);
1988 :     }
1989 : overbeek 1.434 }
1990 :    
1991 : parrello 1.376 my @clusters = ();
1992 : overbeek 1.434 foreach my $tuple (keys(%by_contig))
1993 :     {
1994 : parrello 1.485 my $x = $by_contig{$tuple};
1995 :     my @pegs = sort { $a->[0] <=> $b->[0] } @$x;
1996 :     while ($x = shift @pegs)
1997 :     {
1998 :     my $clust = [$x->[1]];
1999 :     while ((@pegs > 0) && (abs($pegs[0]->[0] - $x->[0]) <= $distance))
2000 :     {
2001 :     $x = shift @pegs;
2002 :     push(@$clust,$x->[1]);
2003 :     }
2004 : parrello 1.518
2005 : parrello 1.485 if (@$clust > 1)
2006 :     {
2007 :     push(@clusters,$clust);
2008 :     }
2009 :     }
2010 : parrello 1.376 }
2011 : overbeek 1.434 return sort { @$b <=> @$a } @clusters;
2012 : parrello 1.376 }
2013 :    
2014 : parrello 1.210 =head3 get_sim_pool_info
2015 : olson 1.123
2016 : parrello 1.287 C<< my ($total_entries, $n_finished, $n_assigned, $n_unassigned) = $fig->get_sim_pool_info($pool_id); >>
2017 :    
2018 :     Return information about the given sim pool.
2019 :    
2020 :     =over 4
2021 :    
2022 :     =item pool_id
2023 :    
2024 :     Pool ID of the similarity processing queue whose information is desired.
2025 :    
2026 :     =item RETURN
2027 :    
2028 :     Returns a four-element list. The first is the number of features in the
2029 :     queue; the second is the number of features that have been processed; the
2030 :     third is the number of features that have been assigned to a
2031 :     processor, and the fourth is the number of features left over.
2032 : olson 1.123
2033 : parrello 1.287 =back
2034 : olson 1.123
2035 :     =cut
2036 : parrello 1.210 #: Return Type @;
2037 : parrello 1.287 sub get_sim_pool_info {
2038 :    
2039 : olson 1.123 my($self, $pool_id) = @_;
2040 :     my($dbh, $res, $total_entries, $n_finished, $n_assigned, $n_unassigned);
2041 :    
2042 :     $dbh = $self->db_handle();
2043 :    
2044 :     $res = $dbh->SQL("select count(chunk_id) from sim_queue where qid = '$pool_id'");
2045 : parrello 1.200 $total_entries = $res->[0]->[0];
2046 : olson 1.123
2047 :     $res = $dbh->SQL("select count(chunk_id) from sim_queue where qid = '$pool_id' and finished");
2048 :     $n_finished = $res->[0]->[0];
2049 :    
2050 :     $res = $dbh->SQL("select count(chunk_id) from sim_queue where qid = '$pool_id' and assigned and not finished");
2051 :     $n_assigned = $res->[0]->[0];
2052 :    
2053 :     $res = $dbh->SQL("select count(chunk_id) from sim_queue where qid = '$pool_id' and not finished and not assigned");
2054 :     $n_unassigned = $res->[0]->[0];
2055 :    
2056 :     return ($total_entries, $n_finished, $n_assigned, $n_unassigned);
2057 : olson 1.93 }
2058 :    
2059 : parrello 1.210 #=head3 get_sim_chunk
2060 :     #
2061 :     #usage: get_sim_chunk($n_seqs, $worker_id)
2062 :     #
2063 :     #Returns a chunk of $n_seqs of work.
2064 :     #
2065 :     #From Ross, about how sims are processed:
2066 :     #
2067 :     #Here is how I process them:
2068 :     #
2069 :     #
2070 :     # bash$ cd /Volumes/seed/olson/Sims/June22.out
2071 :     # bash$ for i in really*
2072 :     # > do
2073 :     # > cat < $i >> /Volumes/laptop/new.sims
2074 :     # > done
2075 :     #
2076 :     #
2077 :     #Then, I need to "reformat" them by adding to columns to each one
2078 :     # and split the result into files of about 3M each This I do using
2079 :     #
2080 :     #reduce_sims /Volumes/laptop/NR/NewNR/peg.synonyms.june21 300 < /Volumes/laptop/new.sims |
2081 :     # reformat_sims /Volumes/laptop/NR/NewNR/checked.nr.june21 > /Volumes/laptop/reformated.sims
2082 :     #rm /Volumes/laptop/new.sims
2083 :     #split_sims /Volumes/laptop/NewSims sims.june24 reformated.sims
2084 :     #rm reformatted.sims
2085 :     #
2086 :     #=cut
2087 : olson 1.93
2088 : parrello 1.287 sub get_sim_chunk {
2089 : parrello 1.210 my($self, $n_seqs, $worker_id) = @_;
2090 :     }
2091 : olson 1.123
2092 : parrello 1.210 =head3 get_local_hostname
2093 : parrello 1.200
2094 : parrello 1.287 C<< my $result = FIG::get_local_hostname(); >>
2095 :    
2096 :     Return the local host name for the current processor. The name may be
2097 :     stored in a configuration file, or we may have to get it from the
2098 :     operating system.
2099 : olson 1.123
2100 : olson 1.93 =cut
2101 : parrello 1.213 #: Return Type $;
2102 : olson 1.10 sub get_local_hostname {
2103 : olson 1.52
2104 :     #
2105 :     # See if there is a FIGdisk/config/hostname file. If there
2106 :     # is, force the hostname to be that.
2107 :     #
2108 :    
2109 :     my $hostfile = "$FIG_Config::fig_disk/config/hostname";
2110 : parrello 1.287 if (-f $hostfile) {
2111 :     my $fh;
2112 :     if (open($fh, $hostfile)) {
2113 :     my $hostname = <$fh>;
2114 :     chomp($hostname);
2115 :     return $hostname;
2116 :     }
2117 : olson 1.52 }
2118 : parrello 1.200
2119 : olson 1.10 #
2120 :     # First check to see if we our hostname is correct.
2121 :     #
2122 :     # Map it to an IP address, and try to bind to that ip.
2123 :     #
2124 :    
2125 : overbeek 1.435 local $/ = "\n";
2126 :    
2127 : olson 1.10 my $tcp = getprotobyname('tcp');
2128 : parrello 1.200
2129 : olson 1.10 my $hostname = `hostname`;
2130 : overbeek 1.435 chomp $hostname;
2131 : olson 1.10
2132 :     my @hostent = gethostbyname($hostname);
2133 :    
2134 : parrello 1.287 if (@hostent > 0) {
2135 :     my $sock;
2136 :     my $ip = $hostent[4];
2137 :    
2138 :     socket($sock, PF_INET, SOCK_STREAM, $tcp);
2139 :     if (bind($sock, sockaddr_in(0, $ip))) {
2140 :     #
2141 :     # It worked. Reverse-map back to a hopefully fqdn.
2142 :     #
2143 :    
2144 :     my @rev = gethostbyaddr($ip, AF_INET);
2145 :     if (@rev > 0) {
2146 :     my $host = $rev[0];
2147 :     #
2148 :     # Check to see if we have a FQDN.
2149 :     #
2150 :    
2151 :     if ($host =~ /\./) {
2152 :     #
2153 :     # Good.
2154 :     #
2155 :     return $host;
2156 :     } else {
2157 :     #
2158 :     # We didn't get a fqdn; bail and return the IP address.
2159 :     #
2160 :     return get_hostname_by_adapter()
2161 :     }
2162 :     } else {
2163 :     return inet_ntoa($ip);
2164 :     }
2165 :     } else {
2166 :     #
2167 :     # Our hostname must be wrong; we can't bind to the IP
2168 :     # address it maps to.
2169 :     # Return the name associated with the adapter.
2170 :     #
2171 :     return get_hostname_by_adapter()
2172 :     }
2173 :     } else {
2174 :     #
2175 :     # Our hostname isn't known to DNS. This isn't good.
2176 :     # Return the name associated with the adapter.
2177 :     #
2178 :     return get_hostname_by_adapter()
2179 :     }
2180 :     }
2181 :    
2182 :     =head3 get_hostname_by_adapter
2183 : parrello 1.200
2184 : parrello 1.287 C<< my $name = FIG::get_hostname_by_adapter(); >>
2185 : olson 1.10
2186 : parrello 1.287 Return the local host name for the current network environment.
2187 : parrello 1.213
2188 :     =cut
2189 :     #: Return Type $;
2190 : olson 1.10 sub get_hostname_by_adapter {
2191 :     #
2192 :     # Attempt to determine our local hostname based on the
2193 :     # network environment.
2194 :     #
2195 :     # This implementation reads the routing table for the default route.
2196 :     # We then look at the interface config for the interface that holds the default.
2197 :     #
2198 :     #
2199 :     # Linux routing table:
2200 :     # [olson@yips 0.0.0]$ netstat -rn
2201 :     # Kernel IP routing table
2202 :     # Destination Gateway Genmask Flags MSS Window irtt Iface
2203 :     # 140.221.34.32 0.0.0.0 255.255.255.224 U 0 0 0 eth0
2204 :     # 169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth0
2205 :     # 127.0.0.0 0.0.0.0 255.0.0.0 U 0 0 0 lo
2206 :     # 0.0.0.0 140.221.34.61 0.0.0.0 UG 0 0 0 eth0
2207 : parrello 1.200 #
2208 : olson 1.10 # Mac routing table:
2209 : parrello 1.200 #
2210 : olson 1.10 # bash-2.05a$ netstat -rn
2211 :     # Routing tables
2212 : parrello 1.200 #
2213 : olson 1.10 # Internet:
2214 :     # Destination Gateway Flags Refs Use Netif Expire
2215 :     # default 140.221.11.253 UGSc 12 120 en0
2216 :     # 127.0.0.1 127.0.0.1 UH 16 8415486 lo0
2217 :     # 140.221.8/22 link#4 UCS 12 0 en0
2218 :     # 140.221.8.78 0:6:5b:f:51:c4 UHLW 0 183 en0 408
2219 :     # 140.221.8.191 0:3:93:84:ab:e8 UHLW 0 92 en0 622
2220 :     # 140.221.8.198 0:e0:98:8e:36:e2 UHLW 0 5 en0 691
2221 :     # 140.221.9.6 0:6:5b:f:51:d6 UHLW 1 63 en0 1197
2222 :     # 140.221.10.135 0:d0:59:34:26:34 UHLW 2 2134 en0 1199
2223 :     # 140.221.10.152 0:30:1b:b0:ec:dd UHLW 1 137 en0 1122
2224 :     # 140.221.10.153 127.0.0.1 UHS 0 0 lo0
2225 :     # 140.221.11.37 0:9:6b:53:4e:4b UHLW 1 624 en0 1136
2226 :     # 140.221.11.103 0:30:48:22:59:e6 UHLW 3 973 en0 1016
2227 :     # 140.221.11.224 0:a:95:6f:7:10 UHLW 1 1 en0 605
2228 :     # 140.221.11.237 0:1:30:b8:80:c0 UHLW 0 0 en0 1158
2229 :     # 140.221.11.250 0:1:30:3:1:0 UHLW 0 0 en0 1141
2230 :     # 140.221.11.253 0:d0:3:e:70:a UHLW 13 0 en0 1199
2231 :     # 169.254 link#4 UCS 0 0 en0
2232 : parrello 1.200 #
2233 : olson 1.10 # Internet6:
2234 :     # Destination Gateway Flags Netif Expire
2235 :     # UH lo0
2236 :     # fe80::%lo0/64 Uc lo0
2237 :     # link#1 UHL lo0
2238 :     # fe80::%en0/64 link#4 UC en0
2239 :     # 0:a:95:a8:26:68 UHL lo0
2240 :     # ff01::/32 U lo0
2241 :     # ff02::%lo0/32 UC lo0
2242 :     # ff02::%en0/32 link#4 UC en0
2243 :    
2244 :     my($fh);
2245 :    
2246 : parrello 1.287 if (!open($fh, "netstat -rn |")) {
2247 :     warn "Cannot run netstat to determine local IP address\n";
2248 :     return "localhost";
2249 : olson 1.10 }
2250 :    
2251 :     my $interface_name;
2252 : parrello 1.200
2253 : parrello 1.287 while (<$fh>) {
2254 :     my @cols = split();
2255 : olson 1.10
2256 : parrello 1.287 if ($cols[0] eq "default" || $cols[0] eq "0.0.0.0") {
2257 :     $interface_name = $cols[$#cols];
2258 :     }
2259 : olson 1.10 }
2260 :     close($fh);
2261 : parrello 1.200
2262 : olson 1.11 # print "Default route on $interface_name\n";
2263 : olson 1.10
2264 :     #
2265 :     # Find ifconfig.
2266 :     #
2267 :    
2268 :     my $ifconfig;
2269 :    
2270 : parrello 1.287 for my $dir ((split(":", $ENV{PATH}), "/sbin", "/usr/sbin")) {
2271 :     if (-x "$dir/ifconfig") {
2272 :     $ifconfig = "$dir/ifconfig";
2273 :     last;
2274 :     }
2275 : olson 1.10 }
2276 :    
2277 : parrello 1.287 if ($ifconfig eq "") {
2278 :     warn "Ifconfig not found\n";
2279 :     return "localhost";
2280 : olson 1.10 }
2281 : olson 1.11 # print "Foudn $ifconfig\n";
2282 : olson 1.10
2283 : parrello 1.287 if (!open($fh, "$ifconfig $interface_name |")) {
2284 :     warn "Could not run $ifconfig: $!\n";
2285 :     return "localhost";
2286 : olson 1.10 }
2287 :    
2288 :     my $ip;
2289 : parrello 1.287 while (<$fh>) {
2290 :     #
2291 :     # Mac:
2292 :     # inet 140.221.10.153 netmask 0xfffffc00 broadcast 140.221.11.255
2293 :     # Linux:
2294 :     # inet addr:140.221.34.37 Bcast:140.221.34.63 Mask:255.255.255.224
2295 :     #
2296 :    
2297 :     chomp;
2298 :     s/^\s*//;
2299 :    
2300 :     # print "Have '$_'\n";
2301 :     if (/inet\s+addr:(\d+\.\d+\.\d+\.\d+)\s+/) {
2302 :     #
2303 :     # Linux hit.
2304 :     #
2305 :     $ip = $1;
2306 :     # print "Got linux $ip\n";
2307 :     last;
2308 :     } elsif (/inet\s+(\d+\.\d+\.\d+\.\d+)\s+/) {
2309 :     #
2310 :     # Mac hit.
2311 :     #
2312 :     $ip = $1;
2313 :     # print "Got mac $ip\n";
2314 :     last;
2315 :     }
2316 : olson 1.10 }
2317 :     close($fh);
2318 :    
2319 : parrello 1.287 if ($ip eq "") {
2320 :     warn "Didn't find an IP\n";
2321 :     return "localhost";
2322 : olson 1.10 }
2323 :    
2324 :     return $ip;
2325 : efrank 1.1 }
2326 :    
2327 : parrello 1.213 =head3 get_seed_id
2328 :    
2329 : parrello 1.287 C<< my $id = FIG::get_seed_id(); >>
2330 :    
2331 :     Return the Universally Unique ID for this SEED instance. If one
2332 :     does not exist, it will be created.
2333 : parrello 1.213
2334 :     =cut
2335 :     #: Return type $;
2336 : olson 1.38 sub get_seed_id {
2337 :     #
2338 :     # Retrieve the seed identifer from FIGdisk/config/seed_id.
2339 :     #
2340 :     # If it's not there, create one, and make it readonly.
2341 :     #
2342 :     my $id;
2343 :     my $id_file = "$FIG_Config::fig_disk/config/seed_id";
2344 : parrello 1.287 if (! -f $id_file) {
2345 :     my $newid = `uuidgen`;
2346 :     if (!$newid) {
2347 :     die "Cannot run uuidgen: $!";
2348 :     }
2349 : olson 1.38
2350 : parrello 1.287 chomp($newid);
2351 :     my $fh = new FileHandle(">$id_file");
2352 :     if (!$fh) {
2353 :     die "error creating $id_file: $!";
2354 :     }
2355 :     print $fh "$newid\n";
2356 :     $fh->close();
2357 :     chmod(0444, $id_file);
2358 : olson 1.38 }
2359 :     my $fh = new FileHandle("<$id_file");
2360 :     $id = <$fh>;
2361 :     chomp($id);
2362 :     return $id;
2363 :     }
2364 :    
2365 : parrello 1.287 =head3 get_release_info
2366 : olson 1.155
2367 : parrello 1.287 C<< my ($name, $id, $inst, $email, $parent_id, $description) = FIG::get_release_info(); >>
2368 : olson 1.155
2369 : parrello 1.287 Return the current data release information..
2370 : olson 1.195
2371 :     The release info comes from the file FIG/Data/RELEASE. It is formatted as:
2372 :    
2373 : parrello 1.287 <release-name>
2374 :     <unique id>
2375 :     <institution>
2376 :     <contact email>
2377 :     <unique id of data release this release derived from>
2378 :     <description>
2379 : olson 1.195
2380 :     For instance:
2381 :    
2382 : parrello 1.287 -----
2383 :     SEED Data Release, 09/15/2004.
2384 :     4148208C-1DF2-11D9-8417-000A95D52EF6
2385 :     ANL/FIG
2386 :     olson@mcs.anl.gov
2387 :    
2388 :     Test release.
2389 :     -----
2390 : olson 1.195
2391 :     If no RELEASE file exists, this routine will create one with a new unique ID. This
2392 :     lets a peer optimize the data transfer by being able to cache ID translations
2393 :     from this instance.
2394 : olson 1.155
2395 :     =cut
2396 : parrello 1.213 #: Return Type @;
2397 : parrello 1.287 sub get_release_info {
2398 : olson 1.196 my($fig, $no_create) = @_;
2399 : olson 1.195
2400 :     my $rel_file = "$FIG_Config::data/RELEASE";
2401 :    
2402 : parrello 1.287 if (! -f $rel_file and !$no_create) {
2403 : parrello 1.298 #
2404 :     # Create a new one.
2405 :     #
2406 : olson 1.195
2407 : parrello 1.287 my $newid = `uuidgen`;
2408 :     if (!$newid) {
2409 :     die "Cannot run uuidgen: $!";
2410 :     }
2411 : olson 1.195
2412 : parrello 1.287 chomp($newid);
2413 : olson 1.195
2414 : parrello 1.287 my $relinfo = "Automatically generated release info " . localtime();
2415 :     my $inst = "Unknown";
2416 :     my $contact = "Unknown";
2417 :     my $parent = "";
2418 :     my( $a, $b, $e, $v, $env ) = $fig->genome_counts;
2419 :     my $description = "Automatically generated release info\n";
2420 :     $description .= "Contains $a archaeal, $b bacterial, $e eukaryal, $v viral and $env environmental genomes.\n";
2421 :    
2422 :     my $fh = new FileHandle(">$rel_file");
2423 :     if (!$fh) {
2424 :     warn "error creating $rel_file: $!";
2425 :     return undef;
2426 :     }
2427 :     print $fh "$relinfo\n";
2428 :     print $fh "$newid\n";
2429 :     print $fh "$inst\n";
2430 :     print $fh "$contact\n";
2431 :     print $fh "$parent\n";
2432 :     print $fh $description;
2433 :     $fh->close();
2434 :     chmod(0444, $rel_file);
2435 : olson 1.195 }
2436 :    
2437 : parrello 1.287 if (open(my $fh, $rel_file)) {
2438 :     my(@lines) = <$fh>;
2439 :     close($fh);
2440 : parrello 1.200
2441 : parrello 1.287 chomp(@lines);
2442 : parrello 1.200
2443 : parrello 1.287 my($info, $id, $inst, $contact, $parent, @desc) = @lines;
2444 : olson 1.195
2445 : parrello 1.287 return ($info, $id, $inst, $contact, $parent, join("\n", @desc));
2446 : olson 1.195 }
2447 : olson 1.155
2448 :     return undef;
2449 :     }
2450 :    
2451 : parrello 1.406 =head3 Title
2452 :    
2453 :     C<< my $title = $fig->Title(); >>
2454 :    
2455 :     Return the title of this database. For SEED, this will return SEED, for Sprout
2456 :     it will return NMPDR, and so forth.
2457 :    
2458 :     =cut
2459 :    
2460 :     sub Title {
2461 :     return "SEED";
2462 :     }
2463 :    
2464 : parrello 1.376 =head3 FIG
2465 :    
2466 :     C<< my $realFig = $fig->FIG(); >>
2467 :    
2468 :     Return this object. This method is provided for compatability with SFXlate.
2469 :    
2470 :     =cut
2471 :    
2472 :     sub FIG {
2473 :     my ($self) = @_;
2474 :     return $self;
2475 :     }
2476 :    
2477 : parrello 1.287 =head3 get_peer_last_update
2478 : olson 1.155
2479 : parrello 1.287 C<< my $date = $fig->get_peer_last_update($peer_id); >>
2480 : parrello 1.213
2481 : olson 1.155 Return the timestamp from the last successful peer-to-peer update with
2482 : parrello 1.287 the given peer. If the specified peer has made updates, comparing this
2483 :     timestamp to the timestamp of the updates can tell you whether or not
2484 :     the updates have been integrated into your SEED data store.
2485 : olson 1.155
2486 :     We store this information in FIG/Data/Global/Peers/<peer-id>.
2487 :    
2488 : parrello 1.287 =over 4
2489 :    
2490 :     =item peer_id
2491 :    
2492 :     Universally Unique ID for the desired peer.
2493 :    
2494 :     =item RETURN
2495 :    
2496 :     Returns the date/time stamp for the last peer-to-peer updated performed
2497 :     with the identified SEED instance.
2498 :    
2499 :     =back
2500 :    
2501 : olson 1.155 =cut
2502 : parrello 1.213 #: Return Type $;
2503 : parrello 1.287 sub get_peer_last_update {
2504 : olson 1.155 my($self, $peer_id) = @_;
2505 :    
2506 :     my $dir = "$FIG_Config::data/Global/Peers";
2507 :     &verify_dir($dir);
2508 :     $dir .= "/$peer_id";
2509 :     &verify_dir($dir);
2510 :    
2511 :     my $update_file = "$dir/last_update";
2512 : parrello 1.287 if (-f $update_file) {
2513 :     my $time = file_head($update_file, 1);
2514 :     chomp $time;
2515 :     return $time;
2516 :     } else {
2517 :     return undef;
2518 : olson 1.155 }
2519 :     }
2520 :    
2521 : parrello 1.287 =head3 set_peer_last_update
2522 : parrello 1.213
2523 : parrello 1.287 C<< $fig->set_peer_last_update($peer_id, $time); >>
2524 : parrello 1.213
2525 : parrello 1.287 Manually set the update timestamp for a specified peer. This informs
2526 :     the SEED that you have all of the assignments and updates from a
2527 :     particular SEED instance as of a certain date.
2528 : parrello 1.213
2529 :     =cut
2530 :     #: Return Type ;
2531 :    
2532 : parrello 1.287 sub set_peer_last_update {
2533 : olson 1.155 my($self, $peer_id, $time) = @_;
2534 :    
2535 :     my $dir = "$FIG_Config::data/Global/Peers";
2536 :     &verify_dir($dir);
2537 :     $dir .= "/$peer_id";
2538 :     &verify_dir($dir);
2539 :    
2540 :     my $update_file = "$dir/last_update";
2541 :     open(F, ">$update_file");
2542 :     print F "$time\n";
2543 :     close(F);
2544 :     }
2545 :    
2546 : redwards 1.302 =head3 clean_spaces
2547 :    
2548 : parrello 1.320 Remove any extra spaces from input fields. This will (currently) remove ^\s, \s$, and concatenate multiple spaces into one.
2549 : redwards 1.302
2550 :     my $input=$fig->clean_spaces($cgi->param('input'));
2551 :    
2552 :     =cut
2553 :    
2554 :     sub clean_spaces
2555 :     {
2556 :     my ($self, $s)=@_;
2557 :     # note at the moment I do not use \s because that recognizes \t and \n too. This should only remove multiple spaces.
2558 : parrello 1.320 $s =~ s/^ +//;
2559 : redwards 1.302 $s =~ s/ +$//;
2560 :     $s =~ s/ +/ /g;
2561 :     return $s;
2562 :     }
2563 :    
2564 :    
2565 :    
2566 : parrello 1.213 =head3 cgi_url
2567 :    
2568 : parrello 1.287 C<< my $url = FIG::$fig->cgi_url(); >>
2569 :    
2570 :     Return the URL for the CGI script directory.
2571 : parrello 1.213
2572 :     =cut
2573 :     #: Return Type $;
2574 : efrank 1.1 sub cgi_url {
2575 : overbeek 1.377 # return &plug_url($FIG_Config::cgi_url);
2576 :    
2577 :     #
2578 :     # In order to globally make relative references work properly, return ".".
2579 :     # This might break some stuff in p2p, but this will get us most of the way there.
2580 :     # The things that break we can repair by inspecting the value of $ENV{SCRIPT_NAME}
2581 :     #
2582 :     return ".";
2583 : efrank 1.1 }
2584 : parrello 1.200
2585 : overbeek 1.382 =head3 top_link
2586 :    
2587 :     C<< my $url = FIG::top_link(); >>
2588 :    
2589 :     Return the relative URL for the top of the CGI script directory.
2590 :    
2591 :     We determine this based on the SCRIPT_NAME environment variable, falling
2592 :     back to FIG_Config::cgi_base if necessary.
2593 :    
2594 :     =cut
2595 :    
2596 :     sub top_link
2597 :     {
2598 : parrello 1.518
2599 : overbeek 1.382 #
2600 :     # Determine if this is a toplevel cgi or one in one of the subdirs (currently
2601 :     # just /p2p).
2602 :     #
2603 :    
2604 :     my @parts = split(/\//, $ENV{SCRIPT_NAME});
2605 :     my $top;
2606 :     if ($parts[-2] eq 'FIG')
2607 :     {
2608 : parrello 1.485 $top = '.';
2609 :     # warn "toplevel @parts\n";
2610 : overbeek 1.382 }
2611 :     elsif ($parts[-3] eq 'FIG')
2612 :     {
2613 : parrello 1.485 $top = '..';
2614 :     # warn "subdir @parts\n";
2615 : overbeek 1.382 }
2616 :     else
2617 :     {
2618 : parrello 1.485 $top = $FIG_Config::cgi_base;
2619 :     # warn "other @parts\n";
2620 : overbeek 1.382 }
2621 :    
2622 :     return $top;
2623 :     }
2624 :    
2625 : parrello 1.213 =head3 temp_url
2626 :    
2627 : parrello 1.287 C<< my $url = FIG::temp_url(); >>
2628 :    
2629 :     Return the URL of the temporary file directory.
2630 : parrello 1.213
2631 :     =cut
2632 :     #: Return Type $;
2633 : efrank 1.1 sub temp_url {
2634 : overbeek 1.377 # return &plug_url($FIG_Config::temp_url);
2635 :    
2636 :     #
2637 :     # Similarly, make this relative.
2638 :     #
2639 :     return "../FIG-Tmp";
2640 : efrank 1.1 }
2641 : parrello 1.200
2642 : parrello 1.213 =head3 plug_url
2643 :    
2644 : parrello 1.287 C<< my $url2 = $fig->plug_url($url); >>
2645 :    
2646 :     or
2647 :    
2648 :     C<< my $url2 = $fig->plug_url($url); >>
2649 :    
2650 :     Change the domain portion of a URL to point to the current domain. This essentially
2651 :     relocates URLs into the current environment.
2652 :    
2653 :     =over 4
2654 :    
2655 :     =item url
2656 :    
2657 :     URL to relocate.
2658 :    
2659 :     =item RETURN
2660 :    
2661 :     Returns a new URL with the base portion converted to the current operating host.
2662 :     If the URL does not begin with C<http://>, the URL will be returned unmodified.
2663 :    
2664 :     =back
2665 : parrello 1.213
2666 :     =cut
2667 :     #: Return Type $;
2668 : efrank 1.1 sub plug_url {
2669 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2670 : efrank 1.1 my($url) = @_;
2671 :    
2672 : golsen 1.44 my $name;
2673 :    
2674 :     # Revised by GJO
2675 :     # First try to get url from the current http request
2676 :    
2677 :     if ( defined( $ENV{ 'HTTP_HOST' } ) # This is where $cgi->url gets its value
2678 :     && ( $name = $ENV{ 'HTTP_HOST' } )
2679 :     && ( $url =~ s~^http://[^/]*~http://$name~ ) # ~ is delimiter
2680 :     ) {}
2681 :    
2682 :     # Otherwise resort to alternative sources
2683 :    
2684 :     elsif ( ( $name = &get_local_hostname )
2685 :     && ( $url =~ s~^http://[^/]*~http://$name~ ) # ~ is delimiter
2686 :     ) {}
2687 :    
2688 : efrank 1.1 return $url;
2689 :     }
2690 :    
2691 : parrello 1.213 =head3 file_read
2692 :    
2693 : parrello 1.287 C<< my $text = $fig->file_read($fileName); >>
2694 :    
2695 :     or
2696 :    
2697 :     C<< my @lines = $fig->file_read($fileName); >>
2698 :    
2699 :     or
2700 :    
2701 :     C<< my $text = FIG::file_read($fileName); >>
2702 :    
2703 :     or
2704 :    
2705 :     C<< my @lines = FIG::file_read($fileName); >>
2706 :    
2707 :     Read an entire file into memory. In a scalar context, the file is returned
2708 :     as a single text string with line delimiters included. In a list context, the
2709 :     file is returned as a list of lines, each line terminated by a line
2710 :     delimiter. (For a method that automatically strips the line delimiters,
2711 :     use C<Tracer::GetFile>.)
2712 :    
2713 :     =over 4
2714 :    
2715 :     =item fileName
2716 :    
2717 :     Fully-qualified name of the file to read.
2718 :    
2719 :     =item RETURN
2720 :    
2721 :     In a list context, returns a list of the file lines. In a scalar context, returns
2722 :     a string containing all the lines of the file with delimiters included.
2723 : parrello 1.213
2724 : parrello 1.287 =back
2725 : parrello 1.213
2726 :     =cut
2727 :     #: Return Type $;
2728 :     #: Return Type @;
2729 : parrello 1.287 sub file_read {
2730 :    
2731 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2732 : parrello 1.287 my($fileName) = @_;
2733 :     return file_head($fileName, '*');
2734 : olson 1.90
2735 :     }
2736 :    
2737 :    
2738 : parrello 1.213 =head3 file_head
2739 :    
2740 : parrello 1.287 C<< my $text = $fig->file_head($fileName, $count); >>
2741 :    
2742 :     or
2743 :    
2744 :     C<< my @lines = $fig->file_head($fileName, $count); >>
2745 : parrello 1.213
2746 : parrello 1.287 or
2747 : parrello 1.213
2748 : parrello 1.287 C<< my $text = FIG::file_head($fileName, $count); >>
2749 : olson 1.90
2750 : parrello 1.287 or
2751 : olson 1.90
2752 : parrello 1.287 C<< my @lines = FIG::file_head($fileName, $count); >>
2753 : olson 1.90
2754 : parrello 1.287 Read a portion of a file into memory. In a scalar context, the file portion is
2755 :     returned as a single text string with line delimiters included. In a list
2756 :     context, the file portion is returned as a list of lines, each line terminated
2757 :     by a line delimiter.
2758 : olson 1.155
2759 : parrello 1.287 =over 4
2760 : olson 1.90
2761 : parrello 1.287 =item fileName
2762 : olson 1.90
2763 : parrello 1.287 Fully-qualified name of the file to read.
2764 : efrank 1.1
2765 : parrello 1.287 =item count (optional)
2766 : efrank 1.1
2767 : parrello 1.287 Number of lines to read from the file. If omitted, C<1> is assumed. If the
2768 :     non-numeric string C<*> is specified, the entire file will be read.
2769 : efrank 1.1
2770 : parrello 1.287 =item RETURN
2771 : efrank 1.1
2772 : parrello 1.287 In a list context, returns a list of the desired file lines. In a scalar context, returns
2773 :     a string containing the desired lines of the file with delimiters included.
2774 : efrank 1.1
2775 : parrello 1.287 =back
2776 : efrank 1.1
2777 :     =cut
2778 : parrello 1.287 #: Return Type $;
2779 :     #: Return Type @;
2780 :     sub file_head {
2781 : efrank 1.1
2782 : parrello 1.287 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2783 :     my($file, $count) = @_;
2784 : efrank 1.1
2785 : parrello 1.287 my ($n, $allFlag);
2786 :     if ($count eq '*') {
2787 : olson 1.304 Trace("Full file read for \"$file\".") if T(3);
2788 : parrello 1.287 $allFlag = 1;
2789 :     $n = 0;
2790 :     } else {
2791 :     $allFlag = 0;
2792 :     $n = (!$count ? 1 : $count);
2793 : olson 1.304 Trace("Reading $n record(s) from \"$file\".") if T(3);
2794 : parrello 1.287 }
2795 : efrank 1.1
2796 : parrello 1.287 if (open(my $fh, "<$file")) {
2797 : parrello 1.298 my(@ret, $i);
2798 : parrello 1.287 $i = 0;
2799 :     while (<$fh>) {
2800 :     push(@ret, $_);
2801 :     $i++;
2802 :     last if !$allFlag && $i >= $n;
2803 :     }
2804 :     close($fh);
2805 :     if (wantarray) {
2806 :     return @ret;
2807 :     } else {
2808 :     return join("", @ret);
2809 :     }
2810 : efrank 1.1 }
2811 :     }
2812 :    
2813 :     ################ Basic Routines [ existed since WIT ] ##########################
2814 :    
2815 : parrello 1.287 =head3 min
2816 :    
2817 :     C<< my $min = FIG::min(@x); >>
2818 :    
2819 :     or
2820 :    
2821 :     C<< my $min = $fig->min(@x); >>
2822 :    
2823 :     Return the minimum numeric value from a list.
2824 :    
2825 :     =over 4
2826 :    
2827 :     =item x1, x2, ... xN
2828 : efrank 1.1
2829 : parrello 1.287 List of numbers to process.
2830 : efrank 1.1
2831 : parrello 1.287 =item RETURN
2832 : efrank 1.1
2833 : parrello 1.287 Returns the numeric value of the list entry possessing the lowest value. Returns
2834 :     C<undef> if the list is empty.
2835 : efrank 1.1
2836 : parrello 1.287 =back
2837 : efrank 1.1
2838 :     =cut
2839 : parrello 1.213 #: Return Type $;
2840 : efrank 1.1 sub min {
2841 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2842 : efrank 1.1 my(@x) = @_;
2843 :     my($min,$i);
2844 :    
2845 :     (@x > 0) || return undef;
2846 :     $min = $x[0];
2847 : parrello 1.287 for ($i=1; ($i < @x); $i++) {
2848 :     $min = ($min > $x[$i]) ? $x[$i] : $min;
2849 : efrank 1.1 }
2850 :     return $min;
2851 :     }
2852 :    
2853 : parrello 1.287 =head3 max
2854 :    
2855 :     C<< my $max = FIG::max(@x); >>
2856 :    
2857 :     or
2858 :    
2859 :     C<< my $max = $fig->max(@x); >>
2860 : efrank 1.1
2861 : parrello 1.287 Return the maximum numeric value from a list.
2862 : efrank 1.1
2863 : parrello 1.287 =over 4
2864 :    
2865 :     =item x1, x2, ... xN
2866 :    
2867 :     List of numbers to process.
2868 :    
2869 :     =item RETURN
2870 :    
2871 :     Returns the numeric value of t/he list entry possessing the highest value. Returns
2872 :     C<undef> if the list is empty.
2873 : efrank 1.1
2874 : parrello 1.287 =back
2875 : efrank 1.1
2876 :     =cut
2877 : parrello 1.213 #: Return Type $;
2878 : efrank 1.1 sub max {
2879 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2880 : efrank 1.1 my(@x) = @_;
2881 :     my($max,$i);
2882 :    
2883 :     (@x > 0) || return undef;
2884 :     $max = $x[0];
2885 : parrello 1.287 for ($i=1; ($i < @x); $i++) {
2886 :     $max = ($max < $x[$i]) ? $x[$i] : $max;
2887 : efrank 1.1 }
2888 :     return $max;
2889 :     }
2890 :    
2891 : parrello 1.287 =head3 between
2892 : efrank 1.1
2893 : parrello 1.287 C<< my $flag = FIG::between($x, $y, $z); >>
2894 : efrank 1.1
2895 : parrello 1.287 or
2896 :    
2897 :     C<< my $flag = $fig->between($x, $y, $z); >>
2898 :    
2899 :     Determine whether or not $y is between $x and $z.
2900 :    
2901 :     =over 4
2902 :    
2903 :     =item x
2904 :    
2905 :     First edge number.
2906 :    
2907 :     =item y
2908 : efrank 1.1
2909 : parrello 1.287 Number to examine.
2910 :    
2911 :     =item z
2912 :    
2913 :     Second edge number.
2914 :    
2915 :     =item RETURN
2916 :    
2917 :     Return TRUE if the number I<$y> is between the numbers I<$x> and I<$z>. The check
2918 :     is inclusive (that is, if I<$y> is equal to I<$x> or I<$z> the function returns
2919 :     TRUE), and the order of I<$x> and I<$z> does not matter. If I<$x> is lower than
2920 :     I<$z>, then the return is TRUE if I<$x> <= I<$y> <= I<$z>. If I<$z> is lower,
2921 :     then the return is TRUE if I<$x> >= I$<$y> >= I<$z>.
2922 :    
2923 :     =back
2924 : efrank 1.1
2925 :     =cut
2926 : parrello 1.213 #: Return Type $;
2927 : efrank 1.1 sub between {
2928 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2929 : efrank 1.1 my($x,$y,$z) = @_;
2930 :    
2931 : parrello 1.287 if ($x < $z) {
2932 :     return (($x <= $y) && ($y <= $z));
2933 :     } else {
2934 :     return (($x >= $y) && ($y >= $z));
2935 : efrank 1.1 }
2936 :     }
2937 :    
2938 : parrello 1.287 =head3 standard_genetic_code
2939 : efrank 1.1
2940 : parrello 1.287 C<< my $code = FIG::standard_genetic_code(); >>
2941 : efrank 1.1
2942 : parrello 1.287 Return a hash containing the standard translation of nucleotide triples to proteins.
2943 :     Methods such as L</translate> can take a translation scheme as a parameter. This method
2944 :     returns the default translation scheme. The scheme is implemented as a reference to a
2945 :     hash that contains nucleotide triplets as keys and has protein letters as values.
2946 : efrank 1.1
2947 :     =cut
2948 : overbeek 1.583
2949 :     sub genetic_code {
2950 :     my ($ncbi_genetic_code_num) = @_;
2951 : overbeek 1.585 my $code = &standard_genetic_code();
2952 : overbeek 1.583
2953 : overbeek 1.584 if ($ncbi_genetic_code_num == 11) {
2954 :     #...Do nothing
2955 :     }
2956 :     elsif ($ncbi_genetic_code_num == 4) {
2957 : overbeek 1.583 $code->{TGA} = 'W';
2958 :     }
2959 : overbeek 1.584 else {
2960 :     die "Sorry, only genetic codes 11 and 4 are currently supported";
2961 :     }
2962 : overbeek 1.583
2963 :     return $code;
2964 :     }
2965 :    
2966 : parrello 1.213 #: Return Type $;
2967 : efrank 1.1 sub standard_genetic_code {
2968 : parrello 1.200
2969 : efrank 1.1 my $code = {};
2970 :    
2971 :     $code->{"AAA"} = "K";
2972 :     $code->{"AAC"} = "N";
2973 :     $code->{"AAG"} = "K";
2974 :     $code->{"AAT"} = "N";
2975 :     $code->{"ACA"} = "T";
2976 :     $code->{"ACC"} = "T";
2977 :     $code->{"ACG"} = "T";
2978 :     $code->{"ACT"} = "T";
2979 :     $code->{"AGA"} = "R";
2980 :     $code->{"AGC"} = "S";
2981 :     $code->{"AGG"} = "R";
2982 :     $code->{"AGT"} = "S";
2983 :     $code->{"ATA"} = "I";
2984 :     $code->{"ATC"} = "I";
2985 :     $code->{"ATG"} = "M";
2986 :     $code->{"ATT"} = "I";
2987 :     $code->{"CAA"} = "Q";
2988 :     $code->{"CAC"} = "H";
2989 :     $code->{"CAG"} = "Q";
2990 :     $code->{"CAT"} = "H";
2991 :     $code->{"CCA"} = "P";
2992 :     $code->{"CCC"} = "P";
2993 :     $code->{"CCG"} = "P";
2994 :     $code->{"CCT"} = "P";
2995 :     $code->{"CGA"} = "R";
2996 :     $code->{"CGC"} = "R";
2997 :     $code->{"CGG"} = "R";
2998 :     $code->{"CGT"} = "R";
2999 :     $code->{"CTA"} = "L";
3000 :     $code->{"CTC"} = "L";
3001 :     $code->{"CTG"} = "L";
3002 :     $code->{"CTT"} = "L";
3003 :     $code->{"GAA"} = "E";
3004 :     $code->{"GAC"} = "D";
3005 :     $code->{"GAG"} = "E";
3006 :     $code->{"GAT"} = "D";
3007 :     $code->{"GCA"} = "A";
3008 :     $code->{"GCC"} = "A";
3009 :     $code->{"GCG"} = "A";
3010 :     $code->{"GCT"} = "A";
3011 :     $code->{"GGA"} = "G";
3012 :     $code->{"GGC"} = "G";
3013 :     $code->{"GGG"} = "G";
3014 :     $code->{"GGT"} = "G";
3015 :     $code->{"GTA"} = "V";
3016 :     $code->{"GTC"} = "V";
3017 :     $code->{"GTG"} = "V";
3018 :     $code->{"GTT"} = "V";
3019 :     $code->{"TAA"} = "*";
3020 :     $code->{"TAC"} = "Y";
3021 :     $code->{"TAG"} = "*";
3022 :     $code->{"TAT"} = "Y";
3023 :     $code->{"TCA"} = "S";
3024 :     $code->{"TCC"} = "S";
3025 :     $code->{"TCG"} = "S";
3026 :     $code->{"TCT"} = "S";
3027 :     $code->{"TGA"} = "*";
3028 :     $code->{"TGC"} = "C";
3029 :     $code->{"TGG"} = "W";
3030 :     $code->{"TGT"} = "C";
3031 :     $code->{"TTA"} = "L";
3032 :     $code->{"TTC"} = "F";
3033 :     $code->{"TTG"} = "L";
3034 :     $code->{"TTT"} = "F";
3035 : parrello 1.200
3036 : efrank 1.1 return $code;
3037 :     }
3038 :    
3039 : hwang 1.547
3040 :     sub fr_to_go {
3041 : overbeek 1.548 my($self,$role) = @_;
3042 : hwang 1.547
3043 : overbeek 1.549 my $roleQ = quotemeta $role;
3044 : overbeek 1.548 my $rdbH = $self->db_handle;
3045 : overbeek 1.549 my $relational_db_response = $rdbH->SQL("SELECT go_id FROM fr2go WHERE role = '$roleQ'");
3046 : overbeek 1.548 return map { $_->[0] } @{$relational_db_response};
3047 : hwang 1.547 }
3048 :    
3049 : parrello 1.287 =head3 translate
3050 :    
3051 :     C<< my $aa_seq = &FIG::translate($dna_seq, $code, $fix_start); >>
3052 :    
3053 :     Translate a DNA sequence to a protein sequence using the specified genetic code.
3054 :     If I<$fix_start> is TRUE, will translate an initial C<TTG> or C<GTG> code to
3055 :     C<M>. (In the standard genetic code, these two combinations normally translate
3056 :     to C<V> and C<L>, respectively.)
3057 :    
3058 :     =over 4
3059 : efrank 1.1
3060 : parrello 1.287 =item dna_seq
3061 : efrank 1.1
3062 : parrello 1.287 DNA sequence to translate. Note that the DNA sequence can only contain
3063 :     known nucleotides.
3064 : efrank 1.1
3065 : parrello 1.287 =item code
3066 : efrank 1.1
3067 : parrello 1.287 Reference to a hash specifying the translation code. The hash is keyed by
3068 :     nucleotide triples, and the value for each key is the corresponding protein
3069 :     letter. If this parameter is omitted, the L</standard_genetic_code> will be
3070 :     used.
3071 : efrank 1.1
3072 : parrello 1.287 =item fix_start
3073 :    
3074 :     TRUE if the first triple is to get special treatment, else FALSE. If TRUE,
3075 :     then a value of C<TTG> or C<GTG> in the first position will be translated to
3076 :     C<M> instead of the value specified in the translation code.
3077 :    
3078 :     =item RETURN
3079 :    
3080 :     Returns a string resulting from translating each nucleotide triple into a
3081 :     protein letter.
3082 :    
3083 :     =back
3084 :    
3085 :     =cut
3086 :     #: Return Type $;
3087 :     sub translate {
3088 :     shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3089 :    
3090 :     my( $dna,$code,$start ) = @_;
3091 :     my( $i,$j,$ln );
3092 :     my( $x,$y );
3093 :     my( $prot );
3094 :    
3095 :     if (! defined($code)) {
3096 :     $code = &FIG::standard_genetic_code;
3097 : efrank 1.1 }
3098 :     $ln = length($dna);
3099 :     $prot = "X" x ($ln/3);
3100 :     $dna =~ tr/a-z/A-Z/;
3101 :    
3102 : parrello 1.287 for ($i=0,$j=0; ($i < ($ln-2)); $i += 3,$j++) {
3103 :     $x = substr($dna,$i,3);
3104 :     if ($y = $code->{$x}) {
3105 :     substr($prot,$j,1) = $y;
3106 : efrank 1.1 }
3107 :     }
3108 : parrello 1.200
3109 : parrello 1.287 if (($start) && ($ln >= 3) && (substr($dna,0,3) =~ /^[GT]TG$/)) {
3110 :     substr($prot,0,1) = 'M';
3111 : efrank 1.1 }
3112 :     return $prot;
3113 :     }
3114 :    
3115 : parrello 1.287 =head3 reverse_comp
3116 :    
3117 :     C<< my $dnaR = FIG::reverse_comp($dna); >>
3118 :    
3119 :     or
3120 :    
3121 :     C<< my $dnaR = $fig->reverse_comp($dna); >>
3122 :    
3123 :     Return the reverse complement os the specified DNA sequence.
3124 : efrank 1.1
3125 : parrello 1.287 NOTE: for extremely long DNA strings, use L</rev_comp>, which allows you to
3126 :     pass the strings around in the form of pointers.
3127 : efrank 1.1
3128 : parrello 1.287 =over 4
3129 :    
3130 :     =item dna
3131 : efrank 1.1
3132 : parrello 1.287 DNA sequence whose reverse complement is desired.
3133 :    
3134 :     =item RETURN
3135 :    
3136 :     Returns the reverse complement of the incoming DNA sequence.
3137 :    
3138 :     =back
3139 : efrank 1.1
3140 :     =cut
3141 : parrello 1.213 #: Return Type $;
3142 : efrank 1.1 sub reverse_comp {
3143 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3144 : efrank 1.1 my($seq) = @_;
3145 :    
3146 :     return ${&rev_comp(\$seq)};
3147 :     }
3148 :    
3149 : parrello 1.287 =head3 rev_comp
3150 :    
3151 :     C<< my $dnaRP = FIG::rev_comp(\$dna); >>
3152 :    
3153 :     or
3154 :    
3155 :     C<< my $dnaRP = $fig->rev_comp(\$dna); >>
3156 :    
3157 :     Return the reverse complement of the specified DNA sequence. The DNA sequence
3158 :     is passed in as a string reference rather than a raw string for performance
3159 :     reasons. If this is unnecessary, use L</reverse_comp>, which processes strings
3160 :     instead of references to strings.
3161 :    
3162 :     =over 4
3163 :    
3164 :     =item dna
3165 :    
3166 :     Reference to the DNA sequence whose reverse complement is desired.
3167 :    
3168 :     =item RETURN
3169 :    
3170 :     Returns a reference to the reverse complement of the incoming DNA sequence.
3171 :    
3172 :     =back
3173 : parrello 1.213
3174 :     =cut
3175 :     #: Return Type $;
3176 : efrank 1.1 sub rev_comp {
3177 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3178 : efrank 1.1 my( $seqP ) = @_;
3179 :     my( $rev );
3180 :    
3181 :     $rev = reverse( $$seqP );
3182 : overbeek 1.317 $rev =~ tr/A-Z/a-z/;
3183 :     $rev =~ tr/acgtumrwsykbdhv/tgcaakywsrmvhdb/;
3184 : efrank 1.1 return \$rev;
3185 :     }
3186 :    
3187 : overbeek 1.572 # This routine was written by Gary to definitively handle the "scratch" subdirectory issue.
3188 :     # It takes as parameters key-value pairs. The relevant ones are
3189 :     #
3190 :     # tmpdir => NameOfTmpDirectoryToBeUsed [can be ommitted]
3191 :     # tmp => TheNameOfTheTmpDirectoryToContainTheSubdirectory [can be ommitted]
3192 :     #
3193 :     # if tmpdir exists, save_tmp is set to "true". You need to test this at the end
3194 :     # of your script and blow away the directory unless save_tmp is true.
3195 :     # if tmpdir does not exist, it will be created if possible.
3196 :     #
3197 :     # tmp is where to put tmpdir, if it is not specified. if tmp is omitted, it
3198 :     # will all be ok.
3199 :     #
3200 :     #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3201 :     # ( $tmp_dir, $save_tmp ) = temporary_directory( \%options )
3202 :     #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3203 :     sub temporary_directory
3204 :     {
3205 :     my $options = shift;
3206 :    
3207 :     my $tmp_dir = $options->{ tmpdir };
3208 :     my $save_tmp = $options->{ savetmp } || '';
3209 :    
3210 :     if ( $tmp_dir )
3211 :     {
3212 :     if ( -d $tmp_dir ) { $options->{ savetmp } = $save_tmp = 1 }
3213 :     }
3214 :     else
3215 :     {
3216 :     my $tmp = $options->{ tmp } && -d $options->{ tmp } ? $options->{ tmp }
3217 :     : $FIG_Config::temp && -d $FIG_Config::temp ? $FIG_Config::temp
3218 :     : -d '/tmp' ? '/tmp'
3219 :     : '.';
3220 :     $tmp_dir = sprintf( "$tmp/fig_tmp_dir.%05d.%09d", $$, int(1000000000*rand) );
3221 :     }
3222 :    
3223 :     if ( $tmp_dir && ! -d $tmp_dir )
3224 :     {
3225 :     mkdir $tmp_dir;
3226 :     if ( ! -d $tmp_dir )
3227 :     {
3228 : overbeek 1.586 print STDERR "FIG::temporary_directory could not create '$tmp_dir: $!'\n";
3229 : overbeek 1.572 $options->{ tmpdir } = $tmp_dir = undef;
3230 :     }
3231 :     }
3232 :    
3233 :     return ( $tmp_dir, $save_tmp );
3234 :     }
3235 :    
3236 : overbeek 1.454 sub verify_external_tool {
3237 :     my(@progs) = @_;
3238 :    
3239 :     my $prog;
3240 :     foreach $prog (@progs)
3241 :     {
3242 :     my @tmp = `which $prog`;
3243 :     if ($tmp[0] =~ /^no $prog/)
3244 :     {
3245 :     print STDERR $tmp[0];
3246 :     exit(1);
3247 :     }
3248 :     }
3249 :     }
3250 :    
3251 : parrello 1.287 =head3 verify_dir
3252 :    
3253 :     C<< FIG::verify_dir($dir); >>
3254 : efrank 1.1
3255 : parrello 1.287 or
3256 : efrank 1.1
3257 : parrello 1.287 C<< $fig->verify_dir($dir); >>
3258 : efrank 1.1
3259 : parrello 1.287 Insure that the specified directory exists. If it must be created, the permissions will
3260 :     be set to C<0777>.
3261 : efrank 1.1
3262 :     =cut
3263 :    
3264 :     sub verify_dir {
3265 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3266 : efrank 1.1 my($dir) = @_;
3267 :    
3268 : olson 1.416 if (!defined($dir))
3269 :     {
3270 : parrello 1.485 Confess("FIG::verify_dir: missing \$dir argument\n");
3271 : olson 1.416 }
3272 :     if ($dir eq "")
3273 :     {
3274 : parrello 1.485 confess("FIG::verify_dir: refusing to create a directory named ''\n");
3275 : olson 1.416 }
3276 :    
3277 : parrello 1.287 if (-d $dir) {
3278 :     return
3279 :     }
3280 : olson 1.416 if ($dir =~ /^(.*)\/[^\/]+$/ and $1 ne '') {
3281 : parrello 1.287 &verify_dir($1);
3282 : efrank 1.1 }
3283 : overbeek 1.522 mkdir($dir,0777) || confess "Could not make directory $dir: $!";
3284 : efrank 1.1 }
3285 :    
3286 : parrello 1.287 =head3 run
3287 : efrank 1.1
3288 : parrello 1.287 C<< FIG::run($cmd); >>
3289 : overbeek 1.283
3290 : parrello 1.287 or
3291 :    
3292 :     C<< $fig->run($cmd); >>
3293 : overbeek 1.283
3294 : parrello 1.287 Run a command. If the command fails, the error will be traced.
3295 : overbeek 1.283
3296 :     =cut
3297 :    
3298 : parrello 1.287 sub run {
3299 :     shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3300 :     my($cmd) = @_;
3301 :    
3302 : overbeek 1.363 if ($ENV{FIG_VERBOSE}) {
3303 : parrello 1.287 my @tmp = `date`;
3304 :     chomp @tmp;
3305 :     print STDERR "$tmp[0]: running $cmd\n";
3306 :     }
3307 :     Trace("Running command: $cmd") if T(3);
3308 :     (system($cmd) == 0) || Confess("FAILED: $cmd");
3309 :     }
3310 :    
3311 : olson 1.388 =head3 run_gathering_output
3312 :    
3313 :     C<< FIG::run_gathering_output($cmd, @args); >>
3314 :    
3315 :     or
3316 :    
3317 :     C<< $fig->run_gathering_output($cmd, @args); >>
3318 :    
3319 :     Run a command, gathering the output. This is similar to the backtick
3320 :     operator, but it does not invoke the shell. Note that the argument list
3321 : parrello 1.518 must be explicitly passed one command line argument per argument to
3322 : olson 1.388 run_gathering_output.
3323 :    
3324 :     If the command fails, the error will be traced.
3325 :    
3326 :     =cut
3327 :    
3328 :     sub run_gathering_output {
3329 :     shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3330 :     my($cmd, @args) = @_;
3331 :    
3332 :     #
3333 :     # Run the command in a safe fork-with-pipe/exec.
3334 :     #
3335 :    
3336 :     my $pid = open(PROC_READ, "-|");
3337 :    
3338 :     if ($pid == 0)
3339 :     {
3340 : parrello 1.485 exec { $cmd } $cmd, @args;
3341 :     die "could not execute $cmd @args: $!\n";
3342 : olson 1.388 }
3343 :    
3344 :     if (wantarray)
3345 :     {
3346 : parrello 1.485 my @out;
3347 :     while (<PROC_READ>)
3348 :     {
3349 :     push(@out, $_);
3350 :     }
3351 :     if (!close(PROC_READ))
3352 :     {
3353 :     Confess("FAILED: $cmd @args with error return $?");
3354 :     }
3355 :     return @out;
3356 : olson 1.388 }
3357 :     else
3358 :     {
3359 : parrello 1.485 my $out = '';
3360 : parrello 1.518
3361 : parrello 1.485 while (<PROC_READ>)
3362 :     {
3363 :     $out .= $_;
3364 :     }
3365 :     if (!close(PROC_READ))
3366 :     {
3367 :     Confess("FAILED: $cmd @args with error return $?");
3368 :     }
3369 :     return $out;
3370 : olson 1.388 }
3371 :     }
3372 :    
3373 : olson 1.633 =head3 interpret_error_code
3374 :    
3375 :     ($exitcode, $signal, $msg) = &FIG::interpret_error_code($?)
3376 :    
3377 :     Determine if the given result code was due to a process exiting abnormally
3378 :     or by receiving a signal.
3379 :    
3380 :     =cut
3381 :    
3382 :     sub interpret_error_code
3383 :     {
3384 :     shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3385 :    
3386 :     my($rc) = @_;
3387 :    
3388 :     if (WIFEXITED($rc))
3389 :     {
3390 :     return (WEXITSTATUS($rc), undef, "Exited with status " . WEXITSTATUS($rc));
3391 :     }
3392 :     elsif (WIFSIGNALED($rc))
3393 :     {
3394 :     return (undef, WTERMSIG($rc), "Terminated with signal " . WTERMSIG($rc));
3395 :     }
3396 :     elsif (WIFSTOPPED($rc))
3397 :     {
3398 :     return (undef, WSTOPSIG($rc), "Stopped with signal " . WSTOPSIG($rc));
3399 :     }
3400 :     else
3401 :     {
3402 :     return ($rc, undef, "Unknown return code $rc");
3403 :     }
3404 :     }
3405 :    
3406 :    
3407 : parrello 1.287 =head3 augment_path
3408 :    
3409 :     C<< FIG::augment_path($dirName); >>
3410 : overbeek 1.283
3411 : parrello 1.287 Add a directory to the system path.
3412 : overbeek 1.283
3413 : parrello 1.287 This method adds a new directory to the front of the system path. It looks in the
3414 :     configuration file to determine whether this is Windows or Unix, and uses the
3415 :     appropriate separator.
3416 : efrank 1.1
3417 : parrello 1.287 =over 4
3418 : efrank 1.1
3419 : parrello 1.287 =item dirName
3420 :    
3421 :     Name of the directory to add to the path.
3422 :    
3423 :     =back
3424 : efrank 1.1
3425 :     =cut
3426 :    
3427 : parrello 1.287 sub augment_path {
3428 :     my ($dirName) = @_;
3429 :     if ($FIG_Config::win_mode) {
3430 :     $ENV{PATH} = "$dirName;$ENV{PATH}";
3431 :     } else {
3432 :     $ENV{PATH} = "$dirName:$ENV{PATH}";
3433 : overbeek 1.278 }
3434 : efrank 1.1 }
3435 :    
3436 : parrello 1.287 =head3 read_fasta_record
3437 : gdpusch 1.45
3438 : parrello 1.287 C<< my ($seq_id, $seq_pointer, $comment) = FIG::read_fasta_record(\*FILEHANDLE); >>
3439 : gdpusch 1.45
3440 : parrello 1.287 or
3441 : gdpusch 1.45
3442 : parrello 1.287 C<< my ($seq_id, $seq_pointer, $comment) = $fig->read_fasta_record(\*FILEHANDLE); >>
3443 : gdpusch 1.45
3444 : parrello 1.287 Read and parse the next logical record of a FASTA file. A FASTA logical record
3445 :     consists of multiple lines of text. The first line begins with a C<< > >> symbol
3446 :     and contains the sequence ID followed by an optional comment. (NOTE: comments
3447 :     are currently deprecated, because not all tools handle them properly.) The
3448 :     remaining lines contain the sequence data.
3449 :    
3450 :     This method uses a trick to smooth its operation: the line terminator character
3451 :     is temporarily changed to C<< \n> >> so that a single read operation brings in
3452 :     the entire logical record.
3453 : gdpusch 1.45
3454 : parrello 1.287 =over 4
3455 : gdpusch 1.45
3456 : parrello 1.287 =item FILEHANDLE
3457 : gdpusch 1.45
3458 : parrello 1.287 Open handle of the FASTA file. If not specified, C<STDIN> is assumed.
3459 :    
3460 :     =item RETURN
3461 :    
3462 :     If we are at the end of the file, returns C<undef>. Otherwise, returns a
3463 :     three-element list. The first element is the sequence ID, the second is
3464 :     a pointer to the sequence data (that is, a string reference as opposed to
3465 :     as string), and the third is the comment.
3466 :    
3467 :     =back
3468 : gdpusch 1.45
3469 :     =cut
3470 : parrello 1.213 #: Return Type @;
3471 : parrello 1.287 sub read_fasta_record {
3472 :    
3473 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3474 : gdpusch 1.45 my ($file_handle) = @_;
3475 : parrello 1.287 my ($old_end_of_record, $fasta_record, @lines, $head, $sequence, $seq_id, $comment, @parsed_fasta_record);
3476 : parrello 1.200
3477 : gdpusch 1.45 if (not defined($file_handle)) { $file_handle = \*STDIN; }
3478 : parrello 1.200
3479 : gdpusch 1.45 $old_end_of_record = $/;
3480 :     $/ = "\n>";
3481 : parrello 1.200
3482 : parrello 1.287 if (defined($fasta_record = <$file_handle>)) {
3483 :     chomp $fasta_record;
3484 :     @lines = split( /\n/, $fasta_record );
3485 :     $head = shift @lines;
3486 :     $head =~ s/^>?//;
3487 :     $head =~ m/^(\S+)/;
3488 :     $seq_id = $1;
3489 :     if ($head =~ m/^\S+\s+(.*)$/) { $comment = $1; } else { $comment = ""; }
3490 :     $sequence = join( "", @lines );
3491 :     @parsed_fasta_record = ( $seq_id, \$sequence, $comment );
3492 :     } else {
3493 :     @parsed_fasta_record = ();
3494 : gdpusch 1.45 }
3495 : parrello 1.200
3496 : gdpusch 1.45 $/ = $old_end_of_record;
3497 : parrello 1.200
3498 : gdpusch 1.45 return @parsed_fasta_record;
3499 :     }
3500 :    
3501 : parrello 1.287 =head3 display_id_and_seq
3502 :    
3503 :     C<< FIG::display_id_and_seq($id_and_comment, $seqP, $fh); >>
3504 :    
3505 :     or
3506 :    
3507 : parrello 1.355 C<< $fig->display_id_and_seq($id_and_comment, \$seqP, $fh); >>
3508 : parrello 1.287
3509 :     Display a fasta ID and sequence to the specified open file. This method is designed
3510 :     to work well with L</read_fasta_sequence> and L</rev_comp>, because it takes as
3511 :     input a string pointer rather than a string. If the file handle is omitted it
3512 :     defaults to STDOUT.
3513 :    
3514 :     The output is formatted into a FASTA record. The first line of the output is
3515 :     preceded by a C<< > >> symbol, and the sequence is split into 60-character
3516 :     chunks displayed one per line. Thus, this method can be used to produce
3517 :     FASTA files from data gathered by the rest of the system.
3518 :    
3519 :     =over 4
3520 :    
3521 :     =item id_and_comment
3522 :    
3523 :     The sequence ID and (optionally) the comment from the sequence's FASTA record.
3524 :     The ID
3525 : gdpusch 1.45
3526 : parrello 1.287 =item seqP
3527 : efrank 1.1
3528 : parrello 1.287 Reference to a string containing the sequence. The sequence is automatically
3529 :     formatted into 60-character chunks displayed one per line.
3530 : efrank 1.1
3531 : parrello 1.287 =item fh
3532 : efrank 1.1
3533 : parrello 1.287 Open file handle to which the ID and sequence should be output. If omitted,
3534 : parrello 1.355 C<\*STDOUT> is assumed.
3535 : parrello 1.287
3536 :     =back
3537 : efrank 1.1
3538 :     =cut
3539 :    
3540 : parrello 1.287 sub display_id_and_seq {
3541 : mkubal 1.53
3542 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3543 : parrello 1.287
3544 : overbeek 1.326 my( $id, $seqP, $fh ) = @_;
3545 : parrello 1.200
3546 : efrank 1.1 if (! defined($fh) ) { $fh = \*STDOUT; }
3547 : parrello 1.200
3548 : efrank 1.1 print $fh ">$id\n";
3549 : overbeek 1.326 &display_seq($seqP, $fh);
3550 : efrank 1.1 }
3551 :    
3552 : parrello 1.355 =head3 display_seq
3553 : parrello 1.287
3554 : parrello 1.355 C<< FIG::display_seq(\$seqP, $fh); >>
3555 : parrello 1.287
3556 :     or
3557 :    
3558 : parrello 1.355 C<< $fig->display_seq(\$seqP, $fh); >>
3559 : parrello 1.287
3560 :     Display a fasta sequence to the specified open file. This method is designed
3561 :     to work well with L</read_fasta_sequence> and L</rev_comp>, because it takes as
3562 :     input a string pointer rather than a string. If the file handle is omitted it
3563 :     defaults to STDOUT.
3564 :    
3565 :     The sequence is split into 60-character chunks displayed one per line for
3566 :     readability.
3567 :    
3568 :     =over 4
3569 :    
3570 :     =item seqP
3571 :    
3572 :     Reference to a string containing the sequence.
3573 :    
3574 :     =item fh
3575 :    
3576 :     Open file handle to which the sequence should be output. If omitted,
3577 :     C<STDOUT> is assumed.
3578 :    
3579 :     =back
3580 :    
3581 :     =cut
3582 :    
3583 : efrank 1.1 sub display_seq {
3584 : parrello 1.287
3585 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3586 : parrello 1.287
3587 : overbeek 1.326 my ( $seqP, $fh ) = @_;
3588 : efrank 1.1 my ( $i, $n, $ln );
3589 : parrello 1.200
3590 : efrank 1.1 if (! defined($fh) ) { $fh = \*STDOUT; }
3591 :    
3592 : overbeek 1.326 $n = length($$seqP);
3593 : efrank 1.1 # confess "zero-length sequence ???" if ( (! defined($n)) || ($n == 0) );
3594 : parrello 1.287 for ($i=0; ($i < $n); $i += 60) {
3595 :     if (($i + 60) <= $n) {
3596 : overbeek 1.326 $ln = substr($$seqP,$i,60);
3597 : parrello 1.287 } else {
3598 : overbeek 1.326 $ln = substr($$seqP,$i,($n-$i));
3599 : parrello 1.287 }
3600 :     print $fh "$ln\n";
3601 : efrank 1.1 }
3602 :     }
3603 :    
3604 : overbeek 1.529
3605 :     =head3 flatten_dumper
3606 :    
3607 :     C<< FIG::flatten_dumper( $perl_ref_or_object_1, ... ); >>
3608 :    
3609 :     C<< $fig->flatten_dumper( $perl_ref_or_object_1, ... ); >>
3610 :    
3611 :     Takes a list of perl references or objects, and "flattens" their Data::Dumper() output
3612 :     so that it can be printed on a single line.
3613 :    
3614 :     =cut
3615 :    
3616 :     sub flatten_dumper {
3617 :     my @x = @_;
3618 :     my $x;
3619 :    
3620 :     foreach $x (@x)
3621 :     {
3622 :     $x = Dumper($x);
3623 :    
3624 :     $x =~ s/\$VAR\d+\s+\=\s+//o;
3625 :     $x =~ s/\n//gso;
3626 :     $x =~ s/\s+/ /go;
3627 :     $x =~ s/\'//go;
3628 :     # $x =~ s/^[^\(\[\{]+//o;
3629 :     # $x =~ s/[^\)\]\}]+$//o;
3630 :     }
3631 :    
3632 :     return @x;
3633 :     }
3634 :    
3635 :    
3636 : efrank 1.1 ########## I commented the pods on the following routines out, since they should not
3637 :     ########## be part of the SOAP/WSTL interface
3638 :     #=pod
3639 :     #
3640 : parrello 1.287 #=head3 file2N
3641 : efrank 1.1 #
3642 :     #usage: $n = $fig->file2N($file)
3643 :     #
3644 :     #In some of the databases I need to store filenames, which can waste a lot of
3645 :     #space. Hence, I maintain a database for converting filenames to/from integers.
3646 :     #
3647 :     #=cut
3648 :     #
3649 : parrello 1.328 sub file2N :Scalar {
3650 : efrank 1.1 my($self,$file) = @_;
3651 :     my($relational_db_response);
3652 :    
3653 :     my $rdbH = $self->db_handle;
3654 :    
3655 : olson 1.403 #
3656 :     # Strip the figdisk path from the file. N2file replaces it if the path
3657 :     # in the database is relative.
3658 :     #
3659 :     $file =~ s,^$FIG_Config::fig_disk/,,;
3660 :    
3661 : efrank 1.1 if (($relational_db_response = $rdbH->SQL("SELECT fileno FROM file_table WHERE ( file = \'$file\')")) &&
3662 : parrello 1.298 (@$relational_db_response == 1)) {
3663 : parrello 1.287 return $relational_db_response->[0]->[0];
3664 :     } elsif (($relational_db_response = $rdbH->SQL("SELECT MAX(fileno) FROM file_table ")) && (@$relational_db_response == 1) && ($relational_db_response->[0]->[0])) {
3665 :     my $fileno = $relational_db_response->[0]->[0] + 1;
3666 :     if ($rdbH->SQL("INSERT INTO file_table ( file, fileno ) VALUES ( \'$file\', $fileno )")) {
3667 :     return $fileno;
3668 :     }
3669 :     } elsif ($rdbH->SQL("INSERT INTO file_table ( file, fileno ) VALUES ( \'$file\', 1 )")) {
3670 :     return 1;
3671 : efrank 1.1 }
3672 :     return undef;
3673 :     }
3674 :    
3675 :     #=pod
3676 :     #
3677 : parrello 1.287 #=head3 N2file
3678 : efrank 1.1 #
3679 :     #usage: $filename = $fig->N2file($n)
3680 :     #
3681 :     #In some of the databases I need to store filenames, which can waste a lot of
3682 :     #space. Hence, I maintain a database for converting filenames to/from integers.
3683 :     #
3684 :     #=cut
3685 :     #
3686 : overbeek 1.364 sub N2file :Scalar
3687 :     {
3688 : efrank 1.1 my($self,$fileno) = @_;
3689 : overbeek 1.364
3690 :     #
3691 :     # Cache outputs. This results in a huge savings of time when files are
3692 :     # accessed multiple times (as in when a bunch of sims are requested).
3693 :     #
3694 :    
3695 :     my $fcache = $self->cached("_n2file");
3696 : parrello 1.379
3697 : overbeek 1.364 my $fname;
3698 :     if (defined($fname = $fcache->{$fileno}))
3699 :     {
3700 : parrello 1.365 return $fname;
3701 : overbeek 1.364 }
3702 : efrank 1.1
3703 :     my $rdbH = $self->db_handle;
3704 : parrello 1.379
3705 : overbeek 1.364 my $relational_db_response = $rdbH->SQL("SELECT file FROM file_table WHERE ( fileno = $fileno )");
3706 : efrank 1.1
3707 : overbeek 1.364 if ($relational_db_response and @$relational_db_response == 1)
3708 :     {
3709 : parrello 1.365 $fname = $relational_db_response->[0]->[0];
3710 : olson 1.403
3711 : parrello 1.420 #
3712 :     # If $fname is relative, prepend the base of the fig_disk.
3713 :     # (Updated to use PERL's system-independent filename utilities.
3714 :     #
3715 : parrello 1.518
3716 : parrello 1.420 $fname = File::Spec->rel2abs($fname, $FIG_Config::fig_disk);
3717 : parrello 1.518
3718 : parrello 1.365 $fcache->{$fileno} = $fname;
3719 :     return $fname;
3720 : efrank 1.1 }
3721 :     return undef;
3722 :     }
3723 :    
3724 :    
3725 :     #=pod
3726 :     #
3727 : parrello 1.287 #=head3 openF
3728 : efrank 1.1 #
3729 :     #usage: $fig->openF($filename)
3730 :     #
3731 :     #Parts of the system rely on accessing numerous different files. The most obvious case is
3732 :     #the situation with similarities. It is important that the system be able to run in cases in
3733 :     #which an arbitrary number of files cannot be open simultaneously. This routine (with closeF) is
3734 :     #a hack to handle this. I should probably just pitch them and insist that the OS handle several
3735 :     #hundred open filehandles.
3736 :     #
3737 :     #=cut
3738 :     #
3739 :     sub openF {
3740 :     my($self,$file) = @_;
3741 :     my($fxs,$x,@fxs,$fh);
3742 :    
3743 :     $fxs = $self->cached('_openF');
3744 : parrello 1.287 if ($x = $fxs->{$file}) {
3745 :     $x->[1] = time();
3746 :     return $x->[0];
3747 : efrank 1.1 }
3748 : parrello 1.200
3749 : efrank 1.1 @fxs = keys(%$fxs);
3750 : parrello 1.287 if (defined($fh = new FileHandle "<$file")) {
3751 :     if (@fxs >= 50) {
3752 :     @fxs = sort { $fxs->{$a}->[1] <=> $fxs->{$b}->[1] } @fxs;
3753 :     $x = $fxs->{$fxs[0]};
3754 :     undef $x->[0];
3755 :     delete $fxs->{$fxs[0]};
3756 :     }
3757 :     $fxs->{$file} = [$fh,time()];
3758 :     return $fh;
3759 : efrank 1.1 }
3760 :     return undef;
3761 :     }
3762 :    
3763 :     #=pod
3764 :     #
3765 : parrello 1.287 #=head3 closeF
3766 : efrank 1.1 #
3767 :     #usage: $fig->closeF($filename)
3768 :     #
3769 :     #Parts of the system rely on accessing numerous different files. The most obvious case is
3770 :     #the situation with similarities. It is important that the system be able to run in cases in
3771 :     #which an arbitrary number of files cannot be open simultaneously. This routine (with openF) is
3772 :     #a hack to handle this. I should probably just pitch them and insist that the OS handle several
3773 :     #hundred open filehandles.
3774 :     #
3775 :     #=cut
3776 :     #
3777 :     sub closeF {
3778 :     my($self,$file) = @_;
3779 :     my($fxs,$x);
3780 :    
3781 : parrello 1.287 if (($fxs = $self->{_openF}) && ($x = $fxs->{$file})) {
3782 :     undef $x->[0];
3783 :     delete $fxs->{$file};
3784 : efrank 1.1 }
3785 :     }
3786 :    
3787 : parrello 1.287 =head3 ec_name
3788 :    
3789 :     C<< my $enzymatic_function = $fig->ec_name($ec); >>
3790 : efrank 1.1
3791 : parrello 1.287 Returns the enzymatic name corresponding to the specified enzyme code.
3792 : efrank 1.1
3793 : parrello 1.287 =over 4
3794 :    
3795 :     =item ec
3796 : efrank 1.1
3797 : parrello 1.287 Code number for the enzyme whose name is desired. The code number is actually
3798 :     a string of digits and periods (e.g. C<1.2.50.6>).
3799 :    
3800 :     =item RETURN
3801 :    
3802 :     Returns the name of the enzyme specified by the indicated code, or a null string
3803 :     if the code is not found in the database.
3804 :    
3805 :     =back
3806 : efrank 1.1
3807 :     =cut
3808 :    
3809 :     sub ec_name {
3810 :     my($self,$ec) = @_;
3811 :    
3812 :     ($ec =~ /^\d+\.\d+\.\d+\.\d+$/) || return "";
3813 :     my $rdbH = $self->db_handle;
3814 :     my $relational_db_response = $rdbH->SQL("SELECT name FROM ec_names WHERE ( ec = \'$ec\' )");
3815 :    
3816 :     return (@$relational_db_response == 1) ? $relational_db_response->[0]->[0] : "";
3817 :     return "";
3818 :     }
3819 :    
3820 : parrello 1.287 =head3 all_roles
3821 : efrank 1.1
3822 : parrello 1.287 C<< my @roles = $fig->all_roles; >>
3823 : efrank 1.1
3824 : parrello 1.287 Return a list of the known roles. Currently, this is a list of the enzyme codes and names.
3825 : efrank 1.1
3826 : parrello 1.287 The return value is a list of list references. Each element of the big list contains an
3827 :     enzyme code (EC) followed by the enzymatic name.
3828 : efrank 1.1
3829 :     =cut
3830 :    
3831 :     sub all_roles {
3832 :     my($self) = @_;
3833 :    
3834 :     my $rdbH = $self->db_handle;
3835 :     my $relational_db_response = $rdbH->SQL("SELECT ec,name FROM ec_names");
3836 :    
3837 :     return @$relational_db_response;
3838 :     }
3839 :    
3840 : parrello 1.287 =head3 expand_ec
3841 : efrank 1.1
3842 : parrello 1.287 C<< my $expanded_ec = $fig->expand_ec($ec); >>
3843 : efrank 1.1
3844 :     Expands "1.1.1.1" to "1.1.1.1 - alcohol dehydrogenase" or something like that.
3845 :    
3846 :     =cut
3847 :    
3848 :     sub expand_ec {
3849 :     my($self,$ec) = @_;
3850 :     my($name);
3851 :    
3852 :     return ($name = $self->ec_name($ec)) ? "$ec - $name" : $ec;
3853 :     }
3854 :    
3855 : parrello 1.287 =head3 clean_tmp
3856 : efrank 1.1
3857 : parrello 1.287 C<< FIG::clean_tmp(); >>
3858 : efrank 1.1
3859 : parrello 1.287 Delete temporary files more than two days old.
3860 : efrank 1.1
3861 :     We store temporary files in $FIG_Config::temp. There are specific classes of files
3862 :     that are created and should be saved for at least a few days. This routine can be
3863 :     invoked to clean out those that are over two days old.
3864 :    
3865 :     =cut
3866 :    
3867 :     sub clean_tmp {
3868 :    
3869 :     my($file);
3870 : parrello 1.287 if (opendir(TMP,"$FIG_Config::temp")) {
3871 :     # change the pattern to pick up other files that need to be cleaned up
3872 :     my @temp = grep { $_ =~ /^(Geno|tmp)/ } readdir(TMP);
3873 :     foreach $file (@temp) {
3874 :     if (-M "$FIG_Config::temp/$file" > 2) {
3875 :     unlink("$FIG_Config::temp/$file");
3876 :     }
3877 :     }
3878 : efrank 1.1 }
3879 :     }
3880 :    
3881 :     ################ Routines to process genomes and genome IDs ##########################
3882 :    
3883 :    
3884 : parrello 1.287 =head3 genomes
3885 : efrank 1.1
3886 : parrello 1.287 C<< my @genome_ids = $fig->genomes($complete, $restrictions, $domain); >>
3887 : efrank 1.1
3888 : parrello 1.287 Return a list of genome IDs. If called with no parameters, all genome IDs
3889 :     in the database will be returned.
3890 : efrank 1.1
3891 :     Genomes are assigned ids of the form X.Y where X is the taxonomic id maintained by
3892 :     NCBI for the species (not the specific strain), and Y is a sequence digit assigned to
3893 :     this particular genome (as one of a set with the same genus/species). Genomes also
3894 :     have versions, but that is a separate issue.
3895 :    
3896 : parrello 1.287 =over 4
3897 :    
3898 :     =item complete
3899 :    
3900 :     TRUE if only complete genomes should be returned, else FALSE.
3901 :    
3902 :     =item restrictions
3903 :    
3904 :     TRUE if only restriction genomes should be returned, else FALSE.
3905 :    
3906 :     =item domain
3907 :    
3908 :     Name of the domain from which the genomes should be returned. Possible values are
3909 :     C<Bacteria>, C<Virus>, C<Eukaryota>, C<unknown>, C<Archaea>, and
3910 :     C<Environmental Sample>. If no domain is specified, all domains will be
3911 :     eligible.
3912 :    
3913 :     =item RETURN
3914 :    
3915 :     Returns a list of all the genome IDs with the specified characteristics.
3916 :    
3917 :     =back
3918 :    
3919 : efrank 1.1 =cut
3920 : parrello 1.320 #: Return Type @;
3921 : parrello 1.328 sub genomes :Remote :List {
3922 : golsen 1.150 my( $self, $complete, $restrictions, $domain ) = @_;
3923 : overbeek 1.13
3924 :     my $rdbH = $self->db_handle;
3925 :    
3926 :     my @where = ();
3927 : parrello 1.287 if ($complete) {
3928 :     push(@where, "( complete = \'1\' )")
3929 : overbeek 1.13 }
3930 :    
3931 : parrello 1.287 if ($restrictions) {
3932 :     push(@where, "( restrictions = \'1\' )")
3933 : overbeek 1.13 }
3934 : golsen 1.150
3935 : parrello 1.287 if ($domain) {
3936 :     push( @where, "( maindomain = '$domain' )" )
3937 : golsen 1.150 }
3938 :    
3939 : overbeek 1.13 my $relational_db_response;
3940 : parrello 1.287 if (@where > 0) {
3941 :     my $where = join(" AND ",@where);
3942 :     $relational_db_response = $rdbH->SQL("SELECT genome FROM genome where $where");
3943 :     } else {
3944 :     $relational_db_response = $rdbH->SQL("SELECT genome FROM genome");
3945 : overbeek 1.13 }
3946 :     my @genomes = sort { $a <=> $b } map { $_->[0] } @$relational_db_response;
3947 : efrank 1.1 return @genomes;
3948 :     }
3949 :    
3950 : paczian 1.599 sub genome_list {
3951 :     my( $self ) = @_;
3952 :    
3953 :     my $rdbH = $self->db_handle;
3954 :     my $relational_db_response = $rdbH->SQL("SELECT genome, gname, maindomain FROM genome where complete=1");
3955 :    
3956 :     return $relational_db_response;
3957 :     }
3958 :    
3959 : parrello 1.287 =head3 is_complete
3960 :    
3961 :     C<< my $flag = $fig->is_complete($genome); >>
3962 :    
3963 :     Return TRUE if the genome with the specified ID is complete, else FALSE.
3964 :    
3965 :     =over 4
3966 :    
3967 :     =item genome
3968 :    
3969 :     ID of the relevant genome.
3970 :    
3971 :     =item RETURN
3972 :    
3973 :     Returns TRUE if there is a complete genome in the database with the specified ID,
3974 :     else FALSE.
3975 :    
3976 :     =back
3977 :    
3978 :     =cut
3979 :    
3980 : overbeek 1.180 sub is_complete {
3981 :     my($self,$genome) = @_;
3982 :    
3983 :     my $rdbH = $self->db_handle;
3984 :     my $relational_db_response = $rdbH->SQL("SELECT genome FROM genome where (genome = '$genome') AND (complete = '1')");
3985 :     return (@$relational_db_response == 1)
3986 : parrello 1.287 }
3987 :    
3988 : parrello 1.490 =head3 is_genome
3989 :    
3990 :     C<< my $flag = $fig->is_genome($genome); >>
3991 :    
3992 :     Return TRUE if the specified genome exists, else FALSE.
3993 :    
3994 :     =over 4
3995 :    
3996 :     =item genome
3997 :    
3998 :     ID of the genome to test.
3999 :    
4000 :     =item RETURN
4001 :    
4002 :     Returns TRUE if a genome with the specified ID exists in the data store, else FALSE.
4003 :    
4004 :     =back
4005 :    
4006 :     =cut
4007 :    
4008 : overbeek 1.421 sub is_genome {
4009 :     my($self,$genome) = @_;
4010 : olson 1.613 my($y);
4011 : overbeek 1.421
4012 : olson 1.613 my $is_genome = $self->cached("_is_genome");
4013 :    
4014 :     if (defined($y = $is_genome->{$genome}))
4015 : overbeek 1.421 {
4016 : olson 1.613 return $y;
4017 : overbeek 1.421 }
4018 :    
4019 :     my $rdbH = $self->db_handle;
4020 :     my $relational_db_response = $rdbH->SQL("SELECT genome FROM genome where (genome = '$genome')");
4021 :     $y = (@$relational_db_response == 1);
4022 : olson 1.613 $is_genome->{$genome} = $y;
4023 : overbeek 1.421 return $y;
4024 :     }
4025 :    
4026 : olson 1.613 =head3 assert_genomes
4027 :    
4028 :     C<< $fig->assert_genomes(gid, gid, ...)>>
4029 :    
4030 :     Assert that the given list of genomes does exist, and allow is_genome() to succeed for them.
4031 :    
4032 :     This is used in FIG-based computations in the context of the RAST genome-import code, so that
4033 :     genomes that currently exist only in RAST are treated as present for the purposes of FIG.pm-based
4034 :     code.
4035 :    
4036 :     =cut
4037 :    
4038 :     sub assert_genomes
4039 :     {
4040 :     my($self, @genomes) = @_;
4041 :    
4042 :     my $assert = $self->cached("_is_genome");
4043 :     map { $assert->{$_} = 1 } @genomes;
4044 :     }
4045 :    
4046 : parrello 1.287 =head3 genome_counts
4047 :    
4048 :     C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $fig->genome_counts($complete); >>
4049 :    
4050 :     Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
4051 :     genomes will be included in the counts.
4052 :    
4053 :     =over 4
4054 :    
4055 :     =item complete
4056 :    
4057 :     TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
4058 :     counted
4059 :    
4060 :     =item RETURN
4061 :    
4062 :     A six-element list containing the number of genomes in each of six categories--
4063 :     Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
4064 :    
4065 :     =back
4066 :    
4067 :     =cut
4068 : golsen 1.150
4069 : efrank 1.2 sub genome_counts {
4070 : overbeek 1.13 my($self,$complete) = @_;
4071 :     my($x,$relational_db_response);
4072 : efrank 1.2
4073 : overbeek 1.13 my $rdbH = $self->db_handle;
4074 :    
4075 : parrello 1.287 if ($complete) {
4076 :     $relational_db_response = $rdbH->SQL("SELECT genome, maindomain FROM genome where complete = '1'");
4077 :     } else {
4078 :     $relational_db_response = $rdbH->SQL("SELECT genome,maindomain FROM genome");
4079 : overbeek 1.13 }
4080 :    
4081 : gdpusch 1.107 my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
4082 : parrello 1.287 if (@$relational_db_response > 0) {
4083 :     foreach $x (@$relational_db_response) {
4084 :     if ($x->[1] =~ /^archaea/i) { ++$arch }
4085 :     elsif ($x->[1] =~ /^bacter/i) { ++$bact }
4086 :     elsif ($x->[1] =~ /^eukar/i) { ++$euk }
4087 :     elsif ($x->[1] =~ /^vir/i) { ++$vir }
4088 :     elsif ($x->[1] =~ /^env/i) { ++$env }
4089 :     else { ++$unk }
4090 : parrello 1.298 }
4091 : efrank 1.2 }
4092 : parrello 1.200
4093 : gdpusch 1.107 return ($arch, $bact, $euk, $vir, $env, $unk);
4094 :     }
4095 :    
4096 :    
4097 : parrello 1.287 =head3 genome_domain
4098 :    
4099 :     C<< my $domain = $fig->genome_domain($genome_id); >>
4100 :    
4101 :     Find the domain of a genome.
4102 : gdpusch 1.107
4103 : parrello 1.287 =over 4
4104 :    
4105 :     =item genome_id
4106 : gdpusch 1.107
4107 : parrello 1.287 ID of the genome whose domain is desired.
4108 : gdpusch 1.107
4109 : parrello 1.287 =item RETURN
4110 :    
4111 :     Returns the name of the genome's domain (archaea, bacteria, etc.), or C<undef> if
4112 :     the genome is not in the database.
4113 : gdpusch 1.107
4114 : parrello 1.292 =back
4115 :    
4116 : gdpusch 1.107 =cut
4117 :    
4118 :     sub genome_domain {
4119 :     my($self,$genome) = @_;
4120 :     my $relational_db_response;
4121 :     my $rdbH = $self->db_handle;
4122 : parrello 1.200
4123 : parrello 1.287 if ($genome) {
4124 :     if (($relational_db_response = $rdbH->SQL("SELECT genome,maindomain FROM genome WHERE ( genome = \'$genome\' )"))
4125 :     && (@$relational_db_response == 1)) {
4126 :     # die Dumper($relational_db_response);
4127 :     return $relational_db_response->[0]->[1];
4128 :     }
4129 : gdpusch 1.107 }
4130 :     return undef;
4131 : efrank 1.2 }
4132 :    
4133 : gdpusch 1.92
4134 : parrello 1.287 =head3 genome_pegs
4135 : gdpusch 1.92
4136 : parrello 1.287 C<< my $num_pegs = $fig->genome_pegs($genome_id); >>
4137 : gdpusch 1.92
4138 : parrello 1.287 Return the number of protein-encoding genes (PEGs) for a specified
4139 :     genome.
4140 : gdpusch 1.92
4141 : parrello 1.287 =over 4
4142 :    
4143 :     =item genome_id
4144 :    
4145 :     ID of the genome whose PEG count is desired.
4146 :    
4147 :     =item RETURN
4148 :    
4149 :     Returns the number of PEGs for the specified genome, or C<undef> if the genome
4150 :     is not indexed in the database.
4151 :    
4152 :     =back
4153 : gdpusch 1.92
4154 :     =cut
4155 :    
4156 :     sub genome_pegs {
4157 :     my($self,$genome) = @_;
4158 :     my $relational_db_response;
4159 :     my $rdbH = $self->db_handle;
4160 : parrello 1.200
4161 : parrello 1.287 if ($genome) {
4162 :     if (($relational_db_response = $rdbH->SQL("SELECT pegs FROM genome WHERE ( genome = \'$genome\' )"))
4163 :     && (@$relational_db_response == 1)) {
4164 :     return $relational_db_response->[0]->[0];
4165 :     }
4166 : gdpusch 1.92 }
4167 :     return undef;
4168 :     }
4169 :    
4170 :    
4171 : parrello 1.287 =head3 genome_rnas
4172 :    
4173 :     C<< my $num_rnas = $fig->genome_rnas($genome_id); >>
4174 :    
4175 :     Return the number of RNA-encoding genes for a genome.
4176 :     "$genome_id" is indexed in the "genome" database, and 'undef' otherwise.
4177 : efrank 1.1
4178 : parrello 1.287 =over 4
4179 :    
4180 :     =item genome_id
4181 :    
4182 :     ID of the genome whose RNA count is desired.
4183 :    
4184 :     =item RETURN
4185 : gdpusch 1.92
4186 : parrello 1.287 Returns the number of RNAs for the specified genome, or C<undef> if the genome
4187 :     is not indexed in the database.
4188 : gdpusch 1.92
4189 : parrello 1.287 =back
4190 : gdpusch 1.92
4191 :     =cut
4192 :    
4193 :     sub genome_rnas {
4194 :     my($self,$genome) = @_;