-
Notifications
You must be signed in to change notification settings - Fork 3
/
alignment.cpp
2260 lines (2061 loc) · 76 KB
/
alignment.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// C++ Implementation: alignment
//
// Description:
//
//
// Author: BUI Quang Minh, Steffen Klaere, Arndt von Haeseler <[email protected]>, (C) 2008
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "alignment.h"
#include "myreader.h"
#include <numeric>
char symbols_protein[] = "ARNDCQEGHILKMFPSTWYVX"; // X for unknown AA
char symbols_dna[] = "ACGT";
char symbols_rna[] = "ACGU";
char symbols_binary[] = "01";
// 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;
}
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 << 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;
}
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;
cout << "Reading alignment file " << filename << " ..." << endl;
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");
checkSeqName();
cout << "Alignment has " << getNSeq() << " sequences with " << getNSite() <<
" columns and " << getNPattern() << " patterns"<< endl;
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;
}
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::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;
} else if (data_type == NxsCharactersBlock::protein) {
num_states = 20;
symbols = symbols_protein;
} else {
num_states = 2;
symbols = symbols_binary;
}
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) {
// 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.computeConst();
push_back(pat);
pattern_index[pat] = size()-1;
site_pattern[site] = size()-1;
} else {
int index = pat_it->second;
at(index).frequency += freq;
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");
}
/**
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_alphabet = 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 (isalnum(*i)) num_alphabet++;
}
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_alphabet) / num_ungap < 0.5)
return SEQ_UNKNOWN;
return SEQ_PROTEIN;
}
void buildStateMap(char *map, SeqType seq_type) {
memset(map, STATE_INVALID, NUM_CHAR);
map[(unsigned char)'?'] = STATE_UNKNOWN;
map[(unsigned char)'-'] = STATE_UNKNOWN;
map[(unsigned char)'.'] = STATE_UNKNOWN;
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
return;
case SEQ_MULTISTATE:
for (int i = 0; i <= STATE_UNKNOWN; i++)
map[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;
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;
default:
return STATE_INVALID;
}
}
char Alignment::convertState(char state) {
switch (num_states) {
case 2: return convertState(state, SEQ_BINARY);
case 4: return convertState(state, SEQ_DNA);
case 20: return convertState(state, SEQ_PROTEIN);
default: return STATE_INVALID;
}
}
char Alignment::convertStateBack(char state) {
if (state == STATE_UNKNOWN) return '-';
if (state == STATE_INVALID) return '?';
switch (num_states) {
case 2:
switch (state) {
case 0:
return '0';
case 1:
return '1';
default:
return STATE_INVALID;
}
case 4: // 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 20: // Protein
if (state < 20)
return symbols_protein[(int)state];
else if (state == 4+8+19) return 'B';
else if (state == 32+64+19) return 'Z';
else
return '-';
default:
// unknown
return '*';
}
}
string Alignment::convertStateBackStr(char state) {
string str;
if (num_states <= 20) {
str = convertStateBack(state);
} else {
// codon data
if (state >= num_states) return "???";
assert(codon_table);
int state_back = codon_table[(int)state];
str = symbols_dna[state_back/16];
str += symbols_dna[(state_back%16)/4];
str += symbols_dna[state_back%4];
}
return str;
}
void Alignment::convertStateStr(string &str, SeqType seq_type) {
for (string::iterator it = str.begin(); it != str.end(); it++)
(*it) = convertState(*it, seq_type);
}
void Alignment::initCodon(char *sequence_type) {
// build index from 64 codons to non-stop codons
int transl_table = 1;
if (strlen(sequence_type) > 5) {
try {
transl_table = convert_int(sequence_type+5);
} catch (string str) {
outError("Wrong genetic code ", sequence_type);
}
switch (transl_table) {
case 1: genetic_code = genetic_code1; break;
case 2: genetic_code = genetic_code2; break;
case 3: genetic_code = genetic_code3; break;
case 4: genetic_code = genetic_code4; break;
case 5: genetic_code = genetic_code5; break;
case 6: genetic_code = genetic_code6; break;
case 9: genetic_code = genetic_code9; break;
case 10: genetic_code = genetic_code10; break;
case 11: genetic_code = genetic_code11; break;
case 12: genetic_code = genetic_code12; break;
case 13: genetic_code = genetic_code13; break;
case 14: genetic_code = genetic_code14; break;
case 15: genetic_code = genetic_code15; break;
case 16: genetic_code = genetic_code16; break;
case 21: genetic_code = genetic_code21; break;
case 22: genetic_code = genetic_code22; break;
case 23: genetic_code = genetic_code23; break;
case 24: genetic_code = genetic_code24; break;
case 25: genetic_code = genetic_code25; break;
default:
outError("Wrong genetic code ", sequence_type);
break;
}
} else {
genetic_code = genetic_code1;
}
assert(strlen(genetic_code) == 64);
cout << "Converting to codon sequences with genetic code " << transl_table << " ..." << endl;
int codon;
num_states = 0;
for (codon = 0; codon < strlen(genetic_code); codon++)
if (genetic_code[codon] != '*')
num_states++; // only count non-stop codons
codon_table = new char[num_states];
non_stop_codon = new char[strlen(genetic_code)];
int state = 0;
for (int codon = 0; codon < strlen(genetic_code); codon++) {
if (genetic_code[codon] != '*') {
non_stop_codon[codon] = state++;
codon_table[(int)non_stop_codon[codon]] = codon;
} else {
non_stop_codon[codon] = STATE_INVALID;
}
}
}
int Alignment::buildPattern(StrVector &sequences, char *sequence_type, int nseq, int nsite) {
int seq_id;
ostringstream err_str;
codon_table = NULL;
genetic_code = NULL;
non_stop_codon = NULL;
if (nseq != seq_names.size()) throw "Different number of sequences than specified";
/* now check that all sequence names are correct */
for (seq_id = 0; seq_id < nseq; seq_id ++) {
ostringstream err_str;
if (seq_names[seq_id] == "")
err_str << "Sequence number " << seq_id+1 << " has no names\n";
// check that all the names are different
for (int i = 0; i < seq_id; i++)
if (seq_names[i] == seq_names[seq_id])
err_str << "The sequence name " << seq_names[seq_id] << " is dupplicated\n";
}
if (err_str.str() != "")
throw err_str.str();
/* now check that all sequences have the same length */
for (seq_id = 0; seq_id < nseq; seq_id ++) {
if (sequences[seq_id].length() != nsite) {
err_str << "Sequence " << seq_names[seq_id] << " contains ";
if (sequences[seq_id].length() < nsite)
err_str << "not enough";
else
err_str << "too many";
err_str << " characters (" << sequences[seq_id].length() << ")\n";
}
}
if (err_str.str() != "")
throw err_str.str();
/* now check data type */
SeqType seq_type = SEQ_UNKNOWN;
seq_type = detectSequenceType(sequences);
switch (seq_type) {
case SEQ_BINARY:
num_states = 2;
cout << "Alignment most likely contains binary sequences" << endl;
break;
case SEQ_DNA:
num_states = 4;
cout << "Alignment most likely contains DNA/RNA sequences" << endl;
break;
case SEQ_PROTEIN:
num_states = 20;
cout << "Alignment most likely contains protein sequences" << endl;
break;
default:
if (!sequence_type)
throw "Unknown sequence type.";
}
if (sequence_type && strcmp(sequence_type,"") != 0) {
SeqType user_seq_type;
if (strcmp(sequence_type, "BIN") == 0) {
num_states = 2;
user_seq_type = SEQ_BINARY;
} else if (strcmp(sequence_type, "DNA") == 0) {
num_states = 4;
user_seq_type = SEQ_DNA;
} else if (strcmp(sequence_type, "AA") == 0) {
num_states = 20;
user_seq_type = SEQ_PROTEIN;
} else if (strcmp(sequence_type, "MULTI") == 0) {
cout << "Multi-state data with " << num_states << " alphabets" << endl;
user_seq_type = SEQ_MULTISTATE;
} else if (strncmp(sequence_type, "CODON", 5) == 0) {
if (seq_type != SEQ_DNA)
outWarning("You want to use codon models but the sequences were not detected as DNA");
seq_type = user_seq_type = SEQ_CODON;
initCodon(sequence_type);
} else
throw "Invalid sequence type.";
if (user_seq_type != seq_type && seq_type != SEQ_UNKNOWN)
outWarning("Your specified sequence type is different from the detected one");
seq_type = user_seq_type;
}
// now convert to patterns
int site, seq, num_gaps_only = 0;
char char_to_state[NUM_CHAR];
buildStateMap(char_to_state, seq_type);
Pattern pat;
pat.resize(nseq);
int step = ((seq_type == SEQ_CODON) ? 3 : 1);
if (nsite % step != 0)
outError("Number of sites is not multiple of 3");
site_pattern.resize(nsite/step, -1);
clear();
pattern_index.clear();
for (site = 0; site < nsite; site+=step) {
for (seq = 0; seq < nseq; seq++) {
//char state = convertState(sequences[seq][site], seq_type);
char state = char_to_state[(int)(sequences[seq][site])];
if (seq_type == SEQ_CODON) {
// special treatment for codon
char state2 = char_to_state[(int)(sequences[seq][site+1])];
char state3 = char_to_state[(int)(sequences[seq][site+2])];
if (state < 4 && state2 < 4 && state3 < 4) {
state = non_stop_codon[state*16 + state2*4 + state3];
if (state == STATE_INVALID) {
err_str << "Sequence " << seq_names[seq] << " has stop codon " <<
sequences[seq][site] << sequences[seq][site+1] << sequences[seq][site+2] <<
" at site " << site+1 << endl;
state = STATE_UNKNOWN;
}
} else if (state == STATE_INVALID || state2 == STATE_INVALID || state3 == STATE_INVALID) {
state = STATE_INVALID;
} else {
if (state != STATE_UNKNOWN || state2 != STATE_UNKNOWN || state3 != STATE_UNKNOWN) {
ostringstream warn_str;
warn_str << "Sequence " << seq_names[seq] << " has ambiguous character " <<
sequences[seq][site] << sequences[seq][site+1] << sequences[seq][site+2] <<
" at site " << site+1 << endl;
outWarning(warn_str.str());
}
state = STATE_UNKNOWN;
}
}
if (state == STATE_INVALID) {
err_str << "Sequence " << seq_names[seq] << " has invalid character " << sequences[seq][site];
if (seq_type == SEQ_CODON) err_str << sequences[seq][site+1] << sequences[seq][site+2];
err_str << " at site " << site+1 << endl;
}
pat[seq] = state;
}
num_gaps_only += addPattern(pat, site/step);
}
if (num_gaps_only)
cout << "WARNING: " << num_gaps_only << " sites contain only gaps or ambiguous chars." << endl;
if (err_str.str() != "")
throw err_str.str();
return 1;
}
int Alignment::readPhylip(char *filename, char *sequence_type) {
StrVector sequences;
ostringstream err_str;
ifstream in;
int line_num = 1;
// set the failbit and badbit
in.exceptions(ios::failbit | ios::badbit);
in.open(filename);
int nseq = 0, nsite = 0;
int seq_id = 0;
string line;
// remove the failbit
in.exceptions(ios::badbit);
bool multi_state = (sequence_type && strcmp(sequence_type,"MULTI") == 0);
num_states = 0;
for (; !in.eof(); line_num++) {
getline(in, line);
if (line == "") continue;
//cout << line << endl;
if (nseq == 0) { // read number of sequences and sites
istringstream line_in(line);
if (!(line_in >> nseq >> nsite))
throw "Invalid PHYLIP format. First line must contain number of sequences and sites";
//cout << "nseq: " << nseq << " nsite: " << nsite << endl;
if (nseq < 3)
throw "There must be at least 3 sequences";
if (nsite < 1)
throw "No alignment columns";
seq_names.resize(nseq, "");
sequences.resize(nseq, "");
} else { // read sequence contents
if (seq_names[seq_id] == "") { // cut out the sequence name
string::size_type pos = line.find(' ');
if (pos == string::npos) pos = 10; // assume standard phylip
seq_names[seq_id] = line.substr(0, pos);
line.erase(0, pos);
}
int old_len = sequences[seq_id].length();
if (multi_state) {
stringstream linestr(line);
int state;
while (!linestr.eof() ) {
state = -1;
linestr >> state;
if (state < 0) break;
sequences[seq_id].append(1, state);
if (num_states < state+1) num_states = state+1;
}
} else
for (string::iterator it = line.begin(); it != line.end(); it++) {
if ((*it) <= ' ') continue;
if (isalnum(*it) || (*it) == '-' || (*it) == '?'|| (*it) == '.')
sequences[seq_id].append(1, toupper(*it));
else {
err_str << "Unrecognized character " << *it << " on line " << line_num;
throw err_str.str();
}
}
if (sequences[seq_id].length() != sequences[0].length()) {
err_str << "Line " << line_num << ": alignment block has variable sequence lengths" << endl;
throw err_str.str();
}
if (sequences[seq_id].length() > old_len)
seq_id++;
if (seq_id == nseq) {
seq_id = 0;
// make sure that all sequences have the same length at this moment
}
}
//sequences.
}
in.clear();
// set the failbit again
in.exceptions(ios::failbit | ios::badbit);
in.close();
return buildPattern(sequences, sequence_type, nseq, nsite);
}
int Alignment::readFasta(char *filename, char *sequence_type) {
StrVector sequences;
ostringstream err_str;
ifstream in;
int line_num = 1;
string line;
// set the failbit and badbit
in.exceptions(ios::failbit | ios::badbit);
in.open(filename);
// remove the failbit
in.exceptions(ios::badbit);
for (; !in.eof(); line_num++) {
getline(in, line);
if (line == "") continue;
//cout << line << endl;
if (line[0] == '>') { // next sequence
string::size_type pos = line.find(' ');
seq_names.push_back(line.substr(1, pos-1));
sequences.push_back("");
continue;
}
// read sequence contents
if (sequences.empty()) throw "First line must begin with '>' to define sequence name";