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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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