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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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