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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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