This repository has been archived by the owner on Feb 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 44
/
phylotesting.cpp
3473 lines (3077 loc) · 126 KB
/
phylotesting.cpp
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
/*
* phylotesting.cpp
*
* Created on: Aug 23, 2013
* Author: minh
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iqtree_config.h>
#include "tree/phylotree.h"
#include "tree/iqtree.h"
#include "tree/phylosupertree.h"
#include "tree/phylotreemixlen.h"
#include "phylotesting.h"
#include "model/modelmarkov.h"
#include "model/modeldna.h"
#include "nclextra/myreader.h"
#include "model/rateheterogeneity.h"
#include "model/rategamma.h"
#include "model/rateinvar.h"
#include "model/rategammainvar.h"
#include "model/ratefree.h"
#include "model/ratefreeinvar.h"
//#include "modeltest_wrapper.h"
#include "model/modelprotein.h"
#include "model/modelbin.h"
#include "model/modelcodon.h"
#include "model/modelmorphology.h"
#include "model/modelmixture.h"
#include "model/modelliemarkov.h"
#include "model/modelpomo.h"
#include "utils/timeutil.h"
#include "model/modelfactorymixlen.h"
#include "tree/phylosupertreeplen.h"
#include "phyloanalysis.h"
#include "gsl/mygsl.h"
#include "utils/MPIHelper.h"
//#include "vectorclass/vectorclass.h"
/******* Binary model set ******/
const char* bin_model_names[] = { "JC2", "GTR2" };
/******* Morphological model set ******/
// 2018-08-20: don't test ORDERED model due to lots of numerical issues
//const char* morph_model_names[] = {"MK", "ORDERED"};
const char* morph_model_names[] = {"MK"};
/******* DNA model set ******/
const char* dna_model_names[] = { "JC", "F81", "K80", "HKY", "TNe",
"TN", "K81", "K81u", "TPM2", "TPM2u", "TPM3", "TPM3u", "TIMe", "TIM",
"TIM2e", "TIM2", "TIM3e", "TIM3", "TVMe", "TVM", "SYM", "GTR" };
/* DNA models supported by PhyML/PartitionFinder */
const char* dna_model_names_old[] ={"JC", "F81", "K80", "HKY", "TNe",
"TN", "K81", "K81u", "TIMe", "TIM", "TVMe", "TVM", "SYM", "GTR"};
/* DNA model supported by RAxML */
const char* dna_model_names_rax[] ={"GTR"};
/* DNA model supported by MrBayes */
const char *dna_model_names_mrbayes[] = {"JC", "F81", "K80", "HKY", "SYM", "GTR"};
//const char* dna_freq_names[] = {"+FO"};
// Lie-Markov models without an RY, WS or MK prefix
const char *dna_model_names_lie_markov_fullsym[] =
{"1.1", "3.3a", "4.4a", "6.7a", "9.20b", "12.12"};
// Lie-Markov models with RY symmetry/distinguished pairing
const char *dna_model_names_lie_markov_ry[] = {
"RY2.2b", "RY3.3b", "RY3.3c", "RY3.4", "RY4.4b",
"RY4.5a", "RY4.5b", "RY5.6a", "RY5.6b", "RY5.7a",
"RY5.7b", "RY5.7c", "RY5.11a", "RY5.11b", "RY5.11c",
"RY5.16", "RY6.6", "RY6.7b", "RY6.8a", "RY6.8b",
"RY6.17a", "RY6.17b","RY8.8", "RY8.10a", "RY8.10b",
"RY8.16", "RY8.17", "RY8.18", "RY9.20a", "RY10.12",
"RY10.34"
};
// Lie-Markov models with WS symmetry/distinguished pairing
const char *dna_model_names_lie_markov_ws[] = {
"WS2.2b", "WS3.3b", "WS3.3c", "WS3.4", "WS4.4b",
"WS4.5a", "WS4.5b", "WS5.6a", "WS5.6b", "WS5.7a",
"WS5.7b", "WS5.7c", "WS5.11a", "WS5.11b", "WS5.11c",
"WS5.16", "WS6.6", "WS6.7b", "WS6.8a", "WS6.8b",
"WS6.17a", "WS6.17b","WS8.8", "WS8.10a", "WS8.10b",
"WS8.16", "WS8.17", "WS8.18", "WS9.20a", "WS10.12",
"WS10.34"
};
// Lie-Markov models with MK symmetry/distinguished pairing
const char *dna_model_names_lie_markov_mk[] = {
"MK2.2b", "MK3.3b", "MK3.3c", "MK3.4", "MK4.4b",
"MK4.5a", "MK4.5b", "MK5.6a", "MK5.6b", "MK5.7a",
"MK5.7b", "MK5.7c", "MK5.11a", "MK5.11b", "MK5.11c",
"MK5.16", "MK6.6", "MK6.7b", "MK6.8a", "MK6.8b",
"MK6.17a", "MK6.17b","MK8.8", "MK8.10a", "MK8.10b",
"MK8.16", "MK8.17", "MK8.18", "MK9.20a", "MK10.12",
"MK10.34"
};
// Lie-Markov models which are strand symmetric
const char *dna_model_names_lie_markov_strsym[] = {
"1.1", "WS2.2b", "3.3a", "WS3.3b", "WS3.3c", "WS3.4",
"WS4.4b", "WS4.5a", "WS4.5b", "WS5.6a", "WS6.6"
};
/****** Protein model set ******/
const char* aa_model_names[] = { "Dayhoff", "mtMAM", "JTT", "WAG",
"cpREV", "mtREV", "rtREV", "mtART", "mtZOA", "VT", "LG", "DCMut", "PMB",
"HIVb", "HIVw", "JTTDCMut", "FLU", "Blosum62" , "mtMet" , "mtVer" , "mtInv" };
/* Protein models supported by PhyML/PartitionFinder */
const char *aa_model_names_phyml[] = { "Dayhoff", "mtMAM", "JTT", "WAG",
"cpREV", "mtREV", "rtREV", "mtART", "VT", "LG", "DCMut",
"HIVb", "HIVw", "Blosum62" };
/* Protein models supported by RAxML */
const char *aa_model_names_rax[] = { "Dayhoff", "mtMAM", "JTT", "WAG",
"cpREV", "mtREV", "rtREV", "mtART", "mtZOA", "PMB", "HIVb", "HIVw", "JTTDCMut", "FLU", "VT", "LG", "DCMut", "Blosum62" };
const char* aa_model_names_mrbayes[] = {"Poisson", "Dayhoff", "mtMAM", "JTT", "WAG",
"cpREV", "mtREV", "rtREV", "VT", "Blosum62" };
const char *aa_model_names_nuclear[] = {"WAG", "Dayhoff","JTT", "LG", "VT", "DCMut", "PMB", "JTTDCMut", "Blosum62"};
const char *aa_model_names_mitochondrial[] = {"mtREV", "mtMAM", "mtART", "mtZOA", "mtMet" , "mtVer" , "mtInv" };
const char *aa_model_names_chloroplast[] = {"cpREV"};
const char *aa_model_names_viral[] = {"HIVb", "HIVw", "FLU", "rtREV"};
const char* aa_freq_names[] = {"", "+F"};
/****** Codon models ******/
//const char *codon_model_names[] = {"GY", "MG", "MGK", "KOSI07", "SCHN05","KOSI07_GY1KTV","SCHN05_GY1KTV"};
//short int std_genetic_code[] = { 0, 0, 0, 1, 1, 1, 1};
const char *codon_model_names[] = {"MG", "MGK", "GY", "KOSI07", "SCHN05"};
short int std_genetic_code[] = { 0, 0, 0, 1, 1};
const char *codon_freq_names[] = {"", "+F1X4", "+F3X4", "+F"};
const double TOL_LIKELIHOOD_MODELTEST = 0.1;
const double TOL_GRADIENT_MODELTEST = 0.0001;
string getSeqTypeName(SeqType seq_type) {
switch (seq_type) {
case SEQ_BINARY: return "binary";
case SEQ_DNA: return "DNA";
case SEQ_PROTEIN: return "protein";
case SEQ_CODON: return "codon";
case SEQ_MORPH: return "morphological";
case SEQ_POMO: return "PoMo";
case SEQ_UNKNOWN: return "unknown";
case SEQ_MULTISTATE: return "MultiState";
}
}
string getUsualModelName(SeqType seq_type) {
switch (seq_type) {
case SEQ_DNA: return "GTR+F+G";
case SEQ_PROTEIN: return "LG+F+G";
case SEQ_CODON: return "GY"; break; // too much computation, thus no +G
case SEQ_BINARY: return "GTR2+G";
case SEQ_MORPH: return "MK+G";
case SEQ_POMO: return "GTR+P";
default: ASSERT(0 && "Unprocessed seq_type"); return "";
}
}
void ModelInfo::computeICScores(size_t sample_size) {
computeInformationScores(logl, df, sample_size, AIC_score, AICc_score, BIC_score);
}
double ModelInfo::computeICScore(size_t sample_size) {
return computeInformationScore(logl, df, sample_size, Params::getInstance().model_test_criterion);
}
bool ModelCheckpoint::getBestModel(string &best_model) {
return getString("best_model_" + criterionName(Params::getInstance().model_test_criterion), best_model);
}
bool ModelCheckpoint::getBestTree(string &best_tree) {
return getString("best_tree_" + criterionName(Params::getInstance().model_test_criterion), best_tree);
}
bool ModelCheckpoint::getOrderedModels(PhyloTree *tree, vector<ModelInfo> &ordered_models) {
double best_score_AIC, best_score_AICc, best_score_BIC;
if (tree->isSuperTree()) {
PhyloSuperTree *stree = (PhyloSuperTree*)tree;
ordered_models.clear();
for (int part = 0; part != stree->size(); part++) {
startStruct(stree->at(part)->aln->name);
ModelInfo info;
if (!getBestModel(info.name)) return false;
info.restoreCheckpoint(this);
info.computeICScores(stree->at(part)->getAlnNSite());
endStruct();
ordered_models.push_back(info);
}
return true;
} else {
CKP_RESTORE2(this, best_score_AIC);
CKP_RESTORE2(this, best_score_AICc);
CKP_RESTORE2(this, best_score_BIC);
double sum_AIC = 0, sum_AICc = 0, sum_BIC = 0;
string str;
bool ret = getString("best_model_list_" + criterionName(Params::getInstance().model_test_criterion), str);
if (!ret) return false;
istringstream istr(str);
string model;
ordered_models.clear();
while (istr >> model) {
ModelInfo info;
info.name = model;
info.restoreCheckpoint(this);
info.computeICScores(tree->getAlnNSite());
sum_AIC += info.AIC_weight = exp(-0.5*(info.AIC_score-best_score_AIC));
sum_AICc += info.AICc_weight = exp(-0.5*(info.AICc_score-best_score_AICc));
sum_BIC += info.BIC_weight = exp(-0.5*(info.BIC_score-best_score_BIC));
ordered_models.push_back(info);
}
sum_AIC = 1.0/sum_AIC;
sum_AICc = 1.0/sum_AICc;
sum_BIC = 1.0/sum_BIC;
for (auto it = ordered_models.begin(); it != ordered_models.end(); it++) {
it->AIC_weight *= sum_AIC;
it->AICc_weight *= sum_AICc;
it->BIC_weight *= sum_BIC;
it->AIC_conf = it->AIC_weight > 0.05;
it->AICc_conf = it->AICc_weight > 0.05;
it->BIC_conf = it->BIC_weight > 0.05;
}
return true;
}
}
/**
* copy from cvec to strvec
*/
void copyCString(const char **cvec, int n, StrVector &strvec, bool touppercase = false) {
strvec.resize(n);
for (int i = 0; i < n; i++) {
strvec[i] = cvec[i];
if (touppercase)
std::transform(strvec[i].begin(), strvec[i].end(), strvec[i].begin(), ::toupper);
}
}
/**
* append from cvec to strvec
*/
void appendCString(const char **cvec, int n, StrVector &strvec, bool touppercase = false) {
strvec.reserve(strvec.size()+n);
for (int i = 0; i < n; i++) {
strvec.push_back(cvec[i]);
if (touppercase)
std::transform(strvec.back().begin(), strvec.back().end(), strvec.back().begin(), ::toupper);
}
}
int detectSeqType(const char *model_name, SeqType &seq_type) {
bool empirical_model = false;
int i;
string model_str = model_name;
std::transform(model_str.begin(), model_str.end(), model_str.begin(), ::toupper);
StrVector model_list;
seq_type = SEQ_UNKNOWN;
copyCString(bin_model_names, sizeof(bin_model_names)/sizeof(char*), model_list, true);
for (i = 0; i < model_list.size(); i++)
if (model_str == model_list[i]) {
seq_type = SEQ_BINARY;
break;
}
copyCString(morph_model_names, sizeof(morph_model_names)/sizeof(char*), model_list, true);
for (i = 0; i < model_list.size(); i++)
if (model_str == model_list[i]) {
seq_type = SEQ_MORPH;
break;
}
copyCString(dna_model_names, sizeof(dna_model_names)/sizeof(char*), model_list, true);
for (i = 0; i < model_list.size(); i++)
if (model_str == model_list[i]) {
seq_type = SEQ_DNA;
break;
}
copyCString(aa_model_names, sizeof(aa_model_names)/sizeof(char*), model_list, true);
for (i = 0; i < model_list.size(); i++)
if (model_str == model_list[i]) {
seq_type = SEQ_PROTEIN;
empirical_model = true;
break;
}
copyCString(codon_model_names, sizeof(codon_model_names)/sizeof(char*), model_list, true);
for (i = 0; i < model_list.size(); i++)
if (model_str.substr(0,model_list[i].length()) == model_list[i]) {
seq_type = SEQ_CODON;
if (std_genetic_code[i]) empirical_model = true;
break;
}
return (empirical_model) ? 2 : 1;
}
string detectSeqTypeName(string model_name) {
SeqType seq_type;
detectSeqType(model_name.c_str(), seq_type);
switch (seq_type) {
case SEQ_BINARY: return "BIN"; break;
case SEQ_MORPH: return "MORPH"; break;
case SEQ_DNA: return "DNA"; break;
case SEQ_PROTEIN: return "AA"; break;
case SEQ_CODON: return "CODON"; break;
default: break;
}
return "";
}
void computeInformationScores(double tree_lh, int df, int ssize, double &AIC, double &AICc, double &BIC) {
AIC = -2 * tree_lh + 2 * df;
AICc = AIC + 2.0 * df * (df + 1) / max(ssize - df - 1, 1);
BIC = -2 * tree_lh + df * log(ssize);
}
double computeInformationScore(double tree_lh, int df, int ssize, ModelTestCriterion mtc) {
double AIC, AICc, BIC;
computeInformationScores(tree_lh, df, ssize, AIC, AICc, BIC);
if (mtc == MTC_AIC)
return AIC;
if (mtc == MTC_AICC)
return AICc;
if (mtc == MTC_BIC)
return BIC;
return 0.0;
}
string criterionName(ModelTestCriterion mtc) {
if (mtc == MTC_AIC)
return "AIC";
if (mtc == MTC_AICC)
return "AICc";
if (mtc == MTC_BIC)
return "BIC";
return "";
}
void printSiteLh(const char*filename, PhyloTree *tree, double *ptn_lh,
bool append, const char *linename) {
int i;
double *pattern_lh;
if (!ptn_lh) {
pattern_lh = new double[tree->getAlnNPattern()];
tree->computePatternLikelihood(pattern_lh);
} else
pattern_lh = ptn_lh;
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
if (append) {
out.open(filename, ios::out | ios::app);
} else {
out.open(filename);
out << 1 << " " << tree->getAlnNSite() << endl;
}
IntVector pattern_index;
tree->aln->getSitePatternIndex(pattern_index);
if (!linename)
out << "Site_Lh ";
else {
out.width(10);
out << left << linename;
}
for (i = 0; i < tree->getAlnNSite(); i++)
out << " " << pattern_lh[pattern_index[i]];
out << endl;
out.close();
if (!append)
cout << "Site log-likelihoods printed to " << filename << endl;
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, filename);
}
if (!ptn_lh)
delete[] pattern_lh;
}
void printPartitionLh(const char*filename, PhyloTree *tree, double *ptn_lh,
bool append, const char *linename) {
ASSERT(tree->isSuperTree());
PhyloSuperTree *stree = (PhyloSuperTree*)tree;
int i;
double *pattern_lh;
if (!ptn_lh) {
pattern_lh = new double[tree->getAlnNPattern()];
tree->computePatternLikelihood(pattern_lh);
} else
pattern_lh = ptn_lh;
double partition_lh[stree->size()];
int part;
double *pattern_lh_ptr = pattern_lh;
for (part = 0; part < stree->size(); part++) {
size_t nptn = stree->at(part)->getAlnNPattern();
partition_lh[part] = 0.0;
for (i = 0; i < nptn; i++)
partition_lh[part] += pattern_lh_ptr[i] * stree->at(part)->ptn_freq[i];
pattern_lh_ptr += nptn;
}
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
if (append) {
out.open(filename, ios::out | ios::app);
} else {
out.open(filename);
out << 1 << " " << stree->size() << endl;
}
if (!linename)
out << "Part_Lh ";
else {
out.width(10);
out << left << linename;
}
for (i = 0; i < stree->size(); i++)
out << " " << partition_lh[i];
out << endl;
out.close();
if (!append)
cout << "Partition log-likelihoods printed to " << filename << endl;
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, filename);
}
if (!ptn_lh)
delete[] pattern_lh;
}
void printSiteLhCategory(const char*filename, PhyloTree *tree, SiteLoglType wsl) {
if (wsl == WSL_NONE || wsl == WSL_SITE)
return;
int ncat = tree->getNumLhCat(wsl);
if (tree->isSuperTree()) {
PhyloSuperTree *stree = (PhyloSuperTree*)tree;
for (auto it = stree->begin(); it != stree->end(); it++) {
int part_ncat = (*it)->getNumLhCat(wsl);
if (part_ncat > ncat)
ncat = part_ncat;
}
}
int i;
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
out.open(filename);
out << "# Site likelihood per rate/mixture category" << endl
<< "# This file can be read in MS Excel or in R with command:" << endl
<< "# tab=read.table('" << filename << "',header=TRUE,fill=TRUE)" << endl
<< "# Columns are tab-separated with following meaning:" << endl;
if (tree->isSuperTree()) {
out << "# Part: Partition ID (1=" << ((PhyloSuperTree*)tree)->at(0)->aln->name << ", etc)" << endl
<< "# Site: Site ID within partition (starting from 1 for each partition)" << endl;
} else
out << "# Site: Alignment site ID" << endl;
out << "# LnL: Logarithm of site likelihood" << endl
<< "# Thus, sum of LnL is equal to tree log-likelihood" << endl
<< "# LnLW_k: Logarithm of (category-k site likelihood times category-k weight)" << endl
<< "# Thus, sum of exp(LnLW_k) is equal to exp(LnL)" << endl;
if (tree->isSuperTree()) {
out << "Part\tSite\tLnL";
} else
out << "Site\tLnL";
for (i = 0; i < ncat; i++)
out << "\tLnLW_" << i+1;
out << endl;
out.precision(4);
out.setf(ios::fixed);
tree->writeSiteLh(out, wsl);
out.close();
cout << "Site log-likelihoods per category printed to " << filename << endl;
/*
if (!tree->isSuperTree()) {
cout << "Log-likelihood of constant sites: " << endl;
double const_prob = 0.0;
for (i = 0; i < tree->aln->getNPattern(); i++)
if (tree->aln->at(i).isConst()) {
Pattern pat = tree->aln->at(i);
for (Pattern::iterator it = pat.begin(); it != pat.end(); it++)
cout << tree->aln->convertStateBackStr(*it);
cout << ": " << pattern_lh[i] << endl;
const_prob += exp(pattern_lh[i]);
}
cout << "Probability of const sites: " << const_prob << endl;
}
*/
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, filename);
}
}
void printAncestralSequences(const char *out_prefix, PhyloTree *tree, AncestralSeqType ast) {
// int *joint_ancestral = NULL;
//
// if (tree->params->print_ancestral_sequence == AST_JOINT) {
// joint_ancestral = new int[nptn*tree->leafNum];
// tree->computeJointAncestralSequences(joint_ancestral);
// }
string filename = (string)out_prefix + ".state";
// string filenameseq = (string)out_prefix + ".stateseq";
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
out.open(filename.c_str());
out.setf(ios::fixed, ios::floatfield);
out.precision(5);
// ofstream outseq;
// outseq.exceptions(ios::failbit | ios::badbit);
// outseq.open(filenameseq.c_str());
NodeVector nodes;
tree->getInternalNodes(nodes);
double *marginal_ancestral_prob;
int *marginal_ancestral_seq;
// if (tree->params->print_ancestral_sequence == AST_JOINT)
// outseq << 2*(tree->nodeNum-tree->leafNum) << " " << nsites << endl;
// else
// outseq << (tree->nodeNum-tree->leafNum) << " " << nsites << endl;
//
// int name_width = max(tree->aln->getMaxSeqNameLength(),6)+10;
out << "# Ancestral state reconstruction for all nodes in " << tree->params->out_prefix << ".treefile" << endl
<< "# This file can be read in MS Excel or in R with command:" << endl
<< "# tab=read.table('" << tree->params->out_prefix << ".state',header=TRUE)" << endl
<< "# Columns are tab-separated with following meaning:" << endl
<< "# Node: Node name in the tree" << endl;
if (tree->isSuperTree()) {
PhyloSuperTree *stree = (PhyloSuperTree*)tree;
out << "# Part: Partition ID (1=" << stree->at(0)->aln->name << ", etc)" << endl
<< "# Site: Site ID within partition (starting from 1 for each partition)" << endl;
} else
out << "# Site: Alignment site ID" << endl;
out << "# State: Most likely state assignment" << endl
<< "# p_X: Posterior probability for state X (empirical Bayesian method)" << endl;
if (tree->isSuperTree()) {
PhyloSuperTree *stree = (PhyloSuperTree*)tree;
out << "Node\tPart\tSite\tState";
for (size_t i = 0; i < stree->front()->aln->num_states; i++)
out << "\tp_" << stree->front()->aln->convertStateBackStr(i);
} else {
out << "Node\tSite\tState";
for (size_t i = 0; i < tree->aln->num_states; i++)
out << "\tp_" << tree->aln->convertStateBackStr(i);
}
out << endl;
bool orig_kernel_nonrev;
tree->initMarginalAncestralState(out, orig_kernel_nonrev, marginal_ancestral_prob, marginal_ancestral_seq);
for (NodeVector::iterator it = nodes.begin(); it != nodes.end(); it++) {
PhyloNode *node = (PhyloNode*)(*it);
PhyloNode *dad = (PhyloNode*)node->neighbors[0]->node;
tree->computeMarginalAncestralState((PhyloNeighbor*)dad->findNeighbor(node), dad,
marginal_ancestral_prob, marginal_ancestral_seq);
// int *joint_ancestral_node = joint_ancestral + (node->id - tree->leafNum)*nptn;
// set node name if neccessary
if (node->name.empty() || !isalpha(node->name[0])) {
node->name = "Node" + convertIntToString(node->id-tree->leafNum+1);
}
// print ancestral state probabilities
tree->writeMarginalAncestralState(out, node, marginal_ancestral_prob, marginal_ancestral_seq);
// print ancestral sequences
// outseq.width(name_width);
// outseq << left << node->name << " ";
// for (i = 0; i < nsites; i++)
// outseq << tree->aln->convertStateBackStr(marginal_ancestral_seq[pattern_index[i]]);
// outseq << endl;
//
// if (tree->params->print_ancestral_sequence == AST_JOINT) {
// outseq.width(name_width);
// outseq << left << (node->name+"_joint") << " ";
// for (i = 0; i < nsites; i++)
// outseq << tree->aln->convertStateBackStr(joint_ancestral_node[pattern_index[i]]);
// outseq << endl;
// }
}
tree->endMarginalAncestralState(orig_kernel_nonrev, marginal_ancestral_prob, marginal_ancestral_seq);
out.close();
// outseq.close();
cout << "Ancestral state probabilities printed to " << filename << endl;
// cout << "Ancestral sequences printed to " << filenameseq << endl;
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, filename);
}
// if (joint_ancestral)
// delete[] joint_ancestral;
}
void printSiteProbCategory(const char*filename, PhyloTree *tree, SiteLoglType wsl) {
if (wsl == WSL_NONE || wsl == WSL_SITE)
return;
// error checking
if (!tree->getModel()->isMixture()) {
if (wsl != WSL_RATECAT) {
outWarning("Switch now to '-wspr' as it is the only option for non-mixture model");
wsl = WSL_RATECAT;
}
} else {
// mixture model
if (wsl == WSL_MIXTURE_RATECAT && tree->getModelFactory()->fused_mix_rate) {
outWarning("-wspmr is not suitable for fused mixture model, switch now to -wspm");
wsl = WSL_MIXTURE;
}
}
size_t cat, ncat = tree->getNumLhCat(wsl);
double *ptn_prob_cat = new double[((size_t)tree->getAlnNPattern())*ncat];
tree->computePatternProbabilityCategory(ptn_prob_cat, wsl);
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
out.open(filename);
if (tree->isSuperTree())
out << "Set\t";
out << "Site";
for (cat = 0; cat < ncat; cat++)
out << "\tp" << cat+1;
out << endl;
IntVector pattern_index;
if (tree->isSuperTree()) {
PhyloSuperTree *super_tree = (PhyloSuperTree*)tree;
size_t offset = 0;
for (PhyloSuperTree::iterator it = super_tree->begin(); it != super_tree->end(); it++) {
size_t part_ncat = (*it)->getNumLhCat(wsl);
(*it)->aln->getSitePatternIndex(pattern_index);
size_t site, nsite = (*it)->aln->getNSite();
for (site = 0; site < nsite; site++) {
out << (it-super_tree->begin())+1 << "\t" << site+1;
double *prob_cat = ptn_prob_cat + (offset+pattern_index[site]*part_ncat);
for (cat = 0; cat < part_ncat; cat++)
out << "\t" << prob_cat[cat];
out << endl;
}
offset += (*it)->aln->getNPattern()*(*it)->getNumLhCat(wsl);
}
} else {
tree->aln->getSitePatternIndex(pattern_index);
int nsite = tree->getAlnNSite();
for (int site = 0; site < nsite; site++) {
out << site+1;
double *prob_cat = ptn_prob_cat + pattern_index[site]*ncat;
for (cat = 0; cat < ncat; cat++) {
out << "\t" << prob_cat[cat];
}
out << endl;
}
}
out.close();
cout << "Site probabilities per category printed to " << filename << endl;
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, filename);
}
}
void printSiteStateFreq(const char*filename, PhyloTree *tree, double *state_freqs) {
int i, j, nsites = tree->getAlnNSite(), nstates = tree->aln->num_states;
double *ptn_state_freq;
if (state_freqs) {
ptn_state_freq = state_freqs;
} else {
ptn_state_freq = new double[((size_t)tree->getAlnNPattern()) * nstates];
tree->computePatternStateFreq(ptn_state_freq);
}
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
out.open(filename);
IntVector pattern_index;
tree->aln->getSitePatternIndex(pattern_index);
for (i = 0; i < nsites; i++) {
out.width(6);
out << left << i+1 << " ";
double *state_freq = &ptn_state_freq[pattern_index[i]*nstates];
for (j = 0; j < nstates; j++) {
out.width(15);
out << state_freq[j] << " ";
}
out << endl;
}
out.close();
cout << "Site state frequency vectors printed to " << filename << endl;
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, filename);
}
if (!state_freqs)
delete [] ptn_state_freq;
}
void printSiteStateFreq(const char* filename, Alignment *aln) {
if (aln->site_state_freq.empty())
return;
int i, j, nsites = aln->getNSite(), nstates = aln->num_states;
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
out.open(filename);
IntVector pattern_index;
aln->getSitePatternIndex(pattern_index);
for (i = 0; i < nsites; i++) {
out.width(6);
out << left << i+1 << " ";
double *state_freq = aln->site_state_freq[pattern_index[i]];
for (j = 0; j < nstates; j++) {
out.width(15);
out << state_freq[j] << " ";
}
out << endl;
}
out.close();
cout << "Site state frequency vectors printed to " << filename << endl;
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, filename);
}
}
/*
bool checkModelFile(ifstream &in, bool is_partitioned, ModelCheckpoint &infos) {
if (!in.is_open()) return false;
in.exceptions(ios::badbit);
string str;
if (is_partitioned) {
in >> str;
if (str != "Charset")
return false;
}
in >> str;
if (str != "Model")
return false;
in >> str;
if (str != "df")
return false;
in >> str;
if (str != "LnL")
return false;
in >> str;
if (str != "TreeLen") {
outWarning(".model file was produced from a previous version of IQ-TREE");
return false;
}
safeGetline(in, str);
while (!in.eof()) {
in >> str;
if (in.eof())
break;
ModelInfo info;
if (is_partitioned) {
info.set_name = str;
in >> str;
}
info.name = str;
in >> info.df >> info.logl >> info.tree_len;
safeGetline(in, str);
info.tree = "";
if (*str.rbegin() == ';') {
size_t pos = str.rfind('\t');
if (pos != string::npos)
info.tree = str.substr(pos+1);
// else
// outWarning(".model file was produced from a previous version of IQ-TREE");
}
infos.push_back(info);
//cout << str << " " << df << " " << logl << endl;
}
in.clear();
return true;
}
bool checkModelFile(string model_file, bool is_partitioned, ModelCheckpoint &infos) {
if (!fileExists(model_file))
return false;
//cout << model_file << " exists, checking this file" << endl;
ifstream in;
try {
in.exceptions(ios::failbit | ios::badbit);
in.open(model_file.c_str());
if (!checkModelFile(in, is_partitioned, infos))
throw false;
// set the failbit again
in.exceptions(ios::failbit | ios::badbit);
in.close();
} catch (bool ret) {
in.close();
return ret;
} catch (ios::failure) {
outError("Cannot read file ", model_file);
}
return true;
}
*/
/**
testing the best-fit model
return in params.freq_type and params.rate_type
@param set_name for partitioned analysis
@param in_tree phylogenetic tree
@param model_info (IN/OUT) information for all models considered
@param set_name for partition model selection
@param print_mem_usage true to print RAM memory used (default: false)
@return name of best-fit-model
*/
string testModel(Params ¶ms, PhyloTree* in_tree, ModelCheckpoint &model_info,
ModelsBlock *models_block, int num_threads, int brlen_type,
string set_name = "", bool print_mem_usage = false, string in_model_name = "");
void runModelFinder(Params ¶ms, IQTree &iqtree, ModelCheckpoint &model_info)
{
ModelsBlock *models_block = readModelsDefinition(params);
// iqtree.setCurScore(-DBL_MAX);
bool test_only = (params.model_name.find("ONLY") != string::npos) ||
(params.model_name.substr(0,2) == "MF" && params.model_name.substr(0,3) != "MFP");
bool empty_model_found = params.model_name.empty() && !iqtree.isSuperTree();
if (params.model_name.empty() && iqtree.isSuperTree()) {
// check whether any partition has empty model_name
PhyloSuperTree *stree = (PhyloSuperTree*)&iqtree;
for (auto i = stree->begin(); i != stree->end(); i++)
if ((*i)->aln->model_name.empty()) {
empty_model_found = true;
break;
}
}
// Model already specifed, nothing to do here
if (!empty_model_found && params.model_name.substr(0, 4) != "TEST" && params.model_name.substr(0, 2) != "MF")
return;
if (MPIHelper::getInstance().getNumProcesses() > 1)
outError("Please use only 1 MPI process! We are currently working on the MPI parallelization of model selection.");
// TODO: check if necessary
// if (iqtree.isSuperTree())
// ((PhyloSuperTree*) &iqtree)->mapTrees();
double cpu_time = getCPUTime();
double real_time = getRealTime();
model_info.setFileName((string)params.out_prefix + ".model.gz");
model_info.setDumpInterval(params.checkpoint_dump_interval);
bool ok_model_file = false;
if (!params.print_site_lh && !params.model_test_again) {
ok_model_file = model_info.load();
}
cout << endl;
ok_model_file &= model_info.size() > 0;
if (ok_model_file)
cout << "NOTE: Restoring information from model checkpoint file " << model_info.getFileName() << endl;
Checkpoint *orig_checkpoint = iqtree.getCheckpoint();
iqtree.setCheckpoint(&model_info);
iqtree.restoreCheckpoint();
int partition_type;
if (CKP_RESTORE2((&model_info), partition_type)) {
if (partition_type != params.partition_type)
outError("Mismatch partition type between checkpoint and partition file command option");
} else {
partition_type = params.partition_type;
CKP_SAVE2((&model_info), partition_type);
}
// compute initial tree
iqtree.computeInitialTree(params.SSE);
if (iqtree.isSuperTree()) {
PhyloSuperTree *stree = (PhyloSuperTree*)&iqtree;
int part = 0;
for (auto it = stree->begin(); it != stree->end(); it++, part++) {
model_info.startStruct((*it)->aln->name);
(*it)->saveCheckpoint();
model_info.endStruct();
}
} else {
iqtree.saveCheckpoint();
}
// also save initial tree to the original .ckp.gz checkpoint
// string initTree = iqtree.getTreeString();
// CKP_SAVE(initTree);
// iqtree.saveCheckpoint();
// checkpoint->dump(true);
//params.model_name =
iqtree.aln->model_name = testModel(params, &iqtree, model_info, models_block, params.num_threads, BRLEN_OPTIMIZE, "", true);
iqtree.setCheckpoint(orig_checkpoint);
params.startCPUTime = cpu_time;
params.start_real_time = real_time;
cpu_time = getCPUTime() - cpu_time;
real_time = getRealTime() - real_time;
cout << endl;
cout << "All model information printed to " << model_info.getFileName() << endl;
cout << "CPU time for ModelFinder: " << cpu_time << " seconds (" << convert_time(cpu_time) << ")" << endl;
cout << "Wall-clock time for ModelFinder: " << real_time << " seconds (" << convert_time(real_time) << ")" << endl;
// alignment = iqtree.aln;
if (test_only) {
params.min_iterations = 0;
}
}
/**
* get the list of model
* @param models (OUT) vectors of model names
* @return maximum number of rate categories
*/
int getModelList(Params ¶ms, Alignment *aln, StrVector &models, bool separate_rate = false) {
StrVector model_names;
StrVector freq_names;
SeqType seq_type = aln->seq_type;
const char *rate_options[] = { "", "+I", "+ASC", "+G", "+I+G", "+ASC+G", "+R", "+ASC+R"};
bool test_options_default[] = {true, true, false, true, true, false,false, false};
bool test_options_morph[] = {true,false, true, true, false, true,false, false};
bool test_options_noASC_I[] = {true,false, false, true, false, false,false, false};
bool test_options_asc[] ={false,false, true,false, false, true,false, false};
bool test_options_new[] = {true, true, false, true, true, false, true, false};
bool test_options_morph_new[] = {true,false, true, true, false, true, true, true};
bool test_options_noASC_I_new[] = {true,false, false, true, false, false, true, false};
bool test_options_asc_new[] ={false,false, true,false, false, true,false, true};
bool test_options_pomo[] = {true, false, false, true, false, false,false, false};
bool test_options_norate[] = {true, false, false, false, false, false,false, false};
bool *test_options = test_options_default;
// bool test_options_codon[] = {true,false, false,false, false, false};
const int noptions = sizeof(rate_options) / sizeof(char*);
int i, j;
if (seq_type == SEQ_BINARY) {
if (params.model_set == NULL) {
copyCString(bin_model_names, sizeof(bin_model_names) / sizeof(char*), model_names);
} else {
convert_string_vec(params.model_set, model_names);
}
} else if (seq_type == SEQ_MORPH) {
if (params.model_set == NULL) {
copyCString(morph_model_names, sizeof(morph_model_names) / sizeof(char*), model_names);
} else {
convert_string_vec(params.model_set, model_names);
}
} else if (seq_type == SEQ_DNA || seq_type == SEQ_POMO) {
if (params.model_set == NULL) {
copyCString(dna_model_names, sizeof(dna_model_names) / sizeof(char*), model_names);
// copyCString(dna_freq_names, sizeof(dna_freq_names)/sizeof(char*), freq_names);
} else if (strcmp(params.model_set, "partitionfinder") == 0 || strcmp(params.model_set, "phyml") == 0) {