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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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