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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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