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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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