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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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