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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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