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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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