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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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