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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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