-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathalignment.cpp
More file actions
6354 lines (5847 loc) · 225 KB
/
alignment.cpp
File metadata and controls
6354 lines (5847 loc) · 225 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
//
// C++ Implementation: alignment
//
// Description:
//
//
// Author: BUI Quang Minh, Steffen Klaere, Arndt von Haeseler <minh.bui@univie.ac.at>, (C) 2008
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "utils/tools.h"
#include "alignment.h"
#include "nclextra/myreader.h"
#include <numeric>
#include <sstream>
#include "model/rategamma.h"
#include "gsl/mygsl.h"
#include "utils/gzstream.h"
#include "utils/timeutil.h" //for getRealTime()
#include "utils/progress.h" //for progress_display
#include "alignmentsummary.h"
#include <Eigen/LU>
#ifdef USE_BOOST
#include <boost/math/distributions/binomial.hpp>
#endif
using namespace std;
using namespace Eigen;
char symbols_protein[] = "ARNDCQEGHILKMFPSTWYVX"; // X for unknown AA
char symbols_dna[] = "ACGT";
char symbols_rna[] = "ACGU";
//char symbols_binary[] = "01";
char symbols_morph[] = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
// genetic code from tri-nucleotides (AAA, AAC, AAG, AAT, ..., TTT) to amino-acids
// Source: http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi
// Base1: AAAAAAAAAAAAAAAACCCCCCCCCCCCCCCCGGGGGGGGGGGGGGGGTTTTTTTTTTTTTTTT
// Base2: AAAACCCCGGGGTTTTAAAACCCCGGGGTTTTAAAACCCCGGGGTTTTAAAACCCCGGGGTTTT
// Base3: ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGT
char genetic_code1[] = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF"; // Standard
char genetic_code2[] = "KNKNTTTT*S*SMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF"; // Vertebrate Mitochondrial
char genetic_code3[] = "KNKNTTTTRSRSMIMIQHQHPPPPRRRRTTTTEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF"; // Yeast Mitochondrial
char genetic_code4[] = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF"; // Mold, Protozoan, etc.
char genetic_code5[] = "KNKNTTTTSSSSMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF"; // Invertebrate Mitochondrial
char genetic_code6[] = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVVQYQYSSSS*CWCLFLF"; // Ciliate, Dasycladacean and Hexamita Nuclear
// note: tables 7 and 8 are not available in NCBI
char genetic_code9[] = "NNKNTTTTSSSSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF"; // Echinoderm and Flatworm Mitochondrial
char genetic_code10[] = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSCCWCLFLF"; // Euplotid Nuclear
char genetic_code11[] = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF"; // Bacterial, Archaeal and Plant Plastid
char genetic_code12[] = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLSLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF"; // Alternative Yeast Nuclear
char genetic_code13[] = "KNKNTTTTGSGSMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF"; // Ascidian Mitochondrial
char genetic_code14[] = "NNKNTTTTSSSSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVVYY*YSSSSWCWCLFLF"; // Alternative Flatworm Mitochondrial
char genetic_code15[] = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*YQYSSSS*CWCLFLF"; // Blepharisma Nuclear
char genetic_code16[] = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*YLYSSSS*CWCLFLF"; // Chlorophycean Mitochondrial
// note: tables 17-20 are not available in NCBI
char genetic_code21[] = "NNKNTTTTSSSSMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF"; // Trematode Mitochondrial
char genetic_code22[] = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*YLY*SSS*CWCLFLF"; // Scenedesmus obliquus mitochondrial
char genetic_code23[] = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWC*FLF"; // Thraustochytrium Mitochondrial
char genetic_code24[] = "KNKNTTTTSSKSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF"; // Pterobranchia mitochondrial
char genetic_code25[] = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSGCWCLFLF"; // Candidate Division SR1 and Gracilibacteria
Alignment::Alignment()
: vector<Pattern>()
{
num_states = 0;
frac_const_sites = 0.0;
frac_invariant_sites = 0.0;
codon_table = NULL;
genetic_code = NULL;
non_stop_codon = NULL;
seq_type = SEQ_UNKNOWN;
STATE_UNKNOWN = 126;
pars_lower_bound = NULL;
}
string &Alignment::getSeqName(int i) {
ASSERT(i >= 0 && i < (int)seq_names.size());
return seq_names[i];
}
void Alignment::addSeqName(string seq_name)
{
if (!seq_name.empty())
{
seq_names.resize(seq_names.size()+1);
seq_names[seq_names.size()-1] = seq_name;
}
}
vector<string>& Alignment::getSeqNames() {
return seq_names;
}
int Alignment::getSeqID(string &seq_name) {
for (size_t i = 0; i < getNSeq(); i++)
if (seq_name == getSeqName(i)) return i;
return -1;
}
int Alignment::getMaxSeqNameLength() {
int len = 0;
for (size_t i = 0; i < getNSeq(); i++)
if (getSeqName(i).length() > len)
len = getSeqName(i).length();
return len;
}
/**
probability that the observed chi-square exceeds chi2 even if model is correct
@param deg degree of freedom
@param chi2 chi-square value
@return p-value
*/
double chi2prob (int deg, double chi2)
{
double a = 0.5*deg;
double x = 0.5*chi2;
return 1.0-RateGamma::cmpIncompleteGamma (x, a, RateGamma::cmpLnGamma(a));
// return IncompleteGammaQ (0.5*deg, 0.5*chi2);
} /* chi2prob */
int Alignment::checkAbsentStates(string msg) {
double *state_freq = new double[num_states];
computeStateFreq(state_freq);
string absent_states, rare_states;
int count = 0;
// Skip check for PoMo.
if (seq_type == SEQ_POMO)
return 0;
for (int i = 0; i < num_states; i++)
if (state_freq[i] == 0.0) {
if (!absent_states.empty())
absent_states += ", ";
absent_states += convertStateBackStr(i);
count++;
} else if (state_freq[i] <= Params::getInstance().min_state_freq) {
if (!rare_states.empty())
rare_states += ", ";
rare_states += convertStateBackStr(i);
}
if (count >= num_states-1 && Params::getInstance().fixed_branch_length != BRLEN_FIX)
outError("Only one state is observed in " + msg);
if (!absent_states.empty())
cout << "NOTE: State(s) " << absent_states << " not present in " << msg << " and thus removed from Markov process to prevent numerical problems" << endl;
if (!rare_states.empty())
cout << "WARNING: States(s) " << rare_states << " rarely appear in " << msg << " and may cause numerical problems" << endl;
delete[] state_freq;
return count;
}
void Alignment::checkSeqName() {
ostringstream warn_str;
StrVector::iterator it;
for (it = seq_names.begin(); it != seq_names.end(); it++) {
string orig_name = (*it);
if (renameString(*it))
warn_str << orig_name << " -> " << (*it) << endl;
}
if (!warn_str.str().empty() && Params::getInstance().compute_seq_composition) {
string str = "Some sequence names are changed as follows:\n";
outWarning(str + warn_str.str());
}
// now check that sequence names are different
StrVector names;
names.insert(names.begin(), seq_names.begin(), seq_names.end());
sort(names.begin(), names.end());
bool ok = true;
for (it = names.begin(); it != names.end(); it++) {
if (it+1==names.end()) break;
if (*it == *(it+1)) {
cout << "ERROR: Duplicated sequence name " << *it << endl;
ok = false;
}
}
if (!ok) outError("Please rename sequences listed above!");
if (!Params::getInstance().compute_seq_composition) {
return;
}
double state_freq[num_states];
unsigned *count_per_seq = new unsigned[num_states*getNSeq()];
computeStateFreq(state_freq);
countStatePerSequence(count_per_seq);
int df = -1; //degrees of freedom (for a chi-squared test)
for (int i = 0; i < num_states; i++) {
if (state_freq[i] > 0.0) {
df++;
}
}
if (seq_type == SEQ_POMO) {
cout << "NOTE: The composition test for PoMo only tests the proportion of fixed states!" << endl;
}
bool listSequences = !Params::getInstance().suppress_list_of_sequences;
int max_len = getMaxSeqNameLength()+1;
if (listSequences) {
cout.width(max_len+14);
cout << right << "Gap/Ambiguity" << " Composition p-value"<< endl;
}
int num_problem_seq = 0;
int total_gaps = 0;
cout.precision(2);
int num_failed = 0;
size_t numSequences = seq_names.size();
size_t numSites = getNSite();
char maxProperState = static_cast<char>(num_states + pomo_sampled_states.size());
AlignmentSummary s(this, true, true);
//The progress bar, displayed by s.constructSequenceMatrixNoisily,
//lies a bit here. We're not counting gap characters,
//we are constructing the sequences (so we can count gap characters quickly).
s.constructSequenceMatrixNoisily(false, "Analyzing sequences", "counted gaps in");
struct SequenceInfo {
double percent_gaps;
bool failed;
double pvalue;
};
SequenceInfo* seqInfo = new SequenceInfo[numSequences];
#ifdef _OPENMP
#pragma omp parallel for reduction(+:total_gaps,num_problem_seq,num_failed)
#endif
for (size_t i = 0; i < numSequences; i++) {
size_t num_gaps = numSites;
if (s.sequenceMatrix!=nullptr) {
//Discount the non-gap characters with a (not-yet-vectorized)
//sweep over the sequence.
const char* sequence = s.sequenceMatrix + i * s.sequenceLength;
for (size_t scan = 0; scan<s.sequenceLength; ++scan) {
if (sequence[scan] < maxProperState) {
num_gaps -= s.siteFrequencies[scan];
}
}
} else {
//Do the discounting the hard way
num_gaps -= countProperChar(i);
}
total_gaps += num_gaps;
seqInfo[i].percent_gaps = ((double)num_gaps / getNSite()) * 100.0;
if ( 50.0 < seqInfo[i].percent_gaps ) {
num_problem_seq++;
}
size_t iRow = i * num_states;
double freq_per_sequence[num_states];
double chi2 = 0.0;
unsigned sum_count = 0;
double pvalue;
if (seq_type == SEQ_POMO) {
// Have to normalize allele frequencies.
double state_freq_norm[num_states];
double sum_freq = 0.0;
for (int j = 0; j < num_states; j++) {
sum_freq += state_freq[j];
state_freq_norm[j] = state_freq[j];
}
for (int j = 0; j < num_states; j++) {
state_freq_norm[j] /= sum_freq;
}
for (int j = 0; j < num_states; j++) {
sum_count += count_per_seq[iRow + j];
}
double sum_inv = 1.0 / sum_count;
for (int j = 0; j < num_states; j++) {
freq_per_sequence[j] = count_per_seq[iRow + j] * sum_inv;
}
for (int j = 0; j < num_states; j++) {
chi2 += (state_freq_norm[j] - freq_per_sequence[j]) * (state_freq_norm[j] - freq_per_sequence[j]) / state_freq_norm[j];
}
chi2 *= sum_count;
pvalue = chi2prob(num_states - 1, chi2);
}
else {
for (int j = 0; j < num_states; j++) {
sum_count += count_per_seq[iRow + j];
}
double sum_inv = 1.0 / sum_count;
for (int j = 0; j < num_states; j++) {
freq_per_sequence[j] = count_per_seq[iRow + j] * sum_inv;
}
for (int j = 0; j < num_states; j++) {
if (state_freq[j] > 0.0) {
chi2 += (state_freq[j] - freq_per_sequence[j]) * (state_freq[j] - freq_per_sequence[j]) / state_freq[j];
}
}
chi2 *= sum_count;
pvalue = chi2prob(df, chi2);
}
seqInfo[i].pvalue = pvalue;
seqInfo[i].failed = (pvalue < 0.05);
num_failed += seqInfo[i].failed ? 1 : 0;
}
if (listSequences) {
for (size_t i = 0; i < numSequences; i++) {
cout.width(4);
cout << right << i + 1 << " ";
cout.width(max_len);
cout << left << seq_names[i] << " ";
cout.width(6);
cout << right << seqInfo[i].percent_gaps << "%";
if (seqInfo[i].failed) {
cout << " failed ";
}
else {
cout << " passed ";
}
cout.width(9);
cout << right << (seqInfo[i].pvalue * 100) << "%";
cout << endl;
}
}
delete[] seqInfo;
if (num_problem_seq) {
cout << "WARNING: " << num_problem_seq << " sequences contain more than 50% gaps/ambiguity" << endl;
}
if (listSequences) {
cout << "**** ";
cout.width(max_len+2);
cout << left << " TOTAL ";
cout.width(6);
cout << right << ((double)total_gaps/getNSite())/getNSeq()*100 << "% ";
cout << " " << num_failed << " sequences failed composition chi2 test (p-value<5%; df=" << df << ")" << endl;
cout.precision(3);
}
delete [] count_per_seq;
}
int Alignment::checkIdenticalSeq()
{
//Todo: This should use sequence hashing.
int num_identical = 0;
IntVector checked;
checked.resize(getNSeq(), 0);
for (size_t seq1 = 0; seq1 < getNSeq(); ++seq1) {
if (checked[seq1]) continue;
bool first = true;
for (size_t seq2 = seq1+1; seq2 < getNSeq(); ++seq2) {
bool equal_seq = true;
for (iterator it = begin(); it != end(); it++)
if ((*it)[seq1] != (*it)[seq2]) {
equal_seq = false;
break;
}
if (equal_seq) {
if (first)
cout << "WARNING: Identical sequences " << getSeqName(seq1);
cout << ", " << getSeqName(seq2);
num_identical++;
checked[seq2] = 1;
first = false;
}
}
checked[seq1] = 1;
if (!first) cout << endl;
}
if (num_identical)
outWarning("Some identical sequences found that should be discarded before the analysis");
return num_identical;
}
Alignment *Alignment::removeIdenticalSeq(string not_remove, bool keep_two, StrVector &removed_seqs, StrVector &target_seqs)
{
auto n = getNSeq();
IntVector checked;
vector<bool> removed;
checked.resize(n, 0);
removed.resize(n, false);
//JB2020-06-17 Begin : Determine hashes for all the sequences
auto startHash = getRealTime();
vector<size_t> hashes;
hashes.resize(n, 0);
progress_display progress(n*2, "Checking for duplicate sequences");
#ifdef _OPENMP
#pragma omp parallel for schedule(static,100)
#endif
for (int seq1=0; seq1<n; ++seq1) {
size_t hash = 0;
for (iterator it = begin(); it != end(); ++it) {
adjustHash((*it)[seq1], hash);
}
hashes[seq1] = hash;
++progress;
}
if (verbose_mode >= VB_MED && !progress_display::getProgressDisplay()) {
auto hashTime = getRealTime() - startHash;
cout << "Hashing sequences took " << hashTime << " wall-clock seconds" << endl;
}
//JB2020-06-17 Finish
bool listIdentical = !Params::getInstance().suppress_duplicate_sequence_warnings;
auto startCheck = getRealTime();
for (size_t seq1 = 0; seq1 < getNSeq(); ++seq1) {
if (checked[seq1]) continue;
bool first_ident_seq = true;
for (size_t seq2 = seq1+1; seq2 < getNSeq(); ++seq2) {
if (getSeqName(seq2) == not_remove || removed[seq2]) continue;
if (hashes[seq1] != hashes[seq2]) continue; //JB2020-06-17
bool equal_seq = true;
for (iterator it = begin(); it != end(); it++) {
if ((*it)[seq1] != (*it)[seq2]) {
equal_seq = false;
break;
}
}
if (!equal_seq) continue;
if (removed_seqs.size()+3 < getNSeq() && (!keep_two || !first_ident_seq)) {
removed_seqs.push_back(getSeqName(seq2));
target_seqs.push_back(getSeqName(seq1));
removed[seq2] = true;
} else {
if (listIdentical) {
cout << "NOTE: " << getSeqName(seq2) << " is identical to " << getSeqName(seq1) << " but kept for subsequent analysis" << endl;
}
}
checked[seq2] = 1;
first_ident_seq = false;
}
checked[seq1] = 1;
++progress;
}
if (verbose_mode >= VB_MED && !progress_display::getProgressDisplay()) {
auto checkTime = getRealTime() - startCheck;
cout << "Checking for duplicate sequences took " << checkTime
<< " wall-clock seconds" << endl;
}
progress.done();
if (removed_seqs.size() > 0) {
double removeDupeStart = getRealTime();
if (removed_seqs.size() + 3 >= getNSeq()) {
outWarning("Your alignment contains too many identical sequences!");
}
IntVector keep_seqs;
for (size_t seq1 = 0; seq1 < getNSeq(); seq1++) {
if (!removed[seq1]) {
keep_seqs.emplace_back(seq1);
}
}
Alignment *aln = new Alignment;
aln->extractSubAlignment(this, keep_seqs, 0);
//cout << "NOTE: Identified " << removed_seqs.size()
// << " sequences as duplicates." << endl;
if (verbose_mode >= VB_MED) {
cout << "Removing " << removed_seqs.size() << " duplicated sequences took "
<< (getRealTime() - removeDupeStart) << " sec." << endl;
}
return aln;
} else return this;
}
void Alignment::adjustHash(StateType v, size_t& hash) const {
//Based on what boost::hash_combine() does.
//For now there's no need for a templated version
//in a separate header file. But if other classes start
//wanting to "roll their own hashing" this should move
//to, say, utils/hashing.h.
hash ^= std::hash<int>()(v) + 0x9e3779b9
+ (hash<<6) + (hash>>2);
}
void Alignment::adjustHash(bool v, size_t& hash) const {
hash ^= std::hash<bool>()(v) + 0x9e3779b9
+ (hash<<6) + (hash>>2);
}
bool Alignment::isGapOnlySeq(size_t seq_id) {
ASSERT(seq_id < getNSeq());
for (iterator it = begin(); it != end(); it++)
if ((*it)[seq_id] != STATE_UNKNOWN) {
return false;
}
return true;
}
// added by TD
vector<float> Alignment::computeSummaryStats(int seq1_idx, int seq2_idx) {
ASSERT(seq1_idx < getNSeq());
ASSERT(seq2_idx < getNSeq());
vector<float> stats(26);
//vector<size_t> freqs_seq1(4);
//vector<size_t> freqs_seq2(4);
//vector<size_t> titv_rates(16);
map<size_t, size_t> bitshift_map = {{0, 1}, {1, 3}, {2, 5}, {3, 7}};
for (iterator it = begin(); it != end(); it++) {
// check if contains gaps, if yes discard position
/*if ((*it)[seq1_idx] == 18 || (*it)[seq2_idx] == 18) { // 18 stands for a gap
continue;
}*/
// count nucleotides for sequence 1
switch ((*it)[seq1_idx]) {
case 0: stats[4]++;
break;
case 1: stats[5]++;
break;
case 2: stats[6]++;
break;
case 3: stats[7]++;
break;
default:
throw "Sequence contains other characters than A, C, G, T";
}
// count nucleotides for sequence 2
switch ((*it)[seq2_idx]) {
case 0: stats[8]++;
break;
case 1: stats[9]++;
break;
case 2: stats[10]++;
break;
case 3: stats[11]++;
break;
default:
throw "Sequence contains other characters than A, C, G, T";
}
// todo: make it clear what happens here with the bitshifting
// count transitions and transversions
switch(bitshift_map[(*it)[seq1_idx]] << bitshift_map[(*it)[seq2_idx]]) {
case 2: stats[0]++; // AA
break;
case 8: stats[14]++; // AC
break;
case 32: stats[15]++; // AG
break;
case 128: stats[16]++; // AT
break;
case 6: stats[20]++; // CA
break;
case 24: stats[1]++; // CC
break;
case 96: stats[18]++; // CG
break;
case 384: stats[17]++; // CT
break;
case 10: stats[21]++; // GA
break;
case 40: stats[24]++; // GC
break;
case 160: stats[2]++; // GG
break;
case 640: stats[19]++; // GT
break;
case 14: stats[22]++; // TA
break;
case 56: stats[23]++; // TC
break;
case 224: stats[25]++; // TG
break;
case 896: stats[3]++; // TT
break;
default:
throw "Bitshift result not known!";
}
}
stats[12] = stats[14] + stats[16] + stats[24] + stats[19] +
stats[25] + stats[22] + stats[18] + stats[20]; // transversion counts
stats[13] = stats[15] + stats[21] + stats[17] + stats[23]; // transition counts
size_t n_sites = getNSite();
// todo: check how to make it work with transform
//std::transform(stats.begin(), stats.end(), stats.begin(), [n_sites](int &c){return c/n_sites;});
for (size_t i = 0; i < 26; i++) {
stats[i] /= n_sites;
}
return stats;
}
Alignment *Alignment::replaceAmbiguousChars() {
IntVector patterns;
for (size_t idx = 0; idx < getNPattern(); idx++) {
patterns.push_back(idx);
}
Alignment *aln = new Alignment;
aln->extractPatterns(this, patterns);
for (size_t idx = 0; idx < aln->size(); idx++) {
for (size_t i = 0; i < getNSeq(); i++) {
if (aln->at(idx)[i] > 3) {
uint32_t base;
//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
switch(aln->at(idx)[i]) {
case 6: { // M: A or C
base = random_int(2); // todo: here input pointer to random number stream
//std::uniform_int_distribution<size_t> dist(0, 1);
//base = dist(rng);
aln->at(idx)[i] = (StateType) base;
}
break;
case 8: { // R: A or G
base = random_int(2);
//std::uniform_int_distribution<size_t> dist(0, 1);
//base = dist(rng);
aln->at(idx)[i] = base == 0 ? (StateType) base: (StateType) 2;
}
break;
case 9: { // S: C or G
base = random_int(2);
//std::uniform_int_distribution<size_t> dist(1, 2);
//base = dist(rng);
aln->at(idx)[i] = base == 0 ? 2 : base;
}
break;
case 10: { // V: A or C or G
base = random_int(3);
//std::uniform_int_distribution<size_t> dist(0, 2);
//base = dist(rng);
aln->at(idx)[i] = base;
}
break;
case 12: { // W: A or T
base = random_int(2);
//std::uniform_int_distribution<size_t> dist(0, 1);
//base = dist(rng);
aln->at(idx)[i] = base == 0 ? (StateType) base: (StateType) 3;
}
break;
case 13: { // Y: C or T
base = random_int(2);
//std::uniform_int_distribution<size_t> dist(1, 2);
//base = dist(rng);
aln->at(idx)[i] = base == 1 ? (StateType) base: (StateType) 3;
}
break;
case 14: { // H: A or C or T
base = random_int(3);
//std::uniform_int_distribution<size_t> dist(0, 2);
//base = dist(rng);
aln->at(idx)[i] = base == 2 ? (StateType) 3 : (StateType) base;
}
break;
case 15: { // K: G or T
base = random_int(2);
//std::uniform_int_distribution<size_t> dist(2, 3);
//base = dist(rng);
aln->at(idx)[i] = base == 0 ? (StateType) 2 : (StateType) 3;
}
break;
case 16: { // D: A or G or T
base = random_int(3);
//std::uniform_int_distribution<size_t> dist(1, 3);
//base = dist(rng);
aln->at(idx)[i] = base == 1 ? (StateType) 3 : (StateType) base;
}
break;
case 17: { // B: C or G or T
base = random_int(3);
//std::uniform_int_distribution<size_t> dist(1, 3);
//base = dist(rng);
aln->at(idx)[i] = base == 0 ? (StateType) 3 : (StateType) base;
}
case 18: { // N
base = random_int(4);
//std::uniform_int_distribution<size_t> dist(0, 3);
//base = dist(rng);
aln->at(idx)[i] = (StateType) base;
}
break;
default:
throw "Ambiguous character not known!";
}
}
}
}
return aln;
}
// added by TD
// todo: make 0.7 a parameter for the user to change
Alignment *Alignment::removeAndFillUpGappySites() {
IntVector keep_patterns;
// remove all sites with > 70% gaps
for (size_t idx = 0; idx < getNPattern(); idx++) {
size_t count_gaps = 0;
Pattern pattern = getPattern(idx);
for (size_t i = 0; i < getNSeq(); i++) {
if (pattern[i] == STATE_UNKNOWN)
count_gaps++;
}
if (count_gaps / getNSeq() <= 0.7) {
keep_patterns.push_back(idx);
}
}
Alignment *aln = new Alignment;
aln->extractPatterns(this, keep_patterns);
for (size_t idx = 0; idx < aln->size(); idx++) {
vector<size_t> freqs = aln->at(idx).freqs;
uint32_t most_frequent_base = std::max_element(freqs.begin(), freqs.end()) - freqs.begin();
for (size_t i = 0; i < getNSeq(); i++) {
if (aln->at(idx)[i] == STATE_UNKNOWN) {
// fill up gap with most frequent base
aln->at(idx)[i] = (StateType)most_frequent_base;
}
}
}
return aln;
}
Alignment *Alignment::removeGappySeq() {
IntVector keep_seqs;
size_t nseq = getNSeq();
for (size_t i = 0; i < nseq; i++)
if (! isGapOnlySeq(i)) {
keep_seqs.push_back(i);
}
if (keep_seqs.size() == nseq)
return this;
// 2015-12-03: if resulting alignment has too few seqs, try to add some back
if (keep_seqs.size() < 3 && getNSeq() >= 3) {
for (size_t i = 0; i < nseq && keep_seqs.size() < 3; i++)
if (isGapOnlySeq(i))
keep_seqs.push_back(i);
}
Alignment *aln = new Alignment;
aln->extractSubAlignment(this, keep_seqs, 0);
return aln;
}
void Alignment::checkGappySeq(bool force_error) {
size_t nseq = getNSeq();
int wrong_seq = 0;
for (size_t i = 0; i < nseq; i++)
if (isGapOnlySeq(i)) {
outWarning("Sequence " + getSeqName(i) + " contains only gaps or missing data");
wrong_seq++;
}
if (wrong_seq && force_error) {
outError("Some sequences (see above) are problematic, please check your alignment again");
}
}
Alignment::Alignment(char *filename, char *sequence_type, InputType &intype, string model) : vector<Pattern>() {
name = "Noname";
this->model_name = model;
if (sequence_type)
this->sequence_type = sequence_type;
aln_file = filename;
num_states = 0;
frac_const_sites = 0.0;
frac_invariant_sites = 0.0;
codon_table = NULL;
genetic_code = NULL;
non_stop_codon = NULL;
seq_type = SEQ_UNKNOWN;
STATE_UNKNOWN = 126;
pars_lower_bound = NULL;
double readStart = getRealTime();
cout << "Reading alignment file " << filename << " ... ";
intype = detectInputFile(filename);
try {
if (intype == IN_NEXUS) {
cout << "Nexus format detected" << endl;
readNexus(filename);
} else if (intype == IN_FASTA) {
cout << "Fasta format detected" << endl;
readFasta(filename, sequence_type);
} else if (intype == IN_PHYLIP) {
cout << "Phylip format detected" << endl;
if (Params::getInstance().phylip_sequential_format)
readPhylipSequential(filename, sequence_type);
else
readPhylip(filename, sequence_type);
} else if (intype == IN_COUNTS) {
cout << "Counts format (PoMo) detected" << endl;
readCountsFormat(filename, sequence_type);
} else if (intype == IN_CLUSTAL) {
cout << "Clustal format detected" << endl;
readClustal(filename, sequence_type);
} else if (intype == IN_MSF) {
cout << "MSF format detected" << endl;
readMSF(filename, sequence_type);
} else {
outError("Unknown sequence format, please use PHYLIP, FASTA, CLUSTAL, MSF, or NEXUS format");
}
} catch (ios::failure) {
outError(ERR_READ_INPUT);
} catch (const char *str) {
outError(str);
} catch (string str) {
outError(str);
}
if (verbose_mode >= VB_MED) {
cout << "Time to read input file was " << (getRealTime() - readStart) << " sec." << endl;
}
if (getNSeq() < 3)
{
outError("Alignment must have at least 3 sequences");
}
double constCountStart = getRealTime();
countConstSite();
if (verbose_mode >= VB_MED) {
cout << "Time to count constant sites was " << (getRealTime() - constCountStart) << " sec." << endl;
}
if (Params::getInstance().compute_seq_composition)
{
cout << "Alignment has " << getNSeq() << " sequences with " << getNSite()
<< " columns, " << getNPattern() << " distinct patterns" << endl
<< num_informative_sites << " parsimony-informative, "
<< num_variant_sites-num_informative_sites << " singleton sites, "
<< (int)(frac_const_sites*getNSite()) << " constant sites" << endl;
}
//buildSeqStates();
checkSeqName();
// OBSOLETE: identical sequences are handled later
// checkIdenticalSeq();
//cout << "Number of character states is " << num_states << endl;
//cout << "Number of patterns = " << size() << endl;
//cout << "Fraction of constant sites: " << frac_const_sites << endl;
}
Alignment::Alignment(NxsDataBlock *data_block, char *sequence_type, string model) : vector<Pattern>() {
name = "Noname";
this->model_name = model;
if (sequence_type)
this->sequence_type = sequence_type;
num_states = 0;
frac_const_sites = 0.0;
frac_invariant_sites = 0.0;
codon_table = NULL;
genetic_code = NULL;
non_stop_codon = NULL;
seq_type = SEQ_UNKNOWN;
STATE_UNKNOWN = 126;
pars_lower_bound = NULL;
extractDataBlock(data_block);
if (verbose_mode >= VB_DEBUG)
data_block->Report(cout);
if (getNSeq() < 3)
outError("Alignment must have at least 3 sequences");
countConstSite();
if (Params::getInstance().compute_seq_composition)
cout << "Alignment has " << getNSeq() << " sequences with " << getNSite()
<< " columns, " << getNPattern() << " distinct patterns" << endl
<< num_informative_sites << " parsimony-informative, "
<< num_variant_sites-num_informative_sites << " singleton sites, "
<< (int)(frac_const_sites*getNSite()) << " constant sites" << endl;
//buildSeqStates();
checkSeqName();
// OBSOLETE: identical sequences are handled later
// checkIdenticalSeq();
//cout << "Number of character states is " << num_states << endl;
//cout << "Number of patterns = " << size() << endl;
//cout << "Fraction of constant sites: " << frac_const_sites << endl;
}
bool Alignment::isStopCodon(int state) {
// 2017-05-27: all stop codon removed from Markov process
return false;
if (seq_type != SEQ_CODON || state >= num_states) return false;
ASSERT(genetic_code);
return (genetic_code[state] == '*');
}
int Alignment::getNumNonstopCodons() {
if (seq_type != SEQ_CODON) return num_states;
ASSERT(genetic_code);
int c = 0;
for (char *ch = genetic_code; *ch != 0; ch++)
if (*ch != '*') c++;
return c;
}
bool Alignment::isStandardGeneticCode() {
if (seq_type != SEQ_CODON) return false;
return (genetic_code == genetic_code1 || genetic_code == genetic_code11);
}
/*
void Alignment::buildSeqStates(vector<vector<int> > &seq_states, bool add_unobs_const) {
vector<StateType> unobs_const;
if (add_unobs_const) {
unobs_const.resize(num_states);
for (StateType state = 0; state < num_states; state++)
unobs_const[state] = state;
}
seq_states.clear();
seq_states.resize(getNSeq());
for (int seq = 0; seq < getNSeq(); seq++) {
vector<bool> has_state;
has_state.resize(STATE_UNKNOWN+1, false);
for (int site = 0; site < getNPattern(); site++)
has_state[at(site)[seq]] = true;
for (StateType it : unobs_const)
has_state[it] = true;
seq_states[seq].clear();
for (int state = 0; state < STATE_UNKNOWN; state++)
if (has_state[state])
seq_states[seq].push_back(state);
}
}
*/
int Alignment::readNexus(char *filename) {
NxsTaxaBlock *taxa_block;
NxsAssumptionsBlock *assumptions_block;
NxsDataBlock *data_block = NULL;
NxsTreesBlock *trees_block = NULL;
NxsCharactersBlock *char_block = NULL;
taxa_block = new NxsTaxaBlock();
assumptions_block = new NxsAssumptionsBlock(taxa_block);
data_block = new NxsDataBlock(taxa_block, assumptions_block);
char_block = new NxsCharactersBlock(taxa_block, assumptions_block);
trees_block = new TreesBlock(taxa_block);
MyReader nexus(filename);
nexus.Add(taxa_block);
nexus.Add(assumptions_block);
nexus.Add(data_block);
nexus.Add(char_block);
nexus.Add(trees_block);
MyToken token(nexus.inf);
nexus.Execute(token);
if (data_block->GetNTax() && char_block->GetNTax()) {
outError("I am confused since both DATA and CHARACTERS blocks were specified");
return 0;
}
if (data_block->GetNTax() == 0 && char_block->GetNTax() == 0) {
outError("No DATA or CHARACTERS blocks found");
return 0;
}
if (char_block->GetNTax() > 0) {
extractDataBlock(char_block);
if (verbose_mode >= VB_DEBUG)
char_block->Report(cout);
} else {
extractDataBlock(data_block);
if (verbose_mode >= VB_DEBUG)
data_block->Report(cout);
}
delete trees_block;
delete char_block;
delete data_block;
delete assumptions_block;
delete taxa_block;
return 1;
}
void Alignment::computeUnknownState() {
switch (seq_type) {
case SEQ_DNA: STATE_UNKNOWN = 18; break;
case SEQ_PROTEIN: STATE_UNKNOWN = 23; break;
case SEQ_POMO: {
if (pomo_sampling_method == SAMPLING_SAMPLED) STATE_UNKNOWN = num_states;
else STATE_UNKNOWN = 0xffffffff; // only dummy, will be initialized later
break;
}
default: STATE_UNKNOWN = num_states; break;
}
}
int getDataBlockMorphStates(NxsCharactersBlock *data_block) {
int nseq = data_block->GetNTax();
int nsite = data_block->GetNCharTotal();
int seq, site;
char ch;
int nstates = 0;
for (seq = 0; seq < nseq; seq++)
for (site = 0; site < nsite; site++) {
int nstate = data_block->GetNumStates(seq, site);
if (nstate == 0)
continue;
if (nstate == 1) {
ch = data_block->GetState(seq, site, 0);
if (!isalnum(ch)) continue;
if (ch >= '0' && ch <= '9')