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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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