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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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