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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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