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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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