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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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