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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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