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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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