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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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