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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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