-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.cpp
750 lines (609 loc) · 17.8 KB
/
base.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
/************************************************************
* Copyright (C) 2005, BGI of Chinese Academy of Sciences
* All rights reserved.
* Filename: base.cpp
* Abstract: Definition of base class for KaKs methods.
* Version: 1.0
* Author: Zhang Zhang ([email protected])
* Date: Feb.2, 2005
*************************************************************/
#include "base.h"
/******** Global variables ********/
/* The Genetic Codes
http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi?mode=c
Last update of the Genetic Codes: October 05, 2000 */
int genetic_code=1; //from 1 to 23
/* Genetic standard codon table, !=stop codon */
const char* transl_table[] = {
"FFLLSSSSYY!!CC!WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "1-Standard Code",
"FFLLSSSSYY!!CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSS!!VVVVAAAADDEEGGGG", "2-Vertebrate Mitochondrial Code",
"FFLLSSSSYY!!CCWWTTTTPPPPHHQQRRRRIIMMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "3-Yeast Mitochondrial Code",
"FFLLSSSSYY!!CCWWLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "4-Mold Mitochondrial Code",
"FFLLSSSSYY!!CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSSSSVVVVAAAADDEEGGGG", "5-Invertebrate Mitochondrial Code",
"FFLLSSSSYYQQCC!WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "6-Ciliate, Dasycladacean and Hexamita Code",
"", "7-",
"", "8-",
"FFLLSSSSYY!!CCWWLLLLPPPPHHQQRRRRIIIMTTTTNNNKSSSSVVVVAAAADDEEGGGG", "9-Echinoderm and Flatworm Mitochondrial Code",
"FFLLSSSSYY!!CCCWLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "10-Euplotid Nuclear Code",
"FFLLSSSSYY!!CC!WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "11-Bacterial and Plant Plastid Code",
"FFLLSSSSYY!!CC!WLLLSPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "12-Alternative Yeast Nuclear Code",
"FFLLSSSSYY!!CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSSGGVVVVAAAADDEEGGGG", "13-Ascidian Mitochondrial Code",
"FFLLSSSSYYY!CCWWLLLLPPPPHHQQRRRRIIIMTTTTNNNKSSSSVVVVAAAADDEEGGGG", "14-Alternative Flatworm Mitochondrial Code",
"FFLLSSSSYY!QCC!WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "15-Blepharisma Nuclear Code",
"FFLLSSSSYY!LCC!WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "16-Chlorophycean Mitochondrial Code",
"", "17-",
"", "18-",
"", "19-",
"", "20-",
"FFLLSSSSYY!!CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNNKSSSSVVVVAAAADDEEGGGG", "21-Trematode Mitochondrial Code",
"FFLLSS!SYY!LCC!WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "22-Scenedesmus obliquus mitochondrial Code",
"FF!LSSSSYY!!CC!WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG", "23-Thraustochytrium Mitochondrial Code"
};
//********End of Global variables**********
//Constructor function
Base::Base() {
srand((unsigned)time(NULL));
}
/********************************************
* Function: addString
* Input Parameter: string, string, string
* Output: result = result + str + flag
* Return Value: void
* Note: flag = "\t" (default) or "\n"
*********************************************/
void Base::addString(string &result, string str, string flag) {
result += str;
result += flag;
}
/**********************************************************************
* Function: getAminoAcid
* Input Parameter: codon or codon's id
* Output: Calculate the amino acid according to codon or codon's id.
* Return Value: char
***********************************************************************/
char Base::getAminoAcid(string codon) {
return transl_table[2*(genetic_code-1)][getID(codon)];
}
char Base::getAminoAcid(int id) {
return transl_table[2*(genetic_code-1)][id];
}
/**********************************
* Function: getNumNonsense
* Input Parameter: int
* Output: get the number of nonsense codons
* Return Value: int
***********************************/
int Base::getNumNonsense(int genetic_code) {
int num, i;
for(num=i=0; i<CODON; i++) {
if(getAminoAcid(i)=='!') num++;
}
return num;
}
/********************************************
* Function: getID
* Input Parameter: codon
* Output: Get codon's id in array of codon_table.
* Return Value: int
*********************************************/
int Base::getID(string codon) {
return (convertChar(codon[0])*XSIZE + convertChar(codon[1])*DNASIZE + convertChar(codon[2]));
}
/********************************************
* Function: getCodon
* Input Parameter: int
* Output: Get the codon according to id;
a reverse funtion of getID.
* Return Value: string
*********************************************/
string Base::getCodon(int IDcodon) {
string codon = "TTT";
if (IDcodon>=0 && IDcodon<64) {
codon[0]=convertInt(IDcodon/16);
codon[1]=convertInt((IDcodon%16)/4);
codon[2]=convertInt(IDcodon%4);
}
return codon;
}
/*********************************************
* Function: convertChar
* Input Parameter: ch as char
* Output: Convert a char-T,C,A,G into a digit
* 0,1,2,3, respectively.
* Return Value: int.
**********************************************/
int Base::convertChar(char ch) {
int ret = -1;
switch(ch) {
case 'T':case 'U':
ret = 0;
break;
case 'C':
ret = 1;
break;
case 'A':
ret = 2;
break;
case 'G':
ret = 3;
break;
}
return ret;
}
/********************************************
* Function: convertInt
* Input Parameter: int
* Output: Convert a digit- 0,1,2,3 into a
* char-T,C,A,G, respectively.
* Return Value: char
*********************************************/
char Base::convertInt(int i) {
char ch = '-';
switch(i) {
case 0:
ch = 'T';
break;
case 1:
ch = 'C';
break;
case 2:
ch = 'A';
break;
case 3:
ch = 'G';
break;
}
return ch;
}
/********************************************
* Function: stringtoUpper
* Input Parameter: string
* Output: upper string
* Return Value: string
*********************************************/
string Base::stringtoUpper(string str) {
int i;
for (i=0; i<str.length(); i++) str[i] = toupper(str[i]);
return str;
}
string Base::Trim(string str) {
int i, flag;
//left trim
flag=0;
for (i=0; i<str.length() && flag==0;) {
int c = (char)str[i];
if (iscntrl(c) || c<33 || c>127) i++;
else flag=1;
}
str = str.substr(i, str.length()-i);
//right trim
flag=0;
for (i=str.length()-1; i>=0 && flag==0;) {
int c = (char)str[i];
if (iscntrl(c) || c<33 || c>127) i--;
else flag=1;
}
str = str.substr(0, i+1);
return str;
}
string Base::filterString(string str) {
int i=0;
string tmp="";
for (;i<str.length();i++) {
int c = (char)(str[i]);
if (c>32 && c<128) tmp += str[i];
}
return tmp;
}
string Base::replaceAll(string str, char from, char to) {
int i=0;
string tmp="";
while (i<str.length()) {
if (str[i]!=from) tmp += str[i];
else tmp += to;
i++;
}
return tmp;
}
string Base::replaceAll(string str, char from) {
int i=0;
string tmp="";
while (i<str.length()) {
if (str[i]!=from) tmp += str[i];
i++;
}
return tmp;
}
/********************************************
* Function: getRandom
* Input Parameter: void
* Output: Generate a radnom integer
* Return Value: int
*********************************************/
int Base::getRandom() {
return rand();
}
double Base::getRandDouble() {
return (double)rand()/RAND_MAX;
}
/*******************
Note: begin<= getRandInt() < end
*******************/
int Base::getRandInt(int begin, int end) {
return (int)((double)(end-begin)*getRandDouble()+begin);
}
/********************************************
* Function: initArray
* Input Parameter: array of int/double, int, int/double(default=0)
* Output: Init the array x[0...n-1]=value
* Return Value: int
*********************************************/
int Base::initArray(double x[], int n, double value) {
int i;
for(i=0; i<n; i++) x[i] = value;
return 0;
}
int Base::initArray(int x[], int n, int value) {
int i;
for(i=0; i<n; i++) x[i] = value;
return 0;
}
/********************************************
* Function: sumArray
* Input Parameter: double/int, int, int(default=0)
* Output: Sum of array x[]
* Return Value: double/int
*********************************************/
double Base::sumArray(double x[], int end, int begin) {
int i;
double sum=0.;
for(i=begin; i<end; sum += x[i], i++);
return sum;
}
int Base::sumArray(int x[], int end, int begin) {
int i, sum=0;
for(i=begin; i<end; sum += x[i], i++);
return sum;
}
/********************************************
* Function: norm
* Input Parameter: array of double, int
* Output: Sqrt of the sum of the elements' square
sqrt(x0*x0 + x1*x1 + ...)
* Return Value: double
*********************************************/
double Base::norm(double x[], int n) {
int i;
double t=0;
for(i=0; i<n; t += square(x[i]), i++);
return sqrt(t);
}
/********************************************
* Function: scaleArray
* Input Parameter: double, array of double, int
* Output: Elements in array are mutipled by scale
* Return Value: int
*********************************************/
int Base::scaleArray(double scale, double x[], int n) {
int i;
for (i=0; i<n; i++) x[i] *= scale;
return 1;
}
/********************************************
* Function: copyArray
* Input Parameter: array, array, int
* Output: Copy array's values one by one: to[] = from[]
* Return Value: int
*********************************************/
int Base::copyArray(double from[], double to[], int n) {
int i;
for(i=0; i<n; i++) to[i] = from[i];
return 1;
}
int Base::countChar(string str, char ch) {
int i, num;
for(i=num=0; i<str.length(); i++) if (str[i]==ch) num++;
return num;
}
/********************************************
* Function: innerp
* Input Parameter: array, array, int
* Output: Sum of 'n' products multiplied by
two elements in x[], y[].
* Return Value: int
*********************************************/
double Base::innerp(double x[], double y[], int n) {
int i;
double t=0;
for(i=0; i<n; t += x[i]*y[i], i++);
return t;
}
/********************************************
* Function: initIdentityMatrix
* Input Parameter: array of double, int
* Output: Set x[i,j]=0 when x!=j and
x[i,j]=1 when x=j
* Return Value: int
*********************************************/
int Base::initIdentityMatrix(double x[], int n) {
int i,j;
for (i=0; i<n; i++) {
for(j=0; j<n; x[i*n+j]=0, j++);
x[i*n+i] = 1;
}
return 0;
}
string Base::RGB(int r, int g, int b) {
char buffer[3];
sprintf(buffer, "%X", r);
string rr = buffer;
if(rr.length()==1) rr = "0" + rr;
sprintf(buffer, "%X", g);
string gg = buffer;
if(gg.length()==1) gg = "0" + gg;
sprintf(buffer, "%X", b);
string bb = buffer;
if(bb.length()==1) bb = "0" + bb;
return rr+gg+bb;
}
/************************************************
* Function: writeFile
* Input Parameter: string, string
* Output: Write content into the given file.
* Return Value: True if succeed, otherwise false.
*************************************************/
bool Base::writeFile(string output_filename, const char* result) {
bool flag = true;
try {
//file name is ok
if (output_filename!="" && output_filename.length()>0) {
ofstream os(output_filename.c_str());
if (!os.is_open()) throw 1;
os<<result;
os.close();
}
}
catch (...) {
cout<<"Error in writing to file..."<<endl;
flag = false;
}
return flag;
}
bool Base::removeCntrl(string name, vector<string> &str) {
bool flag = true;
int i;
try {
//Check whether (sequence length)/3==0
for (i=0; i<str.size(); i++) {
str[i] = stringtoUpper(filterString(str[i]));
if (str[0].length()!=str[i].length()) {
cout<<endl<<"Error. The length of sequences "<<"'"<<name<<"' is not equal."<<endl;
throw 1;
}
}
}
catch (...) {
flag = false;
}
return flag;
}
bool Base::checkValid(string name, vector<string> &str) {
bool flag = true;
long i;
try {
if (removeCntrl(name, str)) {
string str1 = str[0];
string str2 = str[1];
//Delete gap and stop codon
bool found;
int j;
for(i=0; i<str1.length(); i+=3) {
for(found=false, j=0; j<3 && !found; j++) {
if (str1[j+i]=='-' || str2[j+i]=='-') {
found = true;
}
if (convertChar(str1[i+j])==-1 || convertChar(str2[i+j])==-1) {
found = true;
}
}
if ((getAminoAcid(str1.substr(i,3))=='!') || (getAminoAcid(str2.substr(i,3))=='!')) {
found = true;
}
if (found) {
str1 = str1.replace(i, 3, "");
str2 = str2.replace(i, 3, "");
i -= 3;
}
}
str[0] = str1;
str[1] = str2;
}
else {
flag = true;
}
}
catch (...) {
flag = false;
}
return flag;
}
int Base::readAXT(string seqfile, vector<string> &seqname, vector<string> &seq) {
int flag = 1;
try {
ifstream is(seqfile.c_str());
if (!is) {
cout<<"Error in opening file..."<<endl;
throw 1;
}
string temp="", name="", str="";
while (getline(is, temp, '\n')) {
name = temp;
getline(is, temp, '\n');
cout<<"reading first seq"<<endl;
while (temp!="") {
str += temp;
temp = "";
getline(is, temp, '\n');
}
cout<<"reading all seq"<<endl;
cout<<str.length()<<endl;
//Check str's validility
vector<string> strr;
strr.push_back(str.substr(0, str.length()/2));
strr.push_back(str.substr(str.length()/2, str.length()/2));
if (checkValid(name, strr)) {
seq.push_back(generalInput(strr));
seqname.push_back(name);
}
name = str = "";
}
is.close();
is.clear();
}
catch (...) {
cout<<"Error in reading AXT."<<endl;
flag = 0;
}
return flag;
}
int Base::readFasta(string seqfile, vector<string> &seqname, vector<string> &seq) {
int flag = 1;
try {
ifstream is(seqfile.c_str());
if (!is) {
cout<<"Error in opening file..."<<endl;
throw 1;
}
string temp="", name="";
getline(is, temp, '\n');
while ( (int)(temp.find('>')) > -1) {
name = temp.substr(1, temp.length()-1); //remove >
string str="";
getline(is, temp, '\n');
while (temp!="" && (int)(temp.find('>'))<0) {
str += temp;
temp = "";
getline(is, temp, '\n');
}
//name = Trim(filterString(name));
name = Trim(name);
str = Trim(filterString(str));
seqname.push_back(name);
seq.push_back(str);
}
is.close();
is.clear();
}
catch (...) {
flag = 0;
}
return flag;
}
vector<string> Base::split(const char *str, char c)
{
vector<string> result;
do
{
const char *begin = str;
while(*str != c && *str)
str++;
result.push_back(string(begin, str));
//cout << string(begin, str) << endl;
} while (0 != *str++);
return result;
}
int Base::read_input(string seqfile, vector <double> &patient_info, vector <vector <double> > &seq2d)
{
string line;
int i;
ifstream myfile (seqfile.c_str());
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
//cout << line << '\n';
vector <string> split;
split = Base::split(line.c_str(), ',');
patient_info.push_back(std::stod(split[0].c_str()));
vector <double> cur;
for (i = 1; i < split.size(); ++i) {
if (std::strcmp("0", split[i].c_str()) == 0) {
cur.push_back(0);
}
if (std::strcmp("1", split[i].c_str()) == 0) {
cur.push_back(1);
}
if (std::strcmp("M", split[i].c_str()) == 0) {
cur.push_back(2);
}
if (std::strcmp("x", split[i].c_str()) == 0) {
cur.push_back(3);
}
}
seq2d.push_back(cur);
}
myfile.close();
}
}
string Base::generalInput(vector<string> seq) {
int i, j;
string output = "";
for (i=0; i<seq[0].length(); i++) {
int issame = 1;
for (j=1; j<seq.size() && issame==1; j++) {
if (seq[0][i]!=seq[j][i]) issame=0;
}
if (issame==1) output += "0";
else output += "1";
}
return output;
}
/*
int matby (double a[], double b[], double c[], int n,int m,int k)
// a[n*m], b[m*k], c[n*k] ...... c = a*b
{
int i,j,i1;
double t;
FOR (i,n) FOR(j,k) {
for (i1=0,t=0; i1<m; i1++) t+=a[i*m+i1]*b[i1*k+j];
c[i*k+j] = t;
}
return (0);
}
void PMatrixTaylor(double P[], double n, double t) {
// Get approximate PMat using polynomial approximation
// P(t) = I + Qt + (Qt)^2/2 + (Qt)^3/3!
int nterms=1000, i,j,k, c[2],ndiff,pos=0,from[3],to[3];
double *Q=space, *Q1=Q+n*n, *Q2=Q1+n*n, mr, div;
FOR (i,n*n) Q[i]=0;
for (i=0; i<n; i++) FOR (j,i) {
from[0]=i/16; from[1]=(i/4)%4; from[2]=i%4;
to[0]=j/16; to[1]=(j/4)%4; to[2]=j%4;
c[0]=GenetCode[com.icode][i];
c[1]=GenetCode[com.icode][j];
if (c[0]==-1 || c[1]==-1) continue;
for (k=0,ndiff=0; k<3; k++) if (from[k]!=to[k]) { ndiff++; pos=k; }
if (ndiff!=1) continue;
Q[i*n+j]=1;
if ((from[pos]+to[pos]-1)*(from[pos]+to[pos]-5)==0) Q[i*n+j]*=kappa;
if(c[0]!=c[1]) Q[i*n+j]*=omega;
Q[j*n+i]=Q[i*n+j];
}
FOR(i,n) FOR(j,n) Q[i*n+j]*=pi[j];
for (i=0,mr=0;i<n;i++) {
Q[i*n+i]=-sum(Q+i*n,n); mr-=pi[i]*Q[i*n+i];
}
FOR(i,n*n) Q[i]*=t/mr;
xtoy(Q,P,n*n); FOR(i,n) P[i*n+i]++; // I + Qt
xtoy(Q,Q1,n*n);
for (i=2,div=2;i<nterms;i++,div*=i) { // k is divisor
matby(Q, Q1, Q2, n, n, n);
for(j=0,mr=0;j<n*n;j++) { P[j]+=Q2[j]/div; mr+=fabs(Q2[j]); }
mr/=div;
// if(debug) printf("Pmat term %d: norm=%.6e\n", i, mr);
if (mr<e) break;
xtoy(Q2,Q1,n*n);
}
FOR(i,n*n) if(P[i]<0) P[i]=0;
}
*/