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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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