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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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