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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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