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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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