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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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