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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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