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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.368 - (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 : overbeek 1.353
466 :     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 :    
484 : olson 1.93 &run("index_contigs $genome");
485 :     &run("compute_genome_counts $genome");
486 :     &run("load_features $genome");
487 : overbeek 1.353
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.363 &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.210 =head3 get_sim_pool_info
1248 : olson 1.123
1249 : parrello 1.287 C<< my ($total_entries, $n_finished, $n_assigned, $n_unassigned) = $fig->get_sim_pool_info($pool_id); >>
1250 :    
1251 :     Return information about the given sim pool.
1252 :    
1253 :     =over 4
1254 :    
1255 :     =item pool_id
1256 :    
1257 :     Pool ID of the similarity processing queue whose information is desired.
1258 :    
1259 :     =item RETURN
1260 :    
1261 :     Returns a four-element list. The first is the number of features in the
1262 :     queue; the second is the number of features that have been processed; the
1263 :     third is the number of features that have been assigned to a
1264 :     processor, and the fourth is the number of features left over.
1265 : olson 1.123
1266 : parrello 1.287 =back
1267 : olson 1.123
1268 :     =cut
1269 : parrello 1.210 #: Return Type @;
1270 : parrello 1.287 sub get_sim_pool_info {
1271 :    
1272 : olson 1.123 my($self, $pool_id) = @_;
1273 :     my($dbh, $res, $total_entries, $n_finished, $n_assigned, $n_unassigned);
1274 :    
1275 :     $dbh = $self->db_handle();
1276 :    
1277 :     $res = $dbh->SQL("select count(chunk_id) from sim_queue where qid = '$pool_id'");
1278 : parrello 1.200 $total_entries = $res->[0]->[0];
1279 : olson 1.123
1280 :     $res = $dbh->SQL("select count(chunk_id) from sim_queue where qid = '$pool_id' and finished");
1281 :     $n_finished = $res->[0]->[0];
1282 :    
1283 :     $res = $dbh->SQL("select count(chunk_id) from sim_queue where qid = '$pool_id' and assigned and not finished");
1284 :     $n_assigned = $res->[0]->[0];
1285 :    
1286 :     $res = $dbh->SQL("select count(chunk_id) from sim_queue where qid = '$pool_id' and not finished and not assigned");
1287 :     $n_unassigned = $res->[0]->[0];
1288 :    
1289 :     return ($total_entries, $n_finished, $n_assigned, $n_unassigned);
1290 : olson 1.93 }
1291 :    
1292 : parrello 1.210 #=head3 get_sim_chunk
1293 :     #
1294 :     #usage: get_sim_chunk($n_seqs, $worker_id)
1295 :     #
1296 :     #Returns a chunk of $n_seqs of work.
1297 :     #
1298 :     #From Ross, about how sims are processed:
1299 :     #
1300 :     #Here is how I process them:
1301 :     #
1302 :     #
1303 :     # bash$ cd /Volumes/seed/olson/Sims/June22.out
1304 :     # bash$ for i in really*
1305 :     # > do
1306 :     # > cat < $i >> /Volumes/laptop/new.sims
1307 :     # > done
1308 :     #
1309 :     #
1310 :     #Then, I need to "reformat" them by adding to columns to each one
1311 :     # and split the result into files of about 3M each This I do using
1312 :     #
1313 :     #reduce_sims /Volumes/laptop/NR/NewNR/peg.synonyms.june21 300 < /Volumes/laptop/new.sims |
1314 :     # reformat_sims /Volumes/laptop/NR/NewNR/checked.nr.june21 > /Volumes/laptop/reformated.sims
1315 :     #rm /Volumes/laptop/new.sims
1316 :     #split_sims /Volumes/laptop/NewSims sims.june24 reformated.sims
1317 :     #rm reformatted.sims
1318 :     #
1319 :     #=cut
1320 : olson 1.93
1321 : parrello 1.287 sub get_sim_chunk {
1322 : parrello 1.210 my($self, $n_seqs, $worker_id) = @_;
1323 :     }
1324 : olson 1.123
1325 : parrello 1.210 =head3 get_local_hostname
1326 : parrello 1.200
1327 : parrello 1.287 C<< my $result = FIG::get_local_hostname(); >>
1328 :    
1329 :     Return the local host name for the current processor. The name may be
1330 :     stored in a configuration file, or we may have to get it from the
1331 :     operating system.
1332 : olson 1.123
1333 : olson 1.93 =cut
1334 : parrello 1.213 #: Return Type $;
1335 : olson 1.10 sub get_local_hostname {
1336 : olson 1.52
1337 :     #
1338 :     # See if there is a FIGdisk/config/hostname file. If there
1339 :     # is, force the hostname to be that.
1340 :     #
1341 :    
1342 :     my $hostfile = "$FIG_Config::fig_disk/config/hostname";
1343 : parrello 1.287 if (-f $hostfile) {
1344 :     my $fh;
1345 :     if (open($fh, $hostfile)) {
1346 :     my $hostname = <$fh>;
1347 :     chomp($hostname);
1348 :     return $hostname;
1349 :     }
1350 : olson 1.52 }
1351 : parrello 1.200
1352 : olson 1.10 #
1353 :     # First check to see if we our hostname is correct.
1354 :     #
1355 :     # Map it to an IP address, and try to bind to that ip.
1356 :     #
1357 :    
1358 :     my $tcp = getprotobyname('tcp');
1359 : parrello 1.200
1360 : olson 1.10 my $hostname = `hostname`;
1361 : golsen 1.44 chomp($hostname);
1362 : olson 1.10
1363 :     my @hostent = gethostbyname($hostname);
1364 :    
1365 : parrello 1.287 if (@hostent > 0) {
1366 :     my $sock;
1367 :     my $ip = $hostent[4];
1368 :    
1369 :     socket($sock, PF_INET, SOCK_STREAM, $tcp);
1370 :     if (bind($sock, sockaddr_in(0, $ip))) {
1371 :     #
1372 :     # It worked. Reverse-map back to a hopefully fqdn.
1373 :     #
1374 :    
1375 :     my @rev = gethostbyaddr($ip, AF_INET);
1376 :     if (@rev > 0) {
1377 :     my $host = $rev[0];
1378 :     #
1379 :     # Check to see if we have a FQDN.
1380 :     #
1381 :    
1382 :     if ($host =~ /\./) {
1383 :     #
1384 :     # Good.
1385 :     #
1386 :     return $host;
1387 :     } else {
1388 :     #
1389 :     # We didn't get a fqdn; bail and return the IP address.
1390 :     #
1391 :     return get_hostname_by_adapter()
1392 :     }
1393 :     } else {
1394 :     return inet_ntoa($ip);
1395 :     }
1396 :     } else {
1397 :     #
1398 :     # Our hostname must be wrong; we can't bind to the IP
1399 :     # address it maps to.
1400 :     # Return the name associated with the adapter.
1401 :     #
1402 :     return get_hostname_by_adapter()
1403 :     }
1404 :     } else {
1405 :     #
1406 :     # Our hostname isn't known to DNS. This isn't good.
1407 :     # Return the name associated with the adapter.
1408 :     #
1409 :     return get_hostname_by_adapter()
1410 :     }
1411 :     }
1412 :    
1413 :     =head3 get_hostname_by_adapter
1414 : parrello 1.200
1415 : parrello 1.287 C<< my $name = FIG::get_hostname_by_adapter(); >>
1416 : olson 1.10
1417 : parrello 1.287 Return the local host name for the current network environment.
1418 : parrello 1.213
1419 :     =cut
1420 :     #: Return Type $;
1421 : olson 1.10 sub get_hostname_by_adapter {
1422 :     #
1423 :     # Attempt to determine our local hostname based on the
1424 :     # network environment.
1425 :     #
1426 :     # This implementation reads the routing table for the default route.
1427 :     # We then look at the interface config for the interface that holds the default.
1428 :     #
1429 :     #
1430 :     # Linux routing table:
1431 :     # [olson@yips 0.0.0]$ netstat -rn
1432 :     # Kernel IP routing table
1433 :     # Destination Gateway Genmask Flags MSS Window irtt Iface
1434 :     # 140.221.34.32 0.0.0.0 255.255.255.224 U 0 0 0 eth0
1435 :     # 169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth0
1436 :     # 127.0.0.0 0.0.0.0 255.0.0.0 U 0 0 0 lo
1437 :     # 0.0.0.0 140.221.34.61 0.0.0.0 UG 0 0 0 eth0
1438 : parrello 1.200 #
1439 : olson 1.10 # Mac routing table:
1440 : parrello 1.200 #
1441 : olson 1.10 # bash-2.05a$ netstat -rn
1442 :     # Routing tables
1443 : parrello 1.200 #
1444 : olson 1.10 # Internet:
1445 :     # Destination Gateway Flags Refs Use Netif Expire
1446 :     # default 140.221.11.253 UGSc 12 120 en0
1447 :     # 127.0.0.1 127.0.0.1 UH 16 8415486 lo0
1448 :     # 140.221.8/22 link#4 UCS 12 0 en0
1449 :     # 140.221.8.78 0:6:5b:f:51:c4 UHLW 0 183 en0 408
1450 :     # 140.221.8.191 0:3:93:84:ab:e8 UHLW 0 92 en0 622
1451 :     # 140.221.8.198 0:e0:98:8e:36:e2 UHLW 0 5 en0 691
1452 :     # 140.221.9.6 0:6:5b:f:51:d6 UHLW 1 63 en0 1197
1453 :     # 140.221.10.135 0:d0:59:34:26:34 UHLW 2 2134 en0 1199
1454 :     # 140.221.10.152 0:30:1b:b0:ec:dd UHLW 1 137 en0 1122
1455 :     # 140.221.10.153 127.0.0.1 UHS 0 0 lo0
1456 :     # 140.221.11.37 0:9:6b:53:4e:4b UHLW 1 624 en0 1136
1457 :     # 140.221.11.103 0:30:48:22:59:e6 UHLW 3 973 en0 1016
1458 :     # 140.221.11.224 0:a:95:6f:7:10 UHLW 1 1 en0 605
1459 :     # 140.221.11.237 0:1:30:b8:80:c0 UHLW 0 0 en0 1158
1460 :     # 140.221.11.250 0:1:30:3:1:0 UHLW 0 0 en0 1141
1461 :     # 140.221.11.253 0:d0:3:e:70:a UHLW 13 0 en0 1199
1462 :     # 169.254 link#4 UCS 0 0 en0
1463 : parrello 1.200 #
1464 : olson 1.10 # Internet6:
1465 :     # Destination Gateway Flags Netif Expire
1466 :     # UH lo0
1467 :     # fe80::%lo0/64 Uc lo0
1468 :     # link#1 UHL lo0
1469 :     # fe80::%en0/64 link#4 UC en0
1470 :     # 0:a:95:a8:26:68 UHL lo0
1471 :     # ff01::/32 U lo0
1472 :     # ff02::%lo0/32 UC lo0
1473 :     # ff02::%en0/32 link#4 UC en0
1474 :    
1475 :     my($fh);
1476 :    
1477 : parrello 1.287 if (!open($fh, "netstat -rn |")) {
1478 :     warn "Cannot run netstat to determine local IP address\n";
1479 :     return "localhost";
1480 : olson 1.10 }
1481 :    
1482 :     my $interface_name;
1483 : parrello 1.200
1484 : parrello 1.287 while (<$fh>) {
1485 :     my @cols = split();
1486 : olson 1.10
1487 : parrello 1.287 if ($cols[0] eq "default" || $cols[0] eq "0.0.0.0") {
1488 :     $interface_name = $cols[$#cols];
1489 :     }
1490 : olson 1.10 }
1491 :     close($fh);
1492 : parrello 1.200
1493 : olson 1.11 # print "Default route on $interface_name\n";
1494 : olson 1.10
1495 :     #
1496 :     # Find ifconfig.
1497 :     #
1498 :    
1499 :     my $ifconfig;
1500 :    
1501 : parrello 1.287 for my $dir ((split(":", $ENV{PATH}), "/sbin", "/usr/sbin")) {
1502 :     if (-x "$dir/ifconfig") {
1503 :     $ifconfig = "$dir/ifconfig";
1504 :     last;
1505 :     }
1506 : olson 1.10 }
1507 :    
1508 : parrello 1.287 if ($ifconfig eq "") {
1509 :     warn "Ifconfig not found\n";
1510 :     return "localhost";
1511 : olson 1.10 }
1512 : olson 1.11 # print "Foudn $ifconfig\n";
1513 : olson 1.10
1514 : parrello 1.287 if (!open($fh, "$ifconfig $interface_name |")) {
1515 :     warn "Could not run $ifconfig: $!\n";
1516 :     return "localhost";
1517 : olson 1.10 }
1518 :    
1519 :     my $ip;
1520 : parrello 1.287 while (<$fh>) {
1521 :     #
1522 :     # Mac:
1523 :     # inet 140.221.10.153 netmask 0xfffffc00 broadcast 140.221.11.255
1524 :     # Linux:
1525 :     # inet addr:140.221.34.37 Bcast:140.221.34.63 Mask:255.255.255.224
1526 :     #
1527 :    
1528 :     chomp;
1529 :     s/^\s*//;
1530 :    
1531 :     # print "Have '$_'\n";
1532 :     if (/inet\s+addr:(\d+\.\d+\.\d+\.\d+)\s+/) {
1533 :     #
1534 :     # Linux hit.
1535 :     #
1536 :     $ip = $1;
1537 :     # print "Got linux $ip\n";
1538 :     last;
1539 :     } elsif (/inet\s+(\d+\.\d+\.\d+\.\d+)\s+/) {
1540 :     #
1541 :     # Mac hit.
1542 :     #
1543 :     $ip = $1;
1544 :     # print "Got mac $ip\n";
1545 :     last;
1546 :     }
1547 : olson 1.10 }
1548 :     close($fh);
1549 :    
1550 : parrello 1.287 if ($ip eq "") {
1551 :     warn "Didn't find an IP\n";
1552 :     return "localhost";
1553 : olson 1.10 }
1554 :    
1555 :     return $ip;
1556 : efrank 1.1 }
1557 :    
1558 : parrello 1.213 =head3 get_seed_id
1559 :    
1560 : parrello 1.287 C<< my $id = FIG::get_seed_id(); >>
1561 :    
1562 :     Return the Universally Unique ID for this SEED instance. If one
1563 :     does not exist, it will be created.
1564 : parrello 1.213
1565 :     =cut
1566 :     #: Return type $;
1567 : olson 1.38 sub get_seed_id {
1568 :     #
1569 :     # Retrieve the seed identifer from FIGdisk/config/seed_id.
1570 :     #
1571 :     # If it's not there, create one, and make it readonly.
1572 :     #
1573 :     my $id;
1574 :     my $id_file = "$FIG_Config::fig_disk/config/seed_id";
1575 : parrello 1.287 if (! -f $id_file) {
1576 :     my $newid = `uuidgen`;
1577 :     if (!$newid) {
1578 :     die "Cannot run uuidgen: $!";
1579 :     }
1580 : olson 1.38
1581 : parrello 1.287 chomp($newid);
1582 :     my $fh = new FileHandle(">$id_file");
1583 :     if (!$fh) {
1584 :     die "error creating $id_file: $!";
1585 :     }
1586 :     print $fh "$newid\n";
1587 :     $fh->close();
1588 :     chmod(0444, $id_file);
1589 : olson 1.38 }
1590 :     my $fh = new FileHandle("<$id_file");
1591 :     $id = <$fh>;
1592 :     chomp($id);
1593 :     return $id;
1594 :     }
1595 :    
1596 : parrello 1.287 =head3 get_release_info
1597 : olson 1.155
1598 : parrello 1.287 C<< my ($name, $id, $inst, $email, $parent_id, $description) = FIG::get_release_info(); >>
1599 : olson 1.155
1600 : parrello 1.287 Return the current data release information..
1601 : olson 1.195
1602 :     The release info comes from the file FIG/Data/RELEASE. It is formatted as:
1603 :    
1604 : parrello 1.287 <release-name>
1605 :     <unique id>
1606 :     <institution>
1607 :     <contact email>
1608 :     <unique id of data release this release derived from>
1609 :     <description>
1610 : olson 1.195
1611 :     For instance:
1612 :    
1613 : parrello 1.287 -----
1614 :     SEED Data Release, 09/15/2004.
1615 :     4148208C-1DF2-11D9-8417-000A95D52EF6
1616 :     ANL/FIG
1617 :     olson@mcs.anl.gov
1618 :    
1619 :     Test release.
1620 :     -----
1621 : olson 1.195
1622 :     If no RELEASE file exists, this routine will create one with a new unique ID. This
1623 :     lets a peer optimize the data transfer by being able to cache ID translations
1624 :     from this instance.
1625 : olson 1.155
1626 :     =cut
1627 : parrello 1.213 #: Return Type @;
1628 : parrello 1.287 sub get_release_info {
1629 : olson 1.196 my($fig, $no_create) = @_;
1630 : olson 1.195
1631 :     my $rel_file = "$FIG_Config::data/RELEASE";
1632 :    
1633 : parrello 1.287 if (! -f $rel_file and !$no_create) {
1634 : parrello 1.298 #
1635 :     # Create a new one.
1636 :     #
1637 : olson 1.195
1638 : parrello 1.287 my $newid = `uuidgen`;
1639 :     if (!$newid) {
1640 :     die "Cannot run uuidgen: $!";
1641 :     }
1642 : olson 1.195
1643 : parrello 1.287 chomp($newid);
1644 : olson 1.195
1645 : parrello 1.287 my $relinfo = "Automatically generated release info " . localtime();
1646 :     my $inst = "Unknown";
1647 :     my $contact = "Unknown";
1648 :     my $parent = "";
1649 :     my( $a, $b, $e, $v, $env ) = $fig->genome_counts;
1650 :     my $description = "Automatically generated release info\n";
1651 :     $description .= "Contains $a archaeal, $b bacterial, $e eukaryal, $v viral and $env environmental genomes.\n";
1652 :    
1653 :     my $fh = new FileHandle(">$rel_file");
1654 :     if (!$fh) {
1655 :     warn "error creating $rel_file: $!";
1656 :     return undef;
1657 :     }
1658 :     print $fh "$relinfo\n";
1659 :     print $fh "$newid\n";
1660 :     print $fh "$inst\n";
1661 :     print $fh "$contact\n";
1662 :     print $fh "$parent\n";
1663 :     print $fh $description;
1664 :     $fh->close();
1665 :     chmod(0444, $rel_file);
1666 : olson 1.195 }
1667 :    
1668 : parrello 1.287 if (open(my $fh, $rel_file)) {
1669 :     my(@lines) = <$fh>;
1670 :     close($fh);
1671 : parrello 1.200
1672 : parrello 1.287 chomp(@lines);
1673 : parrello 1.200
1674 : parrello 1.287 my($info, $id, $inst, $contact, $parent, @desc) = @lines;
1675 : olson 1.195
1676 : parrello 1.287 return ($info, $id, $inst, $contact, $parent, join("\n", @desc));
1677 : olson 1.195 }
1678 : olson 1.155
1679 :     return undef;
1680 :     }
1681 :    
1682 : parrello 1.287 =head3 get_peer_last_update
1683 : olson 1.155
1684 : parrello 1.287 C<< my $date = $fig->get_peer_last_update($peer_id); >>
1685 : parrello 1.213
1686 : olson 1.155 Return the timestamp from the last successful peer-to-peer update with
1687 : parrello 1.287 the given peer. If the specified peer has made updates, comparing this
1688 :     timestamp to the timestamp of the updates can tell you whether or not
1689 :     the updates have been integrated into your SEED data store.
1690 : olson 1.155
1691 :     We store this information in FIG/Data/Global/Peers/<peer-id>.
1692 :    
1693 : parrello 1.287 =over 4
1694 :    
1695 :     =item peer_id
1696 :    
1697 :     Universally Unique ID for the desired peer.
1698 :    
1699 :     =item RETURN
1700 :    
1701 :     Returns the date/time stamp for the last peer-to-peer updated performed
1702 :     with the identified SEED instance.
1703 :    
1704 :     =back
1705 :    
1706 : olson 1.155 =cut
1707 : parrello 1.213 #: Return Type $;
1708 : parrello 1.287 sub get_peer_last_update {
1709 : olson 1.155 my($self, $peer_id) = @_;
1710 :    
1711 :     my $dir = "$FIG_Config::data/Global/Peers";
1712 :     &verify_dir($dir);
1713 :     $dir .= "/$peer_id";
1714 :     &verify_dir($dir);
1715 :    
1716 :     my $update_file = "$dir/last_update";
1717 : parrello 1.287 if (-f $update_file) {
1718 :     my $time = file_head($update_file, 1);
1719 :     chomp $time;
1720 :     return $time;
1721 :     } else {
1722 :     return undef;
1723 : olson 1.155 }
1724 :     }
1725 :    
1726 : parrello 1.287 =head3 set_peer_last_update
1727 : parrello 1.213
1728 : parrello 1.287 C<< $fig->set_peer_last_update($peer_id, $time); >>
1729 : parrello 1.213
1730 : parrello 1.287 Manually set the update timestamp for a specified peer. This informs
1731 :     the SEED that you have all of the assignments and updates from a
1732 :     particular SEED instance as of a certain date.
1733 : parrello 1.213
1734 :     =cut
1735 :     #: Return Type ;
1736 :    
1737 : parrello 1.287 sub set_peer_last_update {
1738 : olson 1.155 my($self, $peer_id, $time) = @_;
1739 :    
1740 :     my $dir = "$FIG_Config::data/Global/Peers";
1741 :     &verify_dir($dir);
1742 :     $dir .= "/$peer_id";
1743 :     &verify_dir($dir);
1744 :    
1745 :     my $update_file = "$dir/last_update";
1746 :     open(F, ">$update_file");
1747 :     print F "$time\n";
1748 :     close(F);
1749 :     }
1750 :    
1751 : redwards 1.302 =head3 clean_spaces
1752 :    
1753 : parrello 1.320 Remove any extra spaces from input fields. This will (currently) remove ^\s, \s$, and concatenate multiple spaces into one.
1754 : redwards 1.302
1755 :     my $input=$fig->clean_spaces($cgi->param('input'));
1756 :    
1757 :     =cut
1758 :    
1759 :     sub clean_spaces
1760 :     {
1761 :     my ($self, $s)=@_;
1762 :     # note at the moment I do not use \s because that recognizes \t and \n too. This should only remove multiple spaces.
1763 : parrello 1.320 $s =~ s/^ +//;
1764 : redwards 1.302 $s =~ s/ +$//;
1765 :     $s =~ s/ +/ /g;
1766 :     return $s;
1767 :     }
1768 :    
1769 :    
1770 :    
1771 : parrello 1.213 =head3 cgi_url
1772 :    
1773 : parrello 1.287 C<< my $url = FIG::$fig->cgi_url(); >>
1774 :    
1775 :     Return the URL for the CGI script directory.
1776 : parrello 1.213
1777 :     =cut
1778 :     #: Return Type $;
1779 : efrank 1.1 sub cgi_url {
1780 :     return &plug_url($FIG_Config::cgi_url);
1781 :     }
1782 : parrello 1.200
1783 : parrello 1.213 =head3 temp_url
1784 :    
1785 : parrello 1.287 C<< my $url = FIG::temp_url(); >>
1786 :    
1787 :     Return the URL of the temporary file directory.
1788 : parrello 1.213
1789 :     =cut
1790 :     #: Return Type $;
1791 : efrank 1.1 sub temp_url {
1792 :     return &plug_url($FIG_Config::temp_url);
1793 :     }
1794 : parrello 1.200
1795 : parrello 1.213 =head3 plug_url
1796 :    
1797 : parrello 1.287 C<< my $url2 = $fig->plug_url($url); >>
1798 :    
1799 :     or
1800 :    
1801 :     C<< my $url2 = $fig->plug_url($url); >>
1802 :    
1803 :     Change the domain portion of a URL to point to the current domain. This essentially
1804 :     relocates URLs into the current environment.
1805 :    
1806 :     =over 4
1807 :    
1808 :     =item url
1809 :    
1810 :     URL to relocate.
1811 :    
1812 :     =item RETURN
1813 :    
1814 :     Returns a new URL with the base portion converted to the current operating host.
1815 :     If the URL does not begin with C<http://>, the URL will be returned unmodified.
1816 :    
1817 :     =back
1818 : parrello 1.213
1819 :     =cut
1820 :     #: Return Type $;
1821 : efrank 1.1 sub plug_url {
1822 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
1823 : efrank 1.1 my($url) = @_;
1824 :    
1825 : golsen 1.44 my $name;
1826 :    
1827 :     # Revised by GJO
1828 :     # First try to get url from the current http request
1829 :    
1830 :     if ( defined( $ENV{ 'HTTP_HOST' } ) # This is where $cgi->url gets its value
1831 :     && ( $name = $ENV{ 'HTTP_HOST' } )
1832 :     && ( $url =~ s~^http://[^/]*~http://$name~ ) # ~ is delimiter
1833 :     ) {}
1834 :    
1835 :     # Otherwise resort to alternative sources
1836 :    
1837 :     elsif ( ( $name = &get_local_hostname )
1838 :     && ( $url =~ s~^http://[^/]*~http://$name~ ) # ~ is delimiter
1839 :     ) {}
1840 :    
1841 : efrank 1.1 return $url;
1842 :     }
1843 :    
1844 : parrello 1.213 =head3 file_read
1845 :    
1846 : parrello 1.287 C<< my $text = $fig->file_read($fileName); >>
1847 :    
1848 :     or
1849 :    
1850 :     C<< my @lines = $fig->file_read($fileName); >>
1851 :    
1852 :     or
1853 :    
1854 :     C<< my $text = FIG::file_read($fileName); >>
1855 :    
1856 :     or
1857 :    
1858 :     C<< my @lines = FIG::file_read($fileName); >>
1859 :    
1860 :     Read an entire file into memory. In a scalar context, the file is returned
1861 :     as a single text string with line delimiters included. In a list context, the
1862 :     file is returned as a list of lines, each line terminated by a line
1863 :     delimiter. (For a method that automatically strips the line delimiters,
1864 :     use C<Tracer::GetFile>.)
1865 :    
1866 :     =over 4
1867 :    
1868 :     =item fileName
1869 :    
1870 :     Fully-qualified name of the file to read.
1871 :    
1872 :     =item RETURN
1873 :    
1874 :     In a list context, returns a list of the file lines. In a scalar context, returns
1875 :     a string containing all the lines of the file with delimiters included.
1876 : parrello 1.213
1877 : parrello 1.287 =back
1878 : parrello 1.213
1879 :     =cut
1880 :     #: Return Type $;
1881 :     #: Return Type @;
1882 : parrello 1.287 sub file_read {
1883 :    
1884 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
1885 : parrello 1.287 my($fileName) = @_;
1886 :     return file_head($fileName, '*');
1887 : olson 1.90
1888 :     }
1889 :    
1890 :    
1891 : parrello 1.213 =head3 file_head
1892 :    
1893 : parrello 1.287 C<< my $text = $fig->file_head($fileName, $count); >>
1894 :    
1895 :     or
1896 :    
1897 :     C<< my @lines = $fig->file_head($fileName, $count); >>
1898 : parrello 1.213
1899 : parrello 1.287 or
1900 : parrello 1.213
1901 : parrello 1.287 C<< my $text = FIG::file_head($fileName, $count); >>
1902 : olson 1.90
1903 : parrello 1.287 or
1904 : olson 1.90
1905 : parrello 1.287 C<< my @lines = FIG::file_head($fileName, $count); >>
1906 : olson 1.90
1907 : parrello 1.287 Read a portion of a file into memory. In a scalar context, the file portion is
1908 :     returned as a single text string with line delimiters included. In a list
1909 :     context, the file portion is returned as a list of lines, each line terminated
1910 :     by a line delimiter.
1911 : olson 1.155
1912 : parrello 1.287 =over 4
1913 : olson 1.90
1914 : parrello 1.287 =item fileName
1915 : olson 1.90
1916 : parrello 1.287 Fully-qualified name of the file to read.
1917 : efrank 1.1
1918 : parrello 1.287 =item count (optional)
1919 : efrank 1.1
1920 : parrello 1.287 Number of lines to read from the file. If omitted, C<1> is assumed. If the
1921 :     non-numeric string C<*> is specified, the entire file will be read.
1922 : efrank 1.1
1923 : parrello 1.287 =item RETURN
1924 : efrank 1.1
1925 : parrello 1.287 In a list context, returns a list of the desired file lines. In a scalar context, returns
1926 :     a string containing the desired lines of the file with delimiters included.
1927 : efrank 1.1
1928 : parrello 1.287 =back
1929 : efrank 1.1
1930 :     =cut
1931 : parrello 1.287 #: Return Type $;
1932 :     #: Return Type @;
1933 :     sub file_head {
1934 : efrank 1.1
1935 : parrello 1.287 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
1936 :     my($file, $count) = @_;
1937 : efrank 1.1
1938 : parrello 1.287 my ($n, $allFlag);
1939 :     if ($count eq '*') {
1940 : olson 1.304 Trace("Full file read for \"$file\".") if T(3);
1941 : parrello 1.287 $allFlag = 1;
1942 :     $n = 0;
1943 :     } else {
1944 :     $allFlag = 0;
1945 :     $n = (!$count ? 1 : $count);
1946 : olson 1.304 Trace("Reading $n record(s) from \"$file\".") if T(3);
1947 : parrello 1.287 }
1948 : efrank 1.1
1949 : parrello 1.287 if (open(my $fh, "<$file")) {
1950 : parrello 1.298 my(@ret, $i);
1951 : parrello 1.287 $i = 0;
1952 :     while (<$fh>) {
1953 :     push(@ret, $_);
1954 :     $i++;
1955 :     last if !$allFlag && $i >= $n;
1956 :     }
1957 :     close($fh);
1958 :     if (wantarray) {
1959 :     return @ret;
1960 :     } else {
1961 :     return join("", @ret);
1962 :     }
1963 : efrank 1.1 }
1964 :     }
1965 :    
1966 :     ################ Basic Routines [ existed since WIT ] ##########################
1967 :    
1968 : parrello 1.287 =head3 min
1969 :    
1970 :     C<< my $min = FIG::min(@x); >>
1971 :    
1972 :     or
1973 :    
1974 :     C<< my $min = $fig->min(@x); >>
1975 :    
1976 :     Return the minimum numeric value from a list.
1977 :    
1978 :     =over 4
1979 :    
1980 :     =item x1, x2, ... xN
1981 : efrank 1.1
1982 : parrello 1.287 List of numbers to process.
1983 : efrank 1.1
1984 : parrello 1.287 =item RETURN
1985 : efrank 1.1
1986 : parrello 1.287 Returns the numeric value of the list entry possessing the lowest value. Returns
1987 :     C<undef> if the list is empty.
1988 : efrank 1.1
1989 : parrello 1.287 =back
1990 : efrank 1.1
1991 :     =cut
1992 : parrello 1.213 #: Return Type $;
1993 : efrank 1.1 sub min {
1994 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
1995 : efrank 1.1 my(@x) = @_;
1996 :     my($min,$i);
1997 :    
1998 :     (@x > 0) || return undef;
1999 :     $min = $x[0];
2000 : parrello 1.287 for ($i=1; ($i < @x); $i++) {
2001 :     $min = ($min > $x[$i]) ? $x[$i] : $min;
2002 : efrank 1.1 }
2003 :     return $min;
2004 :     }
2005 :    
2006 : parrello 1.287 =head3 max
2007 :    
2008 :     C<< my $max = FIG::max(@x); >>
2009 :    
2010 :     or
2011 :    
2012 :     C<< my $max = $fig->max(@x); >>
2013 : efrank 1.1
2014 : parrello 1.287 Return the maximum numeric value from a list.
2015 : efrank 1.1
2016 : parrello 1.287 =over 4
2017 :    
2018 :     =item x1, x2, ... xN
2019 :    
2020 :     List of numbers to process.
2021 :    
2022 :     =item RETURN
2023 :    
2024 :     Returns the numeric value of t/he list entry possessing the highest value. Returns
2025 :     C<undef> if the list is empty.
2026 : efrank 1.1
2027 : parrello 1.287 =back
2028 : efrank 1.1
2029 :     =cut
2030 : parrello 1.213 #: Return Type $;
2031 : efrank 1.1 sub max {
2032 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2033 : efrank 1.1 my(@x) = @_;
2034 :     my($max,$i);
2035 :    
2036 :     (@x > 0) || return undef;
2037 :     $max = $x[0];
2038 : parrello 1.287 for ($i=1; ($i < @x); $i++) {
2039 :     $max = ($max < $x[$i]) ? $x[$i] : $max;
2040 : efrank 1.1 }
2041 :     return $max;
2042 :     }
2043 :    
2044 : parrello 1.287 =head3 between
2045 : efrank 1.1
2046 : parrello 1.287 C<< my $flag = FIG::between($x, $y, $z); >>
2047 : efrank 1.1
2048 : parrello 1.287 or
2049 :    
2050 :     C<< my $flag = $fig->between($x, $y, $z); >>
2051 :    
2052 :     Determine whether or not $y is between $x and $z.
2053 :    
2054 :     =over 4
2055 :    
2056 :     =item x
2057 :    
2058 :     First edge number.
2059 :    
2060 :     =item y
2061 : efrank 1.1
2062 : parrello 1.287 Number to examine.
2063 :    
2064 :     =item z
2065 :    
2066 :     Second edge number.
2067 :    
2068 :     =item RETURN
2069 :    
2070 :     Return TRUE if the number I<$y> is between the numbers I<$x> and I<$z>. The check
2071 :     is inclusive (that is, if I<$y> is equal to I<$x> or I<$z> the function returns
2072 :     TRUE), and the order of I<$x> and I<$z> does not matter. If I<$x> is lower than
2073 :     I<$z>, then the return is TRUE if I<$x> <= I<$y> <= I<$z>. If I<$z> is lower,
2074 :     then the return is TRUE if I<$x> >= I$<$y> >= I<$z>.
2075 :    
2076 :     =back
2077 : efrank 1.1
2078 :     =cut
2079 : parrello 1.213 #: Return Type $;
2080 : efrank 1.1 sub between {
2081 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2082 : efrank 1.1 my($x,$y,$z) = @_;
2083 :    
2084 : parrello 1.287 if ($x < $z) {
2085 :     return (($x <= $y) && ($y <= $z));
2086 :     } else {
2087 :     return (($x >= $y) && ($y >= $z));
2088 : efrank 1.1 }
2089 :     }
2090 :    
2091 : parrello 1.287 =head3 standard_genetic_code
2092 : efrank 1.1
2093 : parrello 1.287 C<< my $code = FIG::standard_genetic_code(); >>
2094 : efrank 1.1
2095 : parrello 1.287 Return a hash containing the standard translation of nucleotide triples to proteins.
2096 :     Methods such as L</translate> can take a translation scheme as a parameter. This method
2097 :     returns the default translation scheme. The scheme is implemented as a reference to a
2098 :     hash that contains nucleotide triplets as keys and has protein letters as values.
2099 : efrank 1.1
2100 :     =cut
2101 : parrello 1.213 #: Return Type $;
2102 : efrank 1.1 sub standard_genetic_code {
2103 : parrello 1.200
2104 : efrank 1.1 my $code = {};
2105 :    
2106 :     $code->{"AAA"} = "K";
2107 :     $code->{"AAC"} = "N";
2108 :     $code->{"AAG"} = "K";
2109 :     $code->{"AAT"} = "N";
2110 :     $code->{"ACA"} = "T";
2111 :     $code->{"ACC"} = "T";
2112 :     $code->{"ACG"} = "T";
2113 :     $code->{"ACT"} = "T";
2114 :     $code->{"AGA"} = "R";
2115 :     $code->{"AGC"} = "S";
2116 :     $code->{"AGG"} = "R";
2117 :     $code->{"AGT"} = "S";
2118 :     $code->{"ATA"} = "I";
2119 :     $code->{"ATC"} = "I";
2120 :     $code->{"ATG"} = "M";
2121 :     $code->{"ATT"} = "I";
2122 :     $code->{"CAA"} = "Q";
2123 :     $code->{"CAC"} = "H";
2124 :     $code->{"CAG"} = "Q";
2125 :     $code->{"CAT"} = "H";
2126 :     $code->{"CCA"} = "P";
2127 :     $code->{"CCC"} = "P";
2128 :     $code->{"CCG"} = "P";
2129 :     $code->{"CCT"} = "P";
2130 :     $code->{"CGA"} = "R";
2131 :     $code->{"CGC"} = "R";
2132 :     $code->{"CGG"} = "R";
2133 :     $code->{"CGT"} = "R";
2134 :     $code->{"CTA"} = "L";
2135 :     $code->{"CTC"} = "L";
2136 :     $code->{"CTG"} = "L";
2137 :     $code->{"CTT"} = "L";
2138 :     $code->{"GAA"} = "E";
2139 :     $code->{"GAC"} = "D";
2140 :     $code->{"GAG"} = "E";
2141 :     $code->{"GAT"} = "D";
2142 :     $code->{"GCA"} = "A";
2143 :     $code->{"GCC"} = "A";
2144 :     $code->{"GCG"} = "A";
2145 :     $code->{"GCT"} = "A";
2146 :     $code->{"GGA"} = "G";
2147 :     $code->{"GGC"} = "G";
2148 :     $code->{"GGG"} = "G";
2149 :     $code->{"GGT"} = "G";
2150 :     $code->{"GTA"} = "V";
2151 :     $code->{"GTC"} = "V";
2152 :     $code->{"GTG"} = "V";
2153 :     $code->{"GTT"} = "V";
2154 :     $code->{"TAA"} = "*";
2155 :     $code->{"TAC"} = "Y";
2156 :     $code->{"TAG"} = "*";
2157 :     $code->{"TAT"} = "Y";
2158 :     $code->{"TCA"} = "S";
2159 :     $code->{"TCC"} = "S";
2160 :     $code->{"TCG"} = "S";
2161 :     $code->{"TCT"} = "S";
2162 :     $code->{"TGA"} = "*";
2163 :     $code->{"TGC"} = "C";
2164 :     $code->{"TGG"} = "W";
2165 :     $code->{"TGT"} = "C";
2166 :     $code->{"TTA"} = "L";
2167 :     $code->{"TTC"} = "F";
2168 :     $code->{"TTG"} = "L";
2169 :     $code->{"TTT"} = "F";
2170 : parrello 1.200
2171 : efrank 1.1 return $code;
2172 :     }
2173 :    
2174 : parrello 1.287 =head3 translate
2175 :    
2176 :     C<< my $aa_seq = &FIG::translate($dna_seq, $code, $fix_start); >>
2177 :    
2178 :     Translate a DNA sequence to a protein sequence using the specified genetic code.
2179 :     If I<$fix_start> is TRUE, will translate an initial C<TTG> or C<GTG> code to
2180 :     C<M>. (In the standard genetic code, these two combinations normally translate
2181 :     to C<V> and C<L>, respectively.)
2182 :    
2183 :     =over 4
2184 : efrank 1.1
2185 : parrello 1.287 =item dna_seq
2186 : efrank 1.1
2187 : parrello 1.287 DNA sequence to translate. Note that the DNA sequence can only contain
2188 :     known nucleotides.
2189 : efrank 1.1
2190 : parrello 1.287 =item code
2191 : efrank 1.1
2192 : parrello 1.287 Reference to a hash specifying the translation code. The hash is keyed by
2193 :     nucleotide triples, and the value for each key is the corresponding protein
2194 :     letter. If this parameter is omitted, the L</standard_genetic_code> will be
2195 :     used.
2196 : efrank 1.1
2197 : parrello 1.287 =item fix_start
2198 :    
2199 :     TRUE if the first triple is to get special treatment, else FALSE. If TRUE,
2200 :     then a value of C<TTG> or C<GTG> in the first position will be translated to
2201 :     C<M> instead of the value specified in the translation code.
2202 :    
2203 :     =item RETURN
2204 :    
2205 :     Returns a string resulting from translating each nucleotide triple into a
2206 :     protein letter.
2207 :    
2208 :     =back
2209 :    
2210 :     =cut
2211 :     #: Return Type $;
2212 :     sub translate {
2213 :     shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2214 :    
2215 :     my( $dna,$code,$start ) = @_;
2216 :     my( $i,$j,$ln );
2217 :     my( $x,$y );
2218 :     my( $prot );
2219 :    
2220 :     if (! defined($code)) {
2221 :     $code = &FIG::standard_genetic_code;
2222 : efrank 1.1 }
2223 :     $ln = length($dna);
2224 :     $prot = "X" x ($ln/3);
2225 :     $dna =~ tr/a-z/A-Z/;
2226 :    
2227 : parrello 1.287 for ($i=0,$j=0; ($i < ($ln-2)); $i += 3,$j++) {
2228 :     $x = substr($dna,$i,3);
2229 :     if ($y = $code->{$x}) {
2230 :     substr($prot,$j,1) = $y;
2231 : efrank 1.1 }
2232 :     }
2233 : parrello 1.200
2234 : parrello 1.287 if (($start) && ($ln >= 3) && (substr($dna,0,3) =~ /^[GT]TG$/)) {
2235 :     substr($prot,0,1) = 'M';
2236 : efrank 1.1 }
2237 :     return $prot;
2238 :     }
2239 :    
2240 : parrello 1.287 =head3 reverse_comp
2241 :    
2242 :     C<< my $dnaR = FIG::reverse_comp($dna); >>
2243 :    
2244 :     or
2245 :    
2246 :     C<< my $dnaR = $fig->reverse_comp($dna); >>
2247 :    
2248 :     Return the reverse complement os the specified DNA sequence.
2249 : efrank 1.1
2250 : parrello 1.287 NOTE: for extremely long DNA strings, use L</rev_comp>, which allows you to
2251 :     pass the strings around in the form of pointers.
2252 : efrank 1.1
2253 : parrello 1.287 =over 4
2254 :    
2255 :     =item dna
2256 : efrank 1.1
2257 : parrello 1.287 DNA sequence whose reverse complement is desired.
2258 :    
2259 :     =item RETURN
2260 :    
2261 :     Returns the reverse complement of the incoming DNA sequence.
2262 :    
2263 :     =back
2264 : efrank 1.1
2265 :     =cut
2266 : parrello 1.213 #: Return Type $;
2267 : efrank 1.1 sub reverse_comp {
2268 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2269 : efrank 1.1 my($seq) = @_;
2270 :    
2271 :     return ${&rev_comp(\$seq)};
2272 :     }
2273 :    
2274 : parrello 1.287 =head3 rev_comp
2275 :    
2276 :     C<< my $dnaRP = FIG::rev_comp(\$dna); >>
2277 :    
2278 :     or
2279 :    
2280 :     C<< my $dnaRP = $fig->rev_comp(\$dna); >>
2281 :    
2282 :     Return the reverse complement of the specified DNA sequence. The DNA sequence
2283 :     is passed in as a string reference rather than a raw string for performance
2284 :     reasons. If this is unnecessary, use L</reverse_comp>, which processes strings
2285 :     instead of references to strings.
2286 :    
2287 :     =over 4
2288 :    
2289 :     =item dna
2290 :    
2291 :     Reference to the DNA sequence whose reverse complement is desired.
2292 :    
2293 :     =item RETURN
2294 :    
2295 :     Returns a reference to the reverse complement of the incoming DNA sequence.
2296 :    
2297 :     =back
2298 : parrello 1.213
2299 :     =cut
2300 :     #: Return Type $;
2301 : efrank 1.1 sub rev_comp {
2302 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2303 : efrank 1.1 my( $seqP ) = @_;
2304 :     my( $rev );
2305 :    
2306 :     $rev = reverse( $$seqP );
2307 : overbeek 1.317 $rev =~ tr/A-Z/a-z/;
2308 :     $rev =~ tr/acgtumrwsykbdhv/tgcaakywsrmvhdb/;
2309 : efrank 1.1 return \$rev;
2310 :     }
2311 :    
2312 : parrello 1.287 =head3 verify_dir
2313 :    
2314 :     C<< FIG::verify_dir($dir); >>
2315 : efrank 1.1
2316 : parrello 1.287 or
2317 : efrank 1.1
2318 : parrello 1.287 C<< $fig->verify_dir($dir); >>
2319 : efrank 1.1
2320 : parrello 1.287 Insure that the specified directory exists. If it must be created, the permissions will
2321 :     be set to C<0777>.
2322 : efrank 1.1
2323 :     =cut
2324 :    
2325 :     sub verify_dir {
2326 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2327 : efrank 1.1 my($dir) = @_;
2328 :    
2329 : parrello 1.287 if (-d $dir) {
2330 :     return
2331 :     }
2332 :     if ($dir =~ /^(.*)\/[^\/]+$/) {
2333 :     &verify_dir($1);
2334 : efrank 1.1 }
2335 : parrello 1.287 mkdir($dir,0777) || Confess("Could not make directory $dir: $!");
2336 : efrank 1.1 }
2337 :    
2338 : parrello 1.287 =head3 run
2339 : efrank 1.1
2340 : parrello 1.287 C<< FIG::run($cmd); >>
2341 : overbeek 1.283
2342 : parrello 1.287 or
2343 :    
2344 :     C<< $fig->run($cmd); >>
2345 : overbeek 1.283
2346 : parrello 1.287 Run a command. If the command fails, the error will be traced.
2347 : overbeek 1.283
2348 :     =cut
2349 :    
2350 : parrello 1.287 sub run {
2351 :     shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2352 :     my($cmd) = @_;
2353 :    
2354 : overbeek 1.363 if ($ENV{FIG_VERBOSE}) {
2355 : parrello 1.287 my @tmp = `date`;
2356 :     chomp @tmp;
2357 :     print STDERR "$tmp[0]: running $cmd\n";
2358 :     }
2359 :     Trace("Running command: $cmd") if T(3);
2360 :     (system($cmd) == 0) || Confess("FAILED: $cmd");
2361 :     }
2362 :    
2363 :     =head3 augment_path
2364 :    
2365 :     C<< FIG::augment_path($dirName); >>
2366 : overbeek 1.283
2367 : parrello 1.287 Add a directory to the system path.
2368 : overbeek 1.283
2369 : parrello 1.287 This method adds a new directory to the front of the system path. It looks in the
2370 :     configuration file to determine whether this is Windows or Unix, and uses the
2371 :     appropriate separator.
2372 : efrank 1.1
2373 : parrello 1.287 =over 4
2374 : efrank 1.1
2375 : parrello 1.287 =item dirName
2376 :    
2377 :     Name of the directory to add to the path.
2378 :    
2379 :     =back
2380 : efrank 1.1
2381 :     =cut
2382 :    
2383 : parrello 1.287 sub augment_path {
2384 :     my ($dirName) = @_;
2385 :     if ($FIG_Config::win_mode) {
2386 :     $ENV{PATH} = "$dirName;$ENV{PATH}";
2387 :     } else {
2388 :     $ENV{PATH} = "$dirName:$ENV{PATH}";
2389 : overbeek 1.278 }
2390 : efrank 1.1 }
2391 :    
2392 : parrello 1.287 =head3 read_fasta_record
2393 : gdpusch 1.45
2394 : parrello 1.287 C<< my ($seq_id, $seq_pointer, $comment) = FIG::read_fasta_record(\*FILEHANDLE); >>
2395 : gdpusch 1.45
2396 : parrello 1.287 or
2397 : gdpusch 1.45
2398 : parrello 1.287 C<< my ($seq_id, $seq_pointer, $comment) = $fig->read_fasta_record(\*FILEHANDLE); >>
2399 : gdpusch 1.45
2400 : parrello 1.287 Read and parse the next logical record of a FASTA file. A FASTA logical record
2401 :     consists of multiple lines of text. The first line begins with a C<< > >> symbol
2402 :     and contains the sequence ID followed by an optional comment. (NOTE: comments
2403 :     are currently deprecated, because not all tools handle them properly.) The
2404 :     remaining lines contain the sequence data.
2405 :    
2406 :     This method uses a trick to smooth its operation: the line terminator character
2407 :     is temporarily changed to C<< \n> >> so that a single read operation brings in
2408 :     the entire logical record.
2409 : gdpusch 1.45
2410 : parrello 1.287 =over 4
2411 : gdpusch 1.45
2412 : parrello 1.287 =item FILEHANDLE
2413 : gdpusch 1.45
2414 : parrello 1.287 Open handle of the FASTA file. If not specified, C<STDIN> is assumed.
2415 :    
2416 :     =item RETURN
2417 :    
2418 :     If we are at the end of the file, returns C<undef>. Otherwise, returns a
2419 :     three-element list. The first element is the sequence ID, the second is
2420 :     a pointer to the sequence data (that is, a string reference as opposed to
2421 :     as string), and the third is the comment.
2422 :    
2423 :     =back
2424 : gdpusch 1.45
2425 :     =cut
2426 : parrello 1.213 #: Return Type @;
2427 : parrello 1.287 sub read_fasta_record {
2428 :    
2429 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2430 : gdpusch 1.45 my ($file_handle) = @_;
2431 : parrello 1.287 my ($old_end_of_record, $fasta_record, @lines, $head, $sequence, $seq_id, $comment, @parsed_fasta_record);
2432 : parrello 1.200
2433 : gdpusch 1.45 if (not defined($file_handle)) { $file_handle = \*STDIN; }
2434 : parrello 1.200
2435 : gdpusch 1.45 $old_end_of_record = $/;
2436 :     $/ = "\n>";
2437 : parrello 1.200
2438 : parrello 1.287 if (defined($fasta_record = <$file_handle>)) {
2439 :     chomp $fasta_record;
2440 :     @lines = split( /\n/, $fasta_record );
2441 :     $head = shift @lines;
2442 :     $head =~ s/^>?//;
2443 :     $head =~ m/^(\S+)/;
2444 :     $seq_id = $1;
2445 :     if ($head =~ m/^\S+\s+(.*)$/) { $comment = $1; } else { $comment = ""; }
2446 :     $sequence = join( "", @lines );
2447 :     @parsed_fasta_record = ( $seq_id, \$sequence, $comment );
2448 :     } else {
2449 :     @parsed_fasta_record = ();
2450 : gdpusch 1.45 }
2451 : parrello 1.200
2452 : gdpusch 1.45 $/ = $old_end_of_record;
2453 : parrello 1.200
2454 : gdpusch 1.45 return @parsed_fasta_record;
2455 :     }
2456 :    
2457 : parrello 1.287 =head3 display_id_and_seq
2458 :    
2459 :     C<< FIG::display_id_and_seq($id_and_comment, $seqP, $fh); >>
2460 :    
2461 :     or
2462 :    
2463 : parrello 1.355 C<< $fig->display_id_and_seq($id_and_comment, \$seqP, $fh); >>
2464 : parrello 1.287
2465 :     Display a fasta ID and sequence to the specified open file. This method is designed
2466 :     to work well with L</read_fasta_sequence> and L</rev_comp>, because it takes as
2467 :     input a string pointer rather than a string. If the file handle is omitted it
2468 :     defaults to STDOUT.
2469 :    
2470 :     The output is formatted into a FASTA record. The first line of the output is
2471 :     preceded by a C<< > >> symbol, and the sequence is split into 60-character
2472 :     chunks displayed one per line. Thus, this method can be used to produce
2473 :     FASTA files from data gathered by the rest of the system.
2474 :    
2475 :     =over 4
2476 :    
2477 :     =item id_and_comment
2478 :    
2479 :     The sequence ID and (optionally) the comment from the sequence's FASTA record.
2480 :     The ID
2481 : gdpusch 1.45
2482 : parrello 1.287 =item seqP
2483 : efrank 1.1
2484 : parrello 1.287 Reference to a string containing the sequence. The sequence is automatically
2485 :     formatted into 60-character chunks displayed one per line.
2486 : efrank 1.1
2487 : parrello 1.287 =item fh
2488 : efrank 1.1
2489 : parrello 1.287 Open file handle to which the ID and sequence should be output. If omitted,
2490 : parrello 1.355 C<\*STDOUT> is assumed.
2491 : parrello 1.287
2492 :     =back
2493 : efrank 1.1
2494 :     =cut
2495 :    
2496 : parrello 1.287 sub display_id_and_seq {
2497 : mkubal 1.53
2498 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2499 : parrello 1.287
2500 : overbeek 1.326 my( $id, $seqP, $fh ) = @_;
2501 : parrello 1.200
2502 : efrank 1.1 if (! defined($fh) ) { $fh = \*STDOUT; }
2503 : parrello 1.200
2504 : efrank 1.1 print $fh ">$id\n";
2505 : overbeek 1.326 &display_seq($seqP, $fh);
2506 : efrank 1.1 }
2507 :    
2508 : parrello 1.355 =head3 display_seq
2509 : parrello 1.287
2510 : parrello 1.355 C<< FIG::display_seq(\$seqP, $fh); >>
2511 : parrello 1.287
2512 :     or
2513 :    
2514 : parrello 1.355 C<< $fig->display_seq(\$seqP, $fh); >>
2515 : parrello 1.287
2516 :     Display a fasta sequence to the specified open file. This method is designed
2517 :     to work well with L</read_fasta_sequence> and L</rev_comp>, because it takes as
2518 :     input a string pointer rather than a string. If the file handle is omitted it
2519 :     defaults to STDOUT.
2520 :    
2521 :     The sequence is split into 60-character chunks displayed one per line for
2522 :     readability.
2523 :    
2524 :     =over 4
2525 :    
2526 :     =item seqP
2527 :    
2528 :     Reference to a string containing the sequence.
2529 :    
2530 :     =item fh
2531 :    
2532 :     Open file handle to which the sequence should be output. If omitted,
2533 :     C<STDOUT> is assumed.
2534 :    
2535 :     =back
2536 :    
2537 :     =cut
2538 :    
2539 : efrank 1.1 sub display_seq {
2540 : parrello 1.287
2541 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
2542 : parrello 1.287
2543 : overbeek 1.326 my ( $seqP, $fh ) = @_;
2544 : efrank 1.1 my ( $i, $n, $ln );
2545 : parrello 1.200
2546 : efrank 1.1 if (! defined($fh) ) { $fh = \*STDOUT; }
2547 :    
2548 : overbeek 1.326 $n = length($$seqP);
2549 : efrank 1.1 # confess "zero-length sequence ???" if ( (! defined($n)) || ($n == 0) );
2550 : parrello 1.287 for ($i=0; ($i < $n); $i += 60) {
2551 :     if (($i + 60) <= $n) {
2552 : overbeek 1.326 $ln = substr($$seqP,$i,60);
2553 : parrello 1.287 } else {
2554 : overbeek 1.326 $ln = substr($$seqP,$i,($n-$i));
2555 : parrello 1.287 }
2556 :     print $fh "$ln\n";
2557 : efrank 1.1 }
2558 :     }
2559 :    
2560 :     ########## I commented the pods on the following routines out, since they should not
2561 :     ########## be part of the SOAP/WSTL interface
2562 :     #=pod
2563 :     #
2564 : parrello 1.287 #=head3 file2N
2565 : efrank 1.1 #
2566 :     #usage: $n = $fig->file2N($file)
2567 :     #
2568 :     #In some of the databases I need to store filenames, which can waste a lot of
2569 :     #space. Hence, I maintain a database for converting filenames to/from integers.
2570 :     #
2571 :     #=cut
2572 :     #
2573 : parrello 1.328 sub file2N :Scalar {
2574 : efrank 1.1 my($self,$file) = @_;
2575 :     my($relational_db_response);
2576 :    
2577 :     my $rdbH = $self->db_handle;
2578 :    
2579 :     if (($relational_db_response = $rdbH->SQL("SELECT fileno FROM file_table WHERE ( file = \'$file\')")) &&
2580 : parrello 1.298 (@$relational_db_response == 1)) {
2581 : parrello 1.287 return $relational_db_response->[0]->[0];
2582 :     } elsif (($relational_db_response = $rdbH->SQL("SELECT MAX(fileno) FROM file_table ")) && (@$relational_db_response == 1) && ($relational_db_response->[0]->[0])) {
2583 :     my $fileno = $relational_db_response->[0]->[0] + 1;
2584 :     if ($rdbH->SQL("INSERT INTO file_table ( file, fileno ) VALUES ( \'$file\', $fileno )")) {
2585 :     return $fileno;
2586 :     }
2587 :     } elsif ($rdbH->SQL("INSERT INTO file_table ( file, fileno ) VALUES ( \'$file\', 1 )")) {
2588 :     return 1;
2589 : efrank 1.1 }
2590 :     return undef;
2591 :     }
2592 :    
2593 :     #=pod
2594 :     #
2595 : parrello 1.287 #=head3 N2file
2596 : efrank 1.1 #
2597 :     #usage: $filename = $fig->N2file($n)
2598 :     #
2599 :     #In some of the databases I need to store filenames, which can waste a lot of
2600 :     #space. Hence, I maintain a database for converting filenames to/from integers.
2601 :     #
2602 :     #=cut
2603 :     #
2604 : overbeek 1.364 sub N2file :Scalar
2605 :     {
2606 : efrank 1.1 my($self,$fileno) = @_;
2607 : overbeek 1.364
2608 :     #
2609 :     # Cache outputs. This results in a huge savings of time when files are
2610 :     # accessed multiple times (as in when a bunch of sims are requested).
2611 :     #
2612 :    
2613 :    
2614 :     my $fcache = $self->cached("_n2file");
2615 :    
2616 :     my $fname;
2617 :     if (defined($fname = $fcache->{$fileno}))
2618 :     {
2619 : parrello 1.365 return $fname;
2620 : overbeek 1.364 }
2621 : efrank 1.1
2622 :     my $rdbH = $self->db_handle;
2623 : overbeek 1.364
2624 :     my $relational_db_response = $rdbH->SQL("SELECT file FROM file_table WHERE ( fileno = $fileno )");
2625 : efrank 1.1
2626 : overbeek 1.364 if ($relational_db_response and @$relational_db_response == 1)
2627 :     {
2628 : parrello 1.365 $fname = $relational_db_response->[0]->[0];
2629 :     $fcache->{$fileno} = $fname;
2630 :     return $fname;
2631 : efrank 1.1 }
2632 :     return undef;
2633 :     }
2634 :    
2635 :    
2636 :     #=pod
2637 :     #
2638 : parrello 1.287 #=head3 openF
2639 : efrank 1.1 #
2640 :     #usage: $fig->openF($filename)
2641 :     #
2642 :     #Parts of the system rely on accessing numerous different files. The most obvious case is
2643 :     #the situation with similarities. It is important that the system be able to run in cases in
2644 :     #which an arbitrary number of files cannot be open simultaneously. This routine (with closeF) is
2645 :     #a hack to handle this. I should probably just pitch them and insist that the OS handle several
2646 :     #hundred open filehandles.
2647 :     #
2648 :     #=cut
2649 :     #
2650 :     sub openF {
2651 :     my($self,$file) = @_;
2652 :     my($fxs,$x,@fxs,$fh);
2653 :    
2654 :     $fxs = $self->cached('_openF');
2655 : parrello 1.287 if ($x = $fxs->{$file}) {
2656 :     $x->[1] = time();
2657 :     return $x->[0];
2658 : efrank 1.1 }
2659 : parrello 1.200
2660 : efrank 1.1 @fxs = keys(%$fxs);
2661 : parrello 1.287 if (defined($fh = new FileHandle "<$file")) {
2662 :     if (@fxs >= 50) {
2663 :     @fxs = sort { $fxs->{$a}->[1] <=> $fxs->{$b}->[1] } @fxs;
2664 :     $x = $fxs->{$fxs[0]};
2665 :     undef $x->[0];
2666 :     delete $fxs->{$fxs[0]};
2667 :     }
2668 :     $fxs->{$file} = [$fh,time()];
2669 :     return $fh;
2670 : efrank 1.1 }
2671 :     return undef;
2672 :     }
2673 :    
2674 :     #=pod
2675 :     #
2676 : parrello 1.287 #=head3 closeF
2677 : efrank 1.1 #
2678 :     #usage: $fig->closeF($filename)
2679 :     #
2680 :     #Parts of the system rely on accessing numerous different files. The most obvious case is
2681 :     #the situation with similarities. It is important that the system be able to run in cases in
2682 :     #which an arbitrary number of files cannot be open simultaneously. This routine (with openF) is
2683 :     #a hack to handle this. I should probably just pitch them and insist that the OS handle several
2684 :     #hundred open filehandles.
2685 :     #
2686 :     #=cut
2687 :     #
2688 :     sub closeF {
2689 :     my($self,$file) = @_;
2690 :     my($fxs,$x);
2691 :    
2692 : parrello 1.287 if (($fxs = $self->{_openF}) && ($x = $fxs->{$file})) {
2693 :     undef $x->[0];
2694 :     delete $fxs->{$file};
2695 : efrank 1.1 }
2696 :     }
2697 :    
2698 : parrello 1.287 =head3 ec_name
2699 :    
2700 :     C<< my $enzymatic_function = $fig->ec_name($ec); >>
2701 : efrank 1.1
2702 : parrello 1.287 Returns the enzymatic name corresponding to the specified enzyme code.
2703 : efrank 1.1
2704 : parrello 1.287 =over 4
2705 :    
2706 :     =item ec
2707 : efrank 1.1
2708 : parrello 1.287 Code number for the enzyme whose name is desired. The code number is actually
2709 :     a string of digits and periods (e.g. C<1.2.50.6>).
2710 :    
2711 :     =item RETURN
2712 :    
2713 :     Returns the name of the enzyme specified by the indicated code, or a null string
2714 :     if the code is not found in the database.
2715 :    
2716 :     =back
2717 : efrank 1.1
2718 :     =cut
2719 :    
2720 :     sub ec_name {
2721 :     my($self,$ec) = @_;
2722 :    
2723 :     ($ec =~ /^\d+\.\d+\.\d+\.\d+$/) || return "";
2724 :     my $rdbH = $self->db_handle;
2725 :     my $relational_db_response = $rdbH->SQL("SELECT name FROM ec_names WHERE ( ec = \'$ec\' )");
2726 :    
2727 :     return (@$relational_db_response == 1) ? $relational_db_response->[0]->[0] : "";
2728 :     return "";
2729 :     }
2730 :    
2731 : parrello 1.287 =head3 all_roles
2732 : efrank 1.1
2733 : parrello 1.287 C<< my @roles = $fig->all_roles; >>
2734 : efrank 1.1
2735 : parrello 1.287 Return a list of the known roles. Currently, this is a list of the enzyme codes and names.
2736 : efrank 1.1
2737 : parrello 1.287 The return value is a list of list references. Each element of the big list contains an
2738 :     enzyme code (EC) followed by the enzymatic name.
2739 : efrank 1.1
2740 :     =cut
2741 :    
2742 :     sub all_roles {
2743 :     my($self) = @_;
2744 :    
2745 :     my $rdbH = $self->db_handle;
2746 :     my $relational_db_response = $rdbH->SQL("SELECT ec,name FROM ec_names");
2747 :    
2748 :     return @$relational_db_response;
2749 :     }
2750 :    
2751 : parrello 1.287 =head3 expand_ec
2752 : efrank 1.1
2753 : parrello 1.287 C<< my $expanded_ec = $fig->expand_ec($ec); >>
2754 : efrank 1.1
2755 :     Expands "1.1.1.1" to "1.1.1.1 - alcohol dehydrogenase" or something like that.
2756 :    
2757 :     =cut
2758 :    
2759 :     sub expand_ec {
2760 :     my($self,$ec) = @_;
2761 :     my($name);
2762 :    
2763 :     return ($name = $self->ec_name($ec)) ? "$ec - $name" : $ec;
2764 :     }
2765 :    
2766 : parrello 1.287 =head3 clean_tmp
2767 : efrank 1.1
2768 : parrello 1.287 C<< FIG::clean_tmp(); >>
2769 : efrank 1.1
2770 : parrello 1.287 Delete temporary files more than two days old.
2771 : efrank 1.1
2772 :     We store temporary files in $FIG_Config::temp. There are specific classes of files
2773 :     that are created and should be saved for at least a few days. This routine can be
2774 :     invoked to clean out those that are over two days old.
2775 :    
2776 :     =cut
2777 :    
2778 :     sub clean_tmp {
2779 :    
2780 :     my($file);
2781 : parrello 1.287 if (opendir(TMP,"$FIG_Config::temp")) {
2782 :     # change the pattern to pick up other files that need to be cleaned up
2783 :     my @temp = grep { $_ =~ /^(Geno|tmp)/ } readdir(TMP);
2784 :     foreach $file (@temp) {
2785 :     if (-M "$FIG_Config::temp/$file" > 2) {
2786 :     unlink("$FIG_Config::temp/$file");
2787 :     }
2788 :     }
2789 : efrank 1.1 }
2790 :     }
2791 :    
2792 :     ################ Routines to process genomes and genome IDs ##########################
2793 :    
2794 :    
2795 : parrello 1.287 =head3 genomes
2796 : efrank 1.1
2797 : parrello 1.287 C<< my @genome_ids = $fig->genomes($complete, $restrictions, $domain); >>
2798 : efrank 1.1
2799 : parrello 1.287 Return a list of genome IDs. If called with no parameters, all genome IDs
2800 :     in the database will be returned.
2801 : efrank 1.1
2802 :     Genomes are assigned ids of the form X.Y where X is the taxonomic id maintained by
2803 :     NCBI for the species (not the specific strain), and Y is a sequence digit assigned to
2804 :     this particular genome (as one of a set with the same genus/species). Genomes also
2805 :     have versions, but that is a separate issue.
2806 :    
2807 : parrello 1.287 =over 4
2808 :    
2809 :     =item complete
2810 :    
2811 :     TRUE if only complete genomes should be returned, else FALSE.
2812 :    
2813 :     =item restrictions
2814 :    
2815 :     TRUE if only restriction genomes should be returned, else FALSE.
2816 :    
2817 :     =item domain
2818 :    
2819 :     Name of the domain from which the genomes should be returned. Possible values are
2820 :     C<Bacteria>, C<Virus>, C<Eukaryota>, C<unknown>, C<Archaea>, and
2821 :     C<Environmental Sample>. If no domain is specified, all domains will be
2822 :     eligible.
2823 :    
2824 :     =item RETURN
2825 :    
2826 :     Returns a list of all the genome IDs with the specified characteristics.
2827 :    
2828 :     =back
2829 :    
2830 : efrank 1.1 =cut
2831 : parrello 1.320 #: Return Type @;
2832 : parrello 1.328 sub genomes :Remote :List {
2833 : golsen 1.150 my( $self, $complete, $restrictions, $domain ) = @_;
2834 : overbeek 1.13
2835 :     my $rdbH = $self->db_handle;
2836 :    
2837 :     my @where = ();
2838 : parrello 1.287 if ($complete) {
2839 :     push(@where, "( complete = \'1\' )")
2840 : overbeek 1.13 }
2841 :    
2842 : parrello 1.287 if ($restrictions) {
2843 :     push(@where, "( restrictions = \'1\' )")
2844 : overbeek 1.13 }
2845 : golsen 1.150
2846 : parrello 1.287 if ($domain) {
2847 :     push( @where, "( maindomain = '$domain' )" )
2848 : golsen 1.150 }
2849 :    
2850 : overbeek 1.13 my $relational_db_response;
2851 : parrello 1.287 if (@where > 0) {
2852 :     my $where = join(" AND ",@where);
2853 :     $relational_db_response = $rdbH->SQL("SELECT genome FROM genome where $where");
2854 :     } else {
2855 :     $relational_db_response = $rdbH->SQL("SELECT genome FROM genome");
2856 : overbeek 1.13 }
2857 :     my @genomes = sort { $a <=> $b } map { $_->[0] } @$relational_db_response;
2858 : efrank 1.1 return @genomes;
2859 :     }
2860 :    
2861 : parrello 1.287 =head3 is_complete
2862 :    
2863 :     C<< my $flag = $fig->is_complete($genome); >>
2864 :    
2865 :     Return TRUE if the genome with the specified ID is complete, else FALSE.
2866 :    
2867 :     =over 4
2868 :    
2869 :     =item genome
2870 :    
2871 :     ID of the relevant genome.
2872 :    
2873 :     =item RETURN
2874 :    
2875 :     Returns TRUE if there is a complete genome in the database with the specified ID,
2876 :     else FALSE.
2877 :    
2878 :     =back
2879 :    
2880 :     =cut
2881 :    
2882 : overbeek 1.180 sub is_complete {
2883 :     my($self,$genome) = @_;
2884 :    
2885 :     my $rdbH = $self->db_handle;
2886 :     my $relational_db_response = $rdbH->SQL("SELECT genome FROM genome where (genome = '$genome') AND (complete = '1')");
2887 :     return (@$relational_db_response == 1)
2888 : parrello 1.287 }
2889 :    
2890 :     =head3 genome_counts
2891 :    
2892 :     C<< my ($arch, $bact, $euk, $vir, $env, $unk) = $fig->genome_counts($complete); >>
2893 :    
2894 :     Count the number of genomes in each domain. If I<$complete> is TRUE, only complete
2895 :     genomes will be included in the counts.
2896 :    
2897 :     =over 4
2898 :    
2899 :     =item complete
2900 :    
2901 :     TRUE if only complete genomes are to be counted, FALSE if all genomes are to be
2902 :     counted
2903 :    
2904 :     =item RETURN
2905 :    
2906 :     A six-element list containing the number of genomes in each of six categories--
2907 :     Archaea, Bacteria, Eukaryota, Viral, Environmental, and Unknown, respectively.
2908 :    
2909 :     =back
2910 :    
2911 :     =cut
2912 : golsen 1.150
2913 : efrank 1.2 sub genome_counts {
2914 : overbeek 1.13 my($self,$complete) = @_;
2915 :     my($x,$relational_db_response);
2916 : efrank 1.2
2917 : overbeek 1.13 my $rdbH = $self->db_handle;
2918 :    
2919 : parrello 1.287 if ($complete) {
2920 :     $relational_db_response = $rdbH->SQL("SELECT genome, maindomain FROM genome where complete = '1'");
2921 :     } else {
2922 :     $relational_db_response = $rdbH->SQL("SELECT genome,maindomain FROM genome");
2923 : overbeek 1.13 }
2924 :    
2925 : gdpusch 1.107 my ($arch, $bact, $euk, $vir, $env, $unk) = (0, 0, 0, 0, 0, 0);
2926 : parrello 1.287 if (@$relational_db_response > 0) {
2927 :     foreach $x (@$relational_db_response) {
2928 :     if ($x->[1] =~ /^archaea/i) { ++$arch }
2929 :     elsif ($x->[1] =~ /^bacter/i) { ++$bact }
2930 :     elsif ($x->[1] =~ /^eukar/i) { ++$euk }
2931 :     elsif ($x->[1] =~ /^vir/i) { ++$vir }
2932 :     elsif ($x->[1] =~ /^env/i) { ++$env }
2933 :     else { ++$unk }
2934 : parrello 1.298 }
2935 : efrank 1.2 }
2936 : parrello 1.200
2937 : gdpusch 1.107 return ($arch, $bact, $euk, $vir, $env, $unk);
2938 :     }
2939 :    
2940 :    
2941 : parrello 1.287 =head3 genome_domain
2942 :    
2943 :     C<< my $domain = $fig->genome_domain($genome_id); >>
2944 :    
2945 :     Find the domain of a genome.
2946 : gdpusch 1.107
2947 : parrello 1.287 =over 4
2948 :    
2949 :     =item genome_id
2950 : gdpusch 1.107
2951 : parrello 1.287 ID of the genome whose domain is desired.
2952 : gdpusch 1.107
2953 : parrello 1.287 =item RETURN
2954 :    
2955 :     Returns the name of the genome's domain (archaea, bacteria, etc.), or C<undef> if
2956 :     the genome is not in the database.
2957 : gdpusch 1.107
2958 : parrello 1.292 =back
2959 :    
2960 : gdpusch 1.107 =cut
2961 :    
2962 :     sub genome_domain {
2963 :     my($self,$genome) = @_;
2964 :     my $relational_db_response;
2965 :     my $rdbH = $self->db_handle;
2966 : parrello 1.200
2967 : parrello 1.287 if ($genome) {
2968 :     if (($relational_db_response = $rdbH->SQL("SELECT genome,maindomain FROM genome WHERE ( genome = \'$genome\' )"))
2969 :     && (@$relational_db_response == 1)) {
2970 :     # die Dumper($relational_db_response);
2971 :     return $relational_db_response->[0]->[1];
2972 :     }
2973 : gdpusch 1.107 }
2974 :     return undef;
2975 : efrank 1.2 }
2976 :    
2977 : gdpusch 1.92
2978 : parrello 1.287 =head3 genome_pegs
2979 : gdpusch 1.92
2980 : parrello 1.287 C<< my $num_pegs = $fig->genome_pegs($genome_id); >>
2981 : gdpusch 1.92
2982 : parrello 1.287 Return the number of protein-encoding genes (PEGs) for a specified
2983 :     genome.
2984 : gdpusch 1.92
2985 : parrello 1.287 =over 4
2986 :    
2987 :     =item genome_id
2988 :    
2989 :     ID of the genome whose PEG count is desired.
2990 :    
2991 :     =item RETURN
2992 :    
2993 :     Returns the number of PEGs for the specified genome, or C<undef> if the genome
2994 :     is not indexed in the database.
2995 :    
2996 :     =back
2997 : gdpusch 1.92
2998 :     =cut
2999 :    
3000 :     sub genome_pegs {
3001 :     my($self,$genome) = @_;
3002 :     my $relational_db_response;
3003 :     my $rdbH = $self->db_handle;
3004 : parrello 1.200
3005 : parrello 1.287 if ($genome) {
3006 :     if (($relational_db_response = $rdbH->SQL("SELECT pegs FROM genome WHERE ( genome = \'$genome\' )"))
3007 :     && (@$relational_db_response == 1)) {
3008 :     return $relational_db_response->[0]->[0];
3009 :     }
3010 : gdpusch 1.92 }
3011 :     return undef;
3012 :     }
3013 :    
3014 :    
3015 : parrello 1.287 =head3 genome_rnas
3016 :    
3017 :     C<< my $num_rnas = $fig->genome_rnas($genome_id); >>
3018 :    
3019 :     Return the number of RNA-encoding genes for a genome.
3020 :     "$genome_id" is indexed in the "genome" database, and 'undef' otherwise.
3021 : efrank 1.1
3022 : parrello 1.287 =over 4
3023 :    
3024 :     =item genome_id
3025 :    
3026 :     ID of the genome whose RNA count is desired.
3027 :    
3028 :     =item RETURN
3029 : gdpusch 1.92
3030 : parrello 1.287 Returns the number of RNAs for the specified genome, or C<undef> if the genome
3031 :     is not indexed in the database.
3032 : gdpusch 1.92
3033 : parrello 1.287 =back
3034 : gdpusch 1.92
3035 :     =cut
3036 :    
3037 :     sub genome_rnas {
3038 :     my($self,$genome) = @_;
3039 :     my $relational_db_response;
3040 :     my $rdbH = $self->db_handle;
3041 : parrello 1.200
3042 : parrello 1.287 if ($genome) {
3043 :     if (($relational_db_response = $rdbH->SQL("SELECT rnas FROM genome WHERE ( genome = \'$genome\' )"))
3044 :     && (@$relational_db_response == 1)) {
3045 :     return $relational_db_response->[0]->[0];
3046 :     }
3047 : gdpusch 1.92 }
3048 :     return undef;
3049 :     }
3050 :    
3051 :    
3052 : parrello 1.287 =head3 genome_szdna
3053 :    
3054 :     usage: $szdna = $fig->genome_szdna($genome_id);
3055 :    
3056 :     Return the number of DNA base-pairs in a genome's contigs.
3057 :    
3058 :     =over 4
3059 :    
3060 :     =item genome_id
3061 :    
3062 :     ID of the genome whose base-pair count is desired.
3063 : gdpusch 1.92
3064 : parrello 1.287 =item RETURN
3065 : efrank 1.1
3066 : parrello 1.287 Returns the number of base pairs in the specified genome's contigs, or C<undef>
3067 :     if the genome is not indexed in the database.
3068 : gdpusch 1.91
3069 : parrello 1.287 =back
3070 : gdpusch 1.91
3071 :     =cut
3072 :    
3073 : gdpusch 1.92 sub genome_szdna {
3074 : gdpusch 1.91 my($self,$genome) = @_;
3075 :     my $relational_db_response;
3076 :     my $rdbH = $self->db_handle;
3077 : parrello 1.200
3078 : parrello 1.287 if ($genome) {
3079 :     if (($relational_db_response =
3080 :     $rdbH->SQL("SELECT szdna FROM genome WHERE ( genome = \'$genome\' )"))
3081 :     && (@$relational_db_response == 1)) {
3082 :    
3083 :     return $relational_db_response->[0]->[0];
3084 :    
3085 :     }
3086 : gdpusch 1.91 }
3087 :     return undef;
3088 :     }
3089 :    
3090 : parrello 1.287 =head3 genome_version
3091 : gdpusch 1.91
3092 : parrello 1.287 C<< my $version = $fig->genome_version($genome_id); >>
3093 : gdpusch 1.91
3094 : parrello 1.287 Return the version number of the specified genome.
3095 : efrank 1.1
3096 :     Versions are incremented for major updates. They are put in as major
3097 :     updates of the form 1.0, 2.0, ...
3098 :    
3099 :     Users may do local "editing" of the DNA for a genome, but when they do,
3100 :     they increment the digits to the right of the decimal. Two genomes remain
3101 : parrello 1.200 comparable only if the versions match identically. Hence, minor updating should be
3102 : efrank 1.1 committed only by the person/group responsible for updating that genome.
3103 :    
3104 :     We can, of course, identify which genes are identical between any two genomes (by matching
3105 :     the DNA or amino acid sequences). However, the basic intent of the system is to
3106 :     support editing by the main group issuing periodic major updates.
3107 :    
3108 : parrello 1.287 =over 4
3109 :    
3110 :     =item genome_id
3111 :    
3112 :     ID of the genome whose version is desired.
3113 :    
3114 :     =item RETURN
3115 :    
3116 :     Returns the version number of the specified genome, or C<undef> if the genome is not in
3117 :     the data store or no version number has been assigned.
3118 :    
3119 :     =back
3120 :    
3121 : efrank 1.1 =cut
3122 :    
3123 : parrello 1.328 sub genome_version :Scalar {
3124 : efrank 1.1 my($self,$genome) = @_;
3125 :    
3126 :     my(@tmp);
3127 :     if ((-s "$FIG_Config::organisms/$genome/VERSION") &&
3128 : parrello 1.298 (@tmp = `cat $FIG_Config::organisms/$genome/VERSION`) &&
3129 :     ($tmp[0] =~ /^(\S+)$/)) {
3130 :     return $1;
3131 : efrank 1.1 }
3132 :     return undef;
3133 :     }
3134 :    
3135 : parrello 1.287 =head3 genome_md5sum
3136 : olson 1.236
3137 : parrello 1.287 C<< my $md5sum = $fig->genome_md5sum($genome_id); >>
3138 : olson 1.236
3139 : parrello 1.287 Returns the MD5 checksum of the specified genome.
3140 : olson 1.236
3141 :     The checksum of a genome is defined as the checksum of its signature file. The signature
3142 :     file consists of tab-separated lines, one for each contig, ordered by the contig id.
3143 : parrello 1.287 Each line contains the contig ID, the length of the contig in nucleotides, and the
3144 : olson 1.236 MD5 checksum of the nucleotide data, with uppercase letters forced to lower case.
3145 :    
3146 : parrello 1.287 The checksum is indexed in the database. If you know a genome's checksum, you can use
3147 :     the L</genome_with_md5sum> method to find its ID in the database.
3148 :    
3149 :     =over 4
3150 :    
3151 :     =item genome
3152 :    
3153 :     ID of the genome whose checksum is desired.
3154 :    
3155 :     =item RETURN
3156 :    
3157 :     Returns the specified genome's checksum, or C<undef> if the genome is not in the
3158 :     database.
3159 :    
3160 :     =back
3161 : olson 1.236
3162 :     =cut
3163 :    
3164 : parrello 1.328 sub genome_md5sum :Scalar {
3165 : olson 1.236 my($self,$genome) = @_;
3166 :     my $relational_db_response;
3167 :     my $rdbH = $self->db_handle;
3168 :    
3169 : parrello 1.287 if ($genome) {
3170 :     if (($relational_db_response =
3171 :     $rdbH->SQL("SELECT md5sum FROM genome_md5sum WHERE ( genome = \'$genome\' )"))
3172 :     && (@$relational_db_response == 1)) {
3173 :     return $relational_db_response->[0]->[0];
3174 :     }
3175 : olson 1.236 }
3176 :     return undef;
3177 :     }
3178 :    
3179 : parrello 1.287 =head3 genome_with_md5sum
3180 :    
3181 :     C<< my $genome = $fig->genome_with_md5sum($cksum); >>
3182 :    
3183 :     Find a genome with the specified checksum.
3184 :    
3185 :     The MD5 checksum is computed from the content of the genome (see L</genome_md5sum>). This method
3186 :     can be used to determine if a genome already exists for a specified content.
3187 :    
3188 :     =over 4
3189 :    
3190 :     =item cksum
3191 :    
3192 :     Checksum to use for searching the genome table.
3193 : olson 1.260
3194 : parrello 1.287 =item RETURN
3195 :    
3196 :     The ID of a genome with the specified checksum, or C<undef> if no such genome exists.
3197 : olson 1.260
3198 : parrello 1.287 =back
3199 : olson 1.260
3200 :     =cut
3201 :    
3202 : parrello 1.328 sub genome_with_md5sum :Scalar {
3203 : olson 1.260 my($self,$cksum) = @_;
3204 :     my $relational_db_response;
3205 :     my $rdbH = $self->db_handle;
3206 :    
3207 : parrello 1.287 if (($relational_db_response =
3208 :     $rdbH->SQL("SELECT genome FROM genome_md5sum WHERE ( md5sum = \'$cksum\' )"))
3209 : parrello 1.298 && (@$relational_db_response == 1)) {
3210 :     return $relational_db_response->[0]->[0];
3211 : olson 1.260 }
3212 :    
3213 :     return undef;
3214 :     }
3215 :    
3216 : parrello 1.287 =head3 contig_md5sum
3217 :    
3218 :     C<< my $cksum = $fig->contig_md5sum($genome, $contig); >>
3219 :    
3220 :     Return the MD5 checksum for a contig. The MD5 checksum is computed from the content
3221 :     of the contig. This method retrieves the checksum stored in the database. The checksum
3222 :     can be compared to the checksum of an external contig as a cheap way of seeing if they
3223 :     match.
3224 :    
3225 :     =over 4
3226 :    
3227 :     =item genome
3228 :    
3229 :     ID of the genome containing the contig.
3230 :    
3231 :     =item contig
3232 :    
3233 :     ID of the relevant contig.
3234 :    
3235 :     =item RETURN
3236 :    
3237 :     Returns the checksum of the specified contig, or C<undef> if the contig is not in the
3238 :     database.
3239 :    
3240 :     =back
3241 :    
3242 :     =cut
3243 :    
3244 : parrello 1.328 sub contig_md5sum :Scalar {
3245 : olson 1.237 my($self, $genome, $contig) = @_;
3246 :     my $relational_db_response;
3247 :     my $rdbH = $self->db_handle;
3248 :    
3249 : parrello 1.287 if ($genome) {
3250 :     if (($relational_db_response =
3251 :     $rdbH->SQL(qq(SELECT md5 FROM contig_md5sums WHERE (genome = ? AND contig = ?)), undef, $genome, $contig))
3252 :     && (@$relational_db_response == 1)) {
3253 :     return $relational_db_response->[0]->[0];
3254 :     }
3255 : olson 1.237 }
3256 :     return undef;
3257 :     }
3258 :    
3259 : parrello 1.287 =head3 genus_species
3260 :    
3261 :     C<< my $gs = $fig->genus_species($genome_id); >>
3262 :    
3263 :     Return the genus, species, and possibly also the strain of a specified genome.
3264 :    
3265 :     This method converts a genome ID into a more recognizble species name. The species name
3266 :     is stored directly in the genome table of the database. Essentially, if the strain is
3267 :     present in the database, it will be returned by this method, and if it's not present,
3268 :     it won't.
3269 : efrank 1.1
3270 : parrello 1.287 =over 4
3271 :    
3272 :     =item genome_id
3273 :    
3274 :     ID of the genome whose name is desired.
3275 : efrank 1.1
3276 : parrello 1.287 =item RETURN
3277 :    
3278 :     Returns the scientific species name associated with the specified ID, or C<undef> if the
3279 :     ID is not in the database.
3280 : efrank 1.1
3281 : parrello 1.287 =back
3282 : efrank 1.1
3283 :     =cut
3284 : parrello 1.320 #: Return Type $;
3285 : parrello 1.328 sub genus_species :Scalar {
3286 : efrank 1.1 my ($self,$genome) = @_;
3287 : overbeek 1.13 my $ans;
3288 : efrank 1.1
3289 :     my $genus_species = $self->cached('_genus_species');
3290 : parrello 1.287 if (! ($ans = $genus_species->{$genome})) {
3291 :     my $rdbH = $self->db_handle;
3292 :     my $relational_db_response = $rdbH->SQL("SELECT genome,gname FROM genome");
3293 :     my $pair;
3294 :     foreach $pair (@$relational_db_response) {
3295 :     $genus_species->{$pair->[0]} = $pair->[1];
3296 :     }
3297 :     $ans = $genus_species->{$genome};
3298 : efrank 1.1 }
3299 :     return $ans;
3300 :     }
3301 :    
3302 : parrello 1.287 =head3 org_of
3303 :    
3304 :     C<< my $org = $fig->org_of($prot_id); >>
3305 :    
3306 :     Return the genus/species name of the organism containing a protein. Note that in this context
3307 :     I<protein> is not a certain string of amino acids but a protein encoding region on a specific
3308 :     contig.
3309 :    
3310 :     For a FIG protein ID (e.g. C<fig|134537.1.peg.123>), the organism and strain
3311 :     information is always available. In the case of external proteins, we can usually
3312 :     determine an organism, but not anything more precise than genus/species (and
3313 :     often not that). When the organism name is not present, a null string is returned.
3314 :    
3315 :     =over 4
3316 :    
3317 :     =item prot_id
3318 : efrank 1.1
3319 : parrello 1.287 Protein or feature ID.
3320 : efrank 1.1
3321 : parrello 1.287 =item RETURN
3322 :    
3323 :     Returns the displayable scientific name (genus, species, and strain) of the organism containing
3324 :     the identified PEG. If the name is not available, returns a null string. If the PEG is not found,
3325 :     returns C<undef>.
3326 : efrank 1.1
3327 : parrello 1.287 =back
3328 : efrank 1.1
3329 :     =cut
3330 :    
3331 :     sub org_of {
3332 :     my($self,$prot_id) = @_;
3333 :     my $relational_db_response;
3334 :     my $rdbH = $self->db_handle;
3335 :    
3336 : parrello 1.287 if ($prot_id =~ /^fig\|/) {
3337 :     return $self->is_deleted_fid( $prot_id) ? undef
3338 :     : $self->genus_species( $self->genome_of( $prot_id ) ) || "";
3339 : efrank 1.1 }
3340 :    
3341 : parrello 1.287 if (($relational_db_response =
3342 :     $rdbH->SQL("SELECT org FROM external_orgs WHERE ( prot = \'$prot_id\' )")) &&
3343 :     (@$relational_db_response >= 1)) {
3344 :     $relational_db_response->[0]->[0] =~ s/^\d+://;
3345 :     return $relational_db_response->[0]->[0];
3346 : efrank 1.1 }
3347 :     return "";
3348 :     }
3349 :    
3350 : parrello 1.287 =head3 genus_species_domain
3351 :    
3352 :     C<< my ($gs, $domain) = $fig->genus_species_domain($genome_id); >>
3353 :    
3354 :     Returns a genome's genus and species (and strain if that has been properly
3355 :     recorded) in a printable form, along with its domain. This method is similar
3356 :     to L</genus_species>, except it also returns the domain name (archaea,
3357 :     bacteria, etc.).
3358 :    
3359 :     =over 4
3360 :    
3361 :     =item genome_id
3362 :    
3363 :     ID of the genome whose species and domain information is desired.
3364 : golsen 1.130
3365 : parrello 1.287 =item RETURN
3366 : golsen 1.130
3367 : parrello 1.287 Returns a two-element list. The first element is the species name and the
3368 :     second is the domain name.
3369 : golsen 1.130
3370 : parrello 1.287 =back
3371 : golsen 1.130
3372 :     =cut
3373 :    
3374 :     sub genus_species_domain {
3375 :     my ($self, $genome) = @_;
3376 :    
3377 :     my $genus_species_domain = $self->cached('_genus_species_domain');
3378 : parrello 1.287 if ( ! $genus_species_domain->{ $genome } ) {
3379 :     my $rdbH = $self->db_handle;
3380 :     my $relational_db_response = $rdbH->SQL("SELECT genome,gname,maindomain FROM genome");
3381 :     my $triple;
3382 :     foreach $triple ( @$relational_db_response ) {
3383 :     $genus_species_domain->{ $triple->[0] } = [ $triple->[1], $triple->[2] ];
3384 :     }
3385 : golsen 1.130 }
3386 :     my $gsdref = $genus_species_domain->{ $genome };
3387 :     return $gsdref ? @$gsdref : ( "", "" );
3388 :     }
3389 :    
3390 : parrello 1.287 =head3 domain_color
3391 :    
3392 :     C<< my $web_color = FIG::domain_color($domain); >>
3393 :    
3394 :     Return the web color string associated with a specified domain. The colors are
3395 :     extremely subtle (86% luminance), so they absolutely require a black background.
3396 :     Archaea are slightly cyan, bacteria are slightly magenta, eukaryota are slightly
3397 :     yellow, viruses are slightly silver, environmental samples are slightly gray,
3398 :     and unknown or invalid domains are pure white.
3399 :    
3400 :     =over 4
3401 :    
3402 :     =item domain
3403 :    
3404 :     Name of the domain whose color is desired.
3405 :    
3406 :     =item RETURN
3407 :    
3408 :     Returns a web color string for the specified domain (e.g. C<#FFDDFF> for
3409 :     bacteria).
3410 :    
3411 :     =back
3412 :    
3413 :     =cut
3414 : golsen 1.130
3415 :     my %domain_color = ( AR => "#DDFFFF", BA => "#FFDDFF", EU => "#FFFFDD",
3416 :     VI => "#DDDDDD", EN => "#BBBBBB" );
3417 :    
3418 :     sub domain_color {
3419 :     my ($domain) = @_;
3420 :     defined $domain || return "#FFFFFF";
3421 :     return $domain_color{ uc substr($domain, 0, 2) } || "#FFFFFF";
3422 :     }
3423 :    
3424 : parrello 1.287 =head3 org_and_color_of
3425 : golsen 1.130
3426 : parrello 1.287 C<< my ($org, $color) = $fig->org_and_domain_of($prot_id); >>
3427 : golsen 1.130
3428 : parrello 1.287 Return the best guess organism and domain html color string of an organism.
3429 :     In the case of external proteins, we can usually determine an organism, but not
3430 :     anything more precise than genus/species (and often not that).
3431 :    
3432 :     =over 4
3433 :    
3434 :     =item prot_id
3435 :    
3436 :     Relevant protein or feature ID.
3437 :    
3438 :     =item RETURN
3439 : golsen 1.130
3440 : parrello 1.287 Returns a two-element list. The first element is the displayable organism name, and the second
3441 :     is an HTML color string based on the domain (see L</domain_color>).
3442 : golsen 1.130
3443 : parrello 1.287 =back
3444 : golsen 1.130
3445 :     =cut
3446 :    
3447 :     sub org_and_color_of {
3448 :     my($self,$prot_id) = @_;
3449 :     my $relational_db_response;
3450 :     my $rdbH = $self->db_handle;
3451 :    
3452 : parrello 1.287 if ($prot_id =~ /^fig\|/) {
3453 :     my( $gs, $domain ) = $self->genus_species_domain($self->genome_of($prot_id));
3454 :     return ( $gs, domain_color( $domain ) );
3455 : golsen 1.130 }
3456 :    
3457 : parrello 1.287 if (($relational_db_response =
3458 :     $rdbH->SQL("SELECT org FROM external_orgs WHERE ( prot = \'$prot_id\' )")) &&
3459 :     (@$relational_db_response >= 1)) {
3460 :     return ($relational_db_response->[0]->[0], "#FFFFFF");
3461 : golsen 1.130 }
3462 :     return ("", "#FFFFFF");
3463 :     }
3464 :    
3465 : redwards 1.310 =head3 partial_genus_matching
3466 :    
3467 :     Return a list of genome IDs that match a partial genus.
3468 :    
3469 : 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)
3470 : redwards 1.310
3471 :     =cut
3472 :    
3473 :     sub partial_genus_matching {
3474 : redwards 1.311 my ($self, $gen, $complete)=@_;
3475 :     return grep {$self->genus_species($_) =~ /$gen/i} $self->genomes($complete);
3476 : redwards 1.310 }
3477 :    
3478 :    
3479 : parrello 1.287 =head3 abbrev
3480 :    
3481 :     C<< my $abbreviated_name = FIG::abbrev($genome_name); >>
3482 : golsen 1.130
3483 : parrello 1.287 or
3484 : efrank 1.1
3485 : parrello 1.287 C<< my $abbreviated_name = $fig->abbrev($genome_name); >>
3486 : efrank 1.1
3487 : parrello 1.287 Abbreviate a genome name to 10 characters or less.
3488 : efrank 1.1
3489 :     For alignments and such, it is very useful to be able to produce an abbreviation of genus/species.
3490 :     That's what this does. Note that multiple genus/species might reduce to the same abbreviation, so
3491 :     be careful (disambiguate them, if you must).
3492 :    
3493 : parrello 1.287 The abbreviation is formed from the first three letters of the species name followed by the
3494 :     first three letters of the genus name followed by the first three letters of the species name and
3495 :     then the next four nonblank characters.
3496 :    
3497 :     =over 4
3498 :    
3499 :     =item genome_name
3500 :    
3501 :     The name to abbreviate.
3502 :    
3503 :     =item RETURN
3504 :    
3505 :     An abbreviated version of the specified name.
3506 :    
3507 :     =back
3508 :    
3509 : efrank 1.1 =cut
3510 :    
3511 : parrello 1.328 sub abbrev :Scalar {
3512 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3513 : efrank 1.1 my($genome_name) = @_;
3514 :    
3515 :     $genome_name =~ s/^(\S{3})\S+/$1./;
3516 : overbeek 1.198 $genome_name =~ s/^(\S+)\s+(\S{3})\S+/$1$2./;
3517 : overbeek 1.257 $genome_name =~ s/ //g;
3518 : parrello 1.287 if (length($genome_name) > 10) {
3519 : parrello 1.298 $genome_name = substr($genome_name,0,10);
3520 : efrank 1.1 }
3521 :     return $genome_name;
3522 :     }
3523 :    
3524 :     ################ Routines to process Features and Feature IDs ##########################
3525 :    
3526 : parrello 1.287 =head3 ftype
3527 :    
3528 :     C<< my $type = FIG::ftype($fid); >>
3529 : efrank 1.1
3530 : parrello 1.287 or
3531 : efrank 1.1
3532 : parrello 1.287 C<< my $type = $fig->ftype($fid); >>
3533 : efrank 1.1
3534 :     Returns the type of a feature, given the feature ID. This just amounts
3535 : parrello 1.287 to lifting it out of the feature ID, since features have IDs of the form
3536 : efrank 1.1
3537 : parrello 1.287 fig|x.y.f.n
3538 : efrank 1.1
3539 :     where
3540 :     x.y is the genome ID
3541 : parrello 1.287 f is the type of feature
3542 : efrank 1.1 n is an integer that is unique within the genome/type
3543 :    
3544 : parrello 1.287 =over 4
3545 :    
3546 :     =item fid
3547 :    
3548 :     FIG ID of the feature whose type is desired.
3549 :    
3550 :     =item RETURN
3551 :    
3552 :     Returns the feature type (e.g. C<peg>, C<rna>, C<pi>, or C<pp>), or C<undef> if the
3553 :     feature ID is not a FIG ID.
3554 :    
3555 :     =back
3556 :    
3557 : efrank 1.1 =cut
3558 :    
3559 :     sub ftype {
3560 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3561 : efrank 1.1 my($feature_id) = @_;
3562 :    
3563 : parrello 1.287 if ($feature_id =~ /^fig\|\d+\.\d+\.([^\.]+)/) {
3564 : parrello 1.365 return $1;
3565 : efrank 1.1 }
3566 :     return undef;
3567 :     }
3568 :    
3569 : parrello 1.287 =head3 genome_of
3570 :    
3571 :     C<< my $genome_id = $fig->genome_of($fid); >>
3572 :    
3573 :     or
3574 :    
3575 :     C<< my $genome_id = FIG::genome_of($fid); >>
3576 :    
3577 :     Return the genome ID from a feature ID.
3578 : efrank 1.1
3579 : parrello 1.287 =over 4
3580 :    
3581 :     =item fid
3582 :    
3583 :     ID of the feature whose genome ID is desired.
3584 :    
3585 :     =item RETURN
3586 : efrank 1.1
3587 : parrello 1.287 If the feature ID is a FIG ID, returns the genome ID embedded inside it; otherwise, it
3588 :     returns C<undef>.
3589 : efrank 1.1
3590 : parrello 1.287 =back
3591 : efrank 1.1
3592 :     =cut
3593 :    
3594 :    
3595 : parrello 1.328 sub genome_of :Scalar {
3596 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3597 : parrello 1.200 my $prot_id = (@_ == 1) ? $_[0] : $_[1];
3598 : efrank 1.1
3599 :     if ($prot_id =~ /^fig\|(\d+\.\d+)/) { return $1; }
3600 :     return undef;
3601 :     }
3602 :    
3603 : parrello 1.287 =head3 genome_and_peg_of
3604 :    
3605 :     C<< my ($genome_id, $peg_number = FIG::genome_and_peg_of($fid); >>
3606 :    
3607 :     C<< my ($genome_id, $peg_number = $fig->genome_and_peg_of($fid); >>
3608 : olson 1.96
3609 : parrello 1.287 Return the genome ID and peg number from a feature ID.
3610 : olson 1.96
3611 : parrello 1.287 =over 4
3612 :    
3613 :     =item prot_id
3614 :    
3615 :     ID of the feature whose genome and PEG number as desired.
3616 :    
3617 :     =item RETURN
3618 :    
3619 :     Returns the genome ID and peg number associated with a feature if the feature
3620 :     is represented by a FIG ID, else C<undef>.
3621 :    
3622 :     =back
3623 : olson 1.96
3624 :     =cut
3625 :    
3626 :     sub genome_and_peg_of {
3627 : olson 1.111 shift if UNIVERSAL::isa($_[0],__PACKAGE__);
3628 : parrello 1.200 my $prot_id = (@_ == 1) ? $_[0] : $_[1];
3629 : olson 1.96
3630 : parrello 1.287 if ($prot_id =~ /^fig\|(\d+\.\d+)\.peg\.(\d+)/) {
3631 : parrello 1.298 return ($1, $2);
3632 : olson 1.96 }
3633 :     return undef;
3634 :     }
3635 :    
3636 : parrello 1.287 =head3 by_fig_id
3637 :    
3638 :     C<< my @sorted_by_fig_id = sort { FIG::by_fig_id($a,$b) } @fig_ids; >>
3639 :    
3640 :     Compare two feature IDs.
3641 :    
3642 :     This function is designed to assist in sorting features by ID. The sort is by
3643 :     genome ID followed by feature type and then feature number.
3644 :    
3645 :     =over 4
3646 :    
3647 :     =item a
3648 : efrank 1.1
3649 : parrello 1.287 First feature ID.
3650 : efrank 1.1
3651 : parrello 1.287 =item b
3652 : efrank 1.1
3653 : parrello 1.287 Second feature ID.
3654 :    
3655 :     =item RETURN
3656 :    
3657 :     Returns a negative number if the first parameter is smaller, zero if both parameters
3658 :     are equal, and a positive number if the first parameter is greater.
3659 :    
3660 :     =back
3661 : efrank 1.1
3662 :     =cut
3663 :    
3664 :     sub by_fig_id {
3665 :     my($a,$b) = @_;
3666 :     my($g1,$g2,$t1,$t2,$n1,$n2);
3667 :     if (($a =~ /^fig\|(\d+\.\d+).([^\.]+)\.(\d+)$/) && (($g1,$t1,$n1) = ($1,$2,$3)) &&
3668 : parrello 1.298 ($b =~ /^fig\|(\d+\.\d+).([^\.]+)\.(\d+)$/) && (($g2,$t2,$n2) = ($1,$2,$3))) {
3669 :     ($g1 <=> $g2) or ($t1 cmp $t2) or ($n1 <=> $n2);
3670 : parrello 1.287 } else {
3671 : parrello 1.298 $a cmp $b;
3672 : efrank 1.1 }
3673 :     }
3674 :    
3675 : olson 1.357 =head3 by_genome_id
3676 :    
3677 :     C<< my @sorted_by_genome_id = sort { FIG::by_genome_id($a,$b) } @genome_ids; >>
3678 :    
3679 :     Compare two genome IDs.
3680 :    
3681 :     This function is designed to assist in sorting genomes by ID.
3682 :    
3683 :     =over 4
3684 :    
3685 :     =item a
3686 :    
3687 :     First genome ID.
3688 :    
3689 :     =item b
3690 :    
3691 :     Second genome ID.
3692 :    
3693 :     =item RETURN
3694 :    
3695 :     Returns a negative number if the first parameter is smaller, zero if both parameters
3696 :     are equal, and a positive number if the first parameter is greater.
3697 :    
3698 :     =back
3699 :    
3700 :     =cut
3701 :    
3702 :     sub by_genome_id {
3703 :     my($a,$b) = @_;
3704 :     my($g1,$g2,$s1, $s2);
3705 :     if (($a =~ /^(\d+)\.(\d+)$/) && (($g1, $s1) = ($1, $2)) &&
3706 : parrello 1.365 ($b =~ /^(\d+)\.(\d+)$/) && (($g2, $s2) = ($1, $2))) {
3707 : olson 1.357 ($g1 <=> $g2) or ($s1 <=> $s2);
3708 :     } else {
3709 :     $a cmp $b;
3710 :     }
3711 :     }
3712 :    
3713 : parrello 1.287 =head3 genes_in_region
3714 : efrank 1.1
3715 : parrello 1.287 C<< my ($features_in_region, $beg1, $end1) = $fig->genes_in_region($genome, $contig, $beg, $end, size_limit); >>
3716 : efrank 1.1
3717 : parrello 1.287 Locate features that overlap a specified region of a contig. This includes features that begin or end
3718 :     outside that region, just so long as some part of the feature can be found in the region of interest.
3719 : efrank 1.1
3720 :     It is often important to be able to find the genes that occur in a specific region on
3721 :     a chromosome. This routine is designed to provide this information. It returns all genes
3722 : parrello 1.287 that overlap positions from I<$beg> through I<$end> in the specified contig.
3723 :    
3724 :     The I<$size_limit> parameter limits the search process. It is presumed that no features are longer than the
3725 :     specified size limit. A shorter size limit means you'll miss some features; a longer size limit significantly
3726 :     slows the search process. For prokaryotes, a value of C<10000> (the default) seems to work best.
3727 :    
3728 :     =over 4
3729 :    
3730 :     =item genome
3731 :    
3732 :     ID of the genome containing the relevant contig.
3733 :    
3734 :     =item contig
3735 :    
3736 :     ID of the relevant contig.
3737 :    
3738 :     =item beg
3739 :    
3740 :     Position of the first base pair in the region of interest.
3741 :    
3742 :     =item end
3743 :    
3744 :     Position of the last base pair in the region of interest.
3745 :    
3746 :     =item size_limit
3747 :    
3748 :     Maximum allowable size for a feature. If omitted, C<10000> is assumed.
3749 :    
3750 :     =item RETURN
3751 : efrank 1.1
3752 : parrello 1.287 Returns a three-element list. The first element is a reference to a list of the feature IDs found. The second
3753 :     element is the position of the leftmost base pair in any feature found. This may be well before the region of
3754 :     interest begins or it could be somewhere inside. The third element is the position of the rightmost base pair
3755 :     in any feature found. Again, this can be somewhere inside the region or it could be well to the right of it.
3756 :    
3757 :     =back
3758 : efrank 1.1
3759 :     =cut
3760 : parrello 1.213 #: Return Type @;
3761 : efrank 1.1 sub genes_in_region {
3762 : parrello 1.287 my($self, $genome, $contig, $beg, $end, $pad) = @_;
3763 :     if (!defined $pad) { $pad = 10000; }
3764 : efrank 1.1 my($x,$relational_db_response,$feature_id,$b1,$e1,@feat,@tmp,$l,$u);
3765 :    
3766 :     my $rdbH = $self->db_handle;
3767 :    
3768 : parrello 1.200 my $minV = $beg - $pad;
3769 : efrank 1.1 my $maxV = $end + $pad;
3770 : parrello 1.287 if (($relational_db_response = $rdbH->SQL("SELECT id FROM features "
3771 :     . " WHERE ( minloc > $minV ) AND ( minloc < $maxV ) AND ( maxloc < $maxV) AND "
3772 :     . " ( genome = \'$genome\' ) AND ( contig = \'$contig\' );")) &&
3773 :     (@$relational_db_response >= 1)) {
3774 :     @tmp = sort { ($a->[1] cmp $b->[1]) or (($a->[2]+$a->[3]) <=> ($b->[2]+$b->[3])) }
3775 :     map { $feature_id = $_->[0]; $x = $self->feature_location($feature_id); $x ? [$feature_id,&boundaries_of($x)] : ()
3776 :     } @$relational_db_response;
3777 : efrank 1.1
3778 :    
3779 : parrello 1.287 ($l,$u) = (10000000000,0);
3780 :     foreach $x (@tmp)
3781 :     {
3782 :     ($feature_id,undef,$b1,$e1) = @$x;
3783 :     if (&between($beg,&min($b1,$e1),$end) || &between(&min($b1,$e1),$beg,&max($b1,$e1)))
3784 :     {
3785 :     if (! $self->is_deleted_fid($feature_id))
3786 :     {
3787 :     push(@feat,$feature_id);
3788 :     $l = &min($l,&min($b1,$e1));
3789 :     $u = &max($u,&max($b1,$e1));
3790 :     }
3791 :     }
3792 :     }
3793 :     (@feat <= 0) || return ([@feat],$l,$u);
3794 : efrank 1.1 }
3795 :     return ([],$l,$u);
3796 :     }
3797 :    
3798 : golsen 1.141
3799 :     #=============================================================================
3800 :     # Using the following version is better, but it brings out a very annoying
3801 :     # issue with some genomes. It already exists in the current code (above)
3802 :     # for some genes in some genomes. For example, visit fig|70601.1.peg.1.
3803 :     # This is true for any genome that has a feature that crosses the origin.
3804 :     # The root of the problem lies in boundaries_of. I am working on a fix that
3805 :     # replaces boundaries_of with a more sophisticated function. When it is
3806 :     # all done, genes_in_retion should behave as desired. -- GJO, Aug. 22, 2004
3807 :     #=============================================================================
3808 : parrello 1.200 #
3809 : golsen 1.141 # =pod
3810 : parrello 1.200 #
3811 : parrello 1.287 # =head3 genes_in_region
3812 : parrello 1.200 #
3813 : golsen 1.141 # usage: ( $features_in_region, $min_coord, $max_coord )
3814 :     # = $fig->genes_in_region( $genome, $contig, $beg, $end )
3815 : parrello 1.200 #
3816 : golsen 1.141 # It is often important to be able to find the genes that occur in a specific
3817 :     # region on a chromosome. This routine is designed to provide this information.
3818 :     # It returns all genes that overlap the region ( $genome, $contig, $beg, $end ).
3819 :     # $min_coord is set to the minimum coordinate of the returned genes (which may
3820 :     # preceed the given region), and $max_coord the maximum coordinate. Because
3821 :     # the database is indexed by the leftmost and rightmost coordinates of each
3822 :     # feature, the function makes no assumption about the length of the feature, but
3823 :     # it can (and probably will) miss features spanning multiple contigs.
3824 : parrello 1.200 #
3825 : golsen 1.141 # =cut
3826 : parrello 1.200 #
3827 :     #
3828 : golsen 1.141 # sub genes_in_region {
3829 :     # my ( $self, $genome, $contig, $beg, $end ) = @_;
3830 :     # my ( $x, $db_response, $feature_id, $b1, $e1, @tmp, @bounds );
3831 :     # my ( $min_coord, $max_coord );
3832 : parrello 1.200 #
3833 : golsen 1.141 # my @features = ();
3834 :     # my $rdbH = $self->db_handle;
3835 : parrello 1.200 #
3836 : golsen 1.141 # if ( ( $db_response = $rdbH->SQL( "SELECT id
3837 :     # FROM features
3838 :     # WHERE ( contig = '$contig' )
3839 :     # AND ( genome = '$genome' )
3840 : parrello 1.200 # AND ( minloc <= $end )
3841 : golsen 1.141 # AND ( maxloc >= $beg );"
3842 :     # )
3843 :     # )
3844 : parrello 1.365 # && ( @$db_response > 0 )
3845 : golsen 1.141 # )
3846 :     # {
3847 :     # # The sort is unnecessary, but provides a consistent ordering
3848 : parrello 1.200 #
3849 : parrello 1.365 # @tmp = sort { ( $a->[1] cmp $b->[1] ) # contig
3850 :     # || ( ($a->[2] + $a->[3] ) <=> ( $b->[2] + $b->[3] ) ) # midpoint
3851 : golsen 1.141 # }
3852 : parrello 1.365 # map { $feature_id = $_->[0];
3853 :     # ( ( ! $self->is_deleted_fid( $feature_id ) ) # not deleted
3854 : golsen 1.141 # && ( $x = $self->feature_location( $feature_id ) ) # and has location
3855 :     # && ( ( @bounds = boundaries_of( $x ) ) == 3 ) # and has bounds
3856 : parrello 1.200 # ) ? [ $feature_id, @bounds ] : ()
3857 : golsen 1.141 # } @$db_response;
3858 : parrello 1.200 #
3859 : parrello 1.365 # ( $min_coord, $max_coord ) = ( 10000000000, 0 );
3860 : parrello 1.200 #
3861 : parrello 1.365 # foreach $x ( @tmp )
3862 :     # {
3863 :     # ( $feature_id, undef, $b1, $e1 ) = @$x;
3864 :     # push @features, $feature_id;
3865 :     # my ( $min, $max ) = ( $b1 <= $e1 ) ? ( $b1, $e1 ) : ( $e1, $b1 );
3866 :     # ( $min_coord <= $min ) || ( $min_coord = $min );
3867 :     # ( $max_coord >= $max ) || ( $max_coord = $max );
3868 :     # }
3869 : golsen 1.141 # }
3870 : parrello 1.200 #
3871 : golsen 1.141 # return ( @features ) ? ( [ @features ], $min_coord, $max_coord )
3872 :     # : ( [], undef, undef );
3873 :     # }
3874 :    
3875 :     # These will be part of the fix to genes_in_region. -- GJO
3876 :    
3877 : parrello 1.287 =head3 regions_spanned
3878 :    
3879 :     C<< my ( [ $contig, $beg, $end ], ... ) = $fig->regions_spanned( $loc ); >>
3880 : golsen 1.141
3881 : parrello 1.287 or
3882 : golsen 1.141
3883 : parrello 1.287 C<< my ( [ $contig, $beg, $end ], ... ) = FIG::regions_spanned( $loc ); >>
3884 : golsen 1.141
3885 :     The location of a feature in a scalar context is
3886 :    
3887 : parrello 1.287 contig_b1_e1, contig_b2_e2, ... [one contig_b_e for each segment]
3888 :    
3889 :     This routine takes as input a scalar location in the above form
3890 :     and reduces it to one or more regions spanned by the gene. This
3891 :     involves combining regions in the location string that are on the
3892 :     same contig and going in the same direction. Unlike L</boundaries_of>,
3893 :     which returns one region in which the entire gene can be found,
3894 :     B<regions_spanned> handles wrapping through the orgin, features
3895 :     split over contigs and exons that are not ordered nicely along
3896 :     the chromosome (ugly but true).
3897 : golsen 1.141
3898 : parrello 1.287 =over 4
3899 :    
3900 :     =item loc
3901 :    
3902 :     The location string for a feature.
3903 :    
3904 :     =item RETURN
3905 :    
3906 :     Returns a list of list references. Each inner list contains a contig ID, a starting
3907 :     position, and an ending position. The starting position may be numerically greater
3908 :     than the ending position (which indicates a backward-traveling gene). It is
3909 :     guaranteed that the entire feature is covered by the regions in the list.
3910 :    
3911 :     =back
3912 : golsen 1.141
3913 :     =cut
3914 :    
3915 :     sub regions_spanned {
3916 :     shift if UNIVERSAL::isa( $_[0], __PACKAGE__ );
3917 :     my( $location ) = ( @_ == 1 ) ? $_[0] : $_[1];
3918 :     defined( $location ) || return undef;
3919 :    
3920 :     my @regions = ();
3921 :    
3922 :     my ( $cur_contig, $cur_beg, $cur_end, $cur_dir );
3923 :     my ( $contig, $beg, $end, $dir );
3924 :     my @segs = split( /\s*,\s*/, $location ); # should not have space, but ...
3925 :     @segs || return undef;
3926 :    
3927 :     # Process the first segment
3928 :    
3929 :     my $seg = shift @segs;
3930 :     ( ( $cur_contig, $cur_beg, $cur_end ) = ( $seg =~ /^(\S+)_(\d+)_\d+$/ ) )
3931 :     || return undef;
3932 :     $cur_dir = ( $cur_end >= $cur_beg ) ? 1 : -1;
3933 :    
3934 :     foreach $seg ( @segs ) {
3935 : parrello 1.298 ( ( $contig, $beg, $end ) = ( $seg =~ /^(\S+)_(\d+)_\d+$/ ) ) || next;
3936 :     $dir = ( $end >= $beg ) ? 1 : -1;
3937 : golsen 1.141
3938 : parrello 1.298 # Is this a continuation? Update end
3939 : golsen 1.141
3940 : parrello 1.298 if ( ( $contig eq $cur_contig )
3941 :     && ( $dir == $cur_dir )
3942 :     && ( ( ( $dir > 0 ) && ( $end > $cur_end ) )
3943 :     || ( ( $dir < 0 ) && ( $end < $cur_end ) ) )
3944 :     )
3945 :     {
3946 :     $cur_end = $end;
3947 :     }
3948 : golsen 1.141
3949 : parrello 1.298 # Not a continuation. Report previous and update current.
3950 : golsen 1.141
3951 : parrello 1.298 else
3952 :     {
3953 :     push @regions, [ $cur_contig, $cur_beg, $cur_end ];
3954 :     ( $cur_contig, $cur_beg, $cur_end, $cur_dir )
3955 :     = ( $contig, $beg, $end, $dir );
3956 :     }
3957 : golsen 1.141 }
3958 :    
3959 :     # There should alwasy be a valid, unreported region.
3960 :    
3961 :     push @regions, [ $cur_contig, $cur_beg, $cur_end ];
3962 :    
3963 :     return wantarray ? @regions : \@regions;
3964 :     }
3965 :    
3966 : parrello 1.287 =head3 filter_regions
3967 :    
3968 :     C<< my @regions = FIG::filter_regions( $contig, $min, $max, @regions ); >>
3969 :    
3970 :     or
3971 :    
3972 :     C<< my \@regions = FIG::filter_regions( $contig, $min, $max, @regions ); >>
3973 :    
3974 :     or
3975 :    
3976 :     C<< my @regions = FIG::filter_regions( $contig, $min, $max, \@regions ); >>
3977 :    
3978 :     or
3979 :    
3980 :     C<< my \@regions = FIG::filter_regions( $contig, $min, $max, \@regions ); >>
3981 :    
3982 :     Filter a list of regions to those that overlap a specified section of a
3983 :     particular contig. Region definitions correspond to those produced
3984 :     by L</regions_spanned>. That is, C<[>I<contig>C<,>I<beg>C<,>I<end>C<]>.
3985 :     In the function call, either I<$contig> or I<$min> and I<$max> can be
3986 :     undefined (permitting anything). So, for example,
3987 :    
3988 :     my @regions = FIG::filter_regions(undef, 1, 5000, $regionList);
3989 :    
3990 :     would return all regions in C<$regionList> that overlap the first
3991 :     5000 base pairs in any contig. Conversely,
3992 :    
3993 :     my @regions = FIG::filter_regions('NC_003904', undef, undef, $regionList);
3994 : golsen 1.141
3995 : parrello 1.287 would return all regions on the contig C<NC_003904>.
3996 : golsen 1.141
3997 : parrello 1.287 =over 4
3998 :    
3999 :     =item contig
4000 :    
4001 :     ID of the contig whose regions are to be passed by the filter, or C<undef>
4002 :     if the contig doesn't matter.
4003 :    
4004 :     =item min
4005 :    
4006 :     Leftmost position of the region used for filtering. Only regions which contain
4007 :     at least one base pair at or beyond this position will be passed. A value
4008 :     of C<undef> is equivalent to zero.
4009 :    
4010 :     =item max
4011 :    
4012 :     Rightmost position of the region used for filtering. Only regions which contain
4013 :     at least one base pair on or before this position will be passed. A value
4014 :     of C<undef> is equivalent to the length of the contig.
4015 :    
4016 :     =item regionList
4017 : golsen 1.141
4018 : parrello 1.287 A list of regions, or a reference to a list of regions. Each region is a
4019 :     reference to a three-element list, the first element of which is a contig
4020 :     ID, the second element of which is the start position, and the third
4021 :     element of which is the ending position. (The ending position can be
4022 :     before the starting position if the region is backward-traveling.)
4023 :    
4024 :     =item RETURN
4025 :    
4026 :     In a scalar context, returns a reference to a list of the filtered regions.
4027 :     In a list context, returns the list itself.
4028 :    
4029 :     =back
4030 : golsen 1.141
4031 :     =cut
4032 :    
4033 :     sub filter_regions {
4034 :     my ( $contig, $min, $max, @regions ) = @_;
4035 :    
4036 :     @regions || return ();
4037 :     ( ref( $regions[0] ) eq "ARRAY" ) || return undef;
4038 :    
4039 :     # Is it a region list, or a reference to a region list?
4040 :    
4041 :     if ( ref( $regions[0]->[0] ) eq "ARRAY" ) { @regions = @{ $regions[0] } }
4042 :    
4043 :     if ( ! defined( $contig ) )
4044 :     {
4045 : parrello 1.365 ( defined( $min ) && defined( $max ) ) || return undef;
4046 : golsen 1.141 }
4047 :     else # with a defined contig name, allow undefined range
4048 :     {
4049 : parrello 1.365 defined( $min ) || ( $min = 1 );
4050 :     defined( $max ) || ( $max = 1000000000 );
4051 : golsen 1.141 }
4052 :     ( $min <= $max ) || return ();
4053 :    
4054 :     my ( $c, $b, $e );
4055 :     my @filtered = grep { ( @$_ >= 3 ) # Allow extra fields?
4056 :     && ( ( $c, $b, $e ) = @$_ )
4057 :     && ( ( ! defined( $contig ) ) || ( $c eq $contig ) )
4058 :     && ( ( $e >= $b ) || ( ( $b, $e ) = ( $e, $b ) ) )
4059 :     && ( ( $b <= $max ) && ( $e >= $min ) )
4060 :     } @regions;
4061 :    
4062 :     return wantarray ? @filtered : \@filtered;
4063 :     }
4064 :    
4065 : parrello 1.287 =head3 close_genes
4066 :    
4067 :     C<< my @features = $fig->close_genes($fid, $dist); >>
4068 :    
4069 :     Return all features within a certain distance of a specified other feature.
4070 :    
4071 :     This method is a quick way to get genes that are near another gene. It calls
4072 :     L</boundaries_of> to get the boundaries of the incoming gene, then passes
4073 :     the region computed to L</genes_in_region>.
4074 :    
4075 :     So, for example, if the specified I<$dist> is 500, the method would select
4076 :     a region that extends 500 base pairs to either side of the boundaries for
4077 :     the gene I<$fid>, and pass it to C<genes_in_region> for analysis. The
4078 :     features returned would be those that overlap the selected region. Note
4079 :     that the flaws inherent in C<genes_in_region> are also inherent in this
4080 :     method: if a feature is more than 10000 base pairs long, it may not
4081 :     be caught even though it has an overlap in the specified region.
4082 :    
4083 :     =over 4
4084 :    
4085 :     =item fid
4086 :    
4087 :     ID of the relevant feature.
4088 :    
4089 :     =item dist
4090 :    
4091 :     Desired maximum distance.
4092 :    
4093 :     =item RETURN
4094 :    
4095 :     Returns a list of feature IDs for genes that overlap or are close to the boundaries
4096 :     for the specified incoming feature.
4097 :    
4098 :     =back
4099 :    
4100 :     =cut
4101 : golsen 1.141
4102 : efrank 1.1 sub close_genes {
4103 :     my($self,$fid,$dist) = @_;
4104 : parrello 1.200
4105 : mkubal 1.147 # warn "In close_genes, self=$self, fid=$fid";
4106 : parrello 1.200
4107 : efrank 1.1 my $loc = $self->feature_location($fid);
4108 :     if ($loc)
4109 :     {
4110 : parrello 1.298 my($contig,$beg,$end) = &FIG::boundaries_of($loc);
4111 :     if ($contig && $beg && $end)
4112 :     {
4113 :     my $min = &min($beg,$end) - $dist;
4114 :     my $max = &max($beg,$end) + $dist;
4115 :     my $feat;
4116 :     ($feat,undef,undef) = $self->genes_in_region(&FIG::genome_of($fid),$contig,$min,$max);
4117 :     return @$feat;
4118 :     }
4119 : efrank 1.1 }
4120 :     return ();
4121 :     }
4122 :    
4123 : parrello 1.287 =head3 adjacent_genes
4124 :    
4125 :     C<< my ($left_fid, $right_fid) = $fig->adjacent_genes($fid, $dist); >>
4126 :    
4127 :     Return the IDs of the genes immediately to the left and right of a specified
4128 :     feature.
4129 :    
4130 :     This method gets a list of the features within the specified distance of
4131 :     the incoming feature (using L</close_genes>), and then chooses the two
4132 :     closest to the feature found. If the incoming feature is on the + strand,
4133 :     these are features to the left and the right. If the incoming feature is
4134 :     on the - strand, the features will be returned in reverse order.
4135 :    
4136 :     =over 4
4137 :    
4138 :     =item fid
4139 :    
4140 :     ID of the feature whose neighbors are desired.
4141 :    
4142 :     =item dist
4143 :    
4144 :     Maximum permissible distance to the neighbors.
4145 :    
4146 :     =item RETURN
4147 :    
4148 :     Returns a two-element list containing the IDs of the features on either side
4149 :     of the incoming feature.
4150 :    
4151 :     =back
4152 :    
4153 :     =cut
4154 :    
4155 : mkubal 1.147 sub adjacent_genes
4156 :     {
4157 :     my ($self, $fid, $dist) = @_;
4158 :     my (@close, $strand, $i);
4159 : parrello 1.200
4160 : mkubal 1.147 # warn "In adjacent_genes, self=$self, fid=$fid";
4161 : parrello 1.200
4162 :    
4163 : mkubal 1.147 $strand = $self->strand_of($fid);
4164 : parrello 1.200
4165 : mkubal 1.147 $dist = $dist || 2000;
4166 :     @close = $self->close_genes($fid, $dist);
4167 :     for ($i=0; $i < @close; ++$i) { last if ($close[$i] eq $fid); }
4168 : parrello 1.200
4169 : redwards 1.157 # RAE note that if $self->strand_of($close[$i-1]) ne $strand then left/right neighbors
4170 :     # were never set! oops!
4171 : parrello 1.200
4172 : redwards 1.157 # I think the concept of Left and right is confused here. In my mind, left and right
4173 :     # are independent of strand ?? E.g. take a look at PEG fig|196600.1.peg.1806
4174 :     # this is something like
4175 :     #
4176 :     # ---> <--1805--- --1806--> <--1807-- <----
4177 :     #
4178 :     # 1805 is always the left neighbor, no?
4179 :    
4180 :     my ($left_neighbor, $right_neighbor) = ($close[$i-1], $close[$i+1]);
4181 : parrello 1.200
4182 : parrello 1.287 # if (0) # this was if ($i > 0) I just skip this whole section!
4183 :     # {
4184 : parrello 1.298 # if ($self->strand_of($close[$i-1]) eq $strand) { $left_neighbor = $close[$i-1]; }
4185 : parrello 1.287 # }
4186 :    
4187 :     if ($i < $#close)
4188 : mkubal 1.147 {
4189 : parrello 1.298 if ($self->strand_of($close[$i+1]) eq $strand) { $right_neighbor = $close[$i+1]; }
4190 : mkubal 1.147 }
4191 : parrello 1.200
4192 : parrello 1.287 # ...return genes in transcription order...
4193 :     if ($strand eq '-')
4194 : mkubal 1.147 {
4195 : parrello 1.298 ($left_neighbor, $right_neighbor) = ($right_neighbor, $left_neighbor);
4196 : mkubal 1.147 }
4197 : parrello 1.200
4198 : parrello 1.287 return ($left_neighbor, $right_neighbor) ;
4199 :     }
4200 :    
4201 :     =head3 feature_location
4202 :    
4203 :     C<< my $loc = $fig->feature_location($fid); >>
4204 :    
4205 :     or
4206 :    
4207 :     C<< my @loc = $fig->feature_location($fid);; >>
4208 :    
4209 :     Return the location of a feature. The location consists
4210 :     of a list of (contigID, begin, end) triples encoded
4211 :     as strings with an underscore delimiter. So, for example,
4212 :     C<NC_002755_100_199> indicates a location starting at position
4213 :     100 and extending through 199 on the contig C<NC_002755>. If
4214 :     the location goes backward, the start location will be higher
4215 :     than the end location (e.g. C<NC_002755_199_100>).
4216 :    
4217 :     In a scalar context, this method returns the locations as a
4218 :     comma-delimited string
4219 : parrello 1.200
4220 : parrello 1.287 NC_002755_100_199,NC_002755_210_498
4221 : mkubal 1.147
4222 : parrello 1.287 In a list context, the locations are returned as a list
4223 : efrank 1.1
4224 : parrello 1.287 (NC_002755_100_199, NC_002755_210_498)
4225 : efrank 1.1
4226 : parrello 1.287 =over 4
4227 : efrank 1.1
4228 : parrello 1.287 =item fid
4229 : efrank 1.1
4230 : parrello 1.287 ID of the feature whose location is desired.
4231 : efrank 1.1
4232 : parrello 1.287 =item RETURN
4233 : efrank 1.1