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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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