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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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