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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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