forked from diepthihoang/mpboot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalignment.cpp
More file actions
2827 lines (2582 loc) · 94.3 KB
/
alignment.cpp
File metadata and controls
2827 lines (2582 loc) · 94.3 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 "alignment.h"
#include "myreader.h"
#include <numeric>
#include <sstream>
using namespace std;
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
const double MIN_FREQUENCY = 0.0001;
const double MIN_FREQUENCY_DIFF = 0.00001;
Alignment::Alignment()
: vector<Pattern>()
{
num_states = 0;
frac_const_sites = 0.0;
codon_table = NULL;
genetic_code = NULL;
non_stop_codon = NULL;
seq_type = SEQ_UNKNOWN;
STATE_UNKNOWN = 126;
// Diep added:
n_informative_patterns = -1; // use -1 for denoting uninitialization
n_informative_sites = -1; // use -1 for denoting uninitialization
}
void Alignment::operator=(Alignment & aln){
int nsite = aln.getNSite();
seq_names.insert(seq_names.begin(), aln.seq_names.begin(), aln.seq_names.end());
num_states = aln.num_states;
seq_type = aln.seq_type;
site_pattern.resize(nsite);
clear();
pattern_index.clear();
int site = 0;
for(std::vector<Pattern>::iterator it = aln.begin(); it != aln.end(); ++it) {
for(int i = 0; i < it->frequency; i++){
addPattern(*it, site, 1);
site++;
}
}
countConstSite();
// Diep added:
n_informative_patterns = aln.n_informative_patterns;
n_informative_sites = aln.n_informative_sites;
}
void Alignment::updateSitePatternAfterOptimized(){
frac_const_sites = 0.0;
int nsite = getNSite();
int nptn = getNPattern();
site_pattern.resize(nsite);
pattern_index.clear();
n_informative_patterns = 0;
n_informative_sites = 0;
int site = 0;
for(int i = 0; i < nptn; ++i) {
for(int j = 0; j < at(i).frequency; ++j){
site_pattern[site] = i;
site++;
}
pattern_index[at(i)] = i;
// if(at(i).ras_pars_score != 0){
// n_informative_patterns++;
// n_informative_sites += at(i).frequency;
// }
}
countConstSite();
countInformative();
}
void Alignment::modifyPatternFreq(Alignment & aln, unsigned short * new_pattern_freqs, int new_nptn){
assert(new_nptn == aln.getNPattern());
int nsite = aln.getNSite();
seq_names.insert(seq_names.begin(), aln.seq_names.begin(), aln.seq_names.end());
num_states = aln.num_states;
seq_type = aln.seq_type;
site_pattern.resize(nsite);
clear();
pattern_index.clear();
int site = 0;
std::vector<Pattern>::iterator it;
int p;
n_informative_patterns = 0;
n_informative_sites = 0;
int cur_pat = 0;
for(it = aln.begin(), p = 0; it != aln.end(); ++it, ++p) {
if((it->ras_pars_score > 0) && (new_pattern_freqs[p] > 0)){
n_informative_patterns++;
n_informative_sites += new_pattern_freqs[p];
}
for(int i = 0; i < new_pattern_freqs[p]; i++){
Pattern pat = *it; // Diep: (Nov 16, 2016) Fix error that frequencies all equal to 1 since optimizeBootstrapTree
addPattern(pat, site, 1);
// addPattern(*it, site, 1); // WRONG old code
site++;
}
if(new_pattern_freqs[p] > 0){
at(cur_pat).ras_pars_score = it->ras_pars_score;
cur_pat++;
}
}
countConstSite();
}
string &Alignment::getSeqName(int i) {
assert(i >= 0 && i < (int)seq_names.size());
return seq_names[i];
}
int Alignment::getSeqID(string &seq_name) {
for (int i = 0; i < getNSeq(); i++)
if (seq_name == getSeqName(i)) return i;
return -1;
}
int Alignment::getMaxSeqNameLength() {
int len = 0;
for (int i = 0; i < getNSeq(); i++)
if (getSeqName(i).length() > len)
len = getSeqName(i).length();
return len;
}
void Alignment::checkSeqName() {
ostringstream warn_str;
StrVector::iterator it;
for (it = seq_names.begin(); it != seq_names.end(); it++) {
string orig_name = (*it);
for (string::iterator i = it->begin(); i != it->end(); i++) {
if (!isalnum(*i) && (*i) != '_' && (*i) != '-' && (*i) != '.') {
(*i) = '_';
}
}
if (orig_name != (*it))
warn_str << orig_name << " -> " << (*it) << endl;
}
if (warn_str.str() != "") {
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 (verbose_mode >= VB_MIN)*/ {
int max_len = getMaxSeqNameLength()+1;
cout << "ID ";
cout.width(max_len);
cout << left << "Sequence" << " #Gap/Ambiguity" << endl;
int num_problem_seq = 0;
int total_gaps = 0;
for (int i = 0; i < seq_names.size(); i++) {
int num_gaps = getNSite() - countProperChar(i);
total_gaps += num_gaps;
double percent_gaps = ((double)num_gaps / getNSite())*100.0;
cout.width(4);
cout << i+1 << " ";
cout.width(max_len);
cout << left << seq_names[i] << " ";
cout.width(4);
cout << num_gaps << " (" << percent_gaps << "%)";
if (percent_gaps > 50) {
cout << " !!!";
num_problem_seq++;
}
cout << "\t" << seq_states[i].size();
cout << endl;
}
if (num_problem_seq) cout << "WARNING: " << num_problem_seq << " sequences contain more than 50% gaps/ambiguity" << endl;
cout << "**** ";
cout.width(max_len);
cout << left << "TOTAL" << " " << total_gaps << " (" << ((double)total_gaps/getNSite())/getNSeq()*100 << "%)" << endl;
}
}
int Alignment::checkIdenticalSeq()
{
int num_identical = 0;
IntVector checked;
checked.resize(getNSeq(), 0);
for (int seq1 = 0; seq1 < getNSeq(); seq1++) {
if (checked[seq1]) continue;
bool first = true;
for (int 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)
cerr << "WARNING: Identical sequences " << getSeqName(seq1);
cerr << ", " << getSeqName(seq2);
num_identical++;
checked[seq2] = 1;
first = false;
}
}
checked[seq1] = 1;
if (!first) cerr << 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)
{
IntVector checked;
vector<bool> removed;
checked.resize(getNSeq(), 0);
removed.resize(getNSeq(), false);
// map[hash, string] = (countAppearance, firstappearance)
map<pair<int, string>, pair<int, int>> infoAppearance;
int seq1;
for (seq1 = 0; seq1 < getNSeq(); seq1++) {
string rowSequence;
for(int i = 0; i < getNPattern(); ++i) {
rowSequence += at(i)[seq1];
}
pair<int, string> pairValue = make_pair(calculateSequenceHash(rowSequence), (string) rowSequence);
pair<int, int> info = infoAppearance[pairValue];
bool equal_seq = (info.first > 0);
bool first_ident_seq = (info.first == 1);
// check if we can remove this sequence
if (equal_seq && getSeqName(seq1) != not_remove) {
if (!keep_two || !first_ident_seq) {
removed_seqs.push_back(getSeqName(seq1));
target_seqs.push_back(getSeqName(info.second));
removed[seq1] = true;
}
}
pair<int, int> newInfo = make_pair(info.first + 1, info.second);
if (equal_seq == false) {
newInfo.second = seq1;
}
infoAppearance[pairValue] = newInfo;
}
if (removed_seqs.size() > 0) {
if (removed_seqs.size() > getNSeq()-3)
outError("Your alignment contains too many identical sequences, quiting now...");
IntVector keep_seqs;
for (seq1 = 0; seq1 < getNSeq(); seq1++)
if (!removed[seq1]) keep_seqs.push_back(seq1);
Alignment *aln = new Alignment;
aln->extractSubAlignment(this, keep_seqs, 0);
return aln;
} else return this;
}
// // Diep: This is the old removeIdenticalSeq implementation inherited from IQ-TREE1
// to be replace by Nghia's better algorithm
Alignment *Alignment::removeIdenticalSeqObsolete(string not_remove, bool keep_two, StrVector &removed_seqs, StrVector &target_seqs)
{
IntVector checked;
vector<bool> removed;
checked.resize(getNSeq(), 0);
removed.resize(getNSeq(), false);
int seq1;
for (seq1 = 0; seq1 < getNSeq(); seq1++) {
if (checked[seq1]) continue;
bool first_ident_seq = true;
for (int seq2 = seq1+1; seq2 < getNSeq(); seq2++) {
if (getSeqName(seq2) == not_remove) continue;
bool equal_seq = true;
for (iterator it = begin(); it != end(); it++)
if ((*it)[seq1] != (*it)[seq2]) {
equal_seq = false;
break;
}
if (equal_seq) {
if (!keep_two || !first_ident_seq) {
removed_seqs.push_back(getSeqName(seq2));
target_seqs.push_back(getSeqName(seq1));
removed[seq2] = true;
}
checked[seq2] = 1;
first_ident_seq = false;
}
}
checked[seq1] = 1;
}
if (removed_seqs.size() > 0) {
if (removed_seqs.size() > getNSeq()-3)
outError("Your alignment contains too many identical sequences, quiting now...");
IntVector keep_seqs;
for (seq1 = 0; seq1 < getNSeq(); seq1++)
if (!removed[seq1]) keep_seqs.push_back(seq1);
Alignment *aln = new Alignment;
aln->extractSubAlignment(this, keep_seqs, 0);
return aln;
} else return this;
}
bool Alignment::isGapOnlySeq(int seq_id) {
assert(seq_id < getNSeq());
for (iterator it = begin(); it != end(); it++)
if ((*it)[seq_id] != STATE_UNKNOWN) {
return false;
}
return true;
}
Alignment *Alignment::removeGappySeq() {
IntVector keep_seqs;
int i, nseq = getNSeq();
for (i = 0; i < nseq; i++)
if (! isGapOnlySeq(i)) {
keep_seqs.push_back(i);
}
if (keep_seqs.size() == nseq)
return this;
Alignment *aln = new Alignment;
aln->extractSubAlignment(this, keep_seqs, 0);
return aln;
}
void Alignment::checkGappySeq(bool force_error) {
int nseq = getNSeq(), i;
int wrong_seq = 0;
for (i = 0; i < nseq; i++)
if (isGapOnlySeq(i)) {
cout << "ERROR: Sequence " << getSeqName(i) << " contains only gaps or missing data" << endl;
wrong_seq++;
}
if (wrong_seq) {
outError("Some sequences (see above) are problematic, please check your alignment again");
}
}
Alignment::Alignment(char *filename, char *sequence_type, InputType &intype) : vector<Pattern>() {
num_states = 0;
frac_const_sites = 0.0;
codon_table = NULL;
genetic_code = NULL;
non_stop_codon = NULL;
seq_type = SEQ_UNKNOWN;
STATE_UNKNOWN = 126;
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;
readPhylip(filename, sequence_type);
} else {
outError("Unknown sequence format, please use PHYLIP, FASTA, or NEXUS format");
}
} catch (ios::failure) {
outError(ERR_READ_INPUT);
} catch (const char *str) {
outError(str);
} catch (string str) {
outError(str);
}
if (getNSeq() < 3)
outError("Alignment must have at least 3 sequences");
cout << "Alignment has " << getNSeq() << " sequences with " << getNSite() <<
" columns and " << getNPattern() << " patterns"<< 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;
countConstSite();
//cout << "Fraction of constant sites: " << frac_const_sites << endl;
}
void Alignment::buildSeqStates(bool add_unobs_const) {
string unobs_const;
if (add_unobs_const) unobs_const = getUnobservedConstPatterns();
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 (string::iterator it = unobs_const.begin(); it != unobs_const.end(); it++)
has_state[*it] = true;
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 (char_block->GetNTax() == 0) { char_block = data_block; }
if (char_block->GetNTax() == 0) {
outError("No data is given in the input file");
return 0;
}
if (verbose_mode >= VB_DEBUG)
char_block->Report(cout);
extractDataBlock(char_block);
return 1;
}
void Alignment::computeUnknownState() {
switch (seq_type) {
case SEQ_DNA: STATE_UNKNOWN = 18; break;
case SEQ_PROTEIN: STATE_UNKNOWN = 22; break;
default: STATE_UNKNOWN = num_states; break;
}
}
void Alignment::extractDataBlock(NxsCharactersBlock *data_block) {
int nseq = data_block->GetNTax();
int nsite = data_block->GetNCharTotal();
char *symbols = NULL;
//num_states = strlen(symbols);
char char_to_state[NUM_CHAR];
char state_to_char[NUM_CHAR];
NxsCharactersBlock::DataTypesEnum data_type = (NxsCharactersBlock::DataTypesEnum)data_block->GetDataType();
if (data_type == NxsCharactersBlock::continuous) {
outError("Continuous characters not supported");
} else if (data_type == NxsCharactersBlock::dna || data_type == NxsCharactersBlock::rna ||
data_type == NxsCharactersBlock::nucleotide)
{
num_states = 4;
if (data_type == NxsCharactersBlock::rna)
symbols = symbols_rna;
else
symbols = symbols_dna;
seq_type = SEQ_DNA;
} else if (data_type == NxsCharactersBlock::protein) {
num_states = 20;
symbols = symbols_protein;
seq_type = SEQ_PROTEIN;
} else {
// standard morphological character
num_states = data_block->GetMaxObsNumStates();
if (num_states > 32)
outError("Number of states can not exceed 32");
if (num_states < 2)
outError("Number of states can not be below 2");
if (num_states == 2)
seq_type = SEQ_BINARY;
else
seq_type = SEQ_MORPH;
symbols = symbols_morph;
}
computeUnknownState();
memset(char_to_state, STATE_UNKNOWN, NUM_CHAR);
memset(state_to_char, '?', NUM_CHAR);
for (int i = 0; i < strlen(symbols); i++) {
char_to_state[(int)symbols[i]] = i;
state_to_char[i] = symbols[i];
}
state_to_char[(int)STATE_UNKNOWN] = '-';
int seq, site;
for (seq = 0; seq < nseq; seq++) {
seq_names.push_back(data_block->GetTaxonLabel(seq));
}
site_pattern.resize(nsite, -1);
int num_gaps_only = 0;
for (site = 0; site < nsite; site++) {
Pattern pat;
for (seq = 0; seq < nseq; seq++) {
int nstate = data_block->GetNumStates(seq, site);
if (nstate == 0)
pat += STATE_UNKNOWN;
else if (nstate == 1) {
pat += char_to_state[(int)data_block->GetState(seq, site, 0)];
} else {
assert(data_type != NxsCharactersBlock::dna || data_type != NxsCharactersBlock::rna || data_type != NxsCharactersBlock::nucleotide);
char pat_ch = 0;
for (int state = 0; state < nstate; state++) {
pat_ch |= (1 << char_to_state[(int)data_block->GetState(seq, site, state)]);
}
pat_ch += 3;
pat += pat_ch;
}
}
num_gaps_only += addPattern(pat, site);
}
if (num_gaps_only)
cout << "WARNING: " << num_gaps_only << " sites contain only gaps or ambiguous chars." << endl;
if (verbose_mode >= VB_MAX)
for (site = 0; site < size(); site++) {
for (seq = 0; seq < nseq; seq++)
cout << state_to_char[(int)(*this)[site][seq]];
cout << " " << (*this)[site].frequency << endl;
}
}
bool Alignment::addPattern(Pattern &pat, int site, int freq, int ras_pars_score) {
// check if pattern contains only gaps
bool gaps_only = true;
for (Pattern::iterator it = pat.begin(); it != pat.end(); it++)
if ((*it) != STATE_UNKNOWN) {
gaps_only = false;
break;
}
if (gaps_only) {
if (verbose_mode >= VB_DEBUG)
cout << "Site " << site << " contains only gaps or ambiguous characters" << endl;
//return true;
}
PatternIntMap::iterator pat_it = pattern_index.find(pat);
if (pat_it == pattern_index.end()) { // not found
pat.frequency = freq;
pat.ras_pars_score = ras_pars_score;
pat.computeConst(STATE_UNKNOWN);
push_back(pat);
pattern_index[pat] = size()-1;
site_pattern[site] = size()-1;
} else {
int index = pat_it->second;
at(index).frequency += freq;
at(index).ras_pars_score = ras_pars_score;
site_pattern[site] = index;
}
return gaps_only;
}
void Alignment::ungroupSitePattern()
{
vector<Pattern> stored_pat = (*this);
clear();
for (int i = 0; i < getNSite(); i++) {
Pattern pat = stored_pat[getPatternID(i)];
pat.frequency = 1;
push_back(pat);
site_pattern[i] = i;
}
pattern_index.clear();
}
void Alignment::regroupSitePattern(int groups, IntVector& site_group)
{
vector<Pattern> stored_pat = (*this);
IntVector stored_site_pattern = site_pattern;
clear();
site_pattern.clear();
site_pattern.resize(stored_site_pattern.size(), -1);
int count = 0;
for (int g = 0; g < groups; g++) {
pattern_index.clear();
for (int i = 0; i < site_group.size(); i++)
if (site_group[i] == g) {
count++;
Pattern pat = stored_pat[stored_site_pattern[i]];
addPattern(pat, i);
}
}
assert(count == stored_site_pattern.size());
count = 0;
for (iterator it = begin(); it != end(); it++)
count += it->frequency;
assert(count == getNSite());
pattern_index.clear();
//printPhylip("/dev/stdout");
}
void Alignment::condenseParsimonyEquivalentSites(Alignment *aln) {
if (aln->seq_type != SEQ_DNA) return; // TODO: right now only works for DNA
int site, nsite = aln->getNSite();
seq_names.insert(seq_names.begin(), aln->seq_names.begin(), aln->seq_names.end());
num_states = aln->num_states;
seq_type = aln->seq_type;
site_pattern.resize(nsite, -1);
clear();
pattern_index.clear();
char state_map[128];
int i;
for (site = 0; site < nsite; site++) {
Alignment::iterator it = aln->begin() + aln->site_pattern[site];
memset(state_map, -1, 128);
state_map[STATE_UNKNOWN] = STATE_UNKNOWN;
// first map unambiguous characters
char state = 0;
Pattern::iterator c;
Pattern pat_new;
pat_new.resize(getNSeq(), -1);
pat_new.is_const = it->is_const;
for (c = it->begin(); c != it->end(); c++)
if (*c < num_states && state_map[*c] < 0) {
state_map[*c] = state;
state++;
}
// now map ambiguous characters
for (c = it->begin(); c != it->end(); c++)
if (*c >= num_states && *c != STATE_UNKNOWN) {
char ch = (*c) - (num_states-1);
for (char state2 = 0; state2 < num_states; state2++)
if (ch & (1<<state2) && state_map[state2] < 0) {
state_map[state2] = state;
state++;
}
}
for (char state2 = 0; state2 < num_states; state2++)
if (state_map[state2] < 0)
state_map[state2] = state++;
int max_state = (1<<num_states)-1+num_states;
assert(state == num_states);
for (state = num_states; state < max_state; state++) {
char ch = state - (num_states-1);
state_map[state] = num_states-1;
for (char state2 = 0; state2 < num_states; state2++)
if (ch & (1<<state2))
state_map[state] += (1 << state_map[state2]);
}
// now convert current pattern
for (c = it->begin(), i = 0; c != it->end(); c++, i++)
pat_new[i] = state_map[*c];
addPattern(pat_new, site);
if (verbose_mode >= VB_MAX) {
for (c = it->begin(); c != it->end(); c++) {
cout << convertStateBackStr(*c);
}
cout << " -> ";
for (c = pat_new.begin(); c != pat_new.end(); c++) {
cout << convertStateBackStr(*c);
}
cout << endl;
}
}
countConstSite();
countInformative();
cout << "Alignment is condensed into " << size() << " patterns" << endl;
}
/**
detect the data type of the input sequences
@param sequences vector of strings
@return the data type of the input sequences
*/
SeqType Alignment::detectSequenceType(StrVector &sequences) {
int num_nuc = 0;
int num_ungap = 0;
int num_bin = 0;
int num_alpha = 0;
int num_digit = 0;
for (StrVector::iterator it = sequences.begin(); it != sequences.end(); it++)
for (string::iterator i = it->begin(); i != it->end(); i++) {
if ((*i) != '?' && (*i) != '-' && (*i) != '.' && *i != 'N' && *i != 'X') num_ungap++;
if ((*i) == 'A' || (*i) == 'C' || (*i) == 'G' || (*i) == 'T' || (*i) == 'U')
num_nuc++;
if ((*i) == '0' || (*i) == '1')
num_bin++;
if (isalpha(*i)) num_alpha++;
if (isdigit(*i)) num_digit++;
}
if (((double)num_nuc) / num_ungap > 0.9)
return SEQ_DNA;
if (((double)num_bin) / num_ungap > 0.9)
return SEQ_BINARY;
if (((double)num_alpha) / num_ungap > 0.9)
return SEQ_PROTEIN;
if (((double)(num_alpha+num_digit)) / num_ungap > 0.9)
return SEQ_MORPH;
return SEQ_UNKNOWN;
}
void Alignment::buildStateMap(char *map, SeqType seq_type) {
memset(map, STATE_INVALID, NUM_CHAR);
assert(STATE_UNKNOWN < 126);
map[(unsigned char)'?'] = STATE_UNKNOWN;
map[(unsigned char)'-'] = STATE_UNKNOWN;
map[(unsigned char)'.'] = STATE_UNKNOWN;
int len;
switch (seq_type) {
case SEQ_BINARY:
map[(unsigned char)'0'] = 0;
map[(unsigned char)'1'] = 1;
return;
case SEQ_DNA: // DNA
case SEQ_CODON:
map[(unsigned char)'A'] = 0;
map[(unsigned char)'C'] = 1;
map[(unsigned char)'G'] = 2;
map[(unsigned char)'T'] = 3;
map[(unsigned char)'U'] = 3;
map[(unsigned char)'R'] = 1+4+3; // A or G, Purine
map[(unsigned char)'Y'] = 2+8+3; // C or T, Pyrimidine
map[(unsigned char)'N'] = STATE_UNKNOWN;
map[(unsigned char)'X'] = STATE_UNKNOWN;
map[(unsigned char)'W'] = 1+8+3; // A or T, Weak
map[(unsigned char)'S'] = 2+4+3; // G or C, Strong
map[(unsigned char)'M'] = 1+2+3; // A or C, Amino
map[(unsigned char)'K'] = 4+8+3; // G or T, Keto
map[(unsigned char)'B'] = 2+4+8+3; // C or G or T
map[(unsigned char)'H'] = 1+2+8+3; // A or C or T
map[(unsigned char)'D'] = 1+4+8+3; // A or G or T
map[(unsigned char)'V'] = 1+2+4+3; // A or G or C
return;
case SEQ_PROTEIN: // Protein
for (int i = 0; i < 20; i++)
map[(int)symbols_protein[i]] = i;
map[(int)symbols_protein[20]] = STATE_UNKNOWN;
// map[(unsigned char)'B'] = 4+8+19; // N or D
// map[(unsigned char)'Z'] = 32+64+19; // Q or E
map[(unsigned char)'B'] = 20; // N or D
map[(unsigned char)'Z'] = 21; // Q or E
return;
case SEQ_MULTISTATE:
for (int i = 0; i <= STATE_UNKNOWN; i++)
map[i] = i;
return;
case SEQ_MORPH: // Protein
len = strlen(symbols_morph);
for (int i = 0; i < len; i++)
map[(int)symbols_morph[i]] = i;
return;
default:
return;
}
}
/**
convert a raw characer state into ID, indexed from 0
@param state input raw state
@param seq_type data type (SEQ_DNA, etc.)
@return state ID
*/
char Alignment::convertState(char state, SeqType seq_type) {
if (state == '?' || state == '-' || state == '.')
return STATE_UNKNOWN;
char *loc;
switch (seq_type) {
case SEQ_BINARY:
switch (state) {
case '0':
return 0;
case '1':
return 1;
default:
return STATE_INVALID;
}
break;
case SEQ_DNA: // DNA
switch (state) {
case 'A':
return 0;
case 'C':
return 1;
case 'G':
return 2;
case 'T':
return 3;
case 'U':
return 3;
case 'R':
return 1+4+3; // A or G, Purine
case 'Y':
return 2+8+3; // C or T, Pyrimidine
case 'N':
return STATE_UNKNOWN;
case 'W':
return 1+8+3; // A or T, Weak
case 'S':
return 2+4+3; // G or C, Strong
case 'M':
return 1+2+3; // A or C, Amino
case 'K':
return 4+8+3; // G or T, Keto
case 'B':
return 2+4+8+3; // C or G or T
case 'H':
return 1+2+8+3; // A or C or T
case 'D':
return 1+4+8+3; // A or G or T
case 'V':
return 1+2+4+3; // A or G or C
default:
return STATE_INVALID; // unrecognize character
}
return state;
case SEQ_PROTEIN: // Protein
// if (state == 'B') return 4+8+19;
// if (state == 'Z') return 32+64+19;
if (state == 'B') return 20;
if (state == 'Z') return 21;
loc = strchr(symbols_protein, state);
if (!loc) return STATE_INVALID; // unrecognize character
state = loc - symbols_protein;
if (state < 20)
return state;
else
return STATE_UNKNOWN;
case SEQ_MORPH: // Standard morphological character
loc = strchr(symbols_morph, state);
if (!loc) return STATE_INVALID; // unrecognize character
state = loc - symbols_morph;
return state;
default:
return STATE_INVALID;
}
}
char Alignment::convertState(char state) {
return convertState(state, seq_type);
}
char Alignment::convertStateBack(char state) {
if (state == STATE_UNKNOWN) return '-';
if (state == STATE_INVALID) return '?';
switch (seq_type) {
case SEQ_BINARY:
switch (state) {
case 0:
return '0';
case 1:
return '1';
default:
return STATE_INVALID;
}
case SEQ_DNA: // DNA
switch (state) {
case 0:
return 'A';
case 1:
return 'C';
case 2:
return 'G';
case 3:
return 'T';
case 1+4+3:
return 'R'; // A or G, Purine
case 2+8+3:
return 'Y'; // C or T, Pyrimidine
case 1+8+3:
return 'W'; // A or T, Weak
case 2+4+3:
return 'S'; // G or C, Strong
case 1+2+3:
return 'M'; // A or C, Amino
case 4+8+3:
return 'K'; // G or T, Keto
case 2+4+8+3:
return 'B'; // C or G or T
case 1+2+8+3:
return 'H'; // A or C or T
case 1+4+8+3:
return 'D'; // A or G or T
case 1+2+4+3:
return 'V'; // A or G or C
default:
return '?'; // unrecognize character
}
return state;
case SEQ_PROTEIN: // Protein
if (state < 20)
return symbols_protein[(int)state];
else if (state == 20) return 'B';
else if (state == 21) return 'Z';
// else if (state == 4+8+19) return 'B';
// else if (state == 32+64+19) return 'Z';
else
return '-';
case SEQ_MORPH:
// morphological state
if (state < strlen(symbols_morph))
return symbols_morph[(int)state];
else
return '-';
default:
// unknown
return '*';
}
}
string Alignment::convertStateBackStr(char state) {
string str;
if (seq_type != SEQ_CODON) {
str = convertStateBack(state);
} else {
// codon data