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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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