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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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