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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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