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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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