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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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