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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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