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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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