-
Notifications
You must be signed in to change notification settings - Fork 1
/
BadiRate.pl
2375 lines (2201 loc) · 81.2 KB
/
BadiRate.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/env perl
#
# BadiRate - Estimating gene family turnover rates by likelihood-based methods
# Copyright (C) 2012 Pablo Librado, Filipe Garrett Vieira, Julio Rozas and Universitat de Barcelona (UB)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see {http://www.gnu.org/licenses/}.
=head1 NAME
BadiRate.pl - DESCRIPTION
=head1 SYNOPSIS
The basic command is:
perl BadiRate.pl -tree NEWICK_FILE -fam FAMILY_SIZE_FILE [options] > output.bd
-anc = Reconstruct ancestral family sizes and the minimum number of gains/losses in each lineage
-bmodel = Run local or free branch models
-sizefile = Family Size File
-unobs = Correct the likelihood for families absent in all extant species
-h|help = Display this help
-rmodel = Family turnover rates to be estimated
-out = Set the output file
-outlier = Report families escaping the estimated stochastic process
-ep = Define the estimation procedure
-print_ids = Display nodes ids in Newick format
-priorfile = Prior File
-n_max_int = Modify the maximum number of family members in the internal phylogenetic nodes
-root_dist = Estimation method for the root a priori distribution
-seed = Seed of the pseudo-random number generator
-start_val = Starting values for the likelihood methods
-treefile = Phylogenetic tree in Newick format
-version = Report the BadiRate version
-----OR------
perl BadiRate.pl controlfile.bd > output.bd
=head1 DESCRIPTION
This script estimates the gain, birth, death and innovation gene (or DNA element) family rates. It implements three stochastic population models:
1) BDI: Birth-Death-Innovation
2) LI: Lambda-Innovation, where Lambda is the birth-and-death parameter (equal birth and death rates are assumed)
3) GD: Gain-Death, where gain parameter accounts for all gains regardless they are originated by DNA duplications or represent an innovation
4) BD: Birth and Death model
5) L: Lambda, where Lambda is the birth-and-death parameter (equal birth and death rates are assumed)
In addition, for each family or subfamily, it also infers the most likely ancestral content and the (sub)families unlikely evolving under the estimated stochastic process.
=head1 AUTHOR - Pablo Librado Sanz
Email
plibrado@ub.edu
=head1 CONTRIBUTORS
fgarret@ub.edu
jrozas@ub.edu
=cut
# Let the code begin...
use FindBin;
use lib $FindBin::Bin."/lib";
use Inline (C =>'DATA');
use strict;
use warnings;
use Bio::TreeIO;
use Getopt::Long;
use Statistics::Descriptive;
use Math::Amoeba qw(MinimiseND);
$|=1;
#declarations
my (%ortho,%options,%distances,%assoc,%fixed,%max,%min,%difOGs,%bmodel,%priormodel,%OGstring)=();
my (%birth,%death,%innovation,%ancestral,%root,@treepath)=();
my (@usedOG,@nodes,%RatesOrder,%RatesOrder_rev,%OGOrder,%anc_cnt,%Q,@ant_param)=();
my ($tree,$OG_analyzed,$version, $error);
my $MIN=0.0000000001;
my $MAX=99999999999999999999999999;
my $U;
$error=0;
my %ERRORS=(
'0'=>'NO ERRORS',
'1'=>'Amoeba excedeed the maximum number of iterations. Check convergence (see -start_val option)!',
'2'=>'Try using a more complex model, or changing the starting values. See the -rmodel, -bmodel and -start_val options',
);
$version="1.35.00";
$options{'seed'}=int(time()*rand);
$options{'anc'}=0;
$options{'family'}=0;
$options{'outlier'}=0;
$options{'rmodel'}="BDI";
$options{'ep'}="ML";
$options{'help'}=0;
$options{'version'}=0;
$options{'print_ids'}=0;
$options{'priorfile'}="";
$options{'unobs'}=0;
$options{'root_dist'}=1;
$options{'start_val'}=0;
$options{'n_max_int'}=10;
&dieNice if (!defined($ARGV[0]));
if ($ARGV[0]!~/^-/){
(!&readCtlFile(\%options,$ARGV[0])) && do{die "Unable to read control file\n";};
}else{
GetOptions(
'sizefile=s' => \$options{'sizefile'},
'unobs!' => \$options{'unobs'},
'treefile=s' => \$options{'treefile'},
'root_dist=i' => \$options{'root_dist'},
'out:s' => \$options{'out'},
'seed:i' => \$options{'seed'},
'bmodel:s' => \$options{'bmodel'},
'family!' => \$options{'family'},
'rmodel:s' => \$options{'rmodel'},
'outlier!' => \$options{'outlier'},
'anc!' => \$options{'anc'},
'help|h!' => \$options{'help'},
'version!' => \$options{'version'},
'print_ids!' => \$options{'print_ids'},
'priorfile:s' => \$options{'priorfile'},
'start_val:i' => \$options{'start_val'},
'ep:s' => \$options{'ep'},
'n_max_int:i' => \$options{'n_max_int'}
);
}
die "BadiRate version: $version\n" if ($options{'version'});
#set the seed
srand($options{'seed'});
#options checking
$options{'rmodel'}=uc($options{'rmodel'});
$options{'ep'}=uc($options{'ep'});
&dieNice if (!$options{'sizefile'} || !$options{'treefile'} || $options{'help'});
die "model must be BDI, BD, GD, LI or L\n" if ($options{'rmodel'}!~/^(BDI|GD|LI|BD|L)$/);
$options{'anc'}=1 if ($options{'family'} || $options{'outlier'});
die "root_dist option must be between 0 and 4\n" if ($options{'root_dist'} < 0 && $options{'root_dist'}>4);
die "unobs requires root_dist = 1 or root_dist = 3\n" if ($options{'unobs'} && ($options{'root_dist'} == 0 || $options{'root_dist'} == 2 || $options{'root_dist'} == 4));
die "Estimation procedure must be ML, MAP, CML, CMAP, CWP or CSP\n" if ($options{'ep'}!~/^(ML|MAP|CML|CMAP|CWP|CSP)$/);
die "MAP and CMAP estimation procedures require a priorfile defined\n" if ($options{'priorfile'} eq "" && $options{'ep'}=~/MAP/);
die "priorfile defined requires MAP or CMAP estimation procedures\n" if ($options{'priorfile'} ne "" && $options{'ep'}!~/MAP/);
die "-family option must be specified with CML, CMAP, CWP or CSP\n" if ($options{'family'} && $options{'ep'}=~/^(ML|MAP)$/);
#prepare output file
if(defined($options{'out'})) {
if (uc($options{'out'}) ne "STDOUT"){
open(ANC_OUT, '>', $options{'out'}) or die "Couldn't open: $!";
} else{
open(ANC_OUT, ">&", \*STDOUT) or die "Couldn't open: $!";
$options{'out'}="STDOUT";
}
} else {
open(ANC_OUT, ">&", \*STDOUT) or die "Couldn't open: $!";
$options{'out'}="STDOUT";
}
#readortho
(!&readorthotable($options{'sizefile'},\%ortho)) && do{die $!;};
#readnewick
$tree=&readtree($options{'treefile'});
my $root_node=$tree->get_root_node;
my $root_node_id=$root_node->internal_id;
(!&printTreeIDRel(\*ANC_OUT, $tree, \%assoc)) && do{die;};
exit if ($options{'print_ids'});
(!&MakeTreePath(\@treepath)) && do{die;};
(!&GetDistances($tree,\%distances)) && do{die;};
(!&fixedNode) && do{die;};
(!&usedOGs) && do{die;};
die "No valid OG groups or families\n" if (scalar(@usedOG)==0);
foreach my $node ($tree->get_nodes){next unless ($node->ancestor);push(@nodes,$node);}
(!&readmodel($options{'bmodel'})) && do{die;};
if (!$options{'ep'}!~/^(CSP|CWP)$/){
(!&readprior($options{'priorfile'})) && do{die;};
}
#print input stuff
print ANC_OUT "-"x20,"\n";
print ANC_OUT "INPUT\n";
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
printf ANC_OUT "\tExecution date: %4d-%02d-%02d %02d:%02d:%02d\n", $year+1900,$mon+1,$mday,$hour,$min,$sec;;
print ANC_OUT "\tVersion: $version\n";
foreach my $option (keys %options){
if ($option eq "bmodel"){
print ANC_OUT "\tbmodel= \n";
foreach my $branch (keys %bmodel){print ANC_OUT "\t\t$branch\t$bmodel{$branch}\n";}
}elsif ($option ne "bmodel"){
print ANC_OUT "\t$option = $options{$option}\n";
}
}
print ANC_OUT "END INPUT\n";
#output
print ANC_OUT "-"x20,"\n";
print ANC_OUT "OUTPUT\n";
print ANC_OUT "\n\t##Family Turnover Rates\n";
(!&getDifferentOGs) && do{die;};
if ($options{'unobs'}){
foreach my $node ($tree->get_leaf_nodes){
$ancestral{"UnobservedData"}{$node->internal_id}[0]=0;
$min{"UnobservedData"}=0;
$max{"UnobservedData"}=$max{$usedOG[0]};
}
}
(!&AncestralParsimony) && do{die;};
(!&sumAnc) && do{die;};
if ($options{'ep'}=~/(ML|MAP)/){
(!&Ulimit) && do{die;};
}
#Rates estimation
if ($options{'ep'} eq 'ML' || $options{'ep'} eq 'MAP'){ #likelihood methods
(!&FamilyObservedRates(\*ANC_OUT,0)) && do{die;} if ($options{'start_val'} == 0);
if ($options{'rmodel'} eq "BDI"){
print ANC_OUT "\t\t#Likelihood: ",&BDI,"\n";
}elsif ($options{'rmodel'} eq "GD"){
print ANC_OUT "\t\t#Likelihood: ",&GD,"\n";
}elsif ($options{'rmodel'} eq "LI"){
print ANC_OUT "\t\t#Likelihood: ",&LI,"\n";
}elsif ($options{'rmodel'} eq "BD"){
print ANC_OUT "\t\t#Likelihood: ",&BD,"\n";
}elsif ($options{'rmodel'} eq "L"){
print ANC_OUT "\t\t#Likelihood: ",&L,"\n"
}
if ($error!=2){
warn "\t\t#WARN: ".$ERRORS{$error}."\n" if ($error == 1);
(!&printRates(\*ANC_OUT)) && do{die;};
}else{
warn "\t\t#WARN: ".$ERRORS{$error}."\n";
}
}elsif ($options{'ep'} eq 'CML' ||$options{'ep'} eq 'CMAP'){ #hybrid methods
(!&FamilyObservedRates(\*ANC_OUT,0)) && do{die;} if ($options{'start_val'} == 0);
if ($options{'rmodel'} eq "BDI"){&BDI;}
elsif ($options{'rmodel'} eq "GD"){&GD;}
elsif ($options{'rmodel'} eq "LI"){&LI;}
elsif ($options{'rmodel'} eq "BD"){&BD;}
elsif ($options{'rmodel'} eq "L"){&L;}
if ($error != 2){
warn "\t\t#WARN: ".$ERRORS{$error}."\n" if ($error == 1);
my @numAnc=keys %difOGs;
my $numAncSize=scalar(@numAnc);
for (my $j=1; $j<=$numAncSize;$j++){
$OG_analyzed=$difOGs{$numAnc[$j-1]}[0];
my $tmp=&Anc;
}
foreach my $OG (@usedOG){ %{$ancestral{$OG}}=%{$ancestral{$difOGs{$OGstring{$OG}}[0]}}; }
(!&sumAnc) && do{die;};
(!&FamilyObservedRates(\*ANC_OUT,1)) && do{die;};
if (scalar(&keysModel)>1){
(!&readmodel) && do{die;};
(!&FamilyObservedRates(\*ANC_OUT,2)) && do{die;};
(!&readmodel($options{'bmodel'})) && do{die;};
}
}else{
warn "\t\t#WARN: ".$ERRORS{$error}."\n";
}
}elsif ($options{'ep'} eq 'CWP' || $options{'ep'} eq 'CSP'){ #parsimony methods
(!&FamilyObservedRates(\*ANC_OUT,1)) && do{die;};
}
#ancestral and outlier estimation
if ($options{'anc'} && $error != 2){
if ($options{'ep'}=~/(ML|MAP)/ && $options{'family'} == 0){
my @numAnc=keys %difOGs;
my $numAncSize=scalar(@numAnc);
for (my $j=1; $j<=$numAncSize;$j++){
$OG_analyzed=$difOGs{$numAnc[$j-1]}[0];
my $tmp=&Anc;
}
foreach my $OG (@usedOG){ %{$ancestral{$OG}}=%{$ancestral{$difOGs{$OGstring{$OG}}[0]}}; }
(!&sumAnc) && do{die;};
}
print ANC_OUT "\n\t##Ancestral Family Size\n";
print ANC_OUT "\t\t#Family\tAncestral Family Size Tree\n";
foreach my $OG (sort @usedOG){
my $treecp=$tree->clone;
foreach my $node ($treecp->get_nodes){
if (!$node->is_Leaf()){
$node->bootstrap($ancestral{$OG}{$node->internal_id}[0]);
}else{
$node->id($node->id."_$ancestral{$OG}{$node->internal_id}[0]");
}
}
print ANC_OUT "\t\t$OG\t",&printTree(\$treecp);
}
foreach my $node ($tree->get_nodes){
if (!$node->is_Leaf()){
$node->bootstrap($anc_cnt{$node->internal_id});
}else{
$node->id($node->id."_$anc_cnt{$node->internal_id}");
}
}
print ANC_OUT "\t\tTotal Ancestral Size\t",&printTree(\$tree);
print ANC_OUT "\n\t##Minimum number of gains and losses per branch\n";
print ANC_OUT "\t\t#Branch\tGains\tLosses\n";
foreach my $node (@nodes){
my $parent=$node->ancestor;
my $branch=$parent->internal_id."->".$node->internal_id;
my $branchmodel=$bmodel{$branch};
my ($gain,$loss)=&calcGainLoss($parent->internal_id,$node->internal_id,0);
print ANC_OUT "\t\t$branch\t".$gain."\t".$loss."\n";
}
if ($options{'outlier'}){
if ($options{'ep'}=~/^(MAP|ML)$/){
print ANC_OUT "\n\t##Outlier Families per Branch\n";
my (%adjp,@rawp, %pval)=();
@rawp=("-5");
my $cnt=1;
foreach my $OG (@usedOG){
foreach my $node (@nodes){
my $parent=$node->ancestor();
my $branch=$parent->internal_id."->".$node->internal_id;
my $branchmodel=$bmodel{$branch};
my $time=$distances{$parent->internal_id}{$node->internal_id};
my $p=&prob($birth{$branchmodel}[0],$death{$branchmodel}[0],$innovation{$branchmodel}[0],$branchmodel."_".$time,$ancestral{$OG}{$parent->internal_id}[0],$ancestral{$OG}{$node->internal_id}[0]);
$pval{$OG}{$branch}=$cnt++;
push(@rawp,$p);
}
}
(!&fdr(\@rawp,\%adjp)) && do{die;};
print ANC_OUT "\t\t#Family\tBranch\tP-value\tFDR_P-value\n",;
foreach my $OG (@usedOG){
foreach my $node (@nodes){
my $parent=$node->ancestor();
my $branch=$parent->internal_id."->".$node->internal_id;
print ANC_OUT "\t\t",$OG,"\t",$branch,"\t",&printFloatNice($rawp[$pval{$OG}{$branch}]),"\t",&printFloatNice($adjp{$rawp[$pval{$OG}{$branch}]}),"\n" if ($adjp{$rawp[$pval{$OG}{$branch}]}<0.05);
}
}
}else{
print "To detect outlier families, run ep=ML|MAP\n";
}
}
}
print(ANC_OUT "\n\t##Execution time (seconds): ".(time - $^T)."\n");
print(ANC_OUT "END OUTPUT\n");
close(ANC_OUT);
exit(0);
###############################FUNCTIONS########################################
################################################################################
sub readorthotable($$){
#Reads the orthotable. Also an orthogroup id can be selected
my ($orthofile,$ortho)=@_;
(!open (ORTHOTABLE, $orthofile)) && do{print "$!\n";return 0;};
my (@anc,@sp)=();
my $cnt=0;
while(<ORTHOTABLE>){
chomp;
next if($_ =~ /^#/ || $_!~/\S+/);
my @orthogroup=split(/\t+|\s+/,$_);
if ($cnt==0){ #header
for (my $j=1; $j<=$#orthogroup; $j++){
push(@sp,$orthogroup[$j]);
}
}else{
return 0 if (scalar(@sp)+1 != scalar(@orthogroup));
for (my $j=0; $j<scalar(@sp); $j++){
push(@{$$ortho{$orthogroup[0]}{'ID'}},{'cnt'=>$orthogroup[$j+1], 'sp' => $sp[$j]});
}
}
$cnt++;
}
close(ORTHOTABLE);
return 1;
}
########################################################################
sub prior($$){
my ($x,$hash)=@_;
if (defined($$hash{'uniform'})){
return 1/$$hash{'uniform'};
}elsif (defined($$hash{'shape'})){
if ($x == 0 && $$hash{'shape'} == 0){
return 1;
}elsif ($x > 0 && $$hash{'shape'} == 0){
return 0;
}else{
return &gamma_PDF($x,1,$$hash{'shape'});
}
}
}
########################################################################
sub readprior($){
my ($priorfile)=@_;
my @keys=&keysModel;
foreach my $bmodelstr (@keys){
if ($options{'rmodel'} eq "BDI"){
$priormodel{$bmodelstr}{'birth'}{'uniform'}=$priormodel{$bmodelstr}{'death'}{'uniform'}=$priormodel{$bmodelstr}{'innovation'}{'uniform'}=1;
}elsif ($options{'rmodel'} eq "LI"){
$priormodel{$bmodelstr}{'lambda'}{'uniform'}=$priormodel{$bmodelstr}{'innovation'}{'uniform'}=1;
}elsif ($options{'rmodel'} eq "GD"){
$priormodel{$bmodelstr}{'gain'}{'uniform'}=$priormodel{$bmodelstr}{'death'}{'uniform'}=1;
}elsif ($options{'rmodel'} eq "BD"){
$priormodel{$bmodelstr}{'birth'}{'uniform'}=$priormodel{$bmodelstr}{'death'}{'uniform'}=1;
}elsif ($options{'rmodel'} eq "L"){
$priormodel{$bmodelstr}{'lambda'}{'uniform'}=1;
}
}
return 1 if (!-s $priorfile);
(!open(FILE,$priorfile)) && do{die;};
while(<FILE>){
chomp;
next if ($_!~/\S+/ || $_=~/^#/);
my @line=split(/\t+/,$_);
die "No $line[0] branch class\n" if (scalar(grep(/^$line[0]$/,@keys))==0);
if ($options{'rmodel'} eq "BDI"){
if ($line[1] ne "birth" && $line[1] ne "death" && $line[1] ne "innovation"){
print STDERR "$line[1] is not birth, death or innovation\n";
return 0;
}
}elsif ($options{'rmodel'} eq "LI"){
if ($line[1] ne "lambda" && $line[1] ne "innovation"){
print STDERR "$line[1] is not lambda or innovation\n";
return 0;
}
}elsif ($options{'rmodel'} eq "L"){
if ($line[1] ne "lambda"){
print STDERR "$line[1] is not lambda\n";
return 0;
}
}elsif ($options{'rmodel'} eq "GD"){
if ($line[1] ne "gain" && $line[1] ne "death"){
print STDERR "$line[1] is not gain or death\n";
return 0;
}
}elsif ($options{'rmodel'} eq "BD"){
if ($line[1] ne "birth" && $line[1] ne "death"){
print STDERR "$line[1] is not birth or death\n";
return 0;
}
}
$priormodel{$line[0]}{$line[1]}=();
if (uc($line[2]) eq "GAMMA"){
if ($line[3]<0){
die "Wrong gamma parameter\n";
}
$priormodel{$line[0]}{$line[1]}{'shape'}=$line[3];
#$priormodel{$line[0]}{$line[1]}{'scale'}=$line[4];
}else{
die "No Gamma distribution as prior\n";
}
}
close(FILE);
return 1;
}
########################################################################
sub printTree($){
my ($ptree)=@_;
my $tree_string = '';
open(TMP_OUT, "+<", \$tree_string);
my $out = new Bio::TreeIO(-fh => \*TMP_OUT, -format => 'newick');
$out->write_tree($$ptree);
return $tree_string;
}
########################################################################
sub printRates($$){
my ($fh,$mode)=@_;
my @keys=&keysModel;
$mode = 1 if (!defined($mode));
if ($mode != 2){
if ($options{'rmodel'} eq "BDI"){
print $fh "\t\t#Branch_Group\tBirth\tDeath\tInnovation\n";
}elsif ($options{'rmodel'} eq "GD"){
print ANC_OUT "\t\t#Branch_Group\tGain\tDeath\tLoss(approx from death)\n";
}elsif ($options{'rmodel'} eq "LI"){
print ANC_OUT "\t\t#Branch_Group\tLambda\tInnovation\n";
}elsif ($options{'rmodel'} eq "L"){
print ANC_OUT "\t\t#Branch_Group\tLambda\n";
}elsif ($options{'rmodel'} eq "BD"){
print $fh "\t\t#Branch_Group\tBirth\tDeath\n";
}
}
foreach my $bmodelstr (sort {$a <=> $b} @keys){
my $bmodelstr2=$bmodelstr;
$bmodelstr2="Global_Rates" if ($mode == 2);
if ($options{'rmodel'} eq "BDI"){
print $fh "\t\t$bmodelstr2\t",&printFloatNice($birth{$bmodelstr}[0]),"\t",&printFloatNice($death{$bmodelstr}[0]),"\t",&printFloatNice($innovation{$bmodelstr}[0]),"\n";
}elsif ($options{'rmodel'} eq "GD"){
my %loss=&death2loss(\%death);
print $fh "\t\t$bmodelstr2\t",&printFloatNice($innovation{$bmodelstr}[0]),"\t",&printFloatNice($death{$bmodelstr}[0]),"\t",&printFloatNice($loss{$bmodelstr}[0]),"\n";
}elsif ($options{'rmodel'} eq "LI"){
print $fh "\t\t$bmodelstr2\t",&printFloatNice($birth{$bmodelstr}[0]),"\t",&printFloatNice($innovation{$bmodelstr}[0]),"\n";
}elsif ($options{'rmodel'} eq "L"){
print $fh "\t\t$bmodelstr2\t",&printFloatNice($birth{$bmodelstr}[0]),"\n";
}elsif ($options{'rmodel'} eq "BD"){
print $fh "\t\t$bmodelstr2\t",&printFloatNice($birth{$bmodelstr}[0]),"\t",&printFloatNice($death{$bmodelstr}[0]),"\n";
}
}
return 1;
}
########################################################################
sub prob($$$$$){
my ($b,$d,$i,$timeORbranch,$anc,$desc)=@_;
return $Q{$timeORbranch}[$anc*($U+1)+$desc];
}
########################################################################
sub Anc{
#joint ML ancestral reconstruction
my (%L,%C)=();
foreach my $node ($tree->get_leaf_nodes){ #tips
my $parent=$node->ancestor;
my $branch=$parent->internal_id."->".$node->internal_id;
for (my $i=$min{$OG_analyzed};$i<=$max{$OG_analyzed};$i++){
$C{$node->internal_id}{$i}=$ancestral{$OG_analyzed}{$node->internal_id}[0];
$L{$node->internal_id}{$i}=&prob(1,1,1,$bmodel{$branch}."_".$distances{$parent->internal_id}{$node->internal_id},$i,$ancestral{$OG_analyzed}{$node->internal_id}[0]);
}
}
for my $node (@treepath){ #internal_nodes
next if ($node->{'parentid'} eq 'NULL');
for (my $i=$min{$OG_analyzed};$i<=$max{$OG_analyzed};$i++){
my $maxL=-1;
my @desc=@{$node->{'desc'}};
my $parentid=$node->{'parentid'};
my $branch=$parentid."->".$node->{'id'};
for (my $j=$min{$OG_analyzed};$j<=$max{$OG_analyzed};$j++){
my $L_tmp=$L{$desc[0][0]}{$j}*$L{$desc[1][0]}{$j}*&prob(1,1,1,$bmodel{$branch}."_".$distances{$parentid}{$node->{'id'}},$i,$j);
if ($L_tmp>$maxL){
$L{$node->{'id'}}{$i}=$L_tmp;
$C{$node->{'id'}}{$i}=$j;
$maxL=$L_tmp;
}
}
}
}
for my $node (@treepath){#root
if ($node->{'parentid'} eq 'NULL'){
my @desc=@{$node->{'desc'}};
my $maxL=-1;
for (my $j=$min{$OG_analyzed};$j<=$max{$OG_analyzed};$j++){
my $L_tmp=$L{$desc[0][0]}{$j}*$L{$desc[1][0]}{$j}*&rootMLprob($OG_analyzed,$j);
if ($L_tmp>$maxL){
$L{$node->{'id'}}{$j}=$L_tmp;
$maxL=$L_tmp;
$ancestral{$OG_analyzed}{$node->{'id'}}[0]=$j;
}
}
}
}
for my $node (reverse @treepath){
if ($node->{'parentid'} ne 'NULL'){ #non-root
$ancestral{$OG_analyzed}{$node->{'id'}}[0]=$C{$node->{'id'}}{$ancestral{$OG_analyzed}{$node->{'parentid'}}[0]};
}
}
return 1;
}
########################################################################
sub AncestralParsimony{
my @numAnc=keys %difOGs;
my $numAncSize=scalar(@numAnc);
for (my $j=1; $j<=$numAncSize;$j++){
$OG_analyzed=$difOGs{$numAnc[$j-1]}[0];
my %dist=();
foreach my $node ($tree->get_leaf_nodes){$dist{$node->internal_id}{$ancestral{$OG_analyzed}{$node->internal_id}[0]}=1;}
for my $node (@treepath){
if ($options{'ep'} =~/CWP/){
(!&Wagner(\@{$node->{'desc'}},\%dist, $node->{'id'})) && do{die;};
}else{
(!&Sankoff(\@{$node->{'desc'}},\%dist, $node->{'id'})) && do{die;};
}
}
for my $node (reverse @treepath){
if ($node->{'parentid'} ne 'NULL'){
$ancestral{$OG_analyzed}{$node->{'id'}}[0]=&MostProb(\%{$dist{$node->{'id'}}},$ancestral{$OG_analyzed}{$node->{'parentid'}}[0]);
}else{
$ancestral{$OG_analyzed}{$node->{'id'}}[0]=&MostProb(\%{$dist{$node->{'id'}}},-1);
}
}
}
foreach my $OG (@usedOG){ %{$ancestral{$OG}}=%{$ancestral{$difOGs{$OGstring{$OG}}[0]}};}
if ($options{'unobs'}){
my %dist=();
$OG_analyzed="UnobservedData";
foreach my $node ($tree->get_leaf_nodes){$dist{$node->internal_id}{$ancestral{$OG_analyzed}{$node->internal_id}[0]}=1;}
for my $node (@treepath){
if ($options{'ep'} =~/CWP/){
(!&Wagner(\@{$node->{'desc'}},\%dist, $node->{'id'})) && do{die;};
}else{
(!&Sankoff(\@{$node->{'desc'}},\%dist, $node->{'id'})) && do{die;};
}
}
for my $node (reverse @treepath){
if ($node->{'parentid'} ne 'NULL'){
$ancestral{$OG_analyzed}{$node->{'id'}}[0]=&MostProb(\%{$dist{$node->{'id'}}},$ancestral{$OG_analyzed}{$node->{'parentid'}}[0]);
}else{
$ancestral{$OG_analyzed}{$node->{'id'}}[0]=&MostProb(\%{$dist{$node->{'id'}}},-1);
}
}
}
return 1;
}
########################################################################
sub fdr($$){ #bejamini-hochberg
my ($rawp,$adjp)=@_;
my @tmp=@$rawp;
@$rawp= sort {$a <=> $b} @$rawp;
my @rawpcp=();
foreach (@$rawp){push(@rawpcp,$_);}
$$adjp{$$rawp[-1]}=$$rawp[-1];
for (my $i=scalar(@$rawp)-2;$i>=1;$i--){
my @min=($rawpcp[$i+1],(scalar(@$rawp)-1)/$i*$$rawp[$i],1);
my $minv=&min(\@min);
$rawpcp[$i]=$minv;
$$adjp{$$rawp[$i]}=$rawpcp[$i];
}
@$rawp=@tmp;
return 1;
}
########################################################################
sub printFloatNice($){
my ($float)=@_;
my $precision=7;
if ($float eq "NA"){
return "NA";
}else{
return sprintf("%.".$precision."f",$float);
}
}
########################################################################
sub readmodel($){
my ($model)=@_;
%bmodel=();
if (defined($model)){
my $cnt=0;
if (uc($model) eq "FR"){
foreach my $node (@nodes){
my $nodeid=$node->internal_id;
my $parentid=$node->ancestor->internal_id;
my $branch=$parentid."->".$nodeid;
$bmodel{$branch}=$cnt++;
}
}elsif ($model ne ""){
my @groups=split(/_/,$model);
my %branch_ctl=();
foreach my $group (@groups){
my @branches=split(/:/,$group);
foreach my $branch (@branches){
$bmodel{$branch}=$cnt;
$branch_ctl{$branch}=0 unless ($branch_ctl{$branch});
$branch_ctl{$branch}++;
die "Wrong branch model specification: $branch repeated\n" if ($branch_ctl{$branch}>1);
}
$cnt++;
}
foreach my $node (@nodes){
my $nodeid=$node->internal_id;
my $parentid=$node->ancestor->internal_id;
my $branch=$parentid."->".$nodeid;
next if (grep(/^$branch$/,keys %branch_ctl));
$bmodel{$branch}=$cnt;
}
}else{
foreach my $node (@nodes){
my $nodeid=$node->internal_id;
my $parentid=$node->ancestor->internal_id;
my $branch=$parentid."->".$nodeid;
$bmodel{$branch}=0;
}
}
}else{
foreach my $node (@nodes){
my $nodeid=$node->internal_id;
my $parentid=$node->ancestor->internal_id;
my $branch=$parentid."->".$nodeid;
$bmodel{$branch}=0;
}
}
return 1;
}
########################################################################
sub Sankoff($$$){
my ($desc,$dist,$nodeid)=@_;
my $OG=$OG_analyzed;
my $max_changes=($max{$OG}-$min{$OG})/$distances{$$desc[0][0]}{$nodeid} + ($max{$OG}-$min{$OG})/$distances{$$desc[1][0]}{$nodeid};
if (scalar(@{$$desc[2]})>0){
$max_changes+=($max{$OG}-$min{$OG})/$distances{$$desc[2][0]}{$nodeid};
}
my $sum=0;
for (my $i=$min{$OG};$i<=$max{$OG};$i++){
my $tmp1=0;
my $tmp2=0;
my $tmp3=0;
foreach my $k1 (keys %{$$dist{$$desc[0][0]}}){
if ($k1!=$i){
$tmp1+= $max_changes/(abs($k1-$i)/$distances{$$desc[0][0]}{$nodeid})*$$dist{$$desc[0][0]}{$k1};
}else{
$tmp1+=$MAX*$$dist{$$desc[0][0]}{$k1};
}
}
foreach my $k2 (keys %{$$dist{$$desc[1][0]}}){
if ($k2!=$i){
$tmp2+= $max_changes/(abs($k2-$i)/$distances{$$desc[1][0]}{$nodeid})*$$dist{$$desc[1][0]}{$k2};
}else{
$tmp2+=$MAX*$$dist{$$desc[1][0]}{$k2};
}
}
$$dist{$nodeid}{$i}=$tmp1*$tmp2;
if (scalar(@{$$desc[2]})>0){
my $out_weigth=1/scalar(@{$$desc[2]});
foreach my $out (sort @{$$desc[2]}){
foreach my $k3 (keys %{$$dist{$out}}){
if ($k3!=$i){
$tmp3+= $max_changes/(abs($k3-$i)/$distances{$out}{$nodeid})*$$dist{$out}{$k3}*$out_weigth;
}else{
$tmp3+=$MAX*$$dist{$out}{$k3}*$out_weigth;
}
}
}
$$dist{$nodeid}{$i}*=$tmp3;
}
$sum+=$$dist{$nodeid}{$i};
}
for (my $i=$min{$OG};$i<=$max{$OG};$i++){
$$dist{$nodeid}{$i}/=$sum;
}
return 1;
}
########################################################################
sub Wagner($$$){
my ($desc,$dist,$nodeid)=@_;
my @val1=keys %{$$dist{$$desc[0][0]}};
my @val2=keys %{$$dist{$$desc[1][0]}};
my @val=(@val1,@val2);
my $min1=&min(\@val1);
my $min2=&min(\@val2);
my $max1=&max(\@val1);
my $max2=&max(\@val2);
my $max=$min1;
if ($min1<$min2){
$max=$min2;
}
my $min=$max1;
if ($max1>$max2){
$min=$max2;
}
my $start=$max;
my $end=$min;
if ($start>$end){
$start=$min;
$end=$max;
}
for (my $i=$start; $i<=$end;$i++){
$$dist{$nodeid}{$i}=1;
}
return 1;
}
########################################################################
sub keysModel(){
my %modelval=();
foreach my $val (values %bmodel){
$modelval{$val}=0 unless ($modelval{$val});
$modelval{$val}++;
}
return keys %modelval;
}
########################################################################
sub getDifferentOGs(){
#strategy to increase speed computation: some OGs has the same size distribution in taxa, so reconstructing one the rest are the same
foreach my $OG (@usedOG){
my $string="";
foreach my $taxa ($tree->get_leaf_nodes()){
$string.=$ancestral{$OG}{$taxa->internal_id}[0]; #$fixed{$taxa->internal_id}{'v'}{$OG};
}
$OGstring{$OG}=$string;
push(@{$difOGs{$string}},$OG);
}
return 1;
}
########################################################################
sub root_dist($$){
my ($xb,$sm)=@_;
my $cnt=scalar(@$xb);
%OGOrder=();
if ($options{'root_dist'} == 1){
if ($options{'start_val'}==0){
my $sum=0;
foreach my $OG (@usedOG){
$sum+=$ancestral{$OG}{$root_node_id}[0];
}
push(@$xb,$sum/scalar(@usedOG));
push(@$sm,$sum/scalar(@usedOG)/2+$MIN);
}else{
push(@$xb,rand());
push(@$sm,rand());
}
$OGOrder{'ALL'}=$cnt;
}elsif ($options{'root_dist'} == 2){
foreach my $string (keys %difOGs){
my $OG=$difOGs{$string}[0];
$OG_analyzed=$OG;
if ($options{'start_val'}==0){
push(@$xb,$ancestral{$OG_analyzed}{$root_node_id}[0]);
push(@$sm,$ancestral{$OG_analyzed}{$root_node_id}[0]/2+$MIN);
}else{
push(@$xb,rand());
push(@$sm,rand());
}
$OGOrder{$OG_analyzed}=$cnt++;
}
}elsif ($options{'root_dist'} == 3){
if ($options{'start_val'} == 0){
my $sum=0;
foreach my $OG (@usedOG){
$sum+=$ancestral{$OG}{$root_node_id}[0];
}
my $p=0.5; # p = (variance - mean)/mean
my $n=$sum/scalar(@usedOG); #n = mean**2/(variance-mean)
push(@$xb,$n,$p);
push(@$sm,$n/2+$MIN,$p/2+$MIN);
}else{
push(@$xb,rand(),rand());
push(@$sm,rand(),rand());
}
$OGOrder{'ALL'}=$cnt;
}elsif ($options{'root_dist'} == 4){
foreach my $string (keys %difOGs){
my $OG=$difOGs{$string}[0];
$OG_analyzed=$OG;
if ($options{'start_val'} == 0){
my $p=0.5;
my $n=$ancestral{$OG_analyzed}{$root_node_id}[0];
push(@$xb,$n,$p);
push(@$sm,$n/2+$MIN,$p/2+$MIN);
}else{
push(@$xb,rand(),rand());
push(@$sm,rand(),rand());
}
$OGOrder{$OG_analyzed}=$cnt++;
}
}
return 1;
}
########################################################################
sub RatesParamBDI($$){
my ($xb,$sm)=@_;
%RatesOrder=();
%RatesOrder_rev=();
%OGOrder=();
my $cnt=0;
my @rates=("birth","death","innovation");
my @keys=&keysModel;
foreach my $bmodelstr (@keys){
if ($options{'start_val'}==0){
for my $rate (@rates){
if ($options{'ep'}=~/MAP/ && defined($priormodel{$bmodelstr}{$rate}{'shape'})){
push(@$xb,$priormodel{$bmodelstr}{$rate}{'shape'});
if ($priormodel{$bmodelstr}{$rate}{'shape'}>0){
push(@$sm,$priormodel{$bmodelstr}{$rate}{'shape'}/2 + $MIN);
}else{
push(@$sm,0);
}
}else{
if ($rate eq "birth"){
push(@$xb,$birth{$bmodelstr}[0]);
push(@$sm,$birth{$bmodelstr}[0]/2 + $MIN);
}elsif ($rate eq "death"){
push(@$xb,$death{$bmodelstr}[0]);
push(@$sm,$death{$bmodelstr}[0]/2 + $MIN);
}elsif ($rate eq "innovation"){
push(@$xb,$innovation{$bmodelstr}[0]);
push(@$sm,$innovation{$bmodelstr}[0]/2 + $MIN);
}
}
}
}else{
push(@$xb,rand(),rand(),rand());
push(@$sm,rand(),rand(),rand());
}
$RatesOrder{$bmodelstr}=$cnt++;
}
%RatesOrder_rev=reverse %RatesOrder;
(!&root_dist($xb,$sm)) && do{die;};
return 1;
}
########################################################################
sub RatesParamBD($$){
my ($xb,$sm)=@_;
%RatesOrder=();
%RatesOrder_rev=();
%OGOrder=();
my $cnt=0;
my @rates=("birth","death","innovation");
my @keys=&keysModel;
foreach my $bmodelstr (@keys){
if ($options{'start_val'}==0){
for my $rate (@rates){
if ($rate eq "innovation"){
push(@$xb,0);
push(@$sm,0);
}elsif ($options{'ep'}=~/MAP/ && defined($priormodel{$bmodelstr}{$rate}{'shape'})){
push(@$xb,$priormodel{$bmodelstr}{$rate}{'shape'});
if ($priormodel{$bmodelstr}{$rate}{'shape'}>0){
push(@$sm,$priormodel{$bmodelstr}{$rate}{'shape'}/2 + $MIN);
}else{
push(@$sm,0);
}
}else{
if ($rate eq "birth"){
push(@$xb,$birth{$bmodelstr}[0]);
push(@$sm,$birth{$bmodelstr}[0]/2 + $MIN);
}elsif ($rate eq "death"){
push(@$xb,$death{$bmodelstr}[0]);
push(@$sm,$death{$bmodelstr}[0]/2 + $MIN);
}
}
}
}else{
push(@$xb,rand(),rand(),0);
push(@$sm,rand(),rand(),0);
}
$RatesOrder{$bmodelstr}=$cnt++;
}
%RatesOrder_rev=reverse %RatesOrder;
(!&root_dist($xb,$sm)) && do{die;};
return 1;
}
########################################################################
sub RatesParamLI($$){
my ($xb,$sm)=@_;
%RatesOrder=();
%RatesOrder_rev=();
%OGOrder=();
my $cnt=0;
my @rates=("lambda","innovation");
my @keys=&keysModel;
foreach my $bmodelstr (@keys){
if ($options{'start_val'}==0){
for my $rate (@rates){
if ($options{'ep'}=~/MAP/ && defined($priormodel{$bmodelstr}{$rate}{'shape'})){
push(@$xb,$priormodel{$bmodelstr}{$rate}{'shape'});
if ($priormodel{$bmodelstr}{$rate}{'shape'}>0){
push(@$sm,$priormodel{$bmodelstr}{$rate}{'shape'}/2 + $MIN);
}else{
push(@$sm,0);
}
}else{
if ($rate eq "lambda"){
push(@$xb,$birth{$bmodelstr}[0]);