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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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