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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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