forked from jianyangqt/smr
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbfile.cpp
1519 lines (1426 loc) · 61.3 KB
/
bfile.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
//
// bfile.cpp
// SMR_CPP
//
// Created by Futao Zhang on 5/07/2018.
// Copyright © 2018 Futao Zhang. All rights reserved.
//
#include "bfile.hpp"
namespace SMRDATA
{
void read_famfile(bInfo* bdata, string famfile) {
bdata->_autosome_num = 22;
ifstream Fam(famfile.c_str());
if (!Fam) throw ("Error: can not open the file [" + famfile + "] to read.");
cout << "Reading PLINK FAM file from [" + famfile + "]." << endl;
int i = 0;
string str_buf;
bdata->_fid.clear();
bdata->_pid.clear();
bdata->_fa_id.clear();
bdata->_mo_id.clear();
bdata->_sex.clear();
bdata->_pheno.clear();
while (Fam) {
Fam >> str_buf;
if (Fam.eof()) break;
bdata->_fid.push_back(str_buf);
Fam >> str_buf;
bdata->_pid.push_back(str_buf);
Fam >> str_buf;
bdata->_fa_id.push_back(str_buf);
Fam >> str_buf;
bdata->_mo_id.push_back(str_buf);
Fam >> str_buf;
bdata->_sex.push_back(atoi(str_buf.c_str()));
Fam >> str_buf;
bdata->_pheno.push_back(atoi(str_buf.c_str()));
}
Fam.clear();
Fam.close();
bdata->_indi_num = bdata->_fid.size();
cout << bdata->_indi_num << " individuals to be included from [" + famfile + "]." << endl;
// Initialize _keep
bdata->_keep.clear();
bdata->_keep.resize(bdata->_indi_num);
bdata->_id_map.clear();
int size = 0;
for (int i = 0; i < bdata->_indi_num; i++) {
bdata->_keep[i] = i;
bdata->_id_map.insert(pair<string, int>(bdata->_fid[i] + ":" + bdata->_pid[i], i));
if (size == bdata->_id_map.size()) throw ("Error: Duplicate individual ID found: \"" + bdata->_fid[i] + "\t" + bdata->_pid[i] + "\".");
size = bdata->_id_map.size();
}
}
void update_bim(bInfo* bdata,vector<int> &rsnp) {
int i = 0;
//update bim information
vector<int> chr_buf, bp_buf;
vector<string> a1_buf, a2_buf, ref_A_buf, other_A_buf;
vector<string> snp_name_buf;
vector<double> genet_dst_buf, impRsq_buf;
for (i = 0; i < bdata->_snp_num; i++) {
if (!rsnp[i]) continue;
chr_buf.push_back(bdata->_chr[i]);
snp_name_buf.push_back(bdata->_snp_name[i]);
genet_dst_buf.push_back(bdata->_genet_dst[i]);
bp_buf.push_back(bdata->_bp[i]);
a1_buf.push_back(bdata->_allele1[i]);
a2_buf.push_back(bdata->_allele2[i]);
ref_A_buf.push_back(bdata->_ref_A[i]);
other_A_buf.push_back(bdata->_other_A[i]);
if(bdata->_impRsq.size()>0) impRsq_buf.push_back(bdata->_impRsq[i]);
}
bdata->_chr.clear();
bdata->_snp_name.clear();
bdata->_genet_dst.clear();
bdata->_bp.clear();
bdata->_allele1.clear();
bdata->_allele2.clear();
bdata->_ref_A.clear();
bdata->_other_A.clear();
bdata->_impRsq.clear();
bdata->_chr = chr_buf;
bdata->_snp_name = snp_name_buf;
bdata->_genet_dst = genet_dst_buf;
bdata->_bp = bp_buf;
bdata->_allele1 = a1_buf;
bdata->_allele2 = a2_buf;
bdata->_ref_A = ref_A_buf;
bdata->_other_A = other_A_buf;
bdata->_impRsq=impRsq_buf;
bdata->_snp_num = bdata->_chr.size();
bdata->_include.clear();
bdata-> _include.resize(bdata->_snp_num);
bdata->_snp_name_map.clear();
for (i = 0; i < bdata->_snp_num; i++) {
bdata->_include[i] = i;
bdata->_snp_name_map.insert(pair<string, int>(bdata->_snp_name[i], i));
}
}
void update_fam(bInfo* bdata,vector<int> &rindi) {
//update fam information
int i = 0;
vector<string> fid_buf, pid_buf, fa_id_buf, mo_id_buf;
vector<int> sex_buf;
vector<double> pheno_buf;
for (i = 0; i < bdata->_indi_num; i++) {
if (!rindi[i]) continue;
fid_buf.push_back(bdata->_fid[i]);
pid_buf.push_back(bdata->_pid[i]);
fa_id_buf.push_back(bdata->_fa_id[i]);
mo_id_buf.push_back(bdata->_mo_id[i]);
sex_buf.push_back(bdata->_sex[i]);
pheno_buf.push_back(bdata->_pheno[i]);
}
bdata->_fid.clear();
bdata->_pid.clear();
bdata->_fa_id.clear();
bdata->_mo_id.clear();
bdata->_sex.clear();
bdata->_pheno.clear();
bdata->_fid = fid_buf;
bdata->_pid = pid_buf;
bdata->_fa_id = fa_id_buf;
bdata->_mo_id = mo_id_buf;
bdata->_sex = sex_buf;
bdata->_pheno = pheno_buf;
bdata->_indi_num = bdata->_fid.size();
bdata->_keep.clear();
bdata->_keep.resize(bdata->_indi_num);
bdata->_id_map.clear();
for (i = 0; i < bdata->_indi_num; i++) {
bdata->_keep[i] = i;
bdata->_id_map.insert(pair<string, int>(bdata->_fid[i] + ":" + bdata->_pid[i], i));
}
}
void read_bimfile(bInfo* bdata,string bimfile) {
// Read bim file: recombination rate is defined between SNP i and SNP i-1
int ibuf = 0;
string cbuf = "0";
double dbuf = 0.0;
string str_buf;
ifstream Bim(bimfile.c_str());
if (!Bim) throw ("Error: can not open the file [" + bimfile + "] to read.");
cout << "Reading PLINK BIM file from [" + bimfile + "]." << endl;
bdata->_chr.clear();
bdata->_snp_name.clear();
bdata->_genet_dst.clear();
bdata->_bp.clear();
bdata->_allele1.clear();
bdata->_allele2.clear();
while (Bim) {
Bim >> ibuf;
if (Bim.eof()) break;
bdata->_chr.push_back(ibuf);
Bim >> str_buf;
bdata->_snp_name.push_back(str_buf);
Bim >> dbuf;
bdata->_genet_dst.push_back(dbuf);
Bim >> ibuf;
bdata->_bp.push_back(ibuf);
Bim >> cbuf;
StrFunc::to_upper(cbuf);
bdata->_allele1.push_back(cbuf.c_str());
Bim >> cbuf;
StrFunc::to_upper(cbuf);
bdata->_allele2.push_back(cbuf.c_str());
}
Bim.close();
bdata->_snp_num = bdata->_chr.size();
bdata->_ref_A = bdata->_allele1;
bdata->_other_A = bdata->_allele2;
cout << bdata->_snp_num << " SNPs to be included from [" + bimfile + "]." << endl;
// Initialize _include
bdata->_include.clear();
bdata->_include.resize( bdata->_snp_num);
bdata->_snp_name_map.clear();
for (int i = 0; i < bdata->_snp_num; i++) {
bdata->_include[i] = i;
if( bdata->_snp_name_map.find(bdata->_snp_name[i]) != bdata->_snp_name_map.end()){
cout << "Warning: Duplicated SNP ID \"" + bdata->_snp_name[i] + "\" ";
stringstream ss;
ss << bdata->_snp_name[i] << "_" << i + 1;
bdata->_snp_name[i] = ss.str();
cout<<"has been changed to \"" + bdata->_snp_name[i] + "\".\n";
}
bdata->_snp_name_map.insert(pair<string, int>(bdata->_snp_name[i], i));
}
}
// some code are adopted from PLINK with modifications
void read_bedfile(bInfo* bdata, string bedfile)
{
int i = 0, j = 0, k = 0;
// Flag for reading individuals and SNPs
vector<int> rindi, rsnp;
//get_rindi
rindi.clear();
rindi.resize(bdata->_indi_num);
for (int i = 0; i < bdata->_indi_num; i++) {
if (bdata->_id_map.find(bdata->_fid[i] + ":" + bdata->_pid[i]) != bdata->_id_map.end()) rindi[i] = 1;
else rindi[i] = 0;
}
//get_rsnp
rsnp.clear();
rsnp.resize(bdata->_snp_num);
for (int i = 0; i < bdata->_snp_num; i++) {
if (bdata->_snp_name_map.find(bdata->_snp_name[i]) != bdata->_snp_name_map.end()) rsnp[i] = 1;
else rsnp[i] = 0;
}
if (bdata->_include.size() == 0) throw ("Error: No SNP is retained for analysis.");
if (bdata->_keep.size() == 0) throw ("Error: No individual is retained for analysis.");
// Read bed file
char ch[1];
bitset<8> b;
bdata->_snp_1.resize(bdata->_include.size());
bdata->_snp_2.resize(bdata->_include.size());
for (i = 0; i < bdata->_include.size(); i++) {
bdata->_snp_1[i].reserve(bdata->_keep.size());
bdata->_snp_2[i].reserve(bdata->_keep.size());
}
fstream BIT(bedfile.c_str(), ios::in | ios::binary);
if (!BIT) throw ("Error: can not open the file [" + bedfile + "] to read.");
cout << "Reading PLINK BED file from [" + bedfile + "] in SNP-major format ..." << endl;
for (i = 0; i < 3; i++) BIT.read(ch, 1); // skip the first three bytes
int snp_indx = 0, indi_indx = 0;
for (j = 0, snp_indx = 0; j < bdata->_snp_num; j++) { // Read genotype in SNP-major mode, 00: homozygote AA; 11: homozygote BB; 01: hetezygote; 10: missing
if (!rsnp[j]) {
for (i = 0; i < bdata->_indi_num; i += 4) BIT.read(ch, 1);
continue;
}
for (i = 0, indi_indx = 0; i < bdata->_indi_num;) {
BIT.read(ch, 1);
if (!BIT) throw ("Error: problem with the BED file ... has the FAM/BIM file been changed?");
b = ch[0];
k = 0;
while (k < 7 && i < bdata->_indi_num) { // change code: 11 for AA; 00 for BB;
if (!rindi[i]) k += 2;
else {
bdata->_snp_2[snp_indx][indi_indx] = (!b[k++]);
bdata->_snp_1[snp_indx][indi_indx] = (!b[k++]);
indi_indx++;
}
i++;
}
}
if (snp_indx == bdata->_include.size()) break;
snp_indx++;
}
BIT.clear();
BIT.close();
cout << "Genotype data for " << bdata->_keep.size() << " individuals and " << bdata->_include.size() << " SNPs to be included from [" + bedfile + "]." << endl;
update_fam(bdata, rindi);
update_bim(bdata, rsnp);
}
void keep_indi(bInfo* bdata,string indi_list_file)
{
vector<string> indi_list;
read_indi_list(indi_list_file, indi_list);
update_id_map_kp(indi_list, bdata->_id_map, bdata->_keep);
cout<<bdata->_keep.size()<<" individuals are kept from ["+indi_list_file+"]."<<endl;
}
void remove_indi(bInfo* bdata, string indi_list_file) {
vector<string> indi_list;
read_indi_list(indi_list_file, indi_list);
int prev_size = bdata->_keep.size();
update_id_map_rm(indi_list, bdata->_id_map, bdata->_keep);
cout << prev_size - bdata->_keep.size() << " individuals are removed from [" + indi_list_file + "] and there are " << bdata->_keep.size() << " individuals remaining." << endl;
}
void extract_region_bp(bInfo* bdata, int chr, int fromkb, int tokb)
{
int frombp=fromkb*1000;
int tobp=tokb*1000;
vector<string> snplist;
for(int i = 0; i < bdata->_include.size(); i++){
int j = bdata->_include[i];
if(bdata->_chr[j] == chr && bdata->_bp[j]<=tobp && bdata->_bp[j]>=frombp) snplist.push_back(bdata->_snp_name[j]);
}
if(snplist.empty()) throw ("Error: on SNP found in this region.");
update_id_map_kp(snplist, bdata->_snp_name_map, bdata->_include);
cout << bdata->_include.size() << " SNPs are extracted from SNP BP: "<<fromkb<<"Kb"<<"to SNP BP: "<<tokb<<"Kb."<< endl;
}
void extract_snp(bInfo* bdata, int chr)
{
vector<string> snplist;
for(int i = 0; i < bdata->_include.size(); i++){
int j = bdata->_include[i];
if(bdata->_chr[j] == chr) snplist.push_back(bdata->_snp_name[j]);
}
if(snplist.empty()) throw ("Error: on SNP found in this region.");
update_id_map_kp(snplist, bdata->_snp_name_map, bdata->_include);
cout << bdata->_include.size() << " SNPs are extracted from chromosome "<<chr<< "."<<endl;
}
void extract_snp(bInfo* bdata,string snplistfile)
{
vector<string> snplist;
string msg="SNPs";
read_msglist(snplistfile, snplist,msg);
update_id_map_kp(snplist, bdata->_snp_name_map, bdata->_include);
cout<<bdata->_include.size()<<" SNPs are extracted from ["+snplistfile+"]."<<endl;
}
void exclude_snp(bInfo* bdata,string snplistfile)
{
vector<string> snplist;
string msg="SNPs";
read_msglist(snplistfile, snplist,msg);
int prev_size = bdata->_include.size();
update_id_map_rm(snplist, bdata->_snp_name_map, bdata->_include);
cout << prev_size - bdata->_include.size() << " SNPs are excluded from [" + snplistfile + "] and there are " << bdata->_include.size() << " SNPs remaining." << endl;
}
int getMaxNum(bInfo* bdata,int ldWind, vector<uint64_t> &cols)
{
int n=0, loopj=0, preldnum=1;
long window=ldWind*1000;
int maxldnum=0;
cols.resize(bdata->_include.size()+1);
for(int i=0;i<bdata->_include.size();i++)
{
int chri=bdata->_chr[bdata->_include[i]];
int bpi=bdata->_bp[bdata->_include[i]];
int ldnum=0;
for(int j=loopj+1;j<bdata->_include.size();j++)
{
int chrj=bdata->_chr[bdata->_include[j]];
int bpj=bdata->_bp[bdata->_include[j]];
if(chri==chrj && abs(bpj-bpi)<=window)
{
ldnum++;
loopj=j;
}
else
{
break;
}
}
ldnum += preldnum-1;
preldnum=ldnum;
cols[i+1]=cols[i]+ldnum;
if(ldnum>maxldnum) maxldnum=ldnum;
}
++maxldnum;
while((maxldnum>>=1) != 0) n++;
maxldnum=2<<n;
return maxldnum;
}
void mu_func(bInfo* bdata, int j, vector<double> &fac) {
int i = 0;
bdata->_dosage_flag = 0;
double fcount = 0.0, f_buf = 0.0;
if (bdata->_dosage_flag) {
for (i = 0; i < bdata->_keep.size(); i++) {
if (bdata->_geno_dose[bdata->_keep[i]][bdata->_include[j]] < 1e5) {
bdata->_mu[bdata->_include[j]] += fac[i] * bdata->_geno_dose[bdata->_keep[i]][bdata->_include[j]];
fcount += fac[i];
}
}
} else {
for (i = 0; i < bdata->_keep.size(); i++) {
if (!bdata->_snp_1[bdata->_include[j]][bdata->_keep[i]] || bdata->_snp_2[bdata->_include[j]][bdata->_keep[i]]) {
f_buf = (bdata->_snp_1[bdata->_include[j]][bdata->_keep[i]] + bdata->_snp_2[bdata->_include[j]][bdata->_keep[i]]);
if (bdata->_allele2[bdata->_include[j]] == bdata->_ref_A[bdata->_include[j]]) f_buf = 2.0 - f_buf;
bdata->_mu[bdata->_include[j]] += fac[i] * f_buf;
fcount += fac[i];
}
}
}
if (fcount > 0.0)bdata->_mu[bdata->_include[j]] /= fcount;
}
void calcu_mu(bInfo* bdata, bool ssq_flag)
{
int i = 0, j = 0;
vector<double> auto_fac(bdata->_keep.size()), xfac(bdata->_keep.size()), fac(bdata->_keep.size());
for (i = 0; i < bdata->_keep.size(); i++)
{
auto_fac[i] = 1.0;
if (bdata->_sex[bdata->_keep[i]] == 1) xfac[i] = 0.5;
else if (bdata->_sex[bdata->_keep[i]] == 2) xfac[i] = 1.0;
fac[i] = 0.5;
}
cout << "Calculating allele frequencies ..." << endl;
bdata->_mu.clear();
bdata->_mu.resize(bdata->_snp_num);
#pragma omp parallel for
for (j = 0; j < bdata->_include.size(); j++)
{
if (bdata->_chr[bdata->_include[j]]<(bdata->_autosome_num + 1)) mu_func(bdata, j, auto_fac);
else if (bdata->_chr[bdata->_include[j]] == (bdata->_autosome_num + 1)) mu_func(bdata,j, xfac);
else mu_func(bdata, j, fac);
}
}
bool make_XMat_subset(bInfo* bdata, MatrixXf &X, vector<int> &snp_indx, bool divid_by_std)
{
if(snp_indx.empty()) return false;
if (bdata->_mu.empty()) calcu_mu(bdata);
int i = 0, j = 0, k = 0, n = (int)bdata->_keep.size(), m = (int)snp_indx.size();
vector<double> sd_SNP(m);
X.resize(n, m);
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
k = bdata->_include[snp_indx[j]];
if (!bdata->_snp_1[k][bdata->_keep[i]] || bdata->_snp_2[k][bdata->_keep[i]]) {
if (bdata->_allele1[k] == bdata->_ref_A[k]) X(i,j) = bdata->_snp_1[k][bdata->_keep[i]] + bdata->_snp_2[k][bdata->_keep[i]];
else X(i,j) = 2.0 - (bdata->_snp_1[k][bdata->_keep[i]] + bdata->_snp_2[k][bdata->_keep[i]]);
X(i,j) -= bdata->_mu[k];
}
else X(i,j) = 0.0;
sd_SNP[j]+=X(i,j)*X(i,j);
}
}
if(divid_by_std){
for (j = 0; j < m; j++){
sd_SNP[j]=sd_SNP[j]/(n-1.0);
if (fabs(sd_SNP[j]) < 1.0e-50) sd_SNP[j] = 0.0;
else sd_SNP[j] = sqrt(1.0 / sd_SNP[j]);
}
for (j = 0; j < m; j++) X.col(j) = X.col(j).array() * sd_SNP[j];
}
/*
// alternative method. a little different
if(divid_by_std){
vector<double> sd_SNP(m);
for (j = 0; j < m; j++){
k = bdata->_include[snp_indx[j]];
sd_SNP[j] = bdata->_mu[k]*(1.0 - 0.5 * bdata->_mu[k]);
if (fabs(sd_SNP[j]) < 1.0e-50) sd_SNP[j] = 0.0;
else sd_SNP[j] = sqrt(1.0 / sd_SNP[j]);
}
for (j = 0; j < m; j++) X.col(j) = X.col(j).array() * sd_SNP[j];
}
*/
return true;
}
void makex_xVec_subset(bInfo* bdata,int j, VectorXf &x, bool resize, bool divid_by_std)
{
if (resize) x.resize(bdata->_keep.size());
int k=bdata->_include[j];
double sd_SNP=0;
for (int i = 0; i < bdata->_keep.size(); i++)
{
if (!bdata->_snp_1[k][bdata->_keep[i]] || bdata->_snp_2[k][bdata->_keep[i]])
{
if (bdata->_allele1[k] == bdata->_ref_A[k]) x[i] = (bdata->_snp_1[k][bdata->_keep[i]] + bdata->_snp_2[k][bdata->_keep[i]]);
else x(i) = 2.0 - (bdata->_snp_1[k][bdata->_keep[i]] + bdata->_snp_2[k][bdata->_keep[i]]);
x(i) -= bdata->_mu[k];
}
else x(i) = 0.0;
sd_SNP += x(i)*x(i);
}
if(divid_by_std)
{
sd_SNP /= (bdata->_keep.size()-1.0);
if (fabs(sd_SNP) < 1.0e-50) sd_SNP = 0.0;
else sd_SNP = sqrt(1.0 / sd_SNP);
x*=sd_SNP;
}
/*
if(divid_by_std)
{
double sd_SNP = bdata->_mu[k]*(1.0 - 0.5 * bdata->_mu[k]);
if (fabs(sd_SNP) < 1.0e-50) sd_SNP = 0.0;
else sd_SNP = sqrt(1.0 / sd_SNP);
x*=sd_SNP;
}
*/
}
void initX(bInfo* bdata,MatrixXf &X, long snpnum)
{
vector<int> snpids(snpnum);
for(int i=0;i<snpnum;i++) snpids[i]=i;
//make_XMat(bdata, snpids,X,true); //centered
make_XMat_subset(bdata,X,snpids,true);
}
void write_smr_esi(char* outFileName, bInfo* binfo)
{
string epiName=string(outFileName)+".esi";
FILE* efile=fopen(epiName.c_str(),"w");
if (!(efile)) {
printf("Error: Failed to open file %s.\n",epiName.c_str());
exit(EXIT_FAILURE);
}
printf("Saving SNP information ...\n");
for(int i=0;i<binfo->_include.size();i++)
{
string chrstr;
if(binfo->_chr[binfo->_include[i]]==23) chrstr="X";
else if(binfo->_chr[binfo->_include[i]]==24) chrstr="Y";
else chrstr=atosm(binfo->_chr[binfo->_include[i]]);
string freqstr;
if(binfo->_mu.empty()) freqstr="NA";
else freqstr=atos(binfo->_mu[binfo->_include[i]] /2 );
string str=chrstr+'\t'+binfo->_snp_name[binfo->_include[i]]+'\t'+atos(0)+'\t'+atosm(binfo->_bp[binfo->_include[i]])+'\t'+binfo->_allele1[binfo->_include[i]]+'\t'+binfo->_allele2[binfo->_include[i]]+'\t'+freqstr+'\n';
if(fputs_checked(str.c_str(),efile))
{
printf("ERROR: in writing file %s .\n", epiName.c_str());
}
}
fclose(efile);
printf("%ld SNPs have been saved in the file %s .\n", binfo->_include.size(), epiName.c_str());
}
void filter_snp_maf(bInfo* bdata,double maf)
{
if(bdata->_mu.empty()) calcu_mu(bdata);
cout<<"Pruning SNPs with MAF > "<<maf<<" ..."<<endl;
map<string, int> id_map_buf(bdata->_snp_name_map);
map<string, int>::iterator iter, end=id_map_buf.end();
int prev_size=bdata->_include.size();
double fbuf=0.0;
bdata->_include.clear();
bdata->_snp_name_map.clear();
for(iter=id_map_buf.begin(); iter!=end; iter++){
fbuf=bdata->_mu[iter->second]*0.5;
if(fbuf<=maf || (1.0-fbuf)<=maf) continue;
bdata->_snp_name_map.insert(*iter);
bdata->_include.push_back(iter->second);
}
if(bdata->_include.size()==0) throw("Error: No SNP is retained for analysis.");
else{
stable_sort(bdata->_include.begin(), bdata->_include.end());
cout<<"After pruning SNPs with MAF > "<<maf<<", there are "<<bdata->_include.size()<<" SNPs ("<<prev_size-bdata->_include.size()<<" SNPs with MAF < "<<maf<<")."<<endl;
}
}
void ld_calc_o2m(VectorXd &ld_v,long targetid, MatrixXd &X, bool centered)
{
long size=X.cols();
long n=X.rows();
VectorXd tmpX(size);
VectorXd tmpX2(size);
VectorXd tmpXY(size);
if(centered)
{
#pragma omp parallel for
for(int i=0;i<size;i++){
tmpX2[i]=X.col(i).dot(X.col(i));
tmpXY[i]=X.col(targetid).dot(X.col(i));
}
float tmpY2=X.col(targetid).dot(X.col(targetid));
ld_v=tmpXY.array()/sqrt(tmpX2.array()*tmpY2);
}
else
{
#pragma omp parallel for
for(int i=0;i<size;i++){
tmpX[i]=X.col(i).sum();
tmpX2[i]=X.col(i).dot(X.col(i));
tmpXY[i]=X.col(targetid).dot(X.col(i));
}
float tmpY=X.col(targetid).sum();;
float tmpY2=X.col(targetid).dot(X.col(targetid));
ld_v=(tmpXY*n-tmpX*tmpY).array()/sqrt((tmpX2.array()*n-tmpX.array()*tmpX.array())*(tmpY2*n-tmpY*tmpY));
}
}
void extract_snp_kb(bInfo* bdata,string rsnames, int windInKb)
{
map<string, int>::iterator iter;
iter=bdata->_snp_name_map.find(rsnames);
if(iter==bdata->_snp_name_map.end())
{
printf("ERROR: Can't find SNP %s.\n", rsnames.c_str());
exit(EXIT_FAILURE);
}
long idx=iter->second;
int snpbp=bdata->_bp[idx];
int snpchr=bdata->_chr[idx];
int upbound=snpbp+windInKb*1000;
int tmpint=snpbp-windInKb*1000;
int lowbound=tmpint>0?tmpint:0;
vector<string> snplist;
for(int i=0;i<bdata->_include.size();i++)
{
tmpint=bdata->_include[i];
if(bdata->_chr[tmpint]==snpchr && bdata->_bp[tmpint]>=lowbound && bdata->_bp[tmpint]<=upbound) snplist.push_back(bdata->_snp_name[tmpint]);
}
update_id_map_kp(snplist, bdata->_snp_name_map, bdata->_include);
printf("%ld SNPs including %s are extracted.\n",bdata->_include.size(), rsnames.c_str());
}
void ld_report(char* outFileName, char* bFileName,char* indilstName, char* indilst2remove,char* snplstName, char* snplst2exclde,int chr,char* rs, double maf, bool ldr, bool ldr2, int ldWind)
{
if(!(ldr || ldr2))
{
printf("Please specify --r or --r2 \n");
exit(EXIT_FAILURE);
}
bool bitmod=true;
bInfo bdata;
MatrixXf X;
vector<uint64_t> cols;
vector<float> lds;
read_famfile(&bdata, string(bFileName)+".fam");
if(indilstName != NULL) keep_indi(&bdata,indilstName);
if(indilst2remove != NULL) remove_indi(&bdata, indilst2remove);
read_bimfile(&bdata, string(bFileName)+".bim");
if(chr) extract_snp(&bdata, chr);
if(rs != NULL) extract_snp_kb(&bdata,rs,ldWind);
if(snplstName != NULL) extract_snp(&bdata, snplstName);
if(snplst2exclde != NULL) exclude_snp(&bdata, snplst2exclde);
read_bedfile(&bdata, string(bFileName)+".bed");
if (bdata._mu.empty()) calcu_mu(&bdata);
if (maf > 0) filter_snp_maf(&bdata, maf);
int m=getMaxNum(&bdata,ldWind, cols);
if(m==1)
{
printf("No SNP pair included in %d Kb.\n",ldWind);
exit(EXIT_FAILURE);
}
if(m>bdata._include.size())
{
m=(int)bdata._include.size();
bitmod=false;
}
write_smr_esi(outFileName, &bdata);
string bldname=string(outFileName)+".bld";
FILE* outfile=fopen(bldname.c_str(), "wb");
if (!(outfile)) {
printf("Error: Failed to open file %s.\n",bldname.c_str());
exit(EXIT_FAILURE);
}
vector<int> reserved(RESERVEDUNITS);
if(ldr) reserved[0]=0;
else if(ldr2) reserved[0]=1;
reserved[1]=(int)bdata._keep.size();
reserved[2]=(int)bdata._include.size();
reserved[3]=ldWind;
for(int i=4;i<RESERVEDUNITS;i++) reserved[i]=-9;
fwrite(&reserved[0],sizeof(int), RESERVEDUNITS, outfile);
uint64_t valnum=cols[bdata._include.size()];
fwrite(&valnum,sizeof(uint64_t), 1, outfile);
fwrite(&cols[0],sizeof(uint64_t), bdata._include.size()+1, outfile);
long window=ldWind*1000, vc=0;
double cr=0;
for(int i=0;i<bdata._include.size();i++)
{
progress(i, cr, (int)bdata._include.size());
if(X.size()==0) initX(&bdata, X,m);
int start =-9;
if(bitmod) start = (i & (m-1));
else start = i % m;
VectorXf x=X.col(start);
int chri=bdata._chr[bdata._include[i]];
int bpi=bdata._bp[bdata._include[i]];
//clock_t begin_time = clock();
VectorXf ldv=X.col(start)/(X.rows()-1);
ldv=X.transpose()*ldv;
if(ldr2) ldv=ldv.array()*ldv.array();
int st=-9, ed=-9;
for(int j=1;j<m && i+j<bdata._include.size();j++)
{
int chrj=bdata._chr[bdata._include[i+j]];
int bpj=bdata._bp[bdata._include[i+j]];
int cur = -9;
if(bitmod) cur=((start+j) & (m-1));
else cur= (start+j) % m ;
if(chri==chrj && abs(bpj-bpi)<=window)
{
if(st<0) st=cur;
ed=cur;
if(ed==m-1)
{
fwrite(&ldv(st),sizeof(float), ed-st+1, outfile);
st=-9;
ed=-9;
}
vc++;
}
}
if(ed>=0 && st>=0) fwrite(&ldv(st),sizeof(float), ed-st+1, outfile);
//printf(" cost2: %f ms.\n",float( clock () - begin_time ) / 1000);
//begin_time = clock();
if(i+m<bdata._include.size())
{
makex_xVec_subset(&bdata, i+m, x, false, true);
X.col(start)=x;
}
//printf(" cost3: %f ms.\n",float( clock () - begin_time ) / 1000);
}
if(vc!=valnum)
{
printf("Error: predicted number vs observed number: %ld, %llu.\n",vc,valnum);
printf("Please repot this bug.\n");
exit(EXIT_FAILURE);
}
fclose(outfile);
printf("LD information is saved in the binary file %s.\n",bldname.c_str());
}
void read_ld_esifile(ldInfo* ldinfo, char* esiFileName)
{
vector<string> strlist;
uint32_t line_idx = 0;
int colnum=7;
FILE* esifile=fopen(esiFileName, "r");
if (!(esifile)) {
printf("Error: Failed to open file %s.\n",esiFileName);
exit(EXIT_FAILURE);
}
printf("Reading SNP information from %s ...\n", esiFileName);
ldinfo->_esi_chr.clear();
ldinfo->_esi_rs.clear();
ldinfo->_esi_gd.clear();
ldinfo->_esi_bp.clear();
ldinfo->_esi_allele1.clear();
ldinfo->_esi_allele2.clear();
ldinfo->_esi_include.clear();
ldinfo->_snp_name_map.clear();
ldinfo->_esi_freq.clear();
bool chrwarning=false;
bool feqwarning=false, allele1warning=false, allele2warning=false;
bool orienwarning=false;
char Tbuf[MAX_LINE_SIZE];
while(fgets(Tbuf, MAX_LINE_SIZE, esifile))
{
split_string(Tbuf, strlist, ", \t\n");
if(Tbuf[0]=='\0') {
printf("ERROR: Line %u is blank.\n", line_idx);
exit(EXIT_FAILURE);
}
if(strlist.size()<colnum-1)
{
printf("ERROR: Line %u has less than %d items.\n", line_idx,colnum-1);
exit(EXIT_FAILURE);
} else if(strlist.size()==colnum-1) {
if(!feqwarning) {
printf("WARNING: Maybe this is an old .esi file which doesn't contain frequency information. \n");
feqwarning=true;
}
} else if(strlist.size()>colnum) {
//printf("WARNING: Line %u has more than %d items. The first %d columns would be used. \n", line_idx,colnum,colnum);
}
ldinfo->_snp_name_map.insert(pair<string,int>(strlist[1],line_idx));
if(ldinfo->_snp_name_map.size()==line_idx)
{
printf("ERROR: Duplicate SNP : %s.\n", strlist[1].c_str());
exit(EXIT_FAILURE);
}
if(strlist[0]=="X" || strlist[0]=="x") ldinfo->_esi_chr.push_back(23);
else if(strlist[0]=="Y" || strlist[0]=="y") ldinfo->_esi_chr.push_back(24);
else if(strlist[0]=="NA" || strlist[0]=="na"){
ldinfo->_esi_chr.push_back(-9);
if(!chrwarning) {
printf("WARNING: At least one SNP chr is missing.\n");
chrwarning=true;
}
} else if (atoi(strlist[0].c_str())==0 ) {
//printf("WARNING: unrecongized chromosome found. This chromosome is set to 0:\n");
//printf("%s\n",Tbuf);
ldinfo->_esi_chr.push_back(atoi(strlist[0].c_str()));
} else if ( atoi(strlist[0].c_str())>24 || atoi(strlist[0].c_str())<0) {
//printf("WARNING: abmormal chromosome found:\n");
//printf("%s\n",Tbuf);
ldinfo->_esi_chr.push_back(atoi(strlist[0].c_str()));
} else ldinfo->_esi_chr.push_back(atoi(strlist[0].c_str()));
if(strlist[1]=="NA" || strlist[1]=="na") {
printf("ERROR: NA SNP ID found:\n");
printf("%s\n",Tbuf);
exit(EXIT_FAILURE);
}
ldinfo->_esi_rs.push_back(strlist[1]);
ldinfo->_esi_gd.push_back(atoi(strlist[2].c_str()));
if(strlist[3]=="NA" || strlist[3]=="na") ldinfo->_esi_bp.push_back(-9);
else ldinfo->_esi_bp.push_back(atoi(strlist[3].c_str()));
if(strlist[4]=="NA" || strlist[4]=="na") {
if(!allele1warning) {
//printf("WARNING: At least one reference allele is missing.\n");
allele1warning=true;
}
}
to_upper(strlist[4]);
ldinfo->_esi_allele1.push_back(strlist[4].c_str());
if(strlist[5]=="NA" || strlist[5]=="na") {
if(!allele2warning) {
//printf("WARNING: At least one alternative allele is missing.\n");
allele2warning=true;
}
}
to_upper(strlist[5]);
ldinfo->_esi_allele2.push_back(strlist[5].c_str());
if(strlist.size()==colnum)
{
if(strlist[6]=="NA" || strlist[6]=="na"){
if(!orienwarning){
//printf("WARNING: frequency is \"NA\" in one or more rows.\n");
orienwarning=true;
}
ldinfo->_esi_freq.push_back(-9);
} else {
ldinfo->_esi_freq.push_back(atof(strlist[6].c_str()));
}
} else {
ldinfo->_esi_freq.push_back(-9);
}
ldinfo->_esi_include.push_back(line_idx);
line_idx++;
}
ldinfo->_snpNum =line_idx;
fclose(esifile);
printf("%llu SNPs to be included from %s .\n", ldinfo->_snpNum, esiFileName);
}
void extract_ld_esi_by_chr(ldInfo* ldinfo, int snpchr)
{
vector<int> newIcld;
ldinfo->_snp_name_map.clear();
for(int i=0;i<ldinfo->_esi_include.size();i++)
{
int tmpint=ldinfo->_esi_include[i];
if(ldinfo->_esi_chr[tmpint]==snpchr ) {
newIcld.push_back(tmpint);
ldinfo->_snp_name_map.insert(pair<string,int>(ldinfo->_esi_rs[tmpint],tmpint));
}
}
ldinfo->_esi_include.swap(newIcld);
printf("%ld SNPs are extracted from chromosome %d. \n",ldinfo->_esi_include.size(),snpchr);
}
void extract_ld_esi_snps(ldInfo* ldinfo, string snplstName)
{
vector<string> snplist;
string msg = "SNPs";
read_msglist(snplstName, snplist, msg);
update_map_kp(snplist, ldinfo->_snp_name_map, ldinfo->_esi_include);
printf("%ld SNPs are extracted from %s.\n", ldinfo->_esi_include.size() ,snplstName.c_str() );
}
void extract_ld_esi_snps(ldInfo* ldinfo, string snp, int Wind)
{
int bp=-9;
int chr=-9;
map<string, int>::iterator iter;
iter=ldinfo->_snp_name_map.find(snp);
if(iter==ldinfo->_snp_name_map.end())
{
printf("ERROR: Can't find SNP %s.\n", snp.c_str());
exit(EXIT_FAILURE);
}
bp=ldinfo->_esi_bp[iter->second];
chr=ldinfo->_esi_chr[iter->second];
if(chr < 0) {
printf("ERROR: Missing Chromosome found of SNP %s.\n", snp.c_str());
exit(EXIT_FAILURE);
}
if(bp < 0) {
printf("ERROR: Missing BP found of SNP %s.\n", snp.c_str());
exit(EXIT_FAILURE);
}
int upbound=bp+Wind*1000;
int tmpint=bp-Wind*1000;
int lowbound=tmpint>0?tmpint:0;
vector<int> newIcld;
ldinfo->_snp_name_map.clear();
for(int i=0;i<ldinfo->_esi_include.size();i++)
{
tmpint=ldinfo->_esi_include[i];
if(ldinfo->_esi_chr[tmpint]==chr && ldinfo->_esi_bp[tmpint]>=lowbound && ldinfo->_esi_bp[tmpint]<=upbound) {
newIcld.push_back(tmpint);
ldinfo->_snp_name_map.insert(pair<string,int>(ldinfo->_esi_rs[tmpint],tmpint));
}
}
ldinfo->_esi_include.swap(newIcld);
printf("%ld SNPs are extracted from the region: %d Kb around SNP %s.\n", ldinfo->_esi_include.size() ,Wind, snp.c_str());
}
void extract_ld_esi_single_snp(ldInfo* ldinfo, string snprs)
{
map<string, int>::iterator iter;
iter=ldinfo->_snp_name_map.find(snprs);
if(iter==ldinfo->_snp_name_map.end())
{
printf("ERROR: Can't find SNP %s.\n", snprs.c_str());
exit(EXIT_FAILURE);
}
long idx=iter->second;
ldinfo->_esi_include.clear();
ldinfo->_esi_include.push_back((int)idx);
ldinfo->_snp_name_map.clear();
ldinfo->_snp_name_map.insert(pair<string,int>(snprs,idx));
printf("SNP %s is extracted.\n", snprs.c_str());
}
void extract_ld_esi_snps(ldInfo* ldinfo, string fromsnprs, string tosnprs)
{
map<string, int>::iterator iter;
iter=ldinfo->_snp_name_map.find(fromsnprs);
if(iter==ldinfo->_snp_name_map.end())
{
printf("ERROR: Can't find probe %s.\n", fromsnprs.c_str());
exit(EXIT_FAILURE);
}
int fromsnpbp=ldinfo->_esi_bp[iter->second];
int snpchr=ldinfo->_esi_chr[iter->second];
iter=ldinfo->_snp_name_map.find(tosnprs);
if(iter==ldinfo->_snp_name_map.end())
{
printf("ERROR: Can't find probe %s.\n", tosnprs.c_str());
exit(EXIT_FAILURE);
}
int tosnpbp=ldinfo->_esi_bp[iter->second];
int tosnpchr=ldinfo->_esi_chr[iter->second];
if(tosnpchr != snpchr)
{
printf("ERROR: SNP %s and SNP %s are not from the same chromosome.\n", fromsnprs.c_str(), tosnprs.c_str());
exit(EXIT_FAILURE);
}
if(fromsnpbp>tosnpbp)
{
int tmp=fromsnpbp;
fromsnpbp=tosnpbp;
tosnpbp=tmp;
}
vector<string> snplst;
for(int i=0;i<ldinfo->_esi_include.size();i++)
{
int tmpint=ldinfo->_esi_include[i];
if(ldinfo->_esi_chr[tmpint]==snpchr && ldinfo->_esi_bp[tmpint]>=fromsnpbp && ldinfo->_esi_bp[tmpint]<=tosnpbp) snplst.push_back(ldinfo->_esi_rs[tmpint]);
}
update_map_kp(snplst, ldinfo->_snp_name_map, ldinfo->_esi_include);
printf("%ld SNPs are extracted from SNP %s to SNP %s.\n", ldinfo->_esi_include.size(), fromsnprs.c_str(), tosnprs.c_str());
}
void extract_ld_esi_snps(ldInfo* ldinfo, int chr, int fromsnpkb, int tosnpkb)
{
int fromsnpbp=fromsnpkb*1000;
int tosnpbp=tosnpkb*1000;
if(fromsnpbp>tosnpbp)
{
int tmp=fromsnpbp;
fromsnpbp=tosnpbp;
tosnpbp=tmp;
}
vector<int> newIcld;
ldinfo->_snp_name_map.clear();
for(int i=0;i<ldinfo->_esi_include.size();i++)
{
int tmpint=ldinfo->_esi_include[i];
if( ldinfo->_esi_chr[tmpint]==chr &&ldinfo->_esi_bp[tmpint]>=fromsnpbp && ldinfo->_esi_bp[tmpint]<=tosnpbp) {
newIcld.push_back(tmpint);
ldinfo->_snp_name_map.insert(pair<string,int>(ldinfo->_esi_rs[tmpint],tmpint));
}
}
ldinfo->_esi_include.swap(newIcld);
printf("%ld SNPs are extracted from SNP BP: %dKb to SNP BP: %dKb on chromosome %d.\n",ldinfo->_esi_include.size(),fromsnpkb,tosnpkb, chr);
}
void exclude_ld_esi_snp(ldInfo* ldinfo, string snplstName)
{
vector<string> snplist;
string msg="SNPs";
read_msglist(snplstName, snplist,msg);
long pre_num=ldinfo->_esi_include.size();
update_map_rm(snplist, ldinfo->_snp_name_map, ldinfo->_esi_include);