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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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