forked from diepthihoang/mpboot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiqtree.cpp
More file actions
4706 lines (4170 loc) · 167 KB
/
iqtree.cpp
File metadata and controls
4706 lines (4170 loc) · 167 KB
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
/***************************************************************************
* Copyright (C) 2009 by BUI Quang Minh *
* minh.bui@univie.ac.at *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "iqtree.h"
#include "phylosupertree.h"
#include "phylosupertreeplen.h"
#include "mexttree.h"
#include "timeutil.h"
#include "model/modelgtr.h"
#include "model/rategamma.h"
#include <numeric>
#include "pllrepo/src/pllInternal.h"
#include "nnisearch.h"
#include "sprparsimony.h"
#include "treefusing.h"
#include "vectorclass/vectorclass.h"
#include "vectorclass/vectormath_common.h"
#include "parstree.h"
Params *globalParam;
Alignment *globalAlignment;
extern StringIntMap pllTreeCounter;
unsigned int * pllCostMatrix; // Diep: For weighted version
int pllCostNstates; // Diep: For weighted version
parsimonyNumber *vectorCostMatrix = NULL; // BQM: vectorized cost matrix
int pllRepsSegments;
int * pllSegmentUpper;
IQTree::IQTree() : PhyloTree() {
init();
}
void IQTree::init() {
k_represent = 0;
k_delete = k_delete_min = k_delete_max = k_delete_stay = 0;
dist_matrix = NULL;
var_matrix = NULL;
nni_count_est = 0.0;
nni_delta_est = 0;
curScore = 0.0; // Current score of the tree
bestScore = -DBL_MAX; // Best score found so far
curIt = 1;
cur_pars_score = -1;
// enable_parsimony = false;
estimate_nni_cutoff = false;
nni_cutoff = -1e6;
nni_sort = false;
testNNI = false;
print_tree_lh = false;
write_intermediate_trees = 0;
max_candidate_trees = 0;
logl_cutoff = 0.0;
len_scale = 10000;
save_all_br_lens = false;
duplication_counter = 0;
pllInst = NULL;
pllAlignment = NULL;
pllPartitions = NULL;
//boot_splits = new SplitGraph;
pll2iqtree_pattern_index = NULL; // Diep
cost_matrix = NULL; // Diep
fastNNI = true;
reps_segments = -1;
segment_upper = NULL;
original_sample = NULL;
}
IQTree::IQTree(Alignment *aln) : PhyloTree(aln) {
init();
}
void IQTree::setParams(Params ¶ms) {
searchinfo.speednni = params.speednni;
searchinfo.nni_type = params.nni_type;
optimize_by_newton = params.optimize_by_newton;
candidateTrees.aln = aln;
candidateTrees.popSize = params.popSize;
candidateTrees.maxCandidates = params.maxCandidates;
sse = params.SSE;
// if (params.maxtime != 1000000) {
// params.autostop = false;
// }
if (params.min_iterations == -1) {
if (!params.gbo_replicates) {
if (params.stop_condition == SC_UNSUCCESS_ITERATION) {
params.min_iterations = aln->getNSeq() * 100;
} else if (aln->getNSeq() < 100) {
params.min_iterations = 200;
} else {
params.min_iterations = aln->getNSeq() * 2;
}
if (params.iteration_multiple > 1)
params.min_iterations = aln->getNSeq() * params.iteration_multiple;
} else {
params.min_iterations = 100;
}
}
/*
// Minh's assignment for max_iterations
if (params.gbo_replicates)
params.max_iterations = max(params.max_iterations, max(params.min_iterations, 1000));
*/
if (params.gbo_replicates & !params.maximum_parsimony){
params.max_iterations = max(params.max_iterations, max(params.min_iterations, 1000));
}
// These stopcond should work for both search and UFBoot-MP
if(params.maximum_parsimony){
if(params.max_iterations == 1) // if not specifying -nm
params.max_iterations = max(params.max_iterations, 10 * aln->getNSeq());
if(params.unsuccess_iteration < 0) // if not specifying -stop_cond
params.unsuccess_iteration = ((aln->getNSeq() - 1) / 100 + 1) * 100;
}
/*
// Diep's assignment for max_iterations >> causing 100 iteration BUG
if (params.gbo_replicates && params.maximum_parsimony)
params.max_iterations = max(params.max_iterations, params.min_iterations);
*/
k_represent = params.k_representative;
if (params.p_delete == -1.0) {
if (aln->getNSeq() < 4)
params.p_delete = 0.0; // delete nothing
else if (aln->getNSeq() == 4)
params.p_delete = 0.25; // just delete 1 leaf
else if (aln->getNSeq() == 5)
params.p_delete = 0.4; // just delete 2 leaves
else if (aln->getNSeq() < 51)
params.p_delete = 0.5;
else if (aln->getNSeq() < 100)
params.p_delete = 0.3;
else if (aln->getNSeq() < 200)
params.p_delete = 0.2;
else if (aln->getNSeq() < 400)
params.p_delete = 0.1;
else
params.p_delete = 0.05;
}
//tree.setProbDelete(params.p_delete);
if (params.p_delete != -1.0) {
k_delete = k_delete_min = k_delete_max = ceil(params.p_delete * leafNum);
} else {
k_delete = k_delete_min = 10;
k_delete_max = leafNum / 2;
if (k_delete_max > 100)
k_delete_max = 100;
if (k_delete_max < 20)
k_delete_max = 20;
k_delete_stay = ceil(leafNum / k_delete);
}
//tree.setIQPIterations(params.stop_condition, params.stop_confidence, params.min_iterations, params.max_iterations);
stop_rule.initialize(params);
//tree.setIQPAssessQuartet(params.iqp_assess_quartet);
iqp_assess_quartet = params.iqp_assess_quartet;
estimate_nni_cutoff = params.estimate_nni_cutoff;
nni_cutoff = params.nni_cutoff;
nni_sort = params.nni_sort;
testNNI = params.testNNI;
this->params = ¶ms;
globalParam = ¶ms;
globalAlignment = aln;
write_intermediate_trees = params.write_intermediate_trees;
if (write_intermediate_trees > 2 || params.gbo_replicates > 0) {
save_all_trees = 1;
}
if (params.gbo_replicates > 0) {
if (params.iqp_assess_quartet != IQP_BOOTSTRAP) {
save_all_trees = 2;
}
}
if (params.gbo_replicates > 0 && params.do_compression)
save_all_br_lens = true;
print_tree_lh = params.print_tree_lh;
max_candidate_trees = params.max_candidate_trees;
if (max_candidate_trees == 0)
max_candidate_trees = aln->getNSeq() * params.step_iterations;
setRootNode(params.root);
string bootaln_name = params.out_prefix;
bootaln_name += ".bootaln";
if (params.print_bootaln) {
ofstream bootalnout;
bootalnout.open(bootaln_name.c_str());
bootalnout.close();
}
size_t i;
if (params.online_bootstrap && params.gbo_replicates > 0) {
cout << "Generating " << params.gbo_replicates << " samples for bootstrap approximation..." << endl;
size_t nunit; // either number of patterns or number of sites
// allocate memory for boot_samples
if(params.maximum_parsimony)
{
// Diep: For parsimony bootstrap
boot_samples_pars.resize(params.gbo_replicates);
boot_samples_pars_remain_bounds.resize(params.gbo_replicates, NULL);
nunit = getAlnNPattern() + VCSIZE_USHORT;
// BootValTypePars *mem = aligned_alloc<BootValTypePars>(nunit * (size_t)(params.gbo_replicates));
// memset(mem, 0, nunit * (size_t)(params.gbo_replicates) * sizeof(BootValTypePars));
// for (i = 0; i < params.gbo_replicates; i++)
// boot_samples_pars[i] = mem + i*nunit;
// Diep: rewrote the above to properly use load_a in saveCurrentTree
for (i = 0; i < params.gbo_replicates; i++){
boot_samples_pars[i] = aligned_alloc<BootValTypePars>(nunit);
memset(boot_samples_pars[i], 0, nunit * sizeof(BootValTypePars));
}
} else{
boot_samples.resize(params.gbo_replicates);
#ifdef BOOT_VAL_FLOAT
nunit = get_safe_upper_limit_float(getAlnNPattern());
#else
nunit = get_safe_upper_limit(getAlnNPattern());
#endif
BootValType *mem = aligned_alloc<BootValType>(nunit * (size_t)(params.gbo_replicates));
memset(mem, 0, nunit * (size_t)(params.gbo_replicates) * sizeof(BootValType));
for (i = 0; i < params.gbo_replicates; i++)
boot_samples[i] = mem + i*nunit;
}
if(params.maximum_parsimony)
boot_logl.resize(params.gbo_replicates, -LONG_MAX); // Diep: Leaving this out might affect REPS computation
else
boot_logl.resize(params.gbo_replicates, -DBL_MAX);
boot_trees.resize(params.gbo_replicates, -1);
boot_counts.resize(params.gbo_replicates, 0);
if(params.cutoff_from_btrees) boot_tree_orig_logl.resize(params.gbo_replicates, 0); // Diep
if(params.maximum_parsimony && params.multiple_hits){
// boot_best_hits.resize(params.gbo_replicates, 0);
boot_trees_parsimony.resize(params.gbo_replicates);
for(int k = 0; k < params.gbo_replicates; k++) boot_trees_parsimony[k].clear();
// boot_trees_parsimony_score.resize(params.gbo_replicates);
// boot_trees_ls_parsimony.resize(params.gbo_replicates);
}
if(params.maximum_parsimony && params.store_top_boot_trees){
boot_trees_parsimony_top.resize(params.gbo_replicates);
for(int k = 0; k < params.gbo_replicates; k++) boot_trees_parsimony_top[k].clear();
boot_threshold.resize(params.gbo_replicates, -INT_MAX);
}
if(params.maximum_parsimony && (params.distinct_iter_top_boot >= 1)){
boot_trees_parsimony_top.resize(params.gbo_replicates);
for(int k = 0; k < params.gbo_replicates; k++) boot_trees_parsimony_top[k].clear();
boot_threshold.resize(params.gbo_replicates, -INT_MAX);
boot_trees_parsimony_top_iter.resize(params.gbo_replicates);
for(int k = 0; k < params.gbo_replicates; k++)
boot_trees_parsimony_top_iter[k].clear();
}
VerboseMode saved_mode = verbose_mode;
verbose_mode = VB_QUIET;
nunit = getAlnNPattern();
for (i = 0; i < params.gbo_replicates; i++) {
if (params.print_bootaln) {
Alignment* bootstrap_alignment;
if (aln->isSuperAlignment())
bootstrap_alignment = new SuperAlignment;
else
bootstrap_alignment = new Alignment;
IntVector this_sample;
bootstrap_alignment->createBootstrapAlignment(aln, &this_sample, params.bootstrap_spec);
for (size_t j = 0; j < nunit; j++){
if(params.maximum_parsimony)
boot_samples_pars[i][j] = this_sample[j];
else
boot_samples[i][j] = this_sample[j];
}
bootstrap_alignment->printPhylip(bootaln_name.c_str(), true);
delete bootstrap_alignment;
} else {
IntVector this_sample;
aln->createBootstrapAlignment(this_sample, params.bootstrap_spec);
for (size_t j = 0; j < nunit; j++){
if(params.maximum_parsimony)
boot_samples_pars[i][j] = this_sample[j];
else
boot_samples[i][j] = this_sample[j];
}
}
}
verbose_mode = saved_mode;
if (params.print_bootaln) {
cout << "Bootstrap alignments printed to " << bootaln_name << endl;
}
if(!params.maximum_parsimony)
cout << "Max candidate trees (tau): " << max_candidate_trees << endl;
}
if(params.maximum_parsimony){
on_opt_btree = false;
on_ratchet_hclimb1 = false;
on_ratchet_hclimb2 = false;
iter_best = false;
if(params.ratchet_iter >= 0){
size_t nunit = getAlnNPattern() + VCSIZE_USHORT;
original_sample = aligned_alloc<BootValTypePars>(nunit);
memset(original_sample, 0, nunit * sizeof(BootValTypePars));
for (size_t i = 0; i < getAlnNPattern(); i++)
original_sample[i] = aln->at(i).frequency;
}
}
if (params.root_state) {
if (strlen(params.root_state) != 1)
outError("Root state must have exactly 1 character");
root_state = aln->convertState(params.root_state[0]);
if (root_state < 0 || root_state >= aln->num_states)
outError("Invalid root state");
}
}
void myPartitionsDestroy(partitionList *pl) {
int i;
for (i = 0; i < pl->numberOfPartitions; i++) {
rax_free(pl->partitionData[i]->partitionName);
rax_free(pl->partitionData[i]);
}
rax_free(pl->partitionData);
rax_free(pl);
}
// Diep
// To initialize current tree as a RAS tree computed by PLL
// This is done independent of Tung's initializePLL function
// to support reordering aln pattern by parsimony score
void IQTree::initTopologyByPLLRandomAdition(Params ¶ms){
pllInstance * tmpInst = NULL;
pllInstanceAttr tmpAttr;
pllAlignmentData * tmpAlignmentData;
partitionList * tmpPartitions;
/* set PLL instance attributes */
tmpAttr.rateHetModel = PLL_GAMMA;
tmpAttr.fastScaling = PLL_FALSE;
tmpAttr.saveMemory = PLL_FALSE;
tmpAttr.useRecom = PLL_FALSE;
tmpAttr.randomNumberSeed = params.ran_seed;
#ifdef _OPENMP
tmpAttr.numberOfThreads = params.num_threads; /* This only affects the pthreads version */
#else
tmpAttr.numberOfThreads = 1;
#endif
tmpInst = pllCreateInstance (&tmpAttr); /* Create the PLL instance */
/* Read in the aln file */
stringstream pllAln;
if (aln->isSuperAlignment()) {
((SuperAlignment*) aln)->printCombinedAlignment(pllAln);
} else {
aln->printPhylip(pllAln);
}
string pllAlnStr = pllAln.str();
tmpAlignmentData = pllParsePHYLIPString(pllAlnStr.c_str(), pllAlnStr.length());
/* Read in the partition information */
// BQM: to avoid printing file
stringstream pllPartitionFileHandle;
createPLLPartition(params, pllPartitionFileHandle);
pllQueue *partitionInfo = pllPartitionParseString(pllPartitionFileHandle.str().c_str());
/* Validate the partitions */
if (!pllPartitionsValidate(partitionInfo, tmpAlignmentData)) {
outError("pllPartitionsValidate");
}
/* Commit the partitions and build a partitions structure */
tmpPartitions = pllPartitionsCommit(partitionInfo, tmpAlignmentData);
/* We don't need the the intermediate partition queue structure anymore */
pllQueuePartitionsDestroy(&partitionInfo);
if(params.maximum_parsimony)
pllSortedAlignmentRemoveDups(tmpAlignmentData, tmpPartitions); // to sync IQTree aln and PLL one
pllTreeInitTopologyForAlignment(tmpInst, tmpAlignmentData);
/* Connect the aln and partition structure with the tree structure */
if (!pllLoadAlignment(tmpInst, tmpAlignmentData, tmpPartitions)) {
outError("Incompatible tree/aln combination");
}
pllComputeRandomizedStepwiseAdditionParsimonyTree(tmpInst, tmpPartitions, 1);
pllTreeToNewick(tmpInst->tree_string, tmpInst, tmpPartitions, tmpInst->start->back, PLL_TRUE,
PLL_TRUE, 0, 0, 0, PLL_SUMMARIZE_LH, 0, 0);
string treeString = string(tmpInst->tree_string);
readTreeString(treeString);
// clean up PLL temp data */
if (tmpPartitions)
myPartitionsDestroy(tmpPartitions);
if (tmpAlignmentData)
pllAlignmentDataDestroy(tmpAlignmentData);
if (tmpInst)
pllDestroyInstance(tmpInst);
// done clean up
}
BootValTypePars * IQTree::getPatternPars(){
return _pattern_pars;
}
IQTree::~IQTree() {
//if (bonus_values)
//delete bonus_values;
//bonus_values = NULL;
if (dist_matrix)
delete[] dist_matrix;
dist_matrix = NULL;
if (var_matrix)
delete[] var_matrix;
var_matrix = NULL;
for (vector<double*>::reverse_iterator it = treels_ptnlh.rbegin(); it != treels_ptnlh.rend(); it++)
delete[] (*it);
treels_ptnlh.clear();
for (vector<SplitGraph*>::reverse_iterator it2 = boot_splits.rbegin(); it2 != boot_splits.rend(); it2++)
delete (*it2);
//if (boot_splits) delete boot_splits;
if (pllPartitions)
myPartitionsDestroy(pllPartitions);
if (pllAlignment)
pllAlignmentDataDestroy(pllAlignment);
if (pllInst)
pllDestroyInstance(pllInst);
if (!boot_samples.empty())
aligned_free(boot_samples[0]); // free memory
if(!boot_samples_pars.empty()){
for(int i = 0; i < params->gbo_replicates; i++)
aligned_free(boot_samples_pars[i]); // Diep added
}
if(!boot_samples_pars_remain_bounds.empty()){
for(int i = 0; i < params->gbo_replicates; i++)
delete [] boot_samples_pars_remain_bounds[i];
}
if(segment_upper) delete [] segment_upper;
if(original_sample){
aligned_free(original_sample);
original_sample = NULL;
}
#if (defined(__SSE3) || defined(__AVX))
if(vectorCostMatrix != NULL){
rax_free(vectorCostMatrix);
vectorCostMatrix = NULL;
}
#endif
}
void IQTree::createPLLPartition(Params ¶ms, ostream &pllPartitionFileHandle) {
if (isSuperTree()) {
PhyloSuperTree *siqtree = (PhyloSuperTree*) this;
// additional check for stupid PLL hard limit
if (siqtree->size() > PLL_NUM_BRANCHES)
outError("Number of partitions exceeds PLL limit, please increase PLL_NUM_BRANCHES constant in pll.h");
int i = 0;
int startPos = 1;
for (PhyloSuperTree::iterator it = siqtree->begin(); it != siqtree->end(); it++) {
i++;
int curLen = ((*it))->getAlnNSite();
if ((*it)->aln->seq_type == SEQ_DNA) {
pllPartitionFileHandle << "DNA";
} else if ((*it)->aln->seq_type == SEQ_PROTEIN) {
if (siqtree->part_info[i-1].model_name != "" && siqtree->part_info[i-1].model_name.substr(0, 4) != "TEST")
pllPartitionFileHandle << siqtree->part_info[i-1].model_name.substr(0, siqtree->part_info[i-1].model_name.find_first_of("+{"));
else
pllPartitionFileHandle << "WAG";
} else
outError("PLL only works with DNA/protein alignments");
pllPartitionFileHandle << ", p" << i << " = " << startPos << "-" << startPos + curLen - 1 << endl;
startPos = startPos + curLen;
}
} else {
/* create a partition file */
string model;
if (aln->seq_type == SEQ_DNA) {
model = "DNA";
} else if (aln->seq_type == SEQ_PROTEIN) {
if (params.pll && params.model_name != "" && params.model_name.substr(0, 4) != "TEST") {
model = params.model_name.substr(0, params.model_name.find_first_of("+{"));
} else {
model = "WAG";
}
} else if (aln->seq_type == SEQ_MORPH) {
model = "MOR";
} else if (aln->seq_type == SEQ_BINARY) {
model = "BIN";
} else {
model = "WAG";
//outError("PLL currently only supports DNA/protein alignments");
}
pllPartitionFileHandle << model << ", p1 = " << "1-" << getAlnNSite() << endl;
}
}
extern void initializeCostMatrix();
void IQTree::initializePLL(Params ¶ms) {
pllAttr.rateHetModel = PLL_GAMMA;
pllAttr.fastScaling = PLL_FALSE;
pllAttr.saveMemory = PLL_FALSE;
pllAttr.useRecom = PLL_FALSE;
pllAttr.randomNumberSeed = params.ran_seed;
#ifdef _OPENMP
pllAttr.numberOfThreads = params.num_threads; /* This only affects the pthreads version */
#else
pllAttr.numberOfThreads = 1;
#endif
if (pllInst != NULL) {
pllDestroyInstance(pllInst);
}
/* Create a PLL instance */
pllInst = pllCreateInstance(&pllAttr);
/* tree fusing */
pllSourceInst = pllCreateInstance(&pllAttr);
/* Read in the alignment file */
stringstream pllAln;
if (aln->isSuperAlignment()) {
((SuperAlignment*) aln)->printCombinedAlignment(pllAln);
} else {
aln->printPhylip(pllAln);
}
string pllAlnStr = pllAln.str();
pllAlignment = pllParsePHYLIPString(pllAlnStr.c_str(), pllAlnStr.length());
/* Read in the partition information */
// BQM: to avoid printing file
stringstream pllPartitionFileHandle;
createPLLPartition(params, pllPartitionFileHandle);
pllQueue *partitionInfo = pllPartitionParseString(pllPartitionFileHandle.str().c_str());
/* Validate the partitions */
if (!pllPartitionsValidate(partitionInfo, pllAlignment)) {
outError("pllPartitionsValidate");
}
/* Commit the partitions and build a partitions structure */
pllPartitions = pllPartitionsCommit(partitionInfo, pllAlignment);
/* We don't need the the intermediate partition queue structure anymore */
pllQueuePartitionsDestroy(&partitionInfo);
// Diep: Added this IF statement so that UFBoot-MP SPR code doesn't affect other IQTree mode
// alignment in UFBoot-MP SPR branch will be sorted by pattern and site pars score
// PLL eliminates duplicate sites from the alignment and update weights vector
// Diep 2021-12-29:
// For maximum parsimony, SYNCING between two cores (IQ-TREE and PLL) must always be guaranteed!!!!!!!!
// Especially necessary if having ratchet on.
if(params.maximum_parsimony)
pllSortedAlignmentRemoveDups(pllAlignment, pllPartitions); // to sync IQTree aln and PLL one
else
pllAlignmentRemoveDups(pllAlignment, pllPartitions);
pllTreeInitTopologyForAlignment(pllInst, pllAlignment);
/* Connect the alignment and partition structure with the tree structure */
if (!pllLoadAlignment(pllInst, pllAlignment, pllPartitions)) {
outError("Incompatible tree/alignment combination");
}
globalParam = ¶ms;
// Diep: Add initialization for Sankoff if needed
if(params.maximum_parsimony && params.sankoff_cost_file){
pllCostMatrix = cost_matrix;
pllCostNstates = cost_nstates;
pllSegmentUpper = segment_upper;
pllRepsSegments = reps_segments;
initializeCostMatrix();
}else{
pllCostMatrix = NULL;
pllCostNstates = -1;
pllSegmentUpper = NULL;
pllRepsSegments = -1;
}
}
void IQTree::createPLL(Params ¶ms, pllInstance* &pllInst, pllAlignmentData* &pllAlignment, partitionList* &pllPartitions) {
pllInstanceAttr pllAttr;
pllAttr.rateHetModel = PLL_GAMMA;
pllAttr.fastScaling = PLL_FALSE;
pllAttr.saveMemory = PLL_FALSE;
pllAttr.useRecom = PLL_FALSE;
pllAttr.randomNumberSeed = params.ran_seed;
#ifdef _OPENMP
pllAttr.numberOfThreads = params.num_threads; /* This only affects the pthreads version */
#else
pllAttr.numberOfThreads = 1;
#endif
/* Create a PLL instance */
pllInst = pllCreateInstance(&pllAttr);
/* tree fusing */
pllSourceInst = pllCreateInstance(&pllAttr);
/* Read in the alignment file */
stringstream pllAln;
if (aln->isSuperAlignment()) {
((SuperAlignment*) aln)->printCombinedAlignment(pllAln);
} else {
aln->printPhylip(pllAln);
}
string pllAlnStr = pllAln.str();
pllAlignment = pllParsePHYLIPString(pllAlnStr.c_str(), pllAlnStr.length());
/* Read in the partition information */
// BQM: to avoid printing file
stringstream pllPartitionFileHandle;
createPLLPartition(params, pllPartitionFileHandle);
pllQueue *partitionInfo = pllPartitionParseString(pllPartitionFileHandle.str().c_str());
/* Validate the partitions */
if (!pllPartitionsValidate(partitionInfo, pllAlignment)) {
outError("pllPartitionsValidate");
}
/* Commit the partitions and build a partitions structure */
pllPartitions = pllPartitionsCommit(partitionInfo, pllAlignment);
/* We don't need the the intermediate partition queue structure anymore */
pllQueuePartitionsDestroy(&partitionInfo);
// Diep: Added this IF statement so that UFBoot-MP SPR code doesn't affect other IQTree mode
// alignment in UFBoot-MP SPR branch will be sorted by pattern and site pars score
// PLL eliminates duplicate sites from the alignment and update weights vector
// Diep 2021-12-29:
// For maximum parsimony, SYNCING between two cores (IQ-TREE and PLL) must always be guaranteed!!!!!!!!
// Especially necessary if having ratchet on.
if(params.maximum_parsimony)
pllSortedAlignmentRemoveDups(pllAlignment, pllPartitions); // to sync IQTree aln and PLL one
else
pllAlignmentRemoveDups(pllAlignment, pllPartitions);
pllTreeInitTopologyForAlignment(pllInst, pllAlignment);
/* Connect the alignment and partition structure with the tree structure */
if (!pllLoadAlignment(pllInst, pllAlignment, pllPartitions)) {
outError("Incompatible tree/alignment combination");
}
}
void IQTree::initializeModel(Params ¶ms) {
VerboseMode saved_mode;
if(params.maximum_parsimony){
saved_mode = verbose_mode;
verbose_mode = VB_QUIET;
}
try {
if (!getModelFactory()) {
if (isSuperTree()) {
if (params.partition_type) {
setModelFactory(new PartitionModelPlen(params, (PhyloSuperTreePlen*) this));
} else
setModelFactory(new PartitionModel(params, (PhyloSuperTree*) this));
} else {
setModelFactory(new ModelFactory(params, this));
}
}
} catch (string & str) {
outError(str);
}
setModel(getModelFactory()->model);
setRate(getModelFactory()->site_rate);
if (params.pll) {
if (getRate()->getNDiscreteRate() == 1) {
outError("Non-Gamma model is not yet supported by PLL.");
// TODO: change rateHetModel to PLL_CAT in case of non-Gamma model
}
if (getRate()->name.substr(0,2) == "+I")
outError("+Invar model is not yet supported by PLL.");
if (aln->seq_type == SEQ_DNA && getModel()->name != "GTR")
outError("non GTR model for DNA is not yet supported by PLL.");
}
if(params.maximum_parsimony){
verbose_mode = saved_mode;
}
}
double IQTree::getProbDelete() {
return (double) k_delete / leafNum;
}
void IQTree::resetKDelete() {
k_delete = k_delete_min;
k_delete_stay = ceil(leafNum / k_delete);
}
void IQTree::increaseKDelete() {
if (k_delete >= k_delete_max)
return;
k_delete_stay--;
if (k_delete_stay > 0)
return;
k_delete++;
k_delete_stay = ceil(leafNum / k_delete);
if (verbose_mode >= VB_MED)
cout << "Increase k_delete to " << k_delete << endl;
}
//void IQTree::setIQPIterations(STOP_CONDITION stop_condition, double stop_confidence, int min_iterations,
// int max_iterations) {
// stop_rule.setStopCondition(stop_condition);
// stop_rule.setConfidenceValue(stop_confidence);
// stop_rule.setIterationNum(min_iterations, max_iterations);
//}
RepresentLeafSet* IQTree::findRepresentLeaves(vector<RepresentLeafSet*> &leaves_vec, int nei_id, PhyloNode *dad) {
PhyloNode *node = (PhyloNode*) (dad->neighbors[nei_id]->node);
int set_id = dad->id * 3 + nei_id;
if (leaves_vec[set_id])
return leaves_vec[set_id];
RepresentLeafSet *leaves = new RepresentLeafSet;
RepresentLeafSet * leaves_it[2] = { NULL, NULL };
leaves_vec[set_id] = leaves;
RepresentLeafSet::iterator last;
RepresentLeafSet::iterator cur_it;
int i, j;
//double admit_height = 1000000;
leaves->clear();
if (node->isLeaf()) {
// set the depth to zero
//node->height = 0.0;
leaves->insert(new RepLeaf(node, 0));
} else {
for (i = 0, j = 0; i < node->neighbors.size(); i++)
if (node->neighbors[i]->node != dad) {
leaves_it[j++] = findRepresentLeaves(leaves_vec, i, node);
}
assert(j == 2 && leaves_it[0] && leaves_it[1]);
if (leaves_it[0]->empty() && leaves_it[1]->empty()) {
cout << "wrong";
}
RepresentLeafSet::iterator lit[2] = { leaves_it[0]->begin(), leaves_it[1]->begin() };
while (leaves->size() < k_represent) {
int id = -1;
if (lit[0] != leaves_it[0]->end() && lit[1] != leaves_it[1]->end()) {
if ((*lit[0])->height < (*lit[1])->height)
id = 0;
else if ((*lit[0])->height > (*lit[1])->height)
id = 1;
else { // tie, choose at random
id = random_int(2);
}
} else if (lit[0] != leaves_it[0]->end())
id = 0;
else if (lit[1] != leaves_it[1]->end())
id = 1;
else
break;
assert(id < 2 && id >= 0);
leaves->insert(new RepLeaf((*lit[id])->leaf, (*lit[id])->height + 1));
lit[id]++;
}
}
assert(!leaves->empty());
/*
if (verbose_mode >= VB_MAX) {
for (cur_it = leaves->begin(); cur_it != leaves->end(); cur_it++)
cout << (*cur_it)->leaf->name << " ";
cout << endl;
}*/
return leaves;
}
/*
void IQPTree::clearRepresentLeaves(vector<RepresentLeafSet*> &leaves_vec, Node *node, Node *dad) {
int nei_id;
for (nei_id = 0; nei_id < node->neighbors.size(); nei_id++)
if (node->neighbors[nei_id]->node == dad) break;
assert(nei_id < node->neighbors.size());
int set_id = node->id * 3 + nei_id;
if (leaves_vec[set_id]) {
for (RepresentLeafSet::iterator rlit = leaves_vec[set_id]->begin(); rlit != leaves_vec[set_id]->end(); rlit++)
delete (*rlit);
delete leaves_vec[set_id];
leaves_vec[set_id] = NULL;
}
FOR_NEIGHBOR_IT(node, dad, it) {
clearRepresentLeaves(leaves_vec, (*it)->node, node);
}
}*/
void IQTree::deleteNonCherryLeaves(PhyloNodeVector &del_leaves) {
NodeVector cherry_taxa;
NodeVector noncherry_taxa;
// get the vector of non cherry taxa
getNonCherryLeaves(noncherry_taxa, cherry_taxa);
root = NULL;
int num_taxa = aln->getNSeq();
int num_delete = k_delete;
if (num_delete > num_taxa - 4)
num_delete = num_taxa - 4;
if (verbose_mode >= VB_DEBUG) {
cout << "Deleting " << num_delete << " leaves" << endl;
}
vector<unsigned int> indices_noncherry(noncherry_taxa.size());
//iota(indices_noncherry.begin(), indices_noncherry.end(), 0);
unsigned int startValue = 0;
for (vector<unsigned int>::iterator it = indices_noncherry.begin(); it != indices_noncherry.end(); ++it) {
(*it) = startValue;
++startValue;
}
my_random_shuffle(indices_noncherry.begin(), indices_noncherry.end());
int i;
for (i = 0; i < num_delete && i < noncherry_taxa.size(); i++) {
PhyloNode *taxon = (PhyloNode*) noncherry_taxa[indices_noncherry[i]];
del_leaves.push_back(taxon);
deleteLeaf(taxon);
//cout << taxon->id << ", ";
}
int j = 0;
if (i < num_delete) {
vector<unsigned int> indices_cherry(cherry_taxa.size());
//iota(indices_cherry.begin(), indices_cherry.end(), 0);
startValue = 0;
for (vector<unsigned int>::iterator it = indices_cherry.begin(); it != indices_cherry.end(); ++it) {
(*it) = startValue;
++startValue;
}
my_random_shuffle(indices_cherry.begin(), indices_cherry.end());
while (i < num_delete) {
PhyloNode *taxon = (PhyloNode*) cherry_taxa[indices_cherry[j]];
del_leaves.push_back(taxon);
deleteLeaf(taxon);
i++;
j++;
}
}
root = cherry_taxa[j];
}
void IQTree::deleteLeaves(PhyloNodeVector &del_leaves) {
NodeVector taxa;
// get the vector of taxa
getTaxa(taxa);
root = NULL;
//int num_delete = floor(p_delete * taxa.size());
int num_delete = k_delete;
int i;
if (num_delete > taxa.size() - 4)
num_delete = taxa.size() - 4;
if (verbose_mode >= VB_DEBUG) {
cout << "Deleting " << num_delete << " leaves" << endl;
}
// now try to randomly delete some taxa of the probability of p_delete
for (i = 0; i < num_delete;) {
int id = random_int(taxa.size());
if (!taxa[id])
continue;
else
i++;
PhyloNode *taxon = (PhyloNode*) taxa[id];
del_leaves.push_back(taxon);
deleteLeaf(taxon);
taxa[id] = NULL;
}
// set root to the first taxon which was not deleted
for (i = 0; i < taxa.size(); i++)
if (taxa[i]) {
root = taxa[i];
break;
}
}
int IQTree::assessQuartet(Node *leaf0, Node *leaf1, Node *leaf2, Node *del_leaf) {
assert(dist_matrix);
int nseq = aln->getNSeq();
//int id0 = leaf0->id, id1 = leaf1->id, id2 = leaf2->id;
double dist0 = dist_matrix[leaf0->id * nseq + del_leaf->id] + dist_matrix[leaf1->id * nseq + leaf2->id];
double dist1 = dist_matrix[leaf1->id * nseq + del_leaf->id] + dist_matrix[leaf0->id * nseq + leaf2->id];
double dist2 = dist_matrix[leaf2->id * nseq + del_leaf->id] + dist_matrix[leaf0->id * nseq + leaf1->id];
if (dist0 < dist1 && dist0 < dist2)
return 0;
if (dist1 < dist2)
return 1;
return 2;
}
int IQTree::assessQuartetParsimony(Node *leaf0, Node *leaf1, Node *leaf2, Node *del_leaf) {
int score[3] = { 0, 0, 0 };
for (Alignment::iterator it = aln->begin(); it != aln->end(); it++) {
char ch0 = (*it)[leaf0->id];
char ch1 = (*it)[leaf1->id];
char ch2 = (*it)[leaf2->id];
char chd = (*it)[del_leaf->id];
if (ch0 >= aln->num_states || ch1 >= aln->num_states || ch2 >= aln->num_states || chd >= aln->num_states)
continue;
if (chd == ch0 && ch1 == ch2)
score[0] += (*it).frequency;
if (chd == ch1 && ch0 == ch2)
score[1] += (*it).frequency;
if (chd == ch2 && ch0 == ch1)
score[2] += (*it).frequency;
}
if (score[0] == score[1] && score[0] == score[2]) {
int id = random_int(3);
return id;
}
if (score[0] > score[1] && score[0] > score[2])
return 0;
if (score[1] < score[2])
return 2;
return 1;
}
void IQTree::initializeBonus(PhyloNode *node, PhyloNode *dad) {
if (!node)
node = (PhyloNode*) root;
if (dad) {
PhyloNeighbor *node_nei = (PhyloNeighbor*) node->findNeighbor(dad);
PhyloNeighbor *dad_nei = (PhyloNeighbor*) dad->findNeighbor(node);
node_nei->lh_scale_factor = 0.0;
node_nei->partial_lh_computed = 0;
dad_nei->lh_scale_factor = 0.0;
dad_nei->partial_lh_computed = 0;
}
FOR_NEIGHBOR_IT(node, dad, it){
initializeBonus((PhyloNode*) ((*it)->node), node);
}
}
void IQTree::raiseBonus(Neighbor *nei, Node *dad, double bonus) {
((PhyloNeighbor*) nei)->lh_scale_factor += bonus;
if (verbose_mode >= VB_DEBUG)
cout << dad->id << " - " << nei->node->id << " : " << bonus << endl;
// FOR_NEIGHBOR_IT(nei->node, dad, it)
// raiseBonus((*it), nei->node, bonus);
}
double IQTree::computePartialBonus(Node *node, Node* dad) {
PhyloNeighbor *node_nei = (PhyloNeighbor*) node->findNeighbor(dad);
if (node_nei->partial_lh_computed)
return node_nei->lh_scale_factor;
FOR_NEIGHBOR_IT(node, dad, it){
node_nei->lh_scale_factor += computePartialBonus((*it)->node, node);
}
node_nei->partial_lh_computed = 1;
return node_nei->lh_scale_factor;
}
void IQTree::findBestBonus(double &best_score, NodeVector &best_nodes, NodeVector &best_dads, Node *node, Node *dad) {
double score;
if (!node)
node = root;
if (!dad) {
best_score = 0;
} else {