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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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