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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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