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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.381 - (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 : parrello 1.213 =head3 temp_url
1901 :    
1902 : parrello 1.287 C<< my $url = FIG::temp_url(); >>
1903 :    
1904 :     Return the URL of the temporary file directory.
1905 : parrello 1.213
1906 :     =cut
1907 :     #: Return Type $;
1908 : efrank 1.1 sub temp_url {
1909 : overbeek 1.377 # return &plug_url($FIG_Config::temp_url);
1910 :    
1911 :     #
1912 :     # Similarly, make this relative.
1913 :     #
1914 :     return "../FIG-Tmp";
1915 : efrank 1.1 }
1916 : parrello 1.200
1917 : parrello 1.213 =head3 plug_url
1918 :    
1919 : parrello 1.287 C<< my $url2 = $fig->plug_url($url); >>
1920 :    
1921 :     or
1922 :    
1923 :     C<< my $url2 = $fig->plug_url($url); >>
1924 :    
1925 :     Change the domain portion of a URL to point to the current domain. This essentially
1926 :     relocates URLs into the current environment.
1927 :    
1928 :     =over 4
1929 :    
1930 :     =item url
1931 :    
1932 :     URL to relocate.
1933 :    
1934 :     =item RETURN
1935 :    
1936 :     Returns a new URL with the base portion converted to the current operating host.
1937 :     If the URL does not begin with C<http://>, the URL will be returned unmodified.
1938 :    
1939 :     =back
1940 : parrello 1.213
1941 :     =cut
1942 :     #: Return Type $;
1943 : efrank 1.1 sub plug_url {
1944 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
1945 : efrank 1.1 my($url) = @_;
1946 :    
1947 : golsen 1.44 my $name;
1948 :    
1949 :     # Revised by GJO
1950 :     # First try to get url from the current http request
1951 :    
1952 :     if ( defined( $ENV{ 'HTTP_HOST' } ) # This is where $cgi->url gets its value
1953 :     && ( $name = $ENV{ 'HTTP_HOST' } )
1954 :     && ( $url =~ s~^http://[^/]*~http://$name~ ) # ~ is delimiter
1955 :     ) {}
1956 :    
1957 :     # Otherwise resort to alternative sources
1958 :    
1959 :     elsif ( ( $name = &get_local_hostname )
1960 :     && ( $url =~ s~^http://[^/]*~http://$name~ ) # ~ is delimiter
1961 :     ) {}
1962 :    
1963 : efrank 1.1 return $url;
1964 :     }
1965 :    
1966 : parrello 1.213 =head3 file_read
1967 :    
1968 : parrello 1.287 C<< my $text = $fig->file_read($fileName); >>
1969 :    
1970 :     or
1971 :    
1972 :     C<< my @lines = $fig->file_read($fileName); >>
1973 :    
1974 :     or
1975 :    
1976 :     C<< my $text = FIG::file_read($fileName); >>
1977 :    
1978 :     or
1979 :    
1980 :     C<< my @lines = FIG::file_read($fileName); >>
1981 :    
1982 :     Read an entire file into memory. In a scalar context, the file is returned
1983 :     as a single text string with line delimiters included. In a list context, the
1984 :     file is returned as a list of lines, each line terminated by a line
1985 :     delimiter. (For a method that automatically strips the line delimiters,
1986 :     use C<Tracer::GetFile>.)
1987 :    
1988 :     =over 4
1989 :    
1990 :     =item fileName
1991 :    
1992 :     Fully-qualified name of the file to read.
1993 :    
1994 :     =item RETURN
1995 :    
1996 :     In a list context, returns a list of the file lines. In a scalar context, returns
1997 :     a string containing all the lines of the file with delimiters included.
1998 : parrello 1.213
1999 : parrello 1.287 =back
2000 : parrello 1.213
2001 :     =cut
2002 :     #: Return Type $;
2003 :     #: Return Type @;
2004 : parrello 1.287 sub file_read {
2005 :    
2006 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2007 : parrello 1.287 my($fileName) = @_;
2008 :     return file_head($fileName, '*');
2009 : olson 1.90
2010 :     }
2011 :    
2012 :    
2013 : parrello 1.213 =head3 file_head
2014 :    
2015 : parrello 1.287 C<< my $text = $fig->file_head($fileName, $count); >>
2016 :    
2017 :     or
2018 :    
2019 :     C<< my @lines = $fig->file_head($fileName, $count); >>
2020 : parrello 1.213
2021 : parrello 1.287 or
2022 : parrello 1.213
2023 : parrello 1.287 C<< my $text = FIG::file_head($fileName, $count); >>
2024 : olson 1.90
2025 : parrello 1.287 or
2026 : olson 1.90
2027 : parrello 1.287 C<< my @lines = FIG::file_head($fileName, $count); >>
2028 : olson 1.90
2029 : parrello 1.287 Read a portion of a file into memory. In a scalar context, the file portion is
2030 :     returned as a single text string with line delimiters included. In a list
2031 :     context, the file portion is returned as a list of lines, each line terminated
2032 :     by a line delimiter.
2033 : olson 1.155
2034 : parrello 1.287 =over 4
2035 : olson 1.90
2036 : parrello 1.287 =item fileName
2037 : olson 1.90
2038 : parrello 1.287 Fully-qualified name of the file to read.
2039 : efrank 1.1
2040 : parrello 1.287 =item count (optional)
2041 : efrank 1.1
2042 : parrello 1.287 Number of lines to read from the file. If omitted, C<1> is assumed. If the
2043 :     non-numeric string C<*> is specified, the entire file will be read.
2044 : efrank 1.1
2045 : parrello 1.287 =item RETURN
2046 : efrank 1.1
2047 : parrello 1.287 In a list context, returns a list of the desired file lines. In a scalar context, returns
2048 :     a string containing the desired lines of the file with delimiters included.
2049 : efrank 1.1
2050 : parrello 1.287 =back
2051 : efrank 1.1
2052 :     =cut
2053 : parrello 1.287 #: Return Type $;
2054 :     #: Return Type @;
2055 :     sub file_head {
2056 : efrank 1.1
2057 : parrello 1.287 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2058 :     my($file, $count) = @_;
2059 : efrank 1.1
2060 : parrello 1.287 my ($n, $allFlag);
2061 :     if ($count eq '*') {
2062 : olson 1.304 Trace("Full file read for \"$file\".") if T(3);
2063 : parrello 1.287 $allFlag = 1;
2064 :     $n = 0;
2065 :     } else {
2066 :     $allFlag = 0;
2067 :     $n = (!$count ? 1 : $count);
2068 : olson 1.304 Trace("Reading $n record(s) from \"$file\".") if T(3);
2069 : parrello 1.287 }
2070 : efrank 1.1
2071 : parrello 1.287 if (open(my $fh, "<$file")) {
2072 : parrello 1.298 my(@ret, $i);
2073 : parrello 1.287 $i = 0;
2074 :     while (<$fh>) {
2075 :     push(@ret, $_);
2076 :     $i++;
2077 :     last if !$allFlag && $i >= $n;
2078 :     }
2079 :     close($fh);
2080 :     if (wantarray) {
2081 :     return @ret;
2082 :     } else {
2083 :     return join("", @ret);
2084 :     }
2085 : efrank 1.1 }
2086 :     }
2087 :    
2088 :     ################ Basic Routines [ existed since WIT ] ##########################
2089 :    
2090 : parrello 1.287 =head3 min
2091 :    
2092 :     C<< my $min = FIG::min(@x); >>
2093 :    
2094 :     or
2095 :    
2096 :     C<< my $min = $fig->min(@x); >>
2097 :    
2098 :     Return the minimum numeric value from a list.
2099 :    
2100 :     =over 4
2101 :    
2102 :     =item x1, x2, ... xN
2103 : efrank 1.1
2104 : parrello 1.287 List of numbers to process.
2105 : efrank 1.1
2106 : parrello 1.287 =item RETURN
2107 : efrank 1.1
2108 : parrello 1.287 Returns the numeric value of the list entry possessing the lowest value. Returns
2109 :     C<undef> if the list is empty.
2110 : efrank 1.1
2111 : parrello 1.287 =back
2112 : efrank 1.1
2113 :     =cut
2114 : parrello 1.213 #: Return Type $;
2115 : efrank 1.1 sub min {
2116 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2117 : efrank 1.1 my(@x) = @_;
2118 :     my($min,$i);
2119 :    
2120 :     (@x > 0) || return undef;
2121 :     $min = $x[0];
2122 : parrello 1.287 for ($i=1; ($i < @x); $i++) {
2123 :     $min = ($min > $x[$i]) ? $x[$i] : $min;
2124 : efrank 1.1 }
2125 :     return $min;
2126 :     }
2127 :    
2128 : parrello 1.287 =head3 max
2129 :    
2130 :     C<< my $max = FIG::max(@x); >>
2131 :    
2132 :     or
2133 :    
2134 :     C<< my $max = $fig->max(@x); >>
2135 : efrank 1.1
2136 : parrello 1.287 Return the maximum numeric value from a list.
2137 : efrank 1.1
2138 : parrello 1.287 =over 4
2139 :    
2140 :     =item x1, x2, ... xN
2141 :    
2142 :     List of numbers to process.
2143 :    
2144 :     =item RETURN
2145 :    
2146 :     Returns the numeric value of t/he list entry possessing the highest value. Returns
2147 :     C<undef> if the list is empty.
2148 : efrank 1.1
2149 : parrello 1.287 =back
2150 : efrank 1.1
2151 :     =cut
2152 : parrello 1.213 #: Return Type $;
2153 : efrank 1.1 sub max {
2154 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2155 : efrank 1.1 my(@x) = @_;
2156 :     my($max,$i);
2157 :    
2158 :     (@x > 0) || return undef;
2159 :     $max = $x[0];
2160 : parrello 1.287 for ($i=1; ($i < @x); $i++) {
2161 :     $max = ($max < $x[$i]) ? $x[$i] : $max;
2162 : efrank 1.1 }
2163 :     return $max;
2164 :     }
2165 :    
2166 : parrello 1.287 =head3 between
2167 : efrank 1.1
2168 : parrello 1.287 C<< my $flag = FIG::between($x, $y, $z); >>
2169 : efrank 1.1
2170 : parrello 1.287 or
2171 :    
2172 :     C<< my $flag = $fig->between($x, $y, $z); >>
2173 :    
2174 :     Determine whether or not $y is between $x and $z.
2175 :    
2176 :     =over 4
2177 :    
2178 :     =item x
2179 :    
2180 :     First edge number.
2181 :    
2182 :     =item y
2183 : efrank 1.1
2184 : parrello 1.287 Number to examine.
2185 :    
2186 :     =item z
2187 :    
2188 :     Second edge number.
2189 :    
2190 :     =item RETURN
2191 :    
2192 :     Return TRUE if the number I<$y> is between the numbers I<$x> and I<$z>. The check
2193 :     is inclusive (that is, if I<$y> is equal to I<$x> or I<$z> the function returns
2194 :     TRUE), and the order of I<$x> and I<$z> does not matter. If I<$x> is lower than
2195 :     I<$z>, then the return is TRUE if I<$x> <= I<$y> <= I<$z>. If I<$z> is lower,
2196 :     then the return is TRUE if I<$x> >= I$<$y> >= I<$z>.
2197 :    
2198 :     =back
2199 : efrank 1.1
2200 :     =cut
2201 : parrello 1.213 #: Return Type $;
2202 : efrank 1.1 sub between {
2203 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2204 : efrank 1.1 my($x,$y,$z) = @_;
2205 :    
2206 : parrello 1.287 if ($x < $z) {
2207 :     return (($x <= $y) && ($y <= $z));
2208 :     } else {
2209 :     return (($x >= $y) && ($y >= $z));
2210 : efrank 1.1 }
2211 :     }
2212 :    
2213 : parrello 1.287 =head3 standard_genetic_code
2214 : efrank 1.1
2215 : parrello 1.287 C<< my $code = FIG::standard_genetic_code(); >>
2216 : efrank 1.1
2217 : parrello 1.287 Return a hash containing the standard translation of nucleotide triples to proteins.
2218 :     Methods such as L</translate> can take a translation scheme as a parameter. This method
2219 :     returns the default translation scheme. The scheme is implemented as a reference to a
2220 :     hash that contains nucleotide triplets as keys and has protein letters as values.
2221 : efrank 1.1
2222 :     =cut
2223 : parrello 1.213 #: Return Type $;
2224 : efrank 1.1 sub standard_genetic_code {
2225 : parrello 1.200
2226 : efrank 1.1 my $code = {};
2227 :    
2228 :     $code->{"AAA"} = "K";
2229 :     $code->{"AAC"} = "N";
2230 :     $code->{"AAG"} = "K";
2231 :     $code->{"AAT"} = "N";
2232 :     $code->{"ACA"} = "T";
2233 :     $code->{"ACC"} = "T";
2234 :     $code->{"ACG"} = "T";
2235 :     $code->{"ACT"} = "T";
2236 :     $code->{"AGA"} = "R";
2237 :     $code->{"AGC"} = "S";
2238 :     $code->{"AGG"} = "R";
2239 :     $code->{"AGT"} = "S";
2240 :     $code->{"ATA"} = "I";
2241 :     $code->{"ATC"} = "I";
2242 :     $code->{"ATG"} = "M";
2243 :     $code->{"ATT"} = "I";
2244 :     $code->{"CAA"} = "Q";
2245 :     $code->{"CAC"} = "H";
2246 :     $code->{"CAG"} = "Q";
2247 :     $code->{"CAT"} = "H";
2248 :     $code->{"CCA"} = "P";
2249 :     $code->{"CCC"} = "P";
2250 :     $code->{"CCG"} = "P";
2251 :     $code->{"CCT"} = "P";
2252 :     $code->{"CGA"} = "R";
2253 :     $code->{"CGC"} = "R";
2254 :     $code->{"CGG"} = "R";
2255 :     $code->{"CGT"} = "R";
2256 :     $code->{"CTA"} = "L";
2257 :     $code->{"CTC"} = "L";
2258 :     $code->{"CTG"} = "L";
2259 :     $code->{"CTT"} = "L";
2260 :     $code->{"GAA"} = "E";
2261 :     $code->{"GAC"} = "D";
2262 :     $code->{"GAG"} = "E";
2263 :     $code->{"GAT"} = "D";
2264 :     $code->{"GCA"} = "A";
2265 :     $code->{"GCC"} = "A";
2266 :     $code->{"GCG"} = "A";
2267 :     $code->{"GCT"} = "A";
2268 :     $code->{"GGA"} = "G";
2269 :     $code->{"GGC"} = "G";
2270 :     $code->{"GGG"} = "G";
2271 :     $code->{"GGT"} = "G";
2272 :     $code->{"GTA"} = "V";
2273 :     $code->{"GTC"} = "V";
2274 :     $code->{"GTG"} = "V";
2275 :     $code->{"GTT"} = "V";
2276 :     $code->{"TAA"} = "*";
2277 :     $code->{"TAC"} = "Y";
2278 :     $code->{"TAG"} = "*";
2279 :     $code->{"TAT"} = "Y";
2280 :     $code->{"TCA"} = "S";
2281 :     $code->{"TCC"} = "S";
2282 :     $code->{"TCG"} = "S";
2283 :     $code->{"TCT"} = "S";
2284 :     $code->{"TGA"} = "*";
2285 :     $code->{"TGC"} = "C";
2286 :     $code->{"TGG"} = "W";
2287 :     $code->{"TGT"} = "C";
2288 :     $code->{"TTA"} = "L";
2289 :     $code->{"TTC"} = "F";
2290 :     $code->{"TTG"} = "L";
2291 :     $code->{"TTT"} = "F";
2292 : parrello 1.200
2293 : efrank 1.1 return $code;
2294 :     }
2295 :    
2296 : parrello 1.287 =head3 translate
2297 :    
2298 :     C<< my $aa_seq = &FIG::translate($dna_seq, $code, $fix_start); >>
2299 :    
2300 :     Translate a DNA sequence to a protein sequence using the specified genetic code.
2301 :     If I<$fix_start> is TRUE, will translate an initial C<TTG> or C<GTG> code to
2302 :     C<M>. (In the standard genetic code, these two combinations normally translate
2303 :     to C<V> and C<L>, respectively.)
2304 :    
2305 :     =over 4
2306 : efrank 1.1
2307 : parrello 1.287 =item dna_seq
2308 : efrank 1.1
2309 : parrello 1.287 DNA sequence to translate. Note that the DNA sequence can only contain
2310 :     known nucleotides.
2311 : efrank 1.1
2312 : parrello 1.287 =item code
2313 : efrank 1.1
2314 : parrello 1.287 Reference to a hash specifying the translation code. The hash is keyed by
2315 :     nucleotide triples, and the value for each key is the corresponding protein
2316 :     letter. If this parameter is omitted, the L</standard_genetic_code> will be
2317 :     used.
2318 : efrank 1.1
2319 : parrello 1.287 =item fix_start
2320 :    
2321 :     TRUE if the first triple is to get special treatment, else FALSE. If TRUE,
2322 :     then a value of C<TTG> or C<GTG> in the first position will be translated to
2323 :     C<M> instead of the value specified in the translation code.
2324 :    
2325 :     =item RETURN
2326 :    
2327 :     Returns a string resulting from translating each nucleotide triple into a
2328 :     protein letter.
2329 :    
2330 :     =back
2331 :    
2332 :     =cut
2333 :     #: Return Type $;
2334 :     sub translate {
2335 :     shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2336 :    
2337 :     my( $dna,$code,$start ) = @_;
2338 :     my( $i,$j,$ln );
2339 :     my( $x,$y );
2340 :     my( $prot );
2341 :    
2342 :     if (! defined($code)) {
2343 :     $code = &FIG::standard_genetic_code;
2344 : efrank 1.1 }
2345 :     $ln = length($dna);
2346 :     $prot = "X" x ($ln/3);
2347 :     $dna =~ tr/a-z/A-Z/;
2348 :    
2349 : parrello 1.287 for ($i=0,$j=0; ($i < ($ln-2)); $i += 3,$j++) {
2350 :     $x = substr($dna,$i,3);
2351 :     if ($y = $code->{$x}) {
2352 :     substr($prot,$j,1) = $y;
2353 : efrank 1.1 }
2354 :     }
2355 : parrello 1.200
2356 : parrello 1.287 if (($start) && ($ln >= 3) && (substr($dna,0,3) =~ /^[GT]TG$/)) {
2357 :     substr($prot,0,1) = 'M';
2358 : efrank 1.1 }
2359 :     return $prot;
2360 :     }
2361 :    
2362 : parrello 1.287 =head3 reverse_comp
2363 :    
2364 :     C<< my $dnaR = FIG::reverse_comp($dna); >>
2365 :    
2366 :     or
2367 :    
2368 :     C<< my $dnaR = $fig->reverse_comp($dna); >>
2369 :    
2370 :     Return the reverse complement os the specified DNA sequence.
2371 : efrank 1.1
2372 : parrello 1.287 NOTE: for extremely long DNA strings, use L</rev_comp>, which allows you to
2373 :     pass the strings around in the form of pointers.
2374 : efrank 1.1
2375 : parrello 1.287 =over 4
2376 :    
2377 :     =item dna
2378 : efrank 1.1
2379 : parrello 1.287 DNA sequence whose reverse complement is desired.
2380 :    
2381 :     =item RETURN
2382 :    
2383 :     Returns the reverse complement of the incoming DNA sequence.
2384 :    
2385 :     =back
2386 : efrank 1.1
2387 :     =cut
2388 : parrello 1.213 #: Return Type $;
2389 : efrank 1.1 sub reverse_comp {
2390 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2391 : efrank 1.1 my($seq) = @_;
2392 :    
2393 :     return ${&rev_comp(\$seq)};
2394 :     }
2395 :    
2396 : parrello 1.287 =head3 rev_comp
2397 :    
2398 :     C<< my $dnaRP = FIG::rev_comp(\$dna); >>
2399 :    
2400 :     or
2401 :    
2402 :     C<< my $dnaRP = $fig->rev_comp(\$dna); >>
2403 :    
2404 :     Return the reverse complement of the specified DNA sequence. The DNA sequence
2405 :     is passed in as a string reference rather than a raw string for performance
2406 :     reasons. If this is unnecessary, use L</reverse_comp>, which processes strings
2407 :     instead of references to strings.
2408 :    
2409 :     =over 4
2410 :    
2411 :     =item dna
2412 :    
2413 :     Reference to the DNA sequence whose reverse complement is desired.
2414 :    
2415 :     =item RETURN
2416 :    
2417 :     Returns a reference to the reverse complement of the incoming DNA sequence.
2418 :    
2419 :     =back
2420 : parrello 1.213
2421 :     =cut
2422 :     #: Return Type $;
2423 : efrank 1.1 sub rev_comp {
2424 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2425 : efrank 1.1 my( $seqP ) = @_;
2426 :     my( $rev );
2427 :    
2428 :     $rev = reverse( $$seqP );
2429 : overbeek 1.317 $rev =~ tr/A-Z/a-z/;
2430 :     $rev =~ tr/acgtumrwsykbdhv/tgcaakywsrmvhdb/;
2431 : efrank 1.1 return \$rev;
2432 :     }
2433 :    
2434 : parrello 1.287 =head3 verify_dir
2435 :    
2436 :     C<< FIG::verify_dir($dir); >>
2437 : efrank 1.1
2438 : parrello 1.287 or
2439 : efrank 1.1
2440 : parrello 1.287 C<< $fig->verify_dir($dir); >>
2441 : efrank 1.1
2442 : parrello 1.287 Insure that the specified directory exists. If it must be created, the permissions will
2443 :     be set to C<0777>.
2444 : efrank 1.1
2445 :     =cut
2446 :    
2447 :     sub verify_dir {
2448 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2449 : efrank 1.1 my($dir) = @_;
2450 :    
2451 : parrello 1.287 if (-d $dir) {
2452 :     return
2453 :     }
2454 :     if ($dir =~ /^(.*)\/[^\/]+$/) {
2455 :     &verify_dir($1);
2456 : efrank 1.1 }
2457 : parrello 1.287 mkdir($dir,0777) || Confess("Could not make directory $dir: $!");
2458 : efrank 1.1 }
2459 :    
2460 : parrello 1.287 =head3 run
2461 : efrank 1.1
2462 : parrello 1.287 C<< FIG::run($cmd); >>
2463 : overbeek 1.283
2464 : parrello 1.287 or
2465 :    
2466 :     C<< $fig->run($cmd); >>
2467 : overbeek 1.283
2468 : parrello 1.287 Run a command. If the command fails, the error will be traced.
2469 : overbeek 1.283
2470 :     =cut
2471 :    
2472 : parrello 1.287 sub run {
2473 :     shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2474 :     my($cmd) = @_;
2475 :    
2476 : overbeek 1.363 if ($ENV{FIG_VERBOSE}) {
2477 : parrello 1.287 my @tmp = `date`;
2478 :     chomp @tmp;
2479 :     print STDERR "$tmp[0]: running $cmd\n";
2480 :     }
2481 :     Trace("Running command: $cmd") if T(3);
2482 :     (system($cmd) == 0) || Confess("FAILED: $cmd");
2483 :     }
2484 :    
2485 :     =head3 augment_path
2486 :    
2487 :     C<< FIG::augment_path($dirName); >>
2488 : overbeek 1.283
2489 : parrello 1.287 Add a directory to the system path.
2490 : overbeek 1.283
2491 : parrello 1.287 This method adds a new directory to the front of the system path. It looks in the
2492 :     configuration file to determine whether this is Windows or Unix, and uses the
2493 :     appropriate separator.
2494 : efrank 1.1
2495 : parrello 1.287 =over 4
2496 : efrank 1.1
2497 : parrello 1.287 =item dirName
2498 :    
2499 :     Name of the directory to add to the path.
2500 :    
2501 :     =back
2502 : efrank 1.1
2503 :     =cut
2504 :    
2505 : parrello 1.287 sub augment_path {
2506 :     my ($dirName) = @_;
2507 :     if ($FIG_Config::win_mode) {
2508 :     $ENV{PATH} = "$dirName;$ENV{PATH}";
2509 :     } else {
2510 :     $ENV{PATH} = "$dirName:$ENV{PATH}";
2511 : overbeek 1.278 }
2512 : efrank 1.1 }
2513 :    
2514 : parrello 1.287 =head3 read_fasta_record
2515 : gdpusch 1.45
2516 : parrello 1.287 C<< my ($seq_id, $seq_pointer, $comment) = FIG::read_fasta_record(\*FILEHANDLE); >>
2517 : gdpusch 1.45
2518 : parrello 1.287 or
2519 : gdpusch 1.45
2520 : parrello 1.287 C<< my ($seq_id, $seq_pointer, $comment) = $fig->read_fasta_record(\*FILEHANDLE); >>
2521 : gdpusch 1.45
2522 : parrello 1.287 Read and parse the next logical record of a FASTA file. A FASTA logical record
2523 :     consists of multiple lines of text. The first line begins with a C<< > >> symbol
2524 :     and contains the sequence ID followed by an optional comment. (NOTE: comments
2525 :     are currently deprecated, because not all tools handle them properly.) The
2526 :     remaining lines contain the sequence data.
2527 :    
2528 :     This method uses a trick to smooth its operation: the line terminator character
2529 :     is temporarily changed to C<< \n> >> so that a single read operation brings in
2530 :     the entire logical record.
2531 : gdpusch 1.45
2532 : parrello 1.287 =over 4
2533 : gdpusch 1.45
2534 : parrello 1.287 =item FILEHANDLE
2535 : gdpusch 1.45
2536 : parrello 1.287 Open handle of the FASTA file. If not specified, C<STDIN> is assumed.
2537 :    
2538 :     =item RETURN
2539 :    
2540 :     If we are at the end of the file, returns C<undef>. Otherwise, returns a
2541 :     three-element list. The first element is the sequence ID, the second is
2542 :     a pointer to the sequence data (that is, a string reference as opposed to
2543 :     as string), and the third is the comment.
2544 :    
2545 :     =back
2546 : gdpusch 1.45
2547 :     =cut
2548 : parrello 1.213 #: Return Type @;
2549 : parrello 1.287 sub read_fasta_record {
2550 :    
2551 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2552 : gdpusch 1.45 my ($file_handle) = @_;
2553 : parrello 1.287 my ($old_end_of_record, $fasta_record, @lines, $head, $sequence, $seq_id, $comment, @parsed_fasta_record);
2554 : parrello 1.200
2555 : gdpusch 1.45 if (not defined($file_handle)) { $file_handle = \*STDIN; }
2556 : parrello 1.200
2557 : gdpusch 1.45 $old_end_of_record = $/;
2558 :     $/ = "\n>";
2559 : parrello 1.200
2560 : parrello 1.287 if (defined($fasta_record = <$file_handle>)) {
2561 :     chomp $fasta_record;
2562 :     @lines = split( /\n/, $fasta_record );
2563 :     $head = shift @lines;
2564 :     $head =~ s/^>?//;
2565 :     $head =~ m/^(\S+)/;
2566 :     $seq_id = $1;
2567 :     if ($head =~ m/^\S+\s+(.*)$/) { $comment = $1; } else { $comment = ""; }
2568 :     $sequence = join( "", @lines );
2569 :     @parsed_fasta_record = ( $seq_id, \$sequence, $comment );
2570 :     } else {
2571 :     @parsed_fasta_record = ();
2572 : gdpusch 1.45 }
2573 : parrello 1.200
2574 : gdpusch 1.45 $/ = $old_end_of_record;
2575 : parrello 1.200
2576 : gdpusch 1.45 return @parsed_fasta_record;
2577 :     }
2578 :    
2579 : parrello 1.287 =head3 display_id_and_seq
2580 :    
2581 :     C<< FIG::display_id_and_seq($id_and_comment, $seqP, $fh); >>
2582 :    
2583 :     or
2584 :    
2585 : parrello 1.355 C<< $fig->display_id_and_seq($id_and_comment, \$seqP, $fh); >>
2586 : parrello 1.287
2587 :     Display a fasta ID and sequence to the specified open file. This method is designed
2588 :     to work well with L</read_fasta_sequence> and L</rev_comp>, because it takes as
2589 :     input a string pointer rather than a string. If the file handle is omitted it
2590 :     defaults to STDOUT.
2591 :    
2592 :     The output is formatted into a FASTA record. The first line of the output is
2593 :     preceded by a C<< > >> symbol, and the sequence is split into 60-character
2594 :     chunks displayed one per line. Thus, this method can be used to produce
2595 :     FASTA files from data gathered by the rest of the system.
2596 :    
2597 :     =over 4
2598 :    
2599 :     =item id_and_comment
2600 :    
2601 :     The sequence ID and (optionally) the comment from the sequence's FASTA record.
2602 :     The ID
2603 : gdpusch 1.45
2604 : parrello 1.287 =item seqP
2605 : efrank 1.1
2606 : parrello 1.287 Reference to a string containing the sequence. The sequence is automatically
2607 :     formatted into 60-character chunks displayed one per line.
2608 : efrank 1.1
2609 : parrello 1.287 =item fh
2610 : efrank 1.1
2611 : parrello 1.287 Open file handle to which the ID and sequence should be output. If omitted,
2612 : parrello 1.355 C<\*STDOUT> is assumed.
2613 : parrello 1.287
2614 :     =back
2615 : efrank 1.1
2616 :     =cut
2617 :    
2618 : parrello 1.287 sub display_id_and_seq {
2619 : mkubal 1.53
2620 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2621 : parrello 1.287
2622 : overbeek 1.326 my( $id, $seqP, $fh ) = @_;
2623 : parrello 1.200
2624 : efrank 1.1 if (! defined($fh) ) { $fh = \*STDOUT; }
2625 : parrello 1.200
2626 : efrank 1.1 print $fh ">$id\n";
2627 : overbeek 1.326 &display_seq($seqP, $fh);
2628 : efrank 1.1 }
2629 :    
2630 : parrello 1.355 =head3 display_seq
2631 : parrello 1.287
2632 : parrello 1.355 C<< FIG::display_seq(\$seqP, $fh); >>
2633 : parrello 1.287
2634 :     or
2635 :    
2636 : parrello 1.355 C<< $fig->display_seq(\$seqP, $fh); >>
2637 : parrello 1.287
2638 :     Display a fasta sequence to the specified open file. This method is designed
2639 :     to work well with L</read_fasta_sequence> and L</rev_comp>, because it takes as
2640 :     input a string pointer rather than a string. If the file handle is omitted it
2641 :     defaults to STDOUT.
2642 :    
2643 :     The sequence is split into 60-character chunks displayed one per line for
2644 :     readability.
2645 :    
2646 :     =over 4
2647 :    
2648 :     =item seqP
2649 :    
2650 :     Reference to a string containing the sequence.
2651 :    
2652 :     =item fh
2653 :    
2654 :     Open file handle to which the sequence should be output. If omitted,
2655 :     C<STDOUT> is assumed.
2656 :    
2657 :     =back
2658 :    
2659 :     =cut
2660 :    
2661 : efrank 1.1 sub display_seq {
2662 : parrello 1.287
2663 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2664 : parrello 1.287
2665 : overbeek 1.326 my ( $seqP, $fh ) = @_;
2666 : efrank 1.1 my ( $i, $n, $ln );
2667 : parrello 1.200
2668 : efrank 1.1 if (! defined($fh) ) { $fh = \*STDOUT; }
2669 :    
2670 : overbeek 1.326 $n = length($$seqP);
2671 : efrank 1.1 # confess "zero-length sequence ???" if ( (! defined($n)) || ($n == 0) );
2672 : parrello 1.287 for ($i=0; ($i < $n); $i += 60) {
2673 :     if (($i + 60) <= $n) {
2674 : overbeek 1.326 $ln = substr($$seqP,$i,60);
2675 : parrello 1.287 } else {
2676 : overbeek 1.326 $ln = substr($$seqP,$i,($n-$i));
2677 : parrello 1.287 }
2678 :     print $fh "$ln\n";
2679 : efrank 1.1 }
2680 :     }
2681 :    
2682 :     ########## I commented the pods on the following routines out, since they should not
2683 :     ########## be part of the SOAP/WSTL interface
2684 :     #=pod
2685 :     #
2686 : parrello 1.287 #=head3 file2N
2687 : efrank 1.1 #
2688 :     #usage: $n = $fig->file2N($file)
2689 :     #
2690 :     #In some of the databases I need to store filenames, which can waste a lot of
2691 :     #space. Hence, I maintain a database for converting filenames to/from integers.
2692 :     #
2693 :     #=cut
2694 :     #
2695 : parrello 1.328 sub file2N :Scalar {
2696 : efrank 1.1 my($self,$file) = @_;
2697 :     my($relational_db_response);
2698 :    
2699 :     my $rdbH = $self->db_handle;
2700 :    
2701 :     if (($relational_db_response = $rdbH->SQL("SELECT fileno FROM file_table WHERE ( file = \'$file\')")) &&
2702 : parrello 1.298 (@$relational_db_response == 1)) {
2703 : parrello 1.287 return $relational_db_response->[0]->[0];
2704 :     } elsif (($relational_db_response = $rdbH->SQL("SELECT MAX(fileno) FROM file_table ")) && (@$relational_db_response == 1) && ($relational_db_response->[0]->[0])) {
2705 :     my $fileno = $relational_db_response->[0]->[0] + 1;
2706 :     if ($rdbH->SQL("INSERT INTO file_table ( file, fileno ) VALUES ( \'$file\', $fileno )")) {
2707 :     return $fileno;
2708 :     }
2709 :     } elsif ($rdbH->SQL("INSERT INTO file_table ( file, fileno ) VALUES ( \'$file\', 1 )")) {
2710 :     return 1;
2711 : efrank 1.1 }
2712 :     return undef;
2713 :     }
2714 :    
2715 :     #=pod
2716 :     #
2717 : parrello 1.287 #=head3 N2file
2718 : efrank 1.1 #
2719 :     #usage: $filename = $fig->N2file($n)
2720 :     #
2721 :     #In some of the databases I need to store filenames, which can waste a lot of
2722 :     #space. Hence, I maintain a database for converting filenames to/from integers.
2723 :     #
2724 :     #=cut
2725 :     #
2726 : overbeek 1.364 sub N2file :Scalar
2727 :     {
2728 : efrank 1.1 my($self,$fileno) = @_;
2729 : overbeek 1.364
2730 :     #
2731 :     # Cache outputs. This results in a huge savings of time when files are
2732 :     # accessed multiple times (as in when a bunch of sims are requested).
2733 :     #
2734 :    
2735 : parrello 1.379
2736 : overbeek 1.364 my $fcache = $self->cached("_n2file");
2737 : parrello 1.379
2738 : overbeek 1.364 my $fname;
2739 :     if (defined($fname = $fcache->{$fileno}))
2740 :     {
2741 : parrello 1.365 return $fname;
2742 : overbeek 1.364 }
2743 : efrank 1.1
2744 :     my $rdbH = $self->db_handle;
2745 : parrello 1.379
2746 : overbeek 1.364 my $relational_db_response = $rdbH->SQL("SELECT file FROM file_table WHERE ( fileno = $fileno )");
2747 : efrank 1.1
2748 : overbeek 1.364 if ($relational_db_response and @$relational_db_response == 1)
2749 :     {
2750 : parrello 1.365 $fname = $relational_db_response->[0]->[0];
2751 :     $fcache->{$fileno} = $fname;
2752 :     return $fname;
2753 : efrank 1.1 }
2754 :     return undef;
2755 :     }
2756 :    
2757 :    
2758 :     #=pod
2759 :     #
2760 : parrello 1.287 #=head3 openF
2761 : efrank 1.1 #
2762 :     #usage: $fig->openF($filename)
2763 :     #
2764 :     #Parts of the system rely on accessing numerous different files. The most obvious case is
2765 :     #the situation with similarities. It is important that the system be able to run in cases in
2766 :     #which an arbitrary number of files cannot be open simultaneously. This routine (with closeF) is
2767 :     #a hack to handle this. I should probably just pitch them and insist that the OS handle several
2768 :     #hundred open filehandles.
2769 :     #
2770 :     #=cut
2771 :     #
2772 :     sub openF {
2773 :     my($self,$file) = @_;
2774 :     my($fxs,$x,@fxs,$fh);
2775 :    
2776 :     $fxs = $self->cached('_openF');
2777 : parrello 1.287 if ($x = $fxs->{$file}) {
2778 :     $x->[1] = time();
2779 :     return $x->[0];
2780 : efrank 1.1 }
2781 : parrello 1.200
2782 : efrank 1.1 @fxs = keys(%$fxs);
2783 : parrello 1.287 if (defined($fh = new FileHandle "<$file")) {
2784 :     if (@fxs >= 50) {
2785 :     @fxs = sort { $fxs->{$a}->[1] <=> $fxs->{$b}->[1] } @fxs;
2786 :     $x = $fxs->{$fxs[0]};
2787 :     undef $x->[0];
2788 :     delete $fxs->{$fxs[0]};
2789 :     }
2790 :     $fxs->{$file} = [$fh,time()];
2791 :     return $fh;
2792 : efrank 1.1 }
2793 :     return undef;
2794 :     }
2795 :    
2796 :     #=pod
2797 :     #
2798 : parrello 1.287 #=head3 closeF
2799 : efrank 1.1 #
2800 :     #usage: $fig->closeF($filename)
2801 :     #
2802 :     #Parts of the system rely on accessing numerous different files. The most obvious case is
2803 :     #the situation with similarities. It is important that the system be able to run in cases in
2804 :     #which an arbitrary number of files cannot be open simultaneously. This routine (with openF) is
2805 :     #a hack to handle this. I should probably just pitch them and insist that the OS handle several
2806 :     #hundred open filehandles.
2807 :     #
2808 :     #=cut
2809 :     #
2810 :     sub closeF {
2811 :     my($self,$file) = @_;
2812 :     my($fxs,$x);
2813 :    
2814 : parrello 1.287 if (($fxs = $self->{_openF}) && ($x = $fxs->{$file})) {
2815 :     undef $x->[0];
2816 :     delete $fxs->{$file};
2817 : efrank 1.1 }
2818 :     }
2819 :    
2820 : parrello 1.287 =head3 ec_name
2821 :    
2822 :     C<< my $enzymatic_function = $fig->ec_name($ec); >>
2823 : efrank 1.1
2824 : parrello 1.287 Returns the enzymatic name corresponding to the specified enzyme code.
2825 : efrank 1.1
2826 : parrello 1.287 =over 4
2827 :    
2828 :     =item ec
2829 : efrank 1.1
2830 : parrello 1.287 Code number for the enzyme whose name is desired. The code number is actually
2831 :     a string of digits and periods (e.g. C<1.2.50.6>).
2832 :    
2833 :     =item RETURN
2834 :    
2835 :     Returns the name of the enzyme specified by the indicated code, or a null string
2836 :     if the code is not found in the database.
2837 :    
2838 :     =back
2839 : efrank 1.1
2840 :     =cut
2841 :    
2842 :     sub ec_name {
2843 :     my($self,$ec) = @_;
2844 :    
2845 :     ($ec =~ /^\d+\.\d+\.\d+\.\d+$/) || return "";
2846 :     my $rdbH = $self->db_handle;
2847 :     my $relational_db_response = $rdbH->SQL("SELECT name FROM ec_names WHERE ( ec = \'$ec\' )");
2848 :    
2849 :     return (@$relational_db_response == 1) ? $relational_db_response->[0]->[0] : "";
2850 :     return "";
2851 :     }
2852 :    
2853 : parrello 1.287 =head3 all_roles
2854 : efrank 1.1
2855 : parrello 1.287 C<< my @roles = $fig->all_roles; >>
2856 : efrank 1.1
2857 : parrello 1.287 Return a list of the known roles. Currently, this is a list of the enzyme codes and names.
2858 : efrank 1.1
2859 : parrello 1.287 The return value is a list of list references. Each element of the big list contains an
2860 :     enzyme code (EC) followed by the enzymatic name.
2861 : efrank 1.1
2862 :     =cut
2863 :    
2864 :     sub all_roles {
2865 :     my($self) = @_;
2866 :    
2867 :     my $rdbH = $self->db_handle;
2868 :     my $relational_db_response = $rdbH->SQL("SELECT ec,name FROM ec_names");
2869 :    
2870 :     return @$relational_db_response;
2871 :     }
2872 :    
2873 : parrello 1.287 =head3 expand_ec
2874 : efrank 1.1
2875 : parrello 1.287 C<< my $expanded_ec = $fig->expand_ec($ec); >>
2876 : efrank 1.1
2877 :     Expands "1.1.1.1" to "1.1.1.1 - alcohol dehydrogenase" or something like that.
2878 :    
2879 :     =cut
2880 :    
2881 :     sub expand_ec {
2882 :     my($self,$ec) = @_;
2883 :     my($name);
2884 :    
2885 :     return ($name = $self->ec_name($ec)) ? "$ec - $name" : $ec;
2886 :     }
2887 :    
2888 : parrello 1.287 =head3 clean_tmp
2889 : efrank 1.1
2890 : parrello 1.287 C<< FIG::clean_tmp(); >>
2891 : efrank 1.1
2892 : parrello 1.287 Delete temporary files more than two days old.
2893 : efrank 1.1
2894 :     We store temporary files in $FIG_Config::temp. There are specific classes of files
2895 :     that are created and should be saved for at least a few days. This routine can be
2896 :     invoked to clean out those that are over two days old.
2897 :    
2898 :     =cut
2899 :    
2900 :     sub clean_tmp {
2901 :    
2902 :     my($file);
2903 : parrello 1.287 if (opendir(TMP,"$FIG_Config::temp")) {
2904 :     # change the pattern to pick up other files that need to be cleaned up
2905 :     my @temp = grep { $_ =~ /^(Geno|tmp)/ } readdir(TMP);
2906 :     foreach $file (@temp) {
2907 :     if (-M "$FIG_Config::temp/$file" > 2) {
2908 :     unlink("$FIG_Config::temp/$file");
2909 :     }
2910 :     }
2911 : efrank 1.1 }
2912 :     }
2913 :    
2914 :     ################ Routines to process genomes and genome IDs ##########################
2915 :    
2916 :    
2917 : parrello 1.287 =head3 genomes
2918 : efrank 1.1
2919 : parrello 1.287 C<< my @genome_ids = $fig->genomes($complete, $restrictions, $domain); >>
2920 : efrank 1.1
2921 : parrello 1.287 Return a list of genome IDs. If called with no parameters, all genome IDs
2922 :     in the database will be returned.
2923 : efrank 1.1
2924 :     Genomes are assigned ids of the form X.Y where X is the taxonomic id maintained by
2925 :     NCBI for the species (not the specific strain), and Y is a sequence digit assigned to
2926 :     this particular genome (as one of a set with the same genus/species). Genomes also
2927 :     have versions, but that is a separate issue.
2928 :    
2929 : parrello 1.287 =over 4
2930 :    
2931 :     =item complete
2932 :    
2933 :     TRUE if only complete genomes should be returned, else FALSE.
2934 :    
2935 :     =item restrictions
2936 :    
2937 :     TRUE if only restriction genomes should be returned, else FALSE.
2938 :    
2939 :     =item domain
2940 :    
2941 :     Name of the domain from which the genomes should be returned. Possible values are
2942 :     C<Bacteria>, C<Virus>, C<Eukaryota>, C<unknown>, C<Archaea>, and
2943 :     C<Environmental Sample>. If no domain is specified, all domains will be
2944 :     eligible.
2945 :    
2946 :     =item RETURN
2947 :    
2948 :     Returns a list of all the genome IDs with the specified characteristics.
2949 :    
2950 :     =back
2951 :    
2952 : efrank 1.1 =cut
2953 : parrello 1.320 #: Return Type @;
2954 : parrello 1.328 sub genomes :Remote :List {
2955 : golsen 1.150 my( $self, $complete, $restrictions, $domain ) = @_;
2956 : overbeek 1.13
2957 :     my $rdbH = $self->db_handle;
2958 :    
2959 :     my @where = ();
2960 : parrello 1.287 if ($complete) {
2961 :     push(@where, "( complete = \'1\' )")
2962 : overbeek 1.13 }
2963 :    
2964 : parrello 1.287 if ($restrictions) {
2965 :     push(@where, "( restrictions = \'1\' )")
2966 : overbeek 1.13 }
2967 : golsen 1.150
2968 : parrello 1.287 if ($domain) {
2969 :     push( @where, "( maindomain = '$domain' )" )
2970 : golsen 1.150 }
2971 :    
2972 : overbeek 1.13 my $relational_db_response;
2973 : parrello 1.287 if (@where > 0) {
2974 :     my $where = join(" AND ",@where);
2975 :     $relational_db_response = $rdbH->SQL("SELECT genome FROM genome where $where");
2976 :     } else {
2977 :     $relational_db_response = $rdbH->SQL("SELECT genome FROM genome");
2978 : overbeek 1.13 }
2979 :     my @genomes = sort { $a <=> $b } map { $_->[0] } @$relational_db_response;
2980 : efrank 1.1 return @genomes;
2981 :     }
2982 :    
2983 : parrello 1.287 =head3 is_complete
2984 :    
2985 :     C<< my $flag = $fig->is_complete($genome); >>
2986 :    
2987 :     Return TRUE if the genome with the specified ID is complete, else FALSE.
2988 :    
2989 :     =over 4
2990 :    
2991 :     =item genome
2992 :    
2993 :     ID of the relevant genome.
2994 :    
2995 :     =item RETURN
2996 :    
2997 :     Returns TRUE if there is a complete genome in the database with the specified ID,
2998 :     else FALSE.
2999 :    
3000 :     =back
3001 :    
3002 :     =cut
3003 :    
3004 : overbeek 1.180 sub is_complete {
3005 :     my($self,$genome) = @_;
3006 :    
3007 :     my $rdbH = $self->db_handle;
3008 :     my $relational_db_response = $rdbH->SQL("SELECT genome FROM genome where (genome = '$genome') AND (complete = '1')");
3009 :     return (@$relational_db_response == 1)
3010 : parrello 1.287 }
3011 :    
3012 :     =head3 genome_counts
3013 :    
3014 :     C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $fig->genome_counts($complete); >>
3015 :    
3016 :     Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
3017 :     genomes will be included in the counts.
3018 :    
3019 :     =over 4
3020 :    
3021 :     =item complete
3022 :    
3023 :     TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
3024 :     counted
3025 :    
3026 :     =item RETURN
3027 :    
3028 :     A six-element list containing the number of genomes in each of six categories--
3029 :     Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
3030 :    
3031 :     =back
3032 :    
3033 :     =cut
3034 : golsen 1.150
3035 : efrank 1.2 sub genome_counts {
3036 : overbeek 1.13 my($self,$complete) = @_;
3037 :     my($x,$relational_db_response);
3038 : efrank 1.2
3039 : overbeek 1.13 my $rdbH = $self->db_handle;
3040 :    
3041 : parrello 1.287 if ($complete) {
3042 :     $relational_db_response = $rdbH->SQL("SELECT genome, maindomain FROM genome where complete = '1'");
3043 :     } else {
3044 :     $relational_db_response = $rdbH->SQL("SELECT genome,maindomain FROM genome");
3045 : overbeek 1.13 }
3046 :    
3047 : gdpusch 1.107 my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
3048 : parrello 1.287 if (@$relational_db_response > 0) {
3049 :     foreach $x (@$relational_db_response) {
3050 :     if ($x->[1] =~ /^archaea/i) { ++$arch }
3051 :     elsif ($x->[1] =~ /^bacter/i) { ++$bact }
3052 :     elsif ($x->[1] =~ /^eukar/i) { ++$euk }
3053 :     elsif ($x->[1] =~ /^vir/i) { ++$vir }
3054 :     elsif ($x->[1] =~ /^env/i) { ++$env }
3055 :     else { ++$unk }
3056 : parrello 1.298 }
3057 : efrank 1.2 }
3058 : parrello 1.200
3059 : gdpusch 1.107 return ($arch, $bact, $euk, $vir, $env, $unk);
3060 :     }
3061 :    
3062 :    
3063 : parrello 1.287 =head3 genome_domain
3064 :    
3065 :     C<< my $domain = $fig->genome_domain($genome_id); >>
3066 :    
3067 :     Find the domain of a genome.
3068 : gdpusch 1.107
3069 : parrello 1.287 =over 4
3070 :    
3071 :     =item genome_id
3072 : gdpusch 1.107
3073 : parrello 1.287 ID of the genome whose domain is desired.
3074 : gdpusch 1.107
3075 : parrello 1.287 =item RETURN
3076 :    
3077 :     Returns the name of the genome's domain (archaea, bacteria, etc.), or C<undef> if
3078 :     the genome is not in the database.
3079 : gdpusch 1.107
3080 : parrello 1.292 =back
3081 :    
3082 : gdpusch 1.107 =cut
3083 :    
3084 :     sub genome_domain {
3085 :     my($self,$genome) = @_;
3086 :     my $relational_db_response;
3087 :     my $rdbH = $self->db_handle;
3088 : parrello 1.200
3089 : parrello 1.287 if ($genome) {
3090 :     if (($relational_db_response = $rdbH->SQL("SELECT genome,maindomain FROM genome WHERE ( genome = \'$genome\' )"))
3091 :     && (@$relational_db_response == 1)) {
3092 :     # die Dumper($relational_db_response);
3093 :     return $relational_db_response->[0]->[1];
3094 :     }
3095 : gdpusch 1.107 }
3096 :     return undef;
3097 : efrank 1.2 }
3098 :    
3099 : gdpusch 1.92
3100 : parrello 1.287 =head3 genome_pegs
3101 : gdpusch 1.92
3102 : parrello 1.287 C<< my $num_pegs = $fig->genome_pegs($genome_id); >>
3103 : gdpusch 1.92
3104 : parrello 1.287 Return the number of protein-encoding genes (PEGs) for a specified
3105 :     genome.
3106 : gdpusch 1.92
3107 : parrello 1.287 =over 4
3108 :    
3109 :     =item genome_id
3110 :    
3111 :     ID of the genome whose PEG count is desired.
3112 :    
3113 :     =item RETURN
3114 :    
3115 :     Returns the number of PEGs for the specified genome, or C<undef> if the genome
3116 :     is not indexed in the database.
3117 :    
3118 :     =back
3119 : gdpusch 1.92
3120 :     =cut
3121 :    
3122 :     sub genome_pegs {
3123 :     my($self,$genome) = @_;
3124 :     my $relational_db_response;
3125 :     my $rdbH = $self->db_handle;
3126 : parrello 1.200
3127 : parrello 1.287 if ($genome) {
3128 :     if (($relational_db_response = $rdbH->SQL("SELECT pegs FROM genome WHERE ( genome = \'$genome\' )"))
3129 :     && (@$relational_db_response == 1)) {
3130 :     return $relational_db_response->[0]->[0];
3131 :     }
3132 : gdpusch 1.92 }
3133 :     return undef;
3134 :     }
3135 :    
3136 :    
3137 : parrello 1.287 =head3 genome_rnas
3138 :    
3139 :     C<< my $num_rnas = $fig->genome_rnas($genome_id); >>
3140 :    
3141 :     Return the number of RNA-encoding genes for a genome.
3142 :     "$genome_id" is indexed in the "genome" database, and 'undef' otherwise.
3143 : efrank 1.1
3144 : parrello 1.287 =over 4
3145 :    
3146 :     =item genome_id
3147 :    
3148 :     ID of the genome whose RNA count is desired.
3149 :    
3150 :     =item RETURN
3151 : gdpusch 1.92
3152 : parrello 1.287 Returns the number of RNAs for the specified genome, or C<undef> if the genome
3153 :     is not indexed in the database.
3154 : gdpusch 1.92
3155 : parrello 1.287 =back
3156 : gdpusch 1.92
3157 :     =cut
3158 :    
3159 :     sub genome_rnas {
3160 :     my($self,$genome) = @_;
3161 :     my $relational_db_response;
3162 :     my $rdbH = $self->db_handle;
3163 : parrello 1.200
3164 : parrello 1.287 if ($genome) {
3165 :     if (($relational_db_response = $rdbH->SQL("SELECT rnas FROM genome WHERE ( genome = \'$genome\' )"))
3166 :     && (@$relational_db_response == 1)) {
3167 :     return $relational_db_response->[0]->[0];
3168 :     }
3169 : gdpusch 1.92 }
3170 :     return undef;
3171 :     }
3172 :    
3173 :    
3174 : parrello 1.287 =head3 genome_szdna
3175 :    
3176 :     usage: $szdna = $fig->genome_szdna($genome_id);
3177 :    
3178 :     Return the number of DNA base-pairs in a genome's contigs.
3179 :    
3180 :     =over 4
3181 :    
3182 :     =item genome_id
3183 :    
3184 :     ID of the genome whose base-pair count is desired.
3185 : gdpusch 1.92
3186 : parrello 1.287 =item RETURN
3187 : efrank 1.1
3188 : parrello 1.287 Returns the number of base pairs in the specified genome's contigs, or C<undef>
3189 :     if the genome is not indexed in the database.
3190 : gdpusch 1.91
3191 : parrello 1.287 =back
3192 : gdpusch 1.91
3193 :     =cut
3194 :    
3195 : gdpusch 1.92 sub genome_szdna {
3196 : gdpusch 1.91 my($self,$genome) = @_;
3197 :     my $relational_db_response;
3198 :     my $rdbH = $self->db_handle;
3199 : parrello 1.200
3200 : parrello 1.287 if ($genome) {
3201 :     if (($relational_db_response =
3202 :     $rdbH->SQL("SELECT szdna FROM genome WHERE ( genome = \'$genome\' )"))
3203 :     && (@$relational_db_response == 1)) {
3204 :    
3205 :     return $relational_db_response->[0]->[0];
3206 :    
3207 :     }
3208 : gdpusch 1.91 }
3209 :     return undef;
3210 :     }
3211 :    
3212 : parrello 1.287 =head3 genome_version
3213 : gdpusch 1.91
3214 : parrello 1.287 C<< my $version = $fig->genome_version($genome_id); >>
3215 : gdpusch 1.91
3216 : parrello 1.287 Return the version number of the specified genome.
3217 : efrank 1.1
3218 :     Versions are incremented for major updates. They are put in as major
3219 :     updates of the form 1.0, 2.0, ...
3220 :    
3221 :     Users may do local "editing" of the DNA for a genome, but when they do,
3222 :     they increment the digits to the right of the decimal. Two genomes remain
3223 : parrello 1.200 comparable only if the versions match identically. Hence, minor updating should be
3224 : efrank 1.1 committed only by the person/group responsible for updating that genome.
3225 :    
3226 :     We can, of course, identify which genes are identical between any two genomes (by matching
3227 :     the DNA or amino acid sequences). However, the basic intent of the system is to
3228 :     support editing by the main group issuing periodic major updates.
3229 :    
3230 : parrello 1.287 =over 4
3231 :    
3232 :     =item genome_id
3233 :    
3234 :     ID of the genome whose version is desired.
3235 :    
3236 :     =item RETURN
3237 :    
3238 :     Returns the version number of the specified genome, or C<undef> if the genome is not in
3239 :     the data store or no version number has been assigned.
3240 :    
3241 :     =back
3242 :    
3243 : efrank 1.1 =cut
3244 :    
3245 : parrello 1.328 sub genome_version :Scalar {
3246 : efrank 1.1 my($self,$genome) = @_;
3247 :    
3248 :     my(@tmp);
3249 :     if ((-s "$FIG_Config::organisms/$genome/VERSION") &&
3250 : parrello 1.298 (@tmp = `cat $FIG_Config::organisms/$genome/VERSION`) &&
3251 :     ($tmp[0] =~ /^(\S+)$/)) {
3252 :     return $1;
3253 : efrank 1.1 }
3254 :     return undef;
3255 :     }
3256 :    
3257 : parrello 1.287 =head3 genome_md5sum
3258 : olson 1.236
3259 : parrello 1.287 C<< my $md5sum = $fig->genome_md5sum($genome_id); >>
3260 : olson 1.236
3261 : parrello 1.287 Returns the MD5 checksum of the specified genome.
3262 : olson 1.236
3263 :     The checksum of a genome is defined as the checksum of its signature file. The signature
3264 :     file consists of tab-separated lines, one for each contig, ordered by the contig id.
3265 : parrello 1.287 Each line contains the contig ID, the length of the contig in nucleotides, and the
3266 : olson 1.236 MD5 checksum of the nucleotide data, with uppercase letters forced to lower case.
3267 :    
3268 : parrello 1.287 The checksum is indexed in the database. If you know a genome's checksum, you can use
3269 :     the L</genome_with_md5sum> method to find its ID in the database.
3270 :    
3271 :     =over 4
3272 :    
3273 :     =item genome
3274 :    
3275 :     ID of the genome whose checksum is desired.
3276 :    
3277 :     =item RETURN
3278 :    
3279 :     Returns the specified genome's checksum, or C<undef> if the genome is not in the
3280 :     database.
3281 :    
3282 :     =back
3283 : olson 1.236
3284 :     =cut
3285 :    
3286 : parrello 1.328 sub genome_md5sum :Scalar {
3287 : olson 1.236 my($self,$genome) = @_;
3288 :     my $relational_db_response;
3289 :     my $rdbH = $self->db_handle;
3290 :    
3291 : parrello 1.287 if ($genome) {
3292 :     if (($relational_db_response =
3293 :     $rdbH->SQL("SELECT md5sum FROM genome_md5sum WHERE ( genome = \'$genome\' )"))
3294 :     && (@$relational_db_response == 1)) {
3295 :     return $relational_db_response->[0]->[0];
3296 :     }
3297 : olson 1.236 }
3298 :     return undef;
3299 :     }
3300 :    
3301 : parrello 1.287 =head3 genome_with_md5sum
3302 :    
3303 :     C<< my $genome = $fig->genome_with_md5sum($cksum); >>
3304 :    
3305 :     Find a genome with the specified checksum.
3306 :    
3307 :     The MD5 checksum is computed from the content of the genome (see L</genome_md5sum>). This method
3308 :     can be used to determine if a genome already exists for a specified content.
3309 :    
3310 :     =over 4
3311 :    
3312 :     =item cksum
3313 :    
3314 :     Checksum to use for searching the genome table.
3315 : olson 1.260
3316 : parrello 1.287 =item RETURN
3317 :    
3318 :     The ID of a genome with the specified checksum, or C<undef> if no such genome exists.
3319 : olson 1.260
3320 : parrello 1.287 =back
3321 : olson 1.260
3322 :     =cut
3323 :    
3324 : parrello 1.328 sub genome_with_md5sum :Scalar {
3325 : olson 1.260 my($self,$cksum) = @_;
3326 :     my $relational_db_response;
3327 :     my $rdbH = $self->db_handle;
3328 :    
3329 : parrello 1.287 if (($relational_db_response =
3330 :     $rdbH->SQL("SELECT genome FROM genome_md5sum WHERE ( md5sum = \'$cksum\' )"))
3331 : parrello 1.298 && (@$relational_db_response == 1)) {
3332 :     return $relational_db_response->[0]->[0];
3333 : olson 1.260 }
3334 :    
3335 :     return undef;
3336 :     }
3337 :    
3338 : parrello 1.287 =head3 contig_md5sum
3339 :    
3340 :     C<< my $cksum = $fig->contig_md5sum($genome, $contig); >>
3341 :    
3342 :     Return the MD5 checksum for a contig. The MD5 checksum is computed from the content
3343 :     of the contig. This method retrieves the checksum stored in the database. The checksum
3344 :     can be compared to the checksum of an external contig as a cheap way of seeing if they
3345 :     match.
3346 :    
3347 :     =over 4
3348 :    
3349 :     =item genome
3350 :    
3351 :     ID of the genome containing the contig.
3352 :    
3353 :     =item contig
3354 :    
3355 :     ID of the relevant contig.
3356 :    
3357 :     =item RETURN
3358 :    
3359 :     Returns the checksum of the specified contig, or C<undef> if the contig is not in the
3360 :     database.
3361 :    
3362 :     =back
3363 :    
3364 :     =cut
3365 :    
3366 : parrello 1.328 sub contig_md5sum :Scalar {
3367 : olson 1.237 my($self, $genome, $contig) = @_;
3368 :     my $relational_db_response;
3369 :     my $rdbH = $self->db_handle;
3370 :    
3371 : parrello 1.287 if ($genome) {
3372 :     if (($relational_db_response =
3373 :     $rdbH->SQL(qq(SELECT md5 FROM contig_md5sums WHERE (genome = ? AND contig = ?)), undef, $genome, $contig))
3374 :     && (@$relational_db_response == 1)) {
3375 :     return $relational_db_response->[0]->[0];
3376 :     }
3377 : olson 1.237 }
3378 :     return undef;
3379 :     }
3380 :    
3381 : parrello 1.287 =head3 genus_species
3382 :    
3383 :     C<< my $gs = $fig->genus_species($genome_id); >>
3384 :    
3385 :     Return the genus, species, and possibly also the strain of a specified genome.
3386 :    
3387 :     This method converts a genome ID into a more recognizble species name. The species name
3388 :     is stored directly in the genome table of the database. Essentially, if the strain is
3389 :     present in the database, it will be returned by this method, and if it's not present,
3390 :     it won't.
3391 : efrank 1.1
3392 : parrello 1.287 =over 4
3393 :    
3394 :     =item genome_id
3395 :    
3396 :     ID of the genome whose name is desired.
3397 : efrank 1.1
3398 : parrello 1.287 =item RETURN
3399 :    
3400 :     Returns the scientific species name associated with the specified ID, or C<undef> if the
3401 :     ID is not in the database.
3402 : efrank 1.1
3403 : parrello 1.287 =back
3404 : efrank 1.1
3405 :     =cut
3406 : parrello 1.320 #: Return Type $;
3407 : parrello 1.328 sub genus_species :Scalar {
3408 : efrank 1.1 my ($self,$genome) = @_;
3409 : overbeek 1.13 my $ans;
3410 : efrank 1.1
3411 :     my $genus_species = $self->cached('_genus_species');
3412 : parrello 1.287 if (! ($ans = $genus_species->{$genome})) {
3413 :     my $rdbH = $self->db_handle;
3414 :     my $relational_db_response = $rdbH->SQL("SELECT genome,gname FROM genome");
3415 :     my $pair;
3416 :     foreach $pair (@$relational_db_response) {
3417 :     $genus_species->{$pair->[0]} = $pair->[1];
3418 :     }
3419 :     $ans = $genus_species->{$genome};
3420 : efrank 1.1 }
3421 :     return $ans;
3422 :     }
3423 :    
3424 : parrello 1.287 =head3 org_of
3425 :    
3426 :     C<< my $org = $fig->org_of($prot_id); >>
3427 :    
3428 :     Return the genus/species name of the organism containing a protein. Note that in this context
3429 :     I<protein> is not a certain string of amino acids but a protein encoding region on a specific
3430 :     contig.
3431 :    
3432 :     For a FIG protein ID (e.g. C<fig|134537.1.peg.123>), the organism and strain
3433 :     information is always available. In the case of external proteins, we can usually
3434 :     determine an organism, but not anything more precise than genus/species (and
3435 :     often not that). When the organism name is not present, a null string is returned.
3436 :    
3437 :     =over 4
3438 :    
3439 :     =item prot_id
3440 : efrank 1.1
3441 : parrello 1.287 Protein or feature ID.
3442 : efrank 1.1
3443 : parrello 1.287 =item RETURN
3444 :    
3445 :     Returns the displayable scientific name (genus, species, and strain) of the organism containing
3446 :     the identified PEG. If the name is not available, returns a null string. If the PEG is not found,
3447 :     returns C<undef>.
3448 : efrank 1.1
3449 : parrello 1.287 =back
3450 : efrank 1.1
3451 :     =cut
3452 :    
3453 :     sub org_of {
3454 :     my($self,$prot_id) = @_;
3455 :     my $relational_db_response;
3456 :     my $rdbH = $self->db_handle;
3457 :    
3458 : parrello 1.287 if ($prot_id =~ /^fig\|/) {
3459 :     return $self->is_deleted_fid( $prot_id) ? undef
3460 :     : $self->genus_species( $self->genome_of( $prot_id ) ) || "";
3461 : efrank 1.1 }
3462 :    
3463 : parrello 1.287 if (($relational_db_response =
3464 :     $rdbH->SQL("SELECT org FROM external_orgs WHERE ( prot = \'$prot_id\' )")) &&
3465 :     (@$relational_db_response >= 1)) {
3466 :     $relational_db_response->[0]->[0] =~ s/^\d+://;
3467 :     return $relational_db_response->[0]->[0];
3468 : efrank 1.1 }
3469 :     return "";
3470 :     }
3471 :    
3472 : parrello 1.287 =head3 genus_species_domain
3473 :    
3474 :     C<< my ($gs, $domain) = $fig->genus_species_domain($genome_id); >>
3475 :    
3476 :     Returns a genome's genus and species (and strain if that has been properly
3477 :     recorded) in a printable form, along with its domain. This method is similar
3478 :     to L</genus_species>, except it also returns the domain name (archaea,
3479 :     bacteria, etc.).
3480 :    
3481 :     =over 4
3482 :    
3483 :     =item genome_id
3484 :    
3485 :     ID of the genome whose species and domain information is desired.
3486 : golsen 1.130
3487 : parrello 1.287 =item RETURN
3488 : golsen 1.130
3489 : parrello 1.287 Returns a two-element list. The first element is the species name and the
3490 :     second is the domain name.
3491 : golsen 1.130
3492 : parrello 1.287 =back
3493 : golsen 1.130
3494 :     =cut
3495 :    
3496 :     sub genus_species_domain {
3497 :     my ($self, $genome) = @_;
3498 :    
3499 :     my $genus_species_domain = $self->cached('_genus_species_domain');
3500 : parrello 1.287 if ( ! $genus_species_domain->{ $genome } ) {
3501 :     my $rdbH = $self->db_handle;
3502 :     my $relational_db_response = $rdbH->SQL("SELECT genome,gname,maindomain FROM genome");
3503 :     my $triple;
3504 :     foreach $triple ( @$relational_db_response ) {
3505 :     $genus_species_domain->{ $triple->[0] } = [ $triple->[1], $triple->[2] ];
3506 :     }
3507 : golsen 1.130 }
3508 :     my $gsdref = $genus_species_domain->{ $genome };
3509 :     return $gsdref ? @$gsdref : ( "", "" );
3510 :     }
3511 :    
3512 : parrello 1.287 =head3 domain_color
3513 :    
3514 :     C<< my $web_color = FIG::domain_color($domain); >>
3515 :    
3516 :     Return the web color string associated with a specified domain. The colors are
3517 :     extremely subtle (86% luminance), so they absolutely require a black background.
3518 :     Archaea are slightly cyan, bacteria are slightly magenta, eukaryota are slightly
3519 :     yellow, viruses are slightly silver, environmental samples are slightly gray,
3520 :     and unknown or invalid domains are pure white.
3521 :    
3522 :     =over 4
3523 :    
3524 :     =item domain
3525 :    
3526 :     Name of the domain whose color is desired.
3527 :    
3528 :     =item RETURN
3529 :    
3530 :     Returns a web color string for the specified domain (e.g. C<#FFDDFF> for
3531 :     bacteria).
3532 :    
3533 :     =back
3534 :    
3535 :     =cut
3536 : golsen 1.130
3537 :     my %domain_color = ( AR => "#DDFFFF", BA => "#FFDDFF", EU => "#FFFFDD",
3538 :     VI => "#DDDDDD", EN => "#BBBBBB" );
3539 :    
3540 :     sub domain_color {
3541 :     my ($domain) = @_;
3542 :     defined $domain || return "#FFFFFF";
3543 :     return $domain_color{ uc substr($domain, 0, 2) } || "#FFFFFF";
3544 :     }
3545 :    
3546 : parrello 1.287 =head3 org_and_color_of
3547 : golsen 1.130
3548 : parrello 1.287 C<< my ($org, $color) = $fig->org_and_domain_of($prot_id); >>
3549 : golsen 1.130
3550 : parrello 1.287 Return the best guess organism and domain html color string of an organism.
3551 :     In the case of external proteins, we can usually determine an organism, but not
3552 :     anything more precise than genus/species (and often not that).
3553 :    
3554 :     =over 4
3555 :    
3556 :     =item prot_id
3557 :    
3558 :     Relevant protein or feature ID.
3559 :    
3560 :     =item RETURN
3561 : golsen 1.130
3562 : parrello 1.287 Returns a two-element list. The first element is the displayable organism name, and the second
3563 :     is an HTML color string based on the domain (see L</domain_color>).
3564 : golsen 1.130
3565 : parrello 1.287 =back
3566 : golsen 1.130
3567 :     =cut
3568 :    
3569 :     sub org_and_color_of {
3570 :     my($self,$prot_id) = @_;
3571 :     my $relational_db_response;
3572 :     my $rdbH = $self->db_handle;
3573 :    
3574 : parrello 1.287 if ($prot_id =~ /^fig\|/) {
3575 :     my( $gs, $domain ) = $self->genus_species_domain($self->genome_of($prot_id));
3576 :     return ( $gs, domain_color( $domain ) );
3577 : golsen 1.130 }
3578 :    
3579 : parrello 1.287 if (($relational_db_response =
3580 :     $rdbH->SQL("SELECT org FROM external_orgs WHERE ( prot = \'$prot_id\' )")) &&
3581 :     (@$relational_db_response >= 1)) {
3582 :     return ($relational_db_response->[0]->[0], "#FFFFFF");
3583 : golsen 1.130 }
3584 :     return ("", "#FFFFFF");
3585 :     }
3586 :    
3587 : redwards 1.310 =head3 partial_genus_matching
3588 :    
3589 :     Return a list of genome IDs that match a partial genus.
3590 :    
3591 : 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)
3592 : redwards 1.310
3593 :     =cut
3594 :    
3595 :     sub partial_genus_matching {
3596 : redwards 1.311 my ($self, $gen, $complete)=@_;
3597 :     return grep {$self->genus_species($_) =~ /$gen/i} $self->genomes($complete);
3598 : redwards 1.310 }
3599 :    
3600 :    
3601 : parrello 1.287 =head3 abbrev
3602 :    
3603 :     C<< my $abbreviated_name = FIG::abbrev($genome_name); >>
3604 : golsen 1.130
3605 : parrello 1.287 or
3606 : efrank 1.1
3607 : parrello 1.287 C<< my $abbreviated_name = $fig->abbrev($genome_name); >>
3608 : efrank 1.1
3609 : parrello 1.287 Abbreviate a genome name to 10 characters or less.
3610 : efrank 1.1
3611 :     For alignments and such, it is very useful to be able to produce an abbreviation of genus/species.
3612 :     That's what this does. Note that multiple genus/species might reduce to the same abbreviation, so
3613 :     be careful (disambiguate them, if you must).
3614 :    
3615 : parrello 1.287 The abbreviation is formed from the first three letters of the species name followed by the
3616 :     first three letters of the genus name followed by the first three letters of the species name and
3617 :     then the next four nonblank characters.
3618 :    
3619 :     =over 4
3620 :    
3621 :     =item genome_name
3622 :    
3623 :     The name to abbreviate.
3624 :    
3625 :     =item RETURN
3626 :    
3627 :     An abbreviated version of the specified name.
3628 :    
3629 :     =back
3630 :    
3631 : efrank 1.1 =cut
3632 :    
3633 : parrello 1.328 sub abbrev :Scalar {
3634 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3635 : efrank 1.1 my($genome_name) = @_;
3636 :    
3637 :     $genome_name =~ s/^(\S{3})\S+/$1./;
3638 : overbeek 1.198 $genome_name =~ s/^(\S+)\s+(\S{3})\S+/$1$2./;
3639 : overbeek 1.257 $genome_name =~ s/ //g;
3640 : parrello 1.287 if (length($genome_name) > 10) {
3641 : parrello 1.298 $genome_name = substr($genome_name,0,10);
3642 : efrank 1.1 }
3643 :     return $genome_name;
3644 :     }
3645 :    
3646 :     ################ Routines to process Features and Feature IDs ##########################
3647 :    
3648 : parrello 1.287 =head3 ftype
3649 :    
3650 :     C<< my $type = FIG::ftype($fid); >>
3651 : efrank 1.1
3652 : parrello 1.287 or
3653 : efrank 1.1
3654 : parrello 1.287 C<< my $type = $fig->ftype($fid); >>
3655 : efrank 1.1
3656 :     Returns the type of a feature, given the feature ID. This just amounts
3657 : parrello 1.287 to lifting it out of the feature ID, since features have IDs of the form
3658 : efrank 1.1
3659 : parrello 1.287 fig|x.y.f.n
3660 : efrank 1.1
3661 :     where
3662 :     x.y is the genome ID
3663 : parrello 1.287 f is the type of feature
3664 : efrank 1.1 n is an integer that is unique within the genome/type
3665 :    
3666 : parrello 1.287 =over 4
3667 :    
3668 :     =item fid
3669 :    
3670 :     FIG ID of the feature whose type is desired.
3671 :    
3672 :     =item RETURN
3673 :    
3674 :     Returns the feature type (e.g. C<peg>, C<rna>, C<pi>, or C<pp>), or C<undef> if the
3675 :     feature ID is not a FIG ID.
3676 :    
3677 :     =back
3678 :    
3679 : efrank 1.1 =cut
3680 :    
3681 :     sub ftype {
3682 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3683 : efrank 1.1 my($feature_id) = @_;
3684 :    
3685 : parrello 1.287 if ($feature_id =~ /^fig\|\d+\.\d+\.([^\.]+)/) {
3686 : parrello 1.365 return $1;
3687 : efrank 1.1 }
3688 :     return undef;
3689 :     }
3690 :    
3691 : parrello 1.287 =head3 genome_of
3692 :    
3693 :     C<< my $genome_id = $fig->genome_of($fid); >>
3694 :    
3695 :     or
3696 :    
3697 :     C<< my $genome_id = FIG::genome_of($fid); >>
3698 :    
3699 :     Return the genome ID from a feature ID.
3700 : efrank 1.1
3701 : parrello 1.287 =over 4
3702 :    
3703 :     =item fid
3704 :    
3705 :     ID of the feature whose genome ID is desired.
3706 :    
3707 :     =item RETURN
3708 : efrank 1.1
3709 : parrello 1.287 If the feature ID is a FIG ID, returns the genome ID embedded inside it; otherwise, it
3710 :     returns C<undef>.
3711 : efrank 1.1
3712 : parrello 1.287 =back
3713 : efrank 1.1
3714 :     =cut
3715 :    
3716 :    
3717 : parrello 1.328 sub genome_of :Scalar {
3718 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3719 : parrello 1.200 my $prot_id = (@_ == 1) ? $_[0] : $_[1];
3720 : efrank 1.1
3721 :     if ($prot_id =~ /^fig\|(\d+\.\d+)/) { return $1; }
3722 :     return undef;
3723 :     }
3724 :    
3725 : parrello 1.287 =head3 genome_and_peg_of
3726 :    
3727 :     C<< my ($genome_id, $peg_number = FIG::genome_and_peg_of($fid); >>
3728 :    
3729 :     C<< my ($genome_id, $peg_number = $fig->genome_and_peg_of($fid); >>
3730 : olson 1.96
3731 : parrello 1.287 Return the genome ID and peg number from a feature ID.
3732 : olson 1.96
3733 : parrello 1.287 =over 4
3734 :    
3735 :     =item prot_id
3736 :    
3737 :     ID of the feature whose genome and PEG number as desired.
3738 :    
3739 :     =item RETURN
3740 :    
3741 :     Returns the genome ID and peg number associated with a feature if the feature
3742 :     is represented by a FIG ID, else C<undef>.
3743 :    
3744 :     =back
3745 : olson 1.96
3746 :     =cut
3747 :    
3748 :     sub genome_and_peg_of {
3749 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3750 : parrello 1.200 my $prot_id = (@_ == 1) ? $_[0] : $_[1];
3751 : olson 1.96
3752 : parrello 1.287 if ($prot_id =~ /^fig\|(\d+\.\d+)\.peg\.(\d+)/) {
3753 : parrello 1.298 return ($1, $2);
3754 : olson 1.96 }
3755 :     return undef;
3756 :     }
3757 :    
3758 : parrello 1.287 =head3 by_fig_id
3759 :    
3760 :     C<< my @sorted_by_fig_id = sort { FIG::by_fig_id($a,$b) } @fig_ids; >>
3761 :    
3762 :     Compare two feature IDs.
3763 :    
3764 :     This function is designed to assist in sorting features by ID. The sort is by
3765 :     genome ID followed by feature type and then feature number.
3766 :    
3767 :     =over 4
3768 :    
3769 :     =item a
3770 : efrank 1.1
3771 : parrello 1.287 First feature ID.
3772 : efrank 1.1
3773 : parrello 1.287 =item b
3774 : efrank 1.1
3775 : parrello 1.287 Second feature ID.
3776 :    
3777 :     =item RETURN
3778 :    
3779 :     Returns a negative number if the first parameter is smaller, zero if both parameters
3780 :     are equal, and a positive number if the first parameter is greater.
3781 :    
3782 :     =back
3783 : efrank 1.1
3784 :     =cut
3785 :    
3786 :     sub by_fig_id {
3787 :     my($a,$b) = @_;
3788 :     my($g1,$g2,$t1,$t2,$n1,$n2);
3789 :     if (($a =~ /^fig\|(\d+\.\d+).([^\.]+)\.(\d+)$/) && (($g1,$t1,$n1) = ($1,$2,$3)) &&
3790 : parrello 1.298 ($b =~ /^fig\|(\d+\.\d+).([^\.]+)\.(\d+)$/) && (($g2,$t2,$n2) = ($1,$2,$3))) {
3791 :     ($g1 <=> $g2) or ($t1 cmp $t2) or ($n1 <=> $n2);
3792 : parrello 1.287 } else {
3793 : parrello 1.298 $a cmp $b;
3794 : efrank 1.1 }
3795 :     }
3796 :    
3797 : olson 1.357 =head3 by_genome_id
3798 :    
3799 :     C<< my @sorted_by_genome_id = sort { FIG::by_genome_id($a,$b) } @genome_ids; >>
3800 :    
3801 :     Compare two genome IDs.
3802 :    
3803 : parrello 1.379 This function is designed to assist in sorting genomes by ID.
3804 : olson 1.357
3805 :     =over 4
3806 :    
3807 :     =item a
3808 :    
3809 :     First genome ID.
3810 :    
3811 :     =item b
3812 :    
3813 :     Second genome ID.
3814 :    
3815 :     =item RETURN
3816 :    
3817 :     Returns a negative number if the first parameter is smaller, zero if both parameters
3818 :     are equal, and a positive number if the first parameter is greater.
3819 :    
3820 :     =back
3821 :    
3822 :     =cut
3823 :    
3824 :     sub by_genome_id {
3825 :     my($a,$b) = @_;
3826 :     my($g1,$g2,$s1, $s2);
3827 :     if (($a =~ /^(\d+)\.(\d+)$/) && (($g1, $s1) = ($1, $2)) &&
3828 : parrello 1.365 ($b =~ /^(\d+)\.(\d+)$/) && (($g2, $s2) = ($1, $2))) {
3829 : olson 1.357 ($g1 <=> $g2) or ($s1 <=> $s2);
3830 :     } else {
3831 :     $a cmp $b;
3832 :     }
3833 :     }
3834 :    
3835 : parrello 1.287 =head3 genes_in_region
3836 : efrank 1.1
3837 : parrello 1.287 C<< my ($features_in_region, $beg1, $end1) = $fig->genes_in_region($genome, $contig, $beg, $end, size_limit); >>
3838 : efrank 1.1
3839 : parrello 1.287 Locate features that overlap a specified region of a contig. This includes features that begin or end
3840 :     outside that region, just so long as some part of the feature can be found in the region of interest.
3841 : efrank 1.1
3842 :     It is often important to be able to find the genes that occur in a specific region on
3843 :     a chromosome. This routine is designed to provide this information. It returns all genes
3844 : parrello 1.287 that overlap positions from I<$beg> through I<$end> in the specified contig.
3845 :    
3846 :     The I<$size_limit> parameter limits the search process. It is presumed that no features are longer than the
3847 :     specified size limit. A shorter size limit means you'll miss some features; a longer size limit significantly
3848 :     slows the search process. For prokaryotes, a value of C<10000> (the default) seems to work best.
3849 :    
3850 :     =over 4
3851 :    
3852 :     =item genome
3853 :    
3854 :     ID of the genome containing the relevant contig.
3855 :    
3856 :     =item contig
3857 :    
3858 :     ID of the relevant contig.
3859 :    
3860 :     =item beg
3861 :    
3862 :     Position of the first base pair in the region of interest.
3863 :    
3864 :     =item end
3865 :    
3866 :     Position of the last base pair in the region of interest.
3867 :    
3868 :     =item size_limit
3869 :    
3870 :     Maximum allowable size for a feature. If omitted, C<10000> is assumed.
3871 :    
3872 :     =item RETURN
3873 : efrank 1.1
3874 : parrello 1.287 Returns a three-element list. The first element is a reference to a list of the feature IDs found. The second
3875 :     element is the position of the leftmost base pair in any feature found. This may be well before the region of
3876 :     interest begins or it could be somewhere inside. The third element is the position of the rightmost base pair
3877 :     in any feature found. Again, this can be somewhere inside the region or it could be well to the right of it.
3878 :    
3879 :     =back
3880 : efrank 1.1
3881 :     =cut
3882 : parrello 1.213 #: Return Type @;
3883 : efrank 1.1 sub genes_in_region {
3884 : parrello 1.287 my($self, $genome, $contig, $beg, $end, $pad) = @_;
3885 :     if (!defined $pad) { $pad = 10000; }
3886 : efrank 1.1 my($x,$relational_db_response,$feature_id,$b1,$e1,@feat,@tmp,$l,$u);
3887 :    
3888 :     my $rdbH = $self->db_handle;
3889 :    
3890 : parrello 1.200 my $minV = $beg - $pad;
3891 : efrank 1.1 my $maxV = $end + $pad;
3892 : parrello 1.287 if (($relational_db_response = $rdbH->SQL("SELECT id FROM features "
3893 :     . " WHERE ( minloc > $minV ) AND ( minloc < $maxV ) AND ( maxloc < $maxV) AND "
3894 :     . " ( genome = \'$genome\' ) AND ( contig = \'$contig\' );")) &&
3895 :     (@$relational_db_response >= 1)) {
3896 :     @tmp = sort { ($a->[1] cmp $b->[1]) or (($a->[2]+$a->[3]) <=> ($b->[2]+$b->[3])) }
3897 :     map { $feature_id = $_->[0]; $x = $self->feature_location($feature_id); $x ? [$feature_id,&boundaries_of($x)] : ()
3898 :     } @$relational_db_response;
3899 : efrank 1.1
3900 :    
3901 : parrello 1.287 ($l,$u) = (10000000000,0);
3902 :     foreach $x (@tmp)
3903 :     {
3904 :     ($feature_id,undef,$b1,$e1) = @$x;
3905 :     if (&between($beg,&min($b1,$e1),$end) || &between(&min($b1,$e1),$beg,&max($b1,$e1)))
3906 :     {
3907 :     if (! $self->is_deleted_fid($feature_id))
3908 :     {
3909 :     push(@feat,$feature_id);
3910 :     $l = &min($l,&min($b1,$e1));
3911 :     $u = &max($u,&max($b1,$e1));
3912 :     }
3913 :     }
3914 :     }
3915 :     (@feat <= 0) || return ([@feat],$l,$u);
3916 : efrank 1.1 }
3917 :     return ([],$l,$u);
3918 :     }
3919 :    
3920 : golsen 1.141
3921 :     #=============================================================================
3922 :     # Using the following version is better, but it brings out a very annoying
3923 :     # issue with some genomes. It already exists in the current code (above)
3924 :     # for some genes in some genomes. For example, visit fig|70601.1.peg.1.
3925 :     # This is true for any genome that has a feature that crosses the origin.
3926 :     # The root of the problem lies in boundaries_of. I am working on a fix that
3927 :     # replaces boundaries_of with a more sophisticated function. When it is
3928 :     # all done, genes_in_retion should behave as desired. -- GJO, Aug. 22, 2004
3929 :     #=============================================================================
3930 : parrello 1.200 #
3931 : golsen 1.141 # =pod
3932 : parrello 1.200 #
3933 : parrello 1.287 # =head3 genes_in_region
3934 : parrello 1.200 #
3935 : golsen 1.141 # usage: ( $features_in_region, $min_coord, $max_coord )
3936 :     # = $fig->genes_in_region( $genome, $contig, $beg, $end )
3937 : parrello 1.200 #
3938 : golsen 1.141 # It is often important to be able to find the genes that occur in a specific
3939 :     # region on a chromosome. This routine is designed to provide this information.
3940 :     # It returns all genes that overlap the region ( $genome, $contig, $beg, $end ).
3941 :     # $min_coord is set to the minimum coordinate of the returned genes (which may
3942 :     # preceed the given region), and $max_coord the maximum coordinate. Because
3943 :     # the database is indexed by the leftmost and rightmost coordinates of each
3944 :     # feature, the function makes no assumption about the length of the feature, but
3945 :     # it can (and probably will) miss features spanning multiple contigs.
3946 : parrello 1.200 #
3947 : golsen 1.141 # =cut
3948 : parrello 1.200 #
3949 :     #
3950 : golsen 1.141 # sub genes_in_region {
3951 :     # my ( $self, $genome, $contig, $beg, $end ) = @_;
3952 :     # my ( $x, $db_response, $feature_id, $b1, $e1, @tmp, @bounds );
3953 :     # my ( $min_coord, $max_coord );
3954 : parrello 1.200 #
3955 : golsen 1.141 # my @features = ();
3956 :     # my $rdbH = $self->db_handle;
3957 : parrello 1.200 #
3958 : golsen 1.141 # if ( ( $db_response = $rdbH->SQL( "SELECT id
3959 :     # FROM features
3960 :     # WHERE ( contig = '$contig' )
3961 :     # AND ( genome = '$genome' )
3962 : parrello 1.200 # AND ( minloc <= $end )
3963 : golsen 1.141 # AND ( maxloc >= $beg );"
3964 :     # )
3965 :     # )
3966 : parrello 1.365 # && ( @$db_response > 0 )
3967 : golsen 1.141 # )
3968 :     # {
3969 :     # # The sort is unnecessary, but provides a consistent ordering
3970 : parrello 1.200 #
3971 : parrello 1.365 # @tmp = sort { ( $a->[1] cmp $b->[1] ) # contig
3972 :     # || ( ($a->[2] + $a->[3] ) <=> ( $b->[2] + $b->[3] ) ) # midpoint
3973 : golsen 1.141 # }
3974 : parrello 1.365 # map { $feature_id = $_->[0];
3975 :     # ( ( ! $self->is_deleted_fid( $feature_id ) ) # not deleted
3976 : golsen 1.141 # && ( $x = $self->feature_location( $feature_id ) ) # and has location
3977 :     # && ( ( @bounds = boundaries_of( $x ) ) == 3 ) # and has bounds
3978 : parrello 1.200 # ) ? [ $feature_id, @bounds ] : ()
3979 : golsen 1.141 # } @$db_response;
3980 : parrello 1.200 #
3981 : parrello 1.365 # ( $min_coord, $max_coord ) = ( 10000000000, 0 );
3982 : parrello 1.200 #
3983 : parrello 1.365 # foreach $x ( @tmp )
3984 :     # {
3985 :     # ( $feature_id, undef, $b1, $e1 ) = @$x;
3986 :     # push @features, $feature_id;
3987 :     # my ( $min, $max ) = ( $b1 <= $e1 ) ? ( $b1, $e1 ) : ( $e1, $b1 );
3988 :     # ( $min_coord <= $min ) || ( $min_coord = $min );
3989 :     # ( $max_coord >= $max ) || ( $max_coord = $max );
3990 :     # }
3991 : golsen 1.141 # }
3992 : parrello 1.200 #
3993 : golsen 1.141 # return ( @features ) ? ( [ @features ], $min_coord, $max_coord )
3994 :     # : ( [], undef, undef );
3995 :     # }
3996 :    
3997 :     # These will be part of the fix to genes_in_region. -- GJO
3998 :    
3999 : parrello 1.287 =head3 regions_spanned
4000 :    
4001 :     C<< my ( [ $contig, $beg, $end ], ... ) = $fig->regions_spanned( $loc ); >>
4002 : golsen 1.141
4003 : parrello 1.287 or
4004 : golsen 1.141
4005 : parrello 1.287 C<< my ( [ $contig, $beg, $end ], ... ) = FIG::regions_spanned( $loc ); >>
4006 : golsen 1.141
4007 :     The location of a feature in a scalar context is
4008 :    
4009 : parrello 1.287 contig_b1_e1, contig_b2_e2, ... [one contig_b_e for each segment]
4010 :    
4011 :     This routine takes as input a scalar location in the above form
4012 :     and reduces it to one or more regions spanned by the gene. This
4013 :     involves combining regions in the location string that are on the
4014 :     same contig and going in the same direction. Unlike L</boundaries_of>,
4015 :     which returns one region in which the entire gene can be found,
4016 :     B<regions_spanned> handles wrapping through the orgin, features
4017 :     split over contigs and exons that are not ordered nicely along
4018 :     the chromosome (ugly but true).
4019 : golsen 1.141
4020 : parrello 1.287 =over 4
4021 :    
4022 :     =item loc
4023 :    
4024 :     The location string for a feature.
4025 :    
4026 :     =item RETURN
4027 :    
4028 :     Returns a list of list references. Each inner list contains a contig ID, a starting
4029 :     position, and an ending position. The starting position may be numerically greater
4030 :     than the ending position (which indicates a backward-traveling gene). It is
4031 :     guaranteed that the entire feature is covered by the regions in the list.
4032 :    
4033 :     =back
4034 : golsen 1.141
4035 :     =cut
4036 :    
4037 :     sub regions_spanned {
4038 :     shift if UNIVERSAL::isa( $_[0], __PACKAGE__ );
4039 :     my( $location ) = ( @_ == 1 ) ? $_[0] : $_[1];
4040 :     defined( $location ) || return undef;
4041 :    
4042 :     my @regions = ();
4043 :    
4044 :     my ( $cur_contig, $cur_beg, $cur_end, $cur_dir );
4045 :     my ( $contig, $beg, $end, $dir );
4046 :     my @segs = split( /\s*,\s*/, $location ); # should not have space, but ...
4047 :     @segs || return undef;
4048 :    
4049 :     # Process the first segment
4050 :    
4051 :     my $seg = shift @segs;
4052 :     ( ( $cur_contig, $cur_beg, $cur_end ) = ( $seg =~ /^(\S+)_(\d+)_\d+$/ ) )
4053 :     || return undef;
4054 :     $cur_dir = ( $cur_end >= $cur_beg ) ? 1 : -1;
4055 :    
4056 :     foreach $seg ( @segs ) {
4057 : parrello 1.298 ( ( $contig, $beg, $end ) = ( $seg =~ /^(\S+)_(\d+)_\d+$/ ) ) || next;
4058 :     $dir = ( $end >= $beg ) ? 1 : -1;
4059 : golsen 1.141
4060 : parrello 1.298 # Is this a continuation? Update end
4061 : golsen 1.141
4062 : parrello 1.298 if ( ( $contig eq $cur_contig )
4063 :     && ( $dir == $cur_dir )
4064 :     && ( ( ( $dir > 0 ) && ( $end > $cur_end ) )
4065 :     || ( ( $dir < 0 ) && ( $end < $cur_end ) ) )
4066 :     )
4067 :     {
4068 :     $cur_end = $end;
4069 :     }
4070 : golsen 1.141
4071 : parrello 1.298 # Not a continuation. Report previous and update current.
4072 : golsen 1.141
4073 : parrello 1.298 else
4074 :     {
4075 :     push @regions, [ $cur_contig, $cur_beg, $cur_end ];
4076 :     ( $cur_contig, $cur_beg, $cur_end, $cur_dir )
4077 :     = ( $contig, $beg, $end, $dir );
4078 :     }
4079 : golsen 1.141 }
4080 :    
4081 :     # There should alwasy be a valid, unreported region.
4082 :    
4083 :     push @regions, [ $cur_contig, $cur_beg, $cur_end ];
4084 :    
4085 :     return wantarray ? @regions : \@regions;
4086 :     }
4087 :    
4088 : parrello 1.287 =head3 filter_regions
4089 :    
4090 :     C<< my @regions = FIG::filter_regions( $contig, $min, $max, @regions ); >>
4091 :    
4092 :     or
4093 :    
4094 :     C<< my \@regions = FIG::filter_regions( $contig, $min, $max, @regions ); >>
4095 :    
4096 :     or
4097 :    
4098 :     C<< my @regions = FIG::filter_regions( $contig, $min, $max, \@regions ); >>
4099 :    
4100 :     or
4101 :    
4102 :     C<< my \@regions = FIG::filter_regions( $contig, $min, $max, \@regions ); >>
4103 :    
4104 :     Filter a list of regions to those that overlap a specified section of a
4105 :     particular contig. Region definitions correspond to those produced
4106 :     by L</regions_spanned>. That is, C<[>I<contig>C<,>I<beg>C<,>I<end>C<]>.
4107 :     In the function call, either I<$contig> or I<$min> and I<$max> can be
4108 :     undefined (permitting anything). So, for example,
4109 :    
4110 :     my @regions = FIG::filter_regions(undef, 1, 5000, $regionList);
4111 :    
4112 :     would return all regions in C<$regionList> that overlap the first
4113 :     5000 base pairs in any contig. Conversely,
4114 :    
4115 :     my @regions = FIG::filter_regions('NC_003904', undef, undef, $regionList);
4116 : golsen 1.141
4117 : parrello 1.287 would return all regions on the contig C<NC_003904>.
4118 : golsen 1.141
4119 : parrello 1.287 =over 4
4120 :    
4121 :     =item contig
4122 :    
4123 :     ID of the contig whose regions are to be passed by the filter, or C<undef>
4124 :     if the contig doesn't matter.
4125 :    
4126 :     =item min
4127 :    
4128 :     Leftmost position of the region used for filtering. Only regions which contain
4129 :     at least one base pair at or beyond this position will be passed. A value
4130 :     of C<undef> is equivalent to zero.
4131 :    
4132 :     =item max
4133 :    
4134 :     Rightmost position of the region used for filtering. Only regions which contain
4135 :     at least one base pair on or before this position will be passed. A value
4136 :     of C<undef> is equivalent to the length of the contig.
4137 :    
4138 :     =item regionList
4139 : golsen 1.141
4140 : parrello 1.287 A list of regions, or a reference to a list of regions. Each region is a
4141 :     reference to a three-element list, the first element of which is a contig
4142 :     ID, the second element of which is the start position, and the third
4143 :     element of which is the ending position. (The ending position can be
4144 :     before the starting position if the region is backward-traveling.)
4145 :    
4146 :     =item RETURN
4147 :    
4148 :     In a scalar context, returns a reference to a list of the filtered regions.
4149 :     In a list context, returns the list itself.
4150 :    
4151 :     =back
4152 : golsen 1.141
4153 :     =cut
4154 :    
4155 :     sub filter_regions {
4156 :     my ( $contig, $min, $max, @regions ) = @_;
4157 :    
4158 :     @regions || return ();
4159 :     ( ref( $regions[0] ) eq "ARRAY" ) || return undef;
4160 :    
4161 :     # Is it a region list, or a reference to a region list?
4162 :    
4163 :     if ( ref( $regions[0]->[0] ) eq "ARRAY" ) { @regions = @{ $regions[0] } }
4164 :    
4165 :     if ( ! defined( $contig ) )
4166 :     {
4167 : parrello 1.365 ( defined( $min ) && defined( $max ) ) || return undef;
4168 : golsen 1.141 }
4169 :     else # with a defined contig name, allow undefined range
4170 :     {
4171 : parrello 1.365 defined( $min ) || ( $min = 1 );
4172 :     defined( $max ) || ( $max = 1000000000 );
4173 : golsen 1.141 }
4174 :     ( $min <= $max ) || return ();
4175 :    
4176 :     my ( $c, $b, $e );
4177 :     my @filtered = grep { ( @$_ >= 3 ) # Allow extra fields?
4178 :     && ( ( $c, $b, $e ) = @$_ )
4179 :     && ( ( ! defined( $contig ) ) || ( $c eq $contig ) )
4180 :     && ( ( $e >= $b ) || ( ( $b, $e ) = ( $e, $b ) ) )
4181 :     && ( ( $b <= $max ) && ( $e >= $min ) )
4182 :     } @regions;
4183 :    
4184 :     return wantarray ? @filtered : \@filtered;
4185 :     }
4186 :    
4187 : parrello 1.287 =head3 close_genes
4188 :    
4189 :     C<< my @features = $fig->close_genes($fid, $dist); >>
4190 :    
4191 :     Return all features within a certain distance of a specified other feature.
4192 :    
4193 :     This method is a quick way to get genes that are near another gene. It calls
4194 :     L</boundaries_of> to get the boundaries of the incoming gene, then passes
4195 :     the region computed to L</genes_in_region>.
4196 :    
4197 :     So, for example, if the specified I<$dist> is 500, the method would select
4198 :     a region that extends 500 base pairs to either side of the boundaries for
4199 :     the gene I<$fid>, and pass it to C<genes_in_region> for analysis. The
4200 :     features returned would be those that overlap the selected region. Note
4201 :     that the flaws inherent in C<genes_in_region> are also inherent in this
4202 :     method: if a feature is more than 10000 base pairs long, it may not
4203 :     be caught even though it has an overlap in the specified region.
4204 :    
4205 :     =over 4
4206 :    
4207 :     =item fid
4208 :    
4209 :     ID of the relevant feature.
4210 :    
4211 :     =item dist
4212 :    
4213 :     Desired maximum distance.
4214 :    
4215 :     =item RETURN
4216 :    
4217 :     Returns a list of feature IDs for genes that overlap or are close to the boundaries
4218 :     for the specified incoming feature.
4219 :    
4220 :     =back
4221 :    
4222 :     =cut
4223 : golsen 1.141
4224 : efrank 1.1 sub close_genes {
4225 :     my($self,$fid,$dist) = @_;
4226 : parrello 1.200
4227 : mkubal 1.147 # warn "In close_genes, self=$self, fid=$fid";
4228 : parrello 1.200
4229 : efrank 1.1 my $loc = $self->feature_location($fid);
4230 :     if ($loc)
4231 :     {
4232 : parrello 1.298 my($contig,$beg,$end) = &FIG::boundaries_of($loc);
4233 :     if ($contig && $beg && $end)
4234 :     {
4235 :     my $min = &min($beg,$end) - $dist;
4236 :     my $max = &max($beg,$end) + $dist;
4237 :     my $feat;
4238 :     ($feat,undef,undef) = $self->genes_in_region(&FIG::genome_of($fid),$contig,$min,$max);
4239 :     return @$feat;
4240 :     }
4241 : efrank 1.1 }
4242 :