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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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