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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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