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

Annotation of /FigKernelPackages/FIG.pm

Parent Directory Parent Directory | Revision Log Revision Log


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