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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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