-
Notifications
You must be signed in to change notification settings - Fork 5
/
inparanoid.pl
executable file
·2698 lines (2540 loc) · 96.8 KB
/
inparanoid.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/perl
###############################################################################
# InParanoid version 4.1
# Copyright (C) Erik Sonnhammer, Kristoffer Forslund, Isabella Pekkari,
# Ann-Charlotte Berglund, Maido Remm, 2007
#
# This program is provided under the terms of a personal license to the recipient and may only
# be used for the recipient's own research at an academic insititution.
#
# Distribution of the results of this program must be discussed with the authors.
# For using this program in a company or for commercial purposes, a commercial license is required.
# Contact [email protected] in both cases
#
# Make sure that Perl XML libraries are installed!
#
# NOTE: This script requires blastall (NCBI BLAST) version 2.2.16 or higher, that supports
# compositional score matrix adjustment (-C2 flag).
use Data::Dumper;
use File::Basename;
use Getopt::Long;
use Bio::Seq;
use File::Copy;
use File::Temp qw/ tempfile tempdir /;
use Log::Log4perl qw(:easy);
use Cwd;
require 'Configurations/Configuration.pm';
Log::Log4perl->easy_init({
#level => $DEBUG,
level => $WARN,
layout => '%d %p> %F{1}:%L %M - %m%n',
file => ">>".$Configuration::inparanoid_log});
my $ublast = 1;
my $root_directory = getcwd || error("Please specify root directory");
## PROGRAM Path
my $kalign = $Configuration::kalign;
my $hmmconvert = $Configuration::hmmconvert;
my $hmmalign = $Configuration::hmmalign;
my $hmmbuild = $Configuration::hmmbuild;
my $hhmake = $Configuration::hhmake;
my $fasttree = $Configuration::fasttree;
my $muscle = $Configuration::muscle;
my $usearch = $Configuration::usearch;
my $segmasker = $Configuration::segmasker;
=head1 NAME
Inparanoid 4 - This is the official release that was used to build the Inparanoid 7 database.
my $usage =
" Usage: inparanoid.pl <FASTAFILE with sequences of species A> <FASTAFILE with sequences of species B> [FASTAFILE with sequences of species C]";
=cut
###############################################################################
# The program calculates orthologs between 2 datasets of proteins
# called A and B. Both datasets should be in multi-fasta file
# - Additionally, it tries to assign paralogous sequences (in-paralogs) to each
# thus forming paralogous clusters.
# - Confidence of in-paralogs is calculated in relative scale between 0-100%.
# This confidence value is dependent on how far is given sequence from the
# seed ortholog of given group
# - Confidence of groups can be calculated with bootstrapping. This is related
# to score difference between best hit and second best hit.
# - Optionally it can use a species C as outgroup.
###############################################################################
# You may need to run the following command manually to increase your
# default datasize limit: 'limit datasize 500000 kb'
###############################################################################
# Set following variables: #
###############################################################################
# What do you want the program to do? #
$run_blast = 1; # Set to 1 if you don't have the 4 BLAST output files #
# Requires 'blastall', 'formatdb' (NCBI BLAST2) #
# and parser 'blast_parser.pl' #
$blast_two_passes = 1; # Set to 1 to run 2-pass strategy #
# (strongly recommended, but slower) #
$run_inparanoid = 1;
$use_bootstrap = 0; # Use bootstrapping to estimate the confidence of orthologs#
# Needs additional programs 'seqstat.jar' and 'blast2faa.pl'
$use_outgroup = 0; # Use proteins from the third genome as an outgroup #
# Reject best-best hit if outgroup sequence is MORE #
# similar to one of the sequences #
# (by more than $outgroup_cutoff bits) #
# Define location of files and programs:
#$blastall = "blastall -VT"; #Remove -VT for blast version 2.2.12 or earlier
$blastall = "blastall"; #Add -aN to use N processors
$formatdb = "formatdb";
$seqstat = "seqstat.jar";
$blastParser = "blast_parser.pl";
$matrix = "BLOSUM62"; # Reasonable default for comparison of eukaryotes.
#$matrix = "BLOSUM45"; #(for prokaryotes),
#$matrix = "BLOSUM80"; #(orthologs within metazoa),
#$matrix = "PAM70";
#$matrix = "PAM30";
# Output options: #
$output = 0; # table_stats-format output #
$table = 0; # Print tab-delimited table of orthologs to file "table.txt" #
# Each orthologous group with all inparalogs is on one line #
$mysql_table = 1; # Print out sql tables for the web server #
# Each inparalog is on separate line #
$html = 0; # HTML-format output #
# Algorithm parameters:
# Default values should work without problems.
# MAKE SURE, however, that the score cutoff here matches what you used for BLAST!
$bitscore_cutoff = 40; # In bits. Any match below this is ignored #
$outgroup_cutoff = 50; # In bits. Outgroup sequence hit must be this many bits#
# stronger to reject best-best hit between A and B #
$conf_cutoff = 0.05; # Include in-paralogs with this confidence or better #
$group_overlap_cutoff = 0.5; # Merge groups if ortholog in one group has more #
# than this confidence in other group #
$grey_zone = 0; # This many bits signifies the difference between 2 scores #
$show_times = 0; # Show times spent for execution of each part of the program #
# (This does not work properly) #
$debug = 2; # Print debugging messages or not. Levels 0,1,2 and 4 exist #
my $seq_overlap_cutoff = 0.5
; # Match area should cover at least this much of longer sequence. Match area is defined as area from start of
# first segment to end of last segment, i.e segments 1-10 and 90-100 gives a match length of 100.
my $segment_coverage_cutoff =
0.25; # Actually matching segments must cover this much of longer sequence.
# For example, segments 1-10 and 90-100 gives a total length of 20.
###############################################################################
# No changes should be required below this line #
###############################################################################
my $fasta_seq_fileA;
my $fasta_seq_fileB;
my $fasta_seq_fileC;
my $UblastParameters;
my $sqlOutfile;
my $bothAnalyses;
#print join("\n",@ARGV);
#exit;
my $options = GetOptions ("query|q=s" => \$fasta_seq_fileA, # numeric
"db|d=s" => \$fasta_seq_fileB, # string
"outgroup|g=s" => \$fasta_seq_fileC,
"param|p=s" => \$UblastParameters,
"outfile|o=s" => \$sqlOutfile,
"b=s" => \$bothAnalyses
);
# print "both: $bothAnalyses\n";
# exit;
$ENV{CLASSPATH} = "./$seqstat" if ($use_bootstrap);
#if ( !@ARGV ) {
# print STDERR $usage;
# exit 1;
#}
#if ( ( @ARGV < 2 ) and ($run_inparanoid) ) {
# print STDERR
#"\n When \$run_inparanoid=1, at least two distinct FASTA files have to be specified.\n";
# print STDERR $usage;
# exit 1;
#}
#if ( ( !$run_blast ) and ( !$run_inparanoid ) ) {
# print STDERR "run_blast or run_inparanoid has to be set!\n";
# exit 1;
#}
# Input files:
#$fasta_seq_fileA = "$ARGV[0]";
#$fasta_seq_fileB = "$ARGV[1]";
$ARGV[0] = $fasta_seq_fileA;
$ARGV[1] = $fasta_seq_fileB;
### REMOVE '.fa' tail
$fasta_A_name = basename($fasta_seq_fileA);
$fasta_B_name = basename($fasta_seq_fileB);
$fasta_A_name =~ s/\.fa//;
$fasta_B_name =~ s/\.fa//;
if(!$sqlOutfile){
$analysis_directory = dirname($fasta_seq_fileA);
$pseudospecies = basename($analysis_directory);
}
else{
$analysis_directory = dirname($sqlOutfile);
$pseudospecies = basename($sqlOutfile);
}
print "\t saving in $analysis_directory/sqltable.$pseudospecies\n";
#exit;
$fasta_seq_fileC;
$fasta_C_name;
if ($use_outgroup){
# $fasta_seq_fileC = "$ARGV[2]";
$fasta_C_name = basename($fasta_seq_fileC);
$fasta_C_name =~ s/\.fa//;
}
# This is outgroup file
my $blast_outputAB = $analysis_directory."/".$fasta_A_name . "-" . $fasta_B_name;
my $blast_outputBA = $analysis_directory."/".$fasta_B_name . "-" . $fasta_A_name;
my $blast_outputAA = $analysis_directory."/".$fasta_A_name . "-" . $fasta_A_name;
my $blast_outputBB = $analysis_directory."/".$fasta_B_name . "-" . $fasta_B_name;
# test if we have to do simiarlity search
if(-e $blast_outputAB && -s $blast_outputAB &&
-e $blast_outputBA && -s $blast_outputBA &&
-e $blast_outputAA && -s $blast_outputAA &&
-e $blast_outputBB && -s $blast_outputBB ){
print "Similarity search files exist. Skipping...";
print "\t but we find orthologs\n" if $run_inparanoid;
$run_blast = 0;
}
# what happens if A-A and B-B produced hits, but A-B and B-A did not?
if((!-e $blast_outputAB && !-s $blast_outputAB || !-e $blast_outputBA && !-s $blast_outputBA )
&& (-e $blast_outputAA && -s $blast_outputAA &&
-e $blast_outputBB && -s $blast_outputBB) ){
print "Looks like no hits could be found. Skipping orthology detection\n";
exit 1;
}
# test if we have to do orthology prediction
if(-e "$analysis_directory/sqltable.$pseudospecies" && -s "$analysis_directory/sqltable.$pseudospecies"){
print "Orthology detection file exist. Skipping\n";
exit;
}
my ($blast_aa, $blast_ab, $blast_ba, $blast_bb) = (0);
if(!(-e $blast_outputAA && -s $blast_outputAA)){ $blast_aa = 1; }
if(!(-e $blast_outputAB && -s $blast_outputAB)){ $blast_ab = 1; }
if(!(-e $blast_outputBA && -s $blast_outputBA)){ $blast_ba = 1; }
if(!(-e $blast_outputBB && -s $blast_outputBB)){ $blast_bb = 1; }
#print "checking \n$blast_outputAB\n$blast_outputBA\n$blast_outputAA\n$blast_outputBB\n";
#print "\trun blast $run_blast\n";
#print "blastaa: $blast_aa\n"
#exit;
if ($use_outgroup) {
$blast_outputAC = $analysis_directory."/".$fasta_A_name . "-" . $fasta_C_name;
$blast_outputBC = $analysis_directory."/".$fasta_B_name . "-" . $fasta_C_name;
}
my %idA; # Name -> ID combinations for species 1
my %idB; # Name -> ID combinations for species 2
my @nameA; # ID -> Name combinations for species 1
my @nameB; # ID -> Name combinations for species 2
my @nameC;
my %scoreAB; # Hashes with pairwise BLAST scores (in bits)
my %scoreBA;
my %scoreAA;
my %scoreBB;
my @hitnAB; # 1-D arrays that keep the number of pairwise hits
my @hitnBA;
my @hitnAA;
my @hitnBB;
my @hitAB; # 2-D arrays that keep the actual matching IDs
my @hitBA;
my @hitAA;
my @hitBB;
my @besthitAB
; # IDs of best hits in other species (may contain more than one ID)
my @besthitBA
; # IDs of best hits in other species (may contain more than one ID)
my @bestscoreAB; # best match A -> B
my @bestscoreBA; # best match B -> A
my @ortoA; # IDs of ortholog candidates from species A
my @ortoB; # IDs of ortholog candidates from species B
my @ortoS; # Scores between ortoA and ortoB pairs
my @paralogsA; # List of paralog IDs in given cluster
my @paralogsB; # List of paralog IDs in given cluster
my @confPA; # Confidence values for A paralogs
my @confPB; # Confidence values for B paralogs
my @confA; # Confidence values for orthologous groups
my @confB; # Confidence values for orthologous groups
my $prev_time = 0;
$outputfile = "$analysis_directory/Output.$pseudospecies";
if ($output) {
open OUTPUT, ">$outputfile"
or warn "Could not write to OUTPUT file $filename\n";
}
#################################################
# Assign ID numbers for species A
#################################################
open A, "$fasta_seq_fileA"
or die "File A with sequences in FASTA format is missing
Usage $0 <FASTAFILE with sequences of species A> <FASTAFILE with sequences of species B> <FASTAFILE with sequences of species C>\n";
$id = 0;
while (<A>) {
if (/^\>/) {
++$id;
chomp;
s/\>//;
@tmp = split(/\s+/);
#$name = substr($tmp[0],0,25);
$name = $tmp[0];
$idA{$name} = int($id);
$nameA[$id] = $name;
}
}
close A;
$A = $id;
#print "$A sequences in file $fasta_seq_fileA\n";
DEBUG("$A sequences in file $fasta_seq_fileA");
#if ($output) {
# print OUTPUT "$A sequences in file $fasta_seq_fileA\n";
#}
if ( @ARGV >= 2 ) {
#################################################
# Assign ID numbers for species B
#################################################
open B, "$fasta_seq_fileB"
or die "File B with sequences in FASTA format is missing
Usage $0 <FASTAFILE with sequences of species A> <FASTAFILE with sequences of species B> <FASTAFILE with sequences of species C>\n";
$id = 0;
while (<B>) {
if (/^\>/) {
++$id;
chomp;
s/\>//;
@tmp = split(/\s+/);
#$name = substr($tmp[0],0,25);
$name = $tmp[0];
$idB{$name} = int($id);
$nameB[$id] = $name;
}
}
$B = $id;
# print "$B sequences in file $fasta_seq_fileB\n";
close B;
DEBUG("$B sequences in file $fasta_seq_fileB");
#if ($output) {
# print OUTPUT "$B sequences in file $fasta_seq_fileB\n";
#}
}
#################################################
# Assign ID numbers for species C (outgroup)
#################################################
if ($use_outgroup) {
open C, "$fasta_seq_fileC"
or die "File C with sequences in FASTA format is missing
Usage $0 <FASTAFILE with sequences of species A> <FASTAFILE with sequences of species B> <FASTAFILE with sequences of species C>\n";
$id = 0;
while (<C>) {
if (/^\>/) {
++$id;
chomp;
s/\>//;
@tmp = split(/\s+/);
#$name = substr($tmp[0],0,25);
$name = $tmp[0];
$idC{$name} = int($id);
$nameC[$id] = $name;
}
}
$C = $id;
#print "$C sequences in file $fasta_seq_fileC\n";
DEBUG("$C sequences in file $fasta_seq_fileC\n");
close C;
if ($output) {
print OUTPUT "$C sequences in file $fasta_seq_fileC\n";
}
}
#if ($show_times) {
( $user_time,,, ) = times;
DEBUG("Indexing sequences took %.2f seconds", ( $user_time - $prev_time ));
# printf( "Indexing sequences took %.2f seconds\n",
#( $user_time - $prev_time ) );
$prev_time = $user_time;
#}
#################################################
# Run BLAST if not done already
#################################################
if ($run_blast) {
#print
#"Trying to run BLAST now - this may take several hours ... or days in worst case!\n";
INFO("Trying to run BLAST now ($fasta_seq_fileB)!");
# print STDERR "Formatting BLAST databases\n";
if(!$ublast){
DEBUG("Formatting BLAST databases");
system("$formatdb -i $fasta_seq_fileA");
system("$formatdb -i $fasta_seq_fileB") if ( @ARGV >= 2 );
system("$formatdb -i $fasta_seq_fileC") if ($use_outgroup);
#print STDERR "Done formatting\nStarting BLAST searches...\n";
DEBUG("Done formatting. Starting BLAST searches...");
}
# Run blast only if the files do not already exist is not default.
# NOTE: you should have done this beforehand, because you probably
# want two-pass blasting anyway which is not implemented here
# this is also not adapted to use specific compositional adjustment settings
# and might not use the proper blast parser...
# Possible speedup
# 1. A -> B
# Make A' and B' that contain query sequences with hits and hits in B, only
# 2. A' -> B'
#
#if($blast_aa){
do_blast( $fasta_seq_fileA, $fasta_seq_fileA, $A, $A, $blast_outputAA );
#}
#if ( @ARGV >= 2 || ) {
#exit;
do_blast( $fasta_seq_fileA, $fasta_seq_fileB, $B, $B, $blast_outputAB ) if $blast_ab;
do_blast( $fasta_seq_fileB, $fasta_seq_fileA, $A, $A, $blast_outputBA ) if $blast_ba;
do_blast( $fasta_seq_fileB, $fasta_seq_fileB, $B, $B, $blast_outputBB ) if $blast_bb;
#}
if ($use_outgroup) {
do_blast( $fasta_seq_fileA, $fasta_seq_fileC, $A, $C, $blast_outputAC );
do_blast( $fasta_seq_fileB, $fasta_seq_fileC, $B, $C, $blast_outputBC );
}
#if ($show_times) {
( $user_time,,, ) = times;
DEBUG("BLAST searches took %.2f seconds",( $user_time - $prev_time ) );
#printf( "BLAST searches took %.2f seconds\n",
# ( $user_time - $prev_time ) );
#$prev_time = $user_time;
#}
INFO("Done BLAST searches. ");
##### EXIT HERE to split up similarity search and orthology prediction
#if(!$bothAnalyses){exit;}
exit;
} else {
INFO("No BLAST run ");
}
if ($run_inparanoid) {
INFO("Starting ortholog detection...");
print "Starting ortholog detection...\n";
#################################################
# Read in best hits from blast output file AB
#################################################
$count = 0;
DEBUG("Reading hits A->B from $blast_outputAB");
if(! -e $blast_outputAB|| ! -s $blast_outputAB){
WARN("There is not file with hits (A->B), should be $blast_outputAB");
exit;
}
open AB, "$blast_outputAB" or die "Blast output file A->B is missing ($blast_outputAB)\n";
$old_idQ = 0;
while (<AB>) {
# DEBUG($_);
chomp;
@Fld = split(/\s+/); # Get query, match and score
if ( scalar @Fld < 9 ) {
if ( $Fld[0] =~ /done/ ) {
#print STDERR "AB ok\n";
DEBUG("AB ok\n");
}
next;
}
# print "line is $_\n";
$q = $Fld[0];
$m = $Fld[1];
$idQ = $idA{$q}; # ID of query sequence
$idM = $idB{$m}; # ID of match sequence
$score = $Fld[2];
DEBUG("A-B ($q - $m : $idQ - $idM ($score))\n");
if ( !overlap_test(@Fld) ){
DEBUG("\trejected due to not overlap (".join(",",@Fld).")\n");
next;
}
# Score must be equal to or above cut-off
# print "\trejected due to not overlap\n";
if ( $score < $bitscore_cutoff ){
DEBUG("\trejected due to threshold ($q,$m,$idQ, $idM - $score < $bitscore_cutoff)\n");
next;
}
# print "\tcount: $count q: $q and oldq: $oldq\tidQ: $idQ\tidM: $idM\tq:$q\tm:$m";
if ( !$count || $q ne $oldq ) {
DEBUG("Match $m, score $score, ID for $q is missing")
if ( $debug == 2 and !( exists( $idA{$q} ) ) );
$hitnAB[ $idA{$oldq} ] = $hit
if ($count); # Record number of hits for previous query
$hit = 0;
++$count;
$oldq = $q;
}
++$hit;
DEBUG("\thitAB: set value for $idQ and $hit to ".int($idM));
$hitAB[$idQ][$hit] = int($idM);
DEBUG("\t\thitAB[$idQ][$hit] = $id\n");
$scoreAB{"$idQ:$idM"} = $score;
$scoreBA{"$idM:$idQ"} =
$bitscore_cutoff
; # Initialize mutual hit score - sometimes this is below score_cutoff
$old_idQ = $idQ;
# }
}
$hitnAB[$idQ] = $hit; # For the last query
close AB;
# print "dumper score\n";
# print Dumper %scoreBA;
#exit;
DEBUG("Read $count hits for A->B from $blast_outputAB keys(%scoreAB)");
if(!$count){
ERROR("Did not find hits in A-B (that fullfill overlap/bitscore cutoff)\n");
exit;
}
if ($output) {
print OUTPUT
"$count sequences $fasta_seq_fileA have homologs in dataset $fasta_seq_fileB\n";
}
#################################################
# Read in best hits from blast output file BA
#################################################
$count = 0;
DEBUG("Reading hits B->A from $blast_outputBA");
if(! -e $blast_outputBA|| ! -s $blast_outputBA){
WARN("There were no hits (B->A) found in $blast_outputAB");
exit;
}
open BA, "$blast_outputBA" or die "Blast output file B->A is missing\n";
$old_idQ = 0;
while (<BA>) {
chomp;
@Fld = split(/\s+/); # Get query, match and score
if ( scalar @Fld < 9 ) {
if ( $Fld[0] =~ /done/ ) {
#print STDERR "BA ok\n";
DEBUG("BA ok\n");
}
next;
}
$q = $Fld[0];
$m = $Fld[1];
$idQ = $idB{$q};
$idM = $idA{$m};
$score = $Fld[2];
DEBUG("B-A ($q - $m : $idQ - $idM ($score))\n");
if ( !overlap_test(@Fld) ){
DEBUG("\trejected due to not overlap (".join(",",@Fld).")\n");
next;
}
if ( $score < $bitscore_cutoff ){
DEBUG("\trejected due to threshold ($q,$m,$idQ, $idM - $score < $bitscore_cutoff)\n");
next;
}
if ( !$count || $q ne $oldq ) {
DEBUG("ID for $q is missing\n") if (( !exists( $idB{$q} ) ) );
print "ID for $q is missing\n" if ( $debug == 2 and ( !exists( $idB{$q} ) ) );
$hitnBA[ $idB{$oldq} ] = $hit
if ($count); # Record number of hits for previous query
$hit = 0;
++$count;
$oldq = $q;
}
++$hit;
$hitBA[$idQ][$hit] = int($idM);
DEBUG(" hitBA[$idQ][$hit] = ".int($idM));
DEBUG(" \$scoreBA{$idQ:$idM} = $score");
DEBUG(" \$scoreAB{$idM:$idQ} = $bitscore_cutoff");
# printf ("hitBA[%d][%d] = %d\n",$idQ,$hit,$idM);
$scoreBA{"$idQ:$idM"} = $score;
$scoreAB{"$idM:$idQ"} = $bitscore_cutoff
if ( $scoreAB{"$idM:$idQ"} < $bitscore_cutoff )
; # Initialize missing scores
$old_idQ = $idQ;
# }
}
$hitnBA[$idQ] = $hit; # For the last query
DEBUG(("hitnBA[%d] = %d\n",$idQ,$hit));
#printf ("hitnBA[%d] = %d\n",$idQ,$hit);
close BA;
DEBUG("Reading $count hits for B->A from $blast_outputBA");
if(!$count){
ERROR("Did not find hits in B-A (that fullfill overlap/bitscore cutoff)\n");
exit;
}
if ($output) {
print OUTPUT
"$count sequences $fasta_seq_fileB have homologs in dataset $fasta_seq_fileA\n";
}
#print Dumper %scoreAB;
#print Dumper %scoreBA;
#print Dumper @hitAB;
#print Dumper @hitBA;
#exit;
##################### Equalize AB scores and BA scores ##########################
###################################################################################################################################### Modification by Isabella 1
# I removed the time consuming all vs all search and equalize scores for all pairs where there was a hit
foreach my $key ( keys %scoreAB ) {
my ( $a, $b ) = split( ':', $key );
my $key2 = $b . ':' . $a;
# If debugg mod is 5 and the scores A-B and B-A are unequal
# the names of the two sequences and their scores are printed
if ( $scoreAB{$key} != $scoreBA{$key2} ) {
DEBUG("$nameA[$a], $nameB[$b], ".$scoreAB{$key}.", ".$scoreBA{$key2});
printf( "%-20s\t%-20s\t%d\t%d\n",
$nameA[$a], $nameB[$b], $scoreAB{$key}, $scoreBA{$key2} )
if ( $debug == 5 );
}
# Set score AB and score BA to the mean of scores AB and BA.
# The final score is saved as an integer so .5 needs to be added to avoid rounding errors
$scoreAB{$key} = $scoreBA{$key2} =
int( ( $scoreAB{$key} + $scoreBA{$key2} ) / 2.0 + .5 );
}
# For all ids for sequences from organism A
#for $a(1..$A){
#For all ids for sequences from organism B
#for $b(1..$B){
# No need to equalize score if there was no match between sequence with id $a from species A
# and sequence with id $b from species B
# next if (!$scoreAB{"$a:$b"});
# If debugg mod is 5 and the scores A-B and B-A are unequal
# the names of the two sequences and their scores are printed
# if ($scoreAB{"$a:$b"} != $scoreBA{"$b:$a"}){
# printf ("%-20s\t%-20s\t%d\t%d\n",$nameA[$a], $nameB[$b], $scoreAB{"$a:$b"}, $scoreBA{"$b:$a"}) if ($debug == 5);
# }
# Set score AB and score BA to the mean of scores AB and BA.
# The final score is saved as an integer so .5 needs to be added to avoid rounding errors
# $scoreAB{"$a:$b"} = $scoreBA{"$b:$a"} = int(($scoreAB{"$a:$b"} + $scoreBA{"$b:$a"})/2.0 +.5);
# printf ("scoreAB{%d: %d} = %d\n", $a, $b, $scoreAB{"$a:$b"});
# printf ("scoreBA{%d: %d} = %d\n", $b, $a, $scoreBA{"$a:$b"});
#}
# }
####################################################################################################################################### End modification by Isabella 1
##################### Re-sort hits, besthits and bestscore #######################
for $idA ( 1 .. $A ) {
# print "Loop index = $idA\n";
# printf ("hitnAB[%d] = %d\n",$idA, $hitnAB[$idA]);
next if ( !( $hitnAB[$idA] ) );
for $hit ( 1 .. ( $hitnAB[$idA] - 1 ) ) { # Sort hits by score
while ( $scoreAB{"$idA:$hitAB[$idA][$hit]"} <
$scoreAB{"$idA:$hitAB[$idA][$hit+1]"} )
{
$tmp = $hitAB[$idA][$hit];
$hitAB[$idA][$hit] = $hitAB[$idA][ $hit + 1 ];
$hitAB[$idA][ $hit + 1 ] = $tmp;
--$hit if ( $hit > 1 );
}
}
$bestscore = $bestscoreAB[$idA] = $scoreAB{"$idA:$hitAB[$idA][1]"};
$besthitAB[$idA] = $hitAB[$idA][1];
for $hit ( 2 .. $hitnAB[$idA] ) {
if (
$bestscore - $scoreAB{"$idA:$hitAB[$idA][$hit]"} <= $grey_zone )
{
$besthitAB[$idA] .= " $hitAB[$idA][$hit]";
} else {
last;
}
}
undef $is_besthitAB[$idA]; # Create index that we can check later
grep ( vec( $is_besthitAB[$idA], $_, 1 ) = 1,
split( / /, $besthitAB[$idA] ) );
# printf ("besthitAB[%d] = hitAB[%d][%d] = %d\n",$idA,$idA,$hit,$besthitAB[$idA]);
}
for $idB ( 1 .. $B ) {
# print "Loop index = $idB\n";
next if ( !( $hitnBA[$idB] ) );
for $hit ( 1 .. ( $hitnBA[$idB] - 1 ) ) {
# Sort hits by score
while ( $scoreBA{"$idB:$hitBA[$idB][$hit]"} <
$scoreBA{"$idB:$hitBA[$idB][$hit+1]"} )
{
$tmp = $hitBA[$idB][$hit];
$hitBA[$idB][$hit] = $hitBA[$idB][ $hit + 1 ];
$hitBA[$idB][ $hit + 1 ] = $tmp;
--$hit if ( $hit > 1 );
}
}
$bestscore = $bestscoreBA[$idB] = $scoreBA{"$idB:$hitBA[$idB][1]"};
$besthitBA[$idB] = $hitBA[$idB][1];
for $hit ( 2 .. $hitnBA[$idB] ) {
if (
$bestscore - $scoreBA{"$idB:$hitBA[$idB][$hit]"} <= $grey_zone )
{
$besthitBA[$idB] .= " $hitBA[$idB][$hit]";
} else {
last;
}
}
undef $is_besthitBA[$idB]; # Create index that we can check later
grep ( vec( $is_besthitBA[$idB], $_, 1 ) = 1,
split( / /, $besthitBA[$idB] ) );
# printf ("besthitBA[%d] = %d\n",$idA,$besthitAB[$idA]);
}
if ($show_times) {
( $user_time,,, ) = times;
printf( "Reading and sorting homologs took %.2f seconds\n",
( $user_time - $prev_time ) );
$prev_time = $user_time;
}
######################################################
# Now find orthologs:
######################################################
$o = 0;
for $i ( 1 .. $A ) { # For each ID in file A
if ( defined $besthitAB[$i] ) {
@besthits = split( / /, $besthitAB[$i] );
for $hit (@besthits) {
if ( vec( $is_besthitBA[$hit], $i, 1 ) ) {
++$o;
$ortoA[$o] = $i;
$ortoB[$o] = $hit;
$ortoS[$o] = $scoreAB{"$i:$hit"}; # Should be equal both ways
# --$o if ($ortoS[$o] == $bitscore_cutoff); # Ignore orthologs that are exactly at score_cutoff
#print "Accept! " if ( $debug == 2 );
DEBUG("Accept! ");
} else {
#print " " if ( $debug == 2 );
DEBUG(" ");
}
# printf( "%-20s\t%d\t%-20s\t",$nameA[$i], $bestscoreAB[$i], $nameB[$hit] ) if ( $debug == 2 );
# print "$bestscoreBA[$hit]\t$besthitBA[$hit]\n" if ( $debug == 2 );
DEBUG( "$nameA[$i], $bestscoreAB[$i], $nameB[$hit]");
DEBUG("$bestscoreBA[$hit]\t$besthitBA[$hit]\n");
}
}
}
# print "$o ortholog candidates detected\n";
# if ($debug);
#####################################################
# Sort orthologs by ID and then by score:
#####################################################
####################################################################################################### Modification by Isabella 2
# Removed time consuiming bubble sort. Created an index array and sort that according to id and score.
# The put all clusters on the right place.
# Create an array used to store the position each element shall have in the final array
# The elements are initialized with the position numbers
my @position_index_array = ( 1 .. $o );
# Sort the position list according to id
my @id_sorted_position_list =
sort { ( $ortoA[$a] + $ortoB[$a] ) <=> ( $ortoA[$b] + $ortoB[$b] ) }
@position_index_array;
# Sort the list according to score
my @score_id_sorted_position_list =
sort { $ortoS[$b] <=> $ortoS[$a] } @id_sorted_position_list;
# Create new arrays for the sorted information
my @new_ortoA;
my @new_ortoB;
my @new_orthoS;
# Add the information to the new arrays in the orer specifeid by the index array
for ( my $index_in_list = 0 ;
$index_in_list < scalar @score_id_sorted_position_list ;
$index_in_list++ )
{
my $old_index = $score_id_sorted_position_list[$index_in_list];
$new_ortoA[ $index_in_list + 1 ] = $ortoA[$old_index];
$new_ortoB[ $index_in_list + 1 ] = $ortoB[$old_index];
$new_ortoS[ $index_in_list + 1 ] = $ortoS[$old_index];
}
@ortoA = @new_ortoA;
@ortoB = @new_ortoB;
@ortoS = @new_ortoS;
# Use bubblesort to sort ortholog pairs by id
# for $i(1..($o-1)){
# while(($ortoA[$i]+$ortoB[$i]) > ($ortoA[$i+1] + $ortoB[$i+1])){
# $tempA = $ortoA[$i];
# $tempB = $ortoB[$i];
# $tempS = $ortoS[$i];
#
# $ortoA[$i] = $ortoA[$i+1];
# $ortoB[$i] = $ortoB[$i+1];
# $ortoS[$i] = $ortoS[$i+1];
#
# $ortoA[$i+1] = $tempA;
# $ortoB[$i+1] = $tempB;
# $ortoS[$i+1] = $tempS;
#
# --$i if ($i > 1);
# }
# }
#
# # Use bubblesort to sort ortholog pairs by score
# for $i(1..($o-1)){
# while($ortoS[$i] < $ortoS[$i+1]){
# # Swap places:
# $tempA = $ortoA[$i];
# $tempB = $ortoB[$i];
# $tempS = $ortoS[$i];
#
# $ortoA[$i] = $ortoA[$i+1];
# $ortoB[$i] = $ortoB[$i+1];
# $ortoS[$i] = $ortoS[$i+1];
#
# $ortoA[$i+1] = $tempA;
# $ortoB[$i+1] = $tempB;
# $ortoS[$i+1] = $tempS;
#
# --$i if ($i > 1);
# }
# }
###################################################################################################### End modification bt Isabella 2
@all_ortologsA = ();
@all_ortologsB = ();
for $i ( 1 .. $o ) {
push( @all_ortologsA, $ortoA[$i] ); # List of all orthologs
push( @all_ortologsB, $ortoB[$i] );
}
#print Dumper @all_ortologsA, @all_ortologsB;
undef $is_ortologA; # Create index that we can check later
undef $is_ortologB;
grep ( vec( $is_ortologA, $_, 1 ) = 1, @all_ortologsA );
grep ( vec( $is_ortologB, $_, 1 ) = 1, @all_ortologsB );
# print "$is_ortologA\t$is_ortologB\n";
# exit;
if ($show_times) {
( $user_time,,, ) = times;
printf( "Finding and sorting orthologs took %.2f seconds\n",
( $user_time - $prev_time ) );
$prev_time = $user_time;
}
#################################################
# Read in best hits from blast output file AC
#################################################
if ($use_outgroup) {
$count = 0;
open AC, "$blast_outputAC" or die "Blast output file A->C is missing\n";
while (<AC>) {
chomp;
@Fld = split(/\s+/); # Get query, match and score
if ( scalar @Fld < 9 ) {
if ( $Fld[0] =~ /done/ ) {
print STDERR "AC ok\n";
}
next;
}
$q = $Fld[0];
$m = $Fld[1];
$idQ = $idA{$q};
$idM = $idC{$m};
$score = $Fld[2];
next unless ( vec( $is_ortologA, $idQ, 1 ) );
next if ( !overlap_test(@Fld) );
next if ( $score < $bitscore_cutoff );
next if ( $count and ( $q eq $oldq ) );
# Only comes here if this is the best hit:
$besthitAC[$idQ] = $idM;
$bestscoreAC[$idQ] = $score;
$oldq = $q;
++$count;
}
close AC;
#################################################
# Read in best hits from blast output file BC
#################################################
$count = 0;
open BC, "$blast_outputBC" or die "Blast output file B->C is missing\n";
while (<BC>) {
chomp;
@Fld = split(/\s+/); # Get query, match and score
if ( scalar @Fld < 9 ) {
if ( $Fld[0] =~ /done/ ) {
print STDERR "BC ok\n";
}
next;
}
$q = $Fld[0];
$m = $Fld[1];
$idQ = $idB{$q};
$idM = $idC{$m};
$score = $Fld[2];
next unless ( vec( $is_ortologB, $idQ, 1 ) );
next if ( !overlap_test(@Fld) );
next if ( $score < $bitscore_cutoff );
next if ( $count and ( $q eq $oldq ) );
# Only comes here if this is the best hit:
$besthitBC[$idQ] = $idM;
$bestscoreBC[$idQ] = $score;
$oldq = $q;
++$count;
}
close BC;
################################
# Detect rooting problems
################################
$rejected = 0;
@del = ();
$file = "rejected_sequences." . $fasta_seq_fileC;
open OUTGR, ">$file";
for $i ( 1 .. $o ) {
$diff1 = $diff2 = 0;
$idA = $ortoA[$i];
$idB = $ortoB[$i];
$diff1 = $bestscoreAC[$idA] - $ortoS[$i];
$diff2 = $bestscoreBC[$idB] - $ortoS[$i];
if ( $diff1 > $outgroup_cutoff ) {
print OUTGR "Ortholog pair $i ($nameA[$idA]-$nameB[$idB]).
$nameA[$idA] from $fasta_seq_fileA is closer to $nameC[$besthitAC[$idA]] than to $nameB[$idB]\n";
print OUTGR " $ortoS[$i] < $bestscoreAC[$idA] by $diff1\n";
}
if ( $diff2 > $outgroup_cutoff ) {
print OUTGR "Ortholog pair $i ($nameA[$idA]-$nameB[$idB]).
$nameB[$idB] from $fasta_seq_fileB is closer to $nameC[$besthitBC[$idB]] than to $nameA[$idA]\n";
print OUTGR " $ortoS[$i] < $bestscoreBC[$idB] by $diff2\n";
}
if ( ( $diff1 > $outgroup_cutoff )
or ( $diff2 > $outgroup_cutoff ) )
{
++$rejected;
$del[$i] = 1;
}
}
print
"Number of rejected groups: $rejected (outgroup sequence was closer by more than $outgroup_cutoff bits)\n";
close OUTGR;
} # End of $use_outgroup
################################
# Read inside scores from AA
################################
$count = 0;
$max_hit = 0;
open AA, "$blast_outputAA" or die "Blast output file A->A is missing\n";
while (<AA>) {
chomp; # strip newline
@Fld = split(/\s+/); # Get query and match names
if ( scalar @Fld < 9 ) {
if ( $Fld[0] =~ /done/ ) {
print STDERR "AA ok\n";
}
next;
}
$q = $Fld[0];
$m = $Fld[1];
$score = $Fld[2];
next unless ( vec( $is_ortologA, $idA{$q}, 1 ) );
next if ( !overlap_test(@Fld) );
next if ( $score < $bitscore_cutoff );
if ( !$count || $q ne $oldq ) { # New query
$max_hit = $hit if ( $hit > $max_hit );
$hit = 0;
$oldq = $q;
}
++$hit;
++$count;
$scoreAA{"$idA{$q}:$idA{$m}"} = int( $score + 0.5 );
$hitAA[ $idA{$q} ][$hit] = int( $idA{$m} );
$hitnAA[ $idA{$q} ] = $hit;
}
close AA;
if ($output) {
print OUTPUT "$count $fasta_seq_fileA-$fasta_seq_fileA matches\n";
}
################################
# Read inside scores from BB
################################
$count = 0;
open BB, "$blast_outputBB" or die "Blast output file B->B is missing\n";
while (<BB>) {
chomp; # strip newline
@Fld = split(/\s+/); # Get query and match names
if ( scalar @Fld < 9 ) {
if ( $Fld[0] =~ /done/ ) {
print STDERR "BB ok\n";
}
next;
}
$q = $Fld[0];
$m = $Fld[1];
$score = $Fld[2];
next unless ( vec( $is_ortologB, $idB{$q}, 1 ) );
if(!overlap_test(@Fld)){
DEBUG("Ignored (<overlap): $q, $m, $score\n");
next;
}
if ( $score < $bitscore_cutoff ){
DEBUG("Ignored (<bitscore): $q, $m, $score\n");
next;
};
if ( !$count || $q ne $oldq ) { # New query
$max_hit = $hit if ( $hit > $max_hit );
$oldq = $q;
$hit = 0;
}
++$count;
++$hit;
$scoreBB{"$idB{$q}:$idB{$m}"} = int( $score + 0.5 );