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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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