-
Notifications
You must be signed in to change notification settings - Fork 0
/
varfiles.cpp
3002 lines (2648 loc) · 86.6 KB
/
varfiles.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
/*
* Copyright (c) 2017 Anthony J. Greenberg
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
/// Read and write genetic variant files
/** \file
* \author Anthony J. Greenberg
* \copyright Copyright (c) 2017 Anthony J. Greenberg
* \version 0.1
*
* Implementation of classes that read and write various genetic variant file formats.
*
*
*/
#include "varfiles.hpp"
#include "random.hpp"
#include "populations.hpp"
#include <fstream>
#include <string>
#include <vector>
#include <unordered_map>
#include <iostream>
#include <sstream>
#include <cstdint>
#include <cmath>
#include <limits>
#include <system_error>
using std::fstream;
using std::ofstream;
using std::stringstream;
using std::string;
using std::vector;
using std::unordered_map;
using std::cerr;
using std::endl;
using std::flush;
using std::system_error;
using std::ios;
using std::bad_alloc;
using std::streamsize;
using namespace sampFiles;
// GbinFile methods
uint64_t GbinFileI::_numLines(){
if (_varFile.is_open()) {
_varFile.close();
}
try {
_varFile.open(_fileName.c_str(), ios::in | ios::binary | ios::ate);
if (!_varFile.is_open()) {
cerr << "ERROR: failed to open file " << _fileName << " for input" << endl;
exit(2);
}
} catch (system_error &error) {
cerr << "ERROR: cannot open binary file " << _fileName << " for input: " << error.code().message() << flush;
perror(" ");
exit(1);
}
size_t Ntot = _varFile.tellg();
_varFile.close();
if (Ntot % (_elemSize*_nCols)) {
throw string("Number of elements not divisible by row size");
}
return Ntot/(_elemSize*_nCols);
}
void GbinFile::close(){
if (_varFile.is_open()) {
_varFile.close();
}
}
void GbinFileI::open(){
if (_varFile.is_open()) {
_varFile.close();
}
try {
_varFile.open(_fileName.c_str(), ios::in | ios::binary);
if (!_varFile.is_open()) {
cerr << "ERROR: failed to open file " << _fileName << " for input" << endl;
exit(2);
}
} catch (system_error &error) {
cerr << "ERROR: cannot open binary file " << _fileName << " for input: " << error.code().message() << flush;
perror(" ");
exit(1);
}
}
void GbinFileI::sample(GbinFileO &out, const uint64_t &n){
if (n == 0) {
cerr << "WARNING: zero SNPs requested. Nothing to be done." << endl;
return;
}
// start by figuring out the number of rows
// calculate number of rows in the input binary file; file is closed before the function exits.
uint64_t N = _numLines();
// Test for potential problems
if (N < n) {
cerr << "ERROR: requested a sample of " << n << " rows that is greater than the number of rows (" << N << ") in the input file." << endl;
return;
} else if (N == n) {
cerr << "WARNING: sample size (" << n << ") the same as the number of rows (" << N << ") in the input file. Simply copying the file." << endl;
char *buf;
const size_t bufSize = BUF_SIZE;
try {
buf = new char[bufSize];
} catch (bad_alloc&) {
cerr << "ERROR: failed to allocate buffer" << endl;
exit(4);
}
try {
_varFile.open(_fileName.c_str(), ios::in | ios::binary);
if (!_varFile.is_open()) {
cerr << "ERROR: failed to open file " << _fileName << " for input" << endl;
exit(2);
}
} catch (system_error &error) {
cerr << "ERROR: cannot open binary file " << _fileName << " for input: " << error.code().message() << flush;
perror(" ");
exit(1);
}
try {
out._varFile.open(out._fileName.c_str(), ios::out | ios::binary | ios::trunc);
if (!out._varFile.is_open()) {
cerr << "ERROR: failed to open file " << out._fileName << " for output" << endl;
exit(2);
}
} catch (system_error &error) {
cerr << "ERROR: cannot open binary file " << out._fileName << " for output: " << error.code().message() << flush;
perror(" ");
exit(1);
}
while (_varFile) {
_varFile.read(buf, bufSize);
out._varFile.write(buf, _varFile.gcount()); // must be gcount() in case we got to the end of the file
}
_varFile.close();
out._varFile.close();
delete [] buf;
return;
}
// Passed all the tests, proceed to sampling
char *ROWbuf;
size_t rowSize = _nCols*_elemSize;
try {
ROWbuf = new char[rowSize]; // .read() does not append a null-character
} catch (bad_alloc &) {
cerr << "ERROR: failed to allocate the row buffer" << endl;
exit(4);
}
try {
_varFile.open(_fileName.c_str(), ios::in | ios::binary);
if (!_varFile.is_open()) {
cerr << "ERROR: failed to open file " << _fileName << " for input" << endl;
exit(2);
}
} catch (system_error &error) {
cerr << "ERROR: cannot open binary file " << _fileName << " for input: " << error.code().message() << flush;
perror(" ");
exit(1);
}
if (out._varFile.is_open()) {
out.close();
}
try {
out._varFile.open(out._fileName.c_str(), ios::out | ios::binary | ios::trunc);
if (!out._varFile.is_open()) {
cerr << "ERROR: failed to open file " << out._fileName << " for output" << endl;
exit(2);
}
} catch (system_error &error) {
cerr << "ERROR: cannot open binary file " << out._fileName << " for output: " << error.code().message() << flush;
perror(" ");
exit(1);
}
uint64_t nloc = n; // local copy of n
uint64_t S;
uint64_t cumS = 0; // cumulative position in the file
RanDraw *rowSamp; // so that I can catch RanDraw constructor exceptions
try {
rowSamp = new RanDraw();
} catch (string error) {
cerr << "ERROR: " << error << endl;
exit(5);
}
while (nloc) {
try {
S = rowSamp->vitter(nloc, N); // sample the number of rows to skip; keep track of the running total
} catch (string error) {
cerr << "ERROR: " << error << endl;
exit(5);
}
cumS += S;
N -= S + 1;
_varFile.seekg(cumS*rowSize); // seekg() index is base-0
_varFile.read(ROWbuf, rowSize);
cumS++; // step up cumS because seekg() will not change it (unlike the getline() that automatially advances)
out._varFile.write(ROWbuf, rowSize);
nloc--;
}
_varFile.close();
out._varFile.close();
delete [] ROWbuf;
delete rowSamp;
}
void GbinFileO::open(){
if (_varFile.is_open()) {
_varFile.close();
}
try {
_varFile.open(_fileName.c_str(), ios::out | ios::binary);
if (!_varFile.is_open()) {
cerr << "ERROR: failed to open file " << _fileName << " for output" << endl;
exit(2);
}
} catch (system_error &error) {
cerr << "ERROR: cannot open binary file " << _fileName << " for output: " << error.code().message() << flush;
perror(" ");
exit(1);
}
}
// BedFile methods
BedFile::BedFile() : GbinFile() {
_bimFile.exceptions(fstream::badbit); // for some reason, setting failbit | badbit throws errors no matter what
_famFile.exceptions(fstream::badbit);
// _elemSize is set to sizeof(char) in the GbinFile default constructor
}
BedFile::BedFile(const string &stubName) : GbinFile(), _fileStub{stubName} {
_fileName = _fileStub + ".bed";
_bimFile.exceptions(fstream::badbit);
_famFile.exceptions(fstream::badbit);
// _elemSize is set to sizeof(char) in the GbinFile default constructor
}
const vector<char> BedFile::_masks = {static_cast<char>(0x03), static_cast<char>(0x0C), static_cast<char>(0x30), static_cast<char>(0xC0)};
// M is missing, H is heterozygous, homozygous derived is all 0x00, homozygous ancestral is never tested
const unordered_map<char, string> BedFile::_tests = {
{'M', {static_cast<char>(0x01), static_cast<char>(0x04), static_cast<char>(0x10), static_cast<char>(0x40)}},
{'H', {static_cast<char>(0x02), static_cast<char>(0x08), static_cast<char>(0x20), static_cast<char>(0x80)}}
};
BedFile::~BedFile(){
if (_bimFile.is_open()) {
_bimFile.close();
}
if (_famFile.is_open()) {
_famFile.close();
}
}
void BedFile::close(){
if (_varFile.is_open()) {
_varFile.close();
}
if (_bimFile.is_open()) {
_bimFile.close();
}
if (_famFile.is_open()) {
_famFile.close();
}
}
uint64_t BedFileI::_numLines(){
if (!_nCols) {
_nCols = _famLines();
}
if (_varFile.is_open()) {
_varFile.close();
}
try {
_varFile.open(_fileName.c_str(), ios::in | ios::binary | ios::ate);
if (!_varFile.is_open()) {
cerr << "ERROR: failed to open file " << _fileName << " for input" << endl;
exit(2);
}
} catch (system_error &error) {
cerr << "ERROR: cannot open binary file " << _fileName << " for output: " << error.code().message() << flush;
perror(" ");
exit(1);
}
uint64_t Nbed = (_nCols/4UL) + static_cast<uint64_t>( (_nCols%4UL) > 0UL );
uint64_t N = static_cast<uint64_t>(_varFile.tellg()) - 3UL; // 3 is the number of magic bytes
if (N % Nbed) {
cerr << "ERROR: total file size " << N << " not divisible by the number of compressed colums " << Nbed << " in BedFile _numLines()" << endl;
exit(7);
}
_varFile.close();
return N/Nbed;
}
uint64_t BedFileI::_famLines(){
uint64_t N = 0;
/*
* I am using the line-end counting method. It is > 2-fold faster than reading lines with getline().
*/
if (_famFile.is_open()) {
_famFile.close();
}
string famName = _fileStub + ".fam";
try {
_famFile.open(famName.c_str(), ios::in);
if (!_famFile.is_open()) {
cerr << "ERROR: failed to open .fam file " << famName << " for input" << endl;
exit(2);
}
} catch (system_error &error) {
cerr << "ERROR: cannot open .fam file " << famName << " for input: " << error.code().message() << flush;
perror(" ");
exit(1);
}
const size_t bufSize = BUF_SIZE;
char *buf;
try {
buf = new char[bufSize];
} catch (bad_alloc& error) {
cerr << "ERROR: failed to allocate buffer in BedFile::_famLines(): " << error.what() << endl;
exit(4);
}
while (_famFile) {
_famFile.read(buf, bufSize);
for (size_t i = 0; i < _famFile.gcount(); i++) {
if (buf[i] == '\n') {
N++;
}
}
}
delete [] buf;
_famFile.close();
return N;
}
uint64_t BedFileI::_famLines(fstream &fam){
uint64_t N = 0;
/*
* I am using the line-end counting method. It is > 2-fold faster than reading lines with getline().
*/
if (_famFile.is_open()) {
_famFile.close();
}
string famName = _fileStub + ".fam";
try {
_famFile.open(famName.c_str(), ios::in);
if (!_famFile.is_open()) {
cerr << "ERROR: failed to open .fam file " << famName << " for input" << endl;
exit(2);
}
} catch (system_error &error) {
cerr << "ERROR: cannot open .fam file " << famName << " for input: " << error.code().message() << flush;
perror(" ");
exit(1);
}
const size_t bufSize = BUF_SIZE;
char *buf;
try {
buf = new char[bufSize];
} catch (bad_alloc& error) {
cerr << "ERROR: failed to allocate buffer in BedFile::_famLines(): " << error.what() << endl;
exit(4);
}
if (!fam.is_open()) {
throw string("Output .fam filestream not open");
}
while (_famFile) {
_famFile.read(buf, bufSize);
for (size_t i = 0; i < _famFile.gcount(); i++) {
if (buf[i] == '\n') {
N++;
}
}
fam.write(buf, _famFile.gcount());
}
delete [] buf;
_famFile.close();
fam.close();
return N;
}
void BedFileI::_ld(const char *snp1, const char *snp2, const size_t &N, const unsigned short &pad, double &rSq, double &Dprime, double &dcnt1, double &dcnt2){
// Using the Gaunt et al. (2007) formulation
// The data in .bed files are strictly biallelic by definition of the format, so that makes things easier.
// Using derived alleles because they are mostly at low frequency so the expected number of calculations is low
// However, then convert everything to the most common allele frequencies to make things compatible with Gaunt et al.
// Using the notation in that paper, too, to make things more clear
// constants
const char allMiss = static_cast<char>(0x55); // all genotypes missing in a byte
const char homDerv = static_cast<char>(0x00); // homozygous derived for all bit-pair positions
// modifiable parameters
double D = 0.0;
double p1 = 0.0; // frequency of the derived allele at snp1
double q1 = 0.0; // frequency of the derived allele at snp2
double f11 = 0.0; // frequency of the (hom. maj. allele @1, hom. maj.allel @2) haplotype; to be estimated; D = f11 - p1*q1
double n11 = 0.0; // # of 1,1 homozygote haplotypes
double n12 = 0.0; // # of hom. 1, heterozygous 2 haplotypes
double n21 = 0.0; // # of het. 1, hom. 2 haplotypes
double n22 = 0.0; // # of het. 1, het. 2 haplotypes
double Npres = 0.0; // # of present genotypes (present at both loci)
double p1q1; // p1*q1
double p2q2; // p2*q2
// f11 min and max
double f11Min;
double f11Max;
// re-used intermediate variables
double opq; // 1-2p-2q
double smn; // 2n11+n12+n21
double ppq; // p1+q1
// qubic equation coefficients
double a;
double b;
double c;
double d;
// decision variables
double bda; // b/a
double xN;
double deltaSq;
double hSq;
double gammaN;
double Delta3;
char curBitPair1;
char curBitPair2;
// Data missing at either locus are ignored (i.e. I am using pairwise-complete observations)
for (size_t ind = 0; ind < N-1; ind++) { // leave the last byte out for now since it has padding bits (in general)
if ( (snp1[ind] == allMiss) || (snp2[ind] == allMiss) ) { // a byte with all data missing; ignore (NOTE the OR)
continue;
}
// go through the byte from the end
for (size_t inByte = 0; inByte < 4; inByte++) {
curBitPair1 = snp1[ind] & _masks[inByte];
curBitPair2 = snp2[ind] & _masks[inByte];
// Test missingness
if ( (curBitPair1 == _tests.at('M')[inByte]) || (curBitPair2 == _tests.at('M')[inByte]) ) { // must use .at() because _tests is const
continue;
}
Npres += 1.0;
// Go through all the pairwise possibilities; adding up gametes (one per diploid)
if (curBitPair1 == homDerv) {
p1 += 1.0;
if (curBitPair2 == homDerv) {
q1 += 1.0;
n11 += 1.0;
} else if (curBitPair2 == _tests.at('H')[inByte]){
q1 += 0.5;
n12 += 1.0;
}
} else if (curBitPair1 == _tests.at('H')[inByte]){
p1 += 0.5;
if (curBitPair2 == homDerv) {
q1 += 1.0;
n21 += 1.0;
} else if (curBitPair2 == _tests.at('H')[inByte]){
q1 += 0.5;
n22 += 1.0;
}
} else {
if (curBitPair2 == homDerv) {
q1 += 1.0;
} else if (curBitPair2 == _tests.at('H')[inByte]){
q1 += 0.5;
}
}
}
}
// finally, deal with the padded byte
for (size_t inByte = 0; inByte < (4 - pad); inByte++) { // not testing for sane values of pad, since this is a protected function and I can expect sane values in correct class implementation
curBitPair1 = snp1[N-1] & _masks[inByte];
curBitPair2 = snp2[N-1] & _masks[inByte];
// Test missingness
if ( (curBitPair1 == _tests.at('M')[inByte]) || (curBitPair2 == _tests.at('M')[inByte]) ) { // must use .at() because _tests is const
continue;
}
Npres += 1.0;
// Go through all the pairwise possibilities; adding up gametes (one per diploid)
if (curBitPair1 == homDerv) {
p1 += 1.0;
if (curBitPair2 == homDerv) {
q1 += 1.0;
n11 += 1.0;
} else if (curBitPair2 == _tests.at('H')[inByte]){
q1 += 0.5;
n12 += 1.0;
}
} else if (curBitPair1 == _tests.at('H')[inByte]){
p1 += 0.5;
if (curBitPair2 == homDerv) {
q1 += 1.0;
n21 += 1.0;
} else if (curBitPair2 == _tests.at('H')[inByte]){
q1 += 0.5;
n22 += 1.0;
}
} else {
if (curBitPair2 == homDerv) {
q1 += 1.0;
} else if (curBitPair2 == _tests.at('H')[inByte]){
q1 += 0.5;
}
}
}
// minor allele counts
dcnt1 = (p1 <= Npres - p1 ? 2.0*p1 : 2.0*(Npres - p1));
dcnt2 = (q1 <= Npres - q1 ? 2.0*q1 : 2.0*(Npres - q1));
if (Npres <= 1.0) {
rSq = -9.0;
Dprime = -9.0;
return;
}
if ( (dcnt1 == 0.0) || (dcnt2 == 0.0) ) { // even if the SNPs are pre-screened for polymorphism, the alternatives may correspond to missing at the other locus
rSq = -9.0;
Dprime = -9.0;
return;
}
if (n22 == Npres) { // if everyone is het, cannot determine LD because we don't know the phase
rSq = -9.0;
Dprime = -9.0;
return;
}
// Finish calculating statistics if everything is sane
p1 = p1/Npres;
q1 = q1/Npres;
// intermediate values
p1q1 = p1*q1;
if (n22 == 0.0) { // no het/het match-ups; means I can directly enumerate haplotypes
f11 = (n11 + 0.5*(n12 + n21))/Npres;
D = f11 - p1q1;
p2q2 = (1.0-p1)*(1.0-q1);
rSq = (D*D)/(p1q1*p2q2);
if (D < -10.0*EPS) {
double Dmax = ( p1q1 <= p2q2 ? -p1q1 : -p2q2 ); // (9) of Gaunt et al.
Dprime = D/Dmax;
} else if (D > 10.0*EPS) {
p1q1 = p1*(1.0 - q1);
p2q2 = (1.0 - p1)*q1;
double Dmax = ( p1q1 <= p2q2 ? p1q1 : p2q2 ); // (9) of Gaunt et al.
Dprime = D/Dmax;
} else {
Dprime = 0.0;
}
return;
}
// There is n22, so need to estimate f11 via ML (using Gaunt et al. cubic equation); they say f11 is between major alleles, but that is not necessary. Results will be the same for minor or any other combination
// Calculate the bracketing values for f11:
f11Min = n11 + 0.5*(n12 + n21); // i.e., all the het/het haplotypes are crossovers
f11Max = f11Min + 0.5*n22; // i.e., all het/het haplotypes are in phase
f11Min = f11Min/Npres - 100.0*EPS; // some padding to take into account round-off errors
f11Max = f11Max/Npres + 100.0*EPS;
// re-used auxiliary variables
ppq = p1 + q1;
opq = 1.0 - 2.0*ppq;
smn = 2.0*n11 + n12 + n21;
// coefficients
a = 2.0*Npres; // will need to multiply again later to make 4N; doing this to re-use the 2N
b = a*opq - 2.0*smn - n22;
c = a*p1q1 - smn*opq - n22*(1.0 - ppq);
d = -smn*p1q1;
a *= 2.0;
// decision variables
bda = b/a;
xN = -bda/3.0;
deltaSq = bda*bda/9.0 - c/(3.0*a);
hSq = 4.0*a*a*deltaSq*deltaSq*deltaSq;
gammaN = xN*( xN*( a*xN + b ) + c ) + d;
Delta3 = gammaN*gammaN - hSq;
// now decide how many roots we have
if (Delta3 > 100.0*EPS) { // everything is cool, only one distinct root
f11 = xN + cbrt((sqrt(Delta3) - gammaN)/(2.0*a)) + cbrt(-(sqrt(Delta3) + gammaN)/(2.0*a));
} else if (Delta3 < -100.0*EPS){ // Three roots; worst case scenario
double theta = acos(-gammaN/sqrt(hSq))/3.0;
double ddelta = 2.0*sqrt(deltaSq);
double alpha = xN + ddelta*cos(theta);
double beta = xN + ddelta*cos(2.0*PI/3.0 + theta);
double gamma = xN + ddelta*cos(4.0*PI/3.0 + theta);
if ( (alpha < f11Min) || (alpha > f11Max) ) {
if ( (beta < f11Min) || (beta > f11Max) ) {
if ( (gamma < f11Min) || (gamma > f11Max) ) {
rSq = -9.0;
Dprime = -9.0;
return;
} else {
f11 = gamma;
}
} else if ( (gamma < f11Min) || (gamma > f11Max) ) {
f11 = beta;
} else {
// two plausible roots; choose the one with smallest |D|
f11 = (fabs(beta - p1q1) <= fabs(gamma - p1q1) ? beta : gamma);
}
} else {
if ( (beta < f11Min) || (beta > f11Max) ) {
if ( (gamma < f11Min) || (gamma > f11Max) ) {
f11 = alpha;
} else {
// two plausible roots; choose the one with smallest |D|
f11 = (fabs(alpha - p1q1) <= fabs(gamma - p1q1) ? alpha : gamma);
}
} else if ( (gamma < f11Min) || (gamma > f11Max) ) {
// two plausible roots; choose the one with smallest |D|
f11 = (fabs(beta - p1q1) <= fabs(alpha - p1q1) ? beta : alpha);
} else {
// three plausible roots; choose the one with smallest |D|
double minAB = (fabs(beta - p1q1) <= fabs(alpha - p1q1) ? beta : alpha);
f11 = (fabs(minAB - p1q1) <= fabs(gamma - p1q1) ? minAB : gamma);
}
}
} else { // Delta3 == 0; two different roots
double mu = cbrt(gammaN/(2.0*a));
double alpha = xN + mu;
double gamma = xN - 2.0*mu;
if ( (alpha < f11Min) || (alpha > f11Max) ) { // f11 cannot be greater than min(p1, q1)
if ( (gamma < f11Min) || (gamma > f11Max) ) {
rSq = -9.0;
Dprime = -9.0;
return;
} else {
f11 = gamma;
}
} else {
if ( (gamma < f11Min) || (gamma > f11Max) ) { // impossible gamma; going with alpha
f11 = alpha;
} else { // both doable; conservatively choose the one minimzing |D|
f11 = (fabs(alpha - p1q1) <= fabs(gamma - p1q1) ? alpha : gamma);
}
}
}
D = f11 - p1q1;
p2q2 = (1.0-p1)*(1.0-q1);
rSq = (D*D)/(p1q1*p2q2);
if (D < -10.0*EPS) {
double Dmax = ( p1q1 <= p2q2 ? -p1q1 : -p2q2 ); // (9) of Gaunt et al.
Dprime = D/Dmax;
} else if (D > 10.0*EPS) {
p1q1 = p1*(1.0 - q1);
p2q2 = (1.0 - p1)*q1;
double Dmax = ( p1q1 <= p2q2 ? p1q1 : p2q2 ); // (9) of Gaunt et al.
Dprime = D/Dmax;
} else {
Dprime = 0.0;
}
}
void BedFileI::_ld(const char *snp1, const char *snp2, const PopIndex &popID, vector<double> &rSq, vector<double> &Dprime, vector<double> &dcnt1, vector<double> &dcnt2){
// The data in .bed files are strictly biallelic by definition of the format, so that makes things easier.
// Using derived alleles because they are mostly at low frequency so the expected number of calculations is low
// constants
const char homDerv = static_cast<char>(0x00); // homozygous derived for all bit-pair positions
// modifiable parameters
double D;
double p1; // frequency of the derived allele at snp1
double q1; // frequency of the derived allele at snp2
double f11; // frequency of the (hom. maj. allele @1, hom. maj.allel @2) haplotype; to be estimated; D = f11 - p1*q1
double n11; // # of 1,1 homozygote haplotypes
double n12; // # of hom. 1, heterozygous 2 haplotypes
double n21; // # of het. 1, hom. 2 haplotypes
double n22; // # of het. 1, het. 2 haplotypes
double Npres; // # of present genotypes (present at both loci)
double p1q1; // p1*q1
double p2q2; // p2*q2
// f11 min and max
double f11Min;
double f11Max;
// re-used intermediate variables
double opq; // 1-2p-2q
double smn; // 2n11+n12+n21
double ppq; // p1+q1
// qubic equation coefficients
double a;
double b;
double c;
double d;
// decision variables
double bda; // b/a
double xN;
double deltaSq;
double hSq;
double gammaN;
double Delta3;
char curBitPair1;
char curBitPair2;
for (size_t iPop = 0; iPop < popID.popNumber(); iPop++) {
// reset everything
p1 = 0.0;
q1 = 0.0;
f11 = 0.0;
n11 = 0.0;
n12 = 0.0;
n21 = 0.0;
n22 = 0.0;
Npres = 0.0;
for (auto popIt = popID[iPop].begin(); popIt != popID[iPop].end(); ++popIt) {
size_t byteInd = (*popIt)/4;
size_t bitPairInd = (*popIt) % 4; // will automatically index from the end of the byte
curBitPair1 = snp1[byteInd] & _masks[bitPairInd];
curBitPair2 = snp2[byteInd] & _masks[bitPairInd];
// Test miss
if ( (curBitPair1 == _tests.at('M')[bitPairInd]) || (curBitPair2 == _tests.at('M')[bitPairInd]) ) { // must use .at() because _tests is const
continue;
}
Npres += 1.0;
// Go through all the pairwise possibilities; adding up gametes (one per diploid)
if (curBitPair1 == homDerv) {
p1 += 1.0;
if (curBitPair2 == homDerv) {
q1 += 1.0;
n11 += 1.0;
} else if (curBitPair2 == _tests.at('H')[bitPairInd]){
q1 += 0.5;
n12 += 1.0;
}
} else if (curBitPair1 == _tests.at('H')[bitPairInd]){
p1 += 0.5;
if (curBitPair2 == homDerv) {
q1 += 1.0;
n21 += 1.0;
} else if (curBitPair2 == _tests.at('H')[bitPairInd]){
q1 += 0.5;
n22 += 1.0;
}
} else {
if (curBitPair2 == homDerv) {
q1 += 1.0;
} else if (curBitPair2 == _tests.at('H')[bitPairInd]){
q1 += 0.5;
}
}
}
dcnt1[iPop] = (p1 <= Npres - p1 ? 2.0*p1 : 2.0*(Npres - p1));
dcnt2[iPop] = (q1 <= Npres - q1 ? 2.0*q1 : 2.0*(Npres - q1));
if (Npres <= 1.0) {
rSq[iPop] = -9.0;
Dprime[iPop] = -9.0;
continue;
}
if ( (dcnt1[iPop] == 0.0) || (dcnt2[iPop] == 0.0) ) { // even if the SNPs are pre-screened for polymorphism, the alternatives may correspond to missing at the other locus
rSq[iPop] = -9.0;
Dprime[iPop] = -9.0;
continue;
}
if (n22 == Npres) { // if everyone is het, cannot determine LD because we don't know the phase
rSq[iPop] = -9.0;
Dprime[iPop] = -9.0;
continue;
}
// Finish calculating statistics if everything is sane
p1 = p1/Npres;
q1 = q1/Npres;
// intermediate values
p1q1 = p1*q1;
if (n22 == 0.0) { // no het/het match-ups; means I can directly enumerate haplotypes
f11 = (n11 + 0.5*(n12 + n21))/Npres;
D = f11 - p1q1;
p2q2 = (1.0-p1)*(1.0-q1);
rSq[iPop] = (D*D)/(p1q1*p2q2);
if (D < -10.0*EPS) {
double Dmax = ( p1q1 <= p2q2 ? -p1q1 : -p2q2 ); // (9) of Gaunt et al.
Dprime[iPop] = D/Dmax;
} else if (D > 10.0*EPS) {
p1q1 = p1*(1.0 - q1);
p2q2 = (1.0 - p1)*q1;
double Dmax = ( p1q1 <= p2q2 ? p1q1 : p2q2 ); // (9) of Gaunt et al.
Dprime[iPop] = D/Dmax;
} else {
Dprime[iPop] = 0.0;
}
} else {
// There is n22, so need to estimate f11 via ML (using Gaunt et al. cubic equation); they say f11 is between major alleles, but that is not necessary. Results will be the same for minor or any other combination
// Calculate the bracketing values for f11:
f11Min = n11 + 0.5*(n12 + n21); // i.e., all the het/het haplotypes are crossovers
f11Max = f11Min + 0.5*n22; // i.e., all het/het haplotypes are in phase
f11Min = f11Min/Npres - 100.0*EPS; // some padding to take into account round-off errors
f11Max = f11Max/Npres + 100.0*EPS;
// re-used auxiliary variables
ppq = p1 + q1;
opq = 1.0 - 2.0*ppq;
smn = 2.0*n11 + n12 + n21;
// coefficients
a = 2.0*Npres; // will need to multiply again later to make 4N; doing this to re-use the 2N
b = a*opq - 2.0*smn - n22;
c = a*p1q1 - smn*opq - n22*(1.0 - ppq);
d = -smn*p1q1;
a *= 2.0;
// decision variables
bda = b/a;
xN = -bda/3.0;
deltaSq = bda*bda/9.0 - c/(3.0*a);
hSq = 4.0*a*a*deltaSq*deltaSq*deltaSq;
gammaN = xN*( xN*( a*xN + b ) + c ) + d;
Delta3 = gammaN*gammaN - hSq;
// now decide how many roots we have
if (Delta3 > 100.0*EPS) { // everything is cool, only one distinct root
f11 = xN + cbrt((sqrt(Delta3) - gammaN)/(2.0*a)) + cbrt(-(sqrt(Delta3) + gammaN)/(2.0*a));
} else if (Delta3 < -100.0*EPS){ // Three roots; worst case scenario
double theta = acos(-gammaN/sqrt(hSq))/3.0;
double ddelta = 2.0*sqrt(deltaSq);
double alpha = xN + ddelta*cos(theta);
double beta = xN + ddelta*cos(2.0*PI/3.0 + theta);
double gamma = xN + ddelta*cos(4.0*PI/3.0 + theta);
if ( (alpha < f11Min) || (alpha > f11Max) ) {
if ( (beta < f11Min) || (beta > f11Max) ) {
if ( (gamma < f11Min) || (gamma > f11Max) ) {
rSq[iPop] = -9.0;
Dprime[iPop] = -9.0;
continue;
} else {
f11 = gamma;
}
} else if ( (gamma < f11Min) || (gamma > f11Max) ) {
f11 = beta;
} else {
// two plausible roots; choose the one with smallest |D|
f11 = (fabs(beta - p1q1) <= fabs(gamma - p1q1) ? beta : gamma);
}
} else {
if ( (beta < f11Min) || (beta > f11Max) ) {
if ( (gamma < f11Min) || (gamma > f11Max) ) {
f11 = alpha;
} else {
// two plausible roots; choose the one with smallest |D|
f11 = (fabs(alpha - p1q1) <= fabs(gamma - p1q1) ? alpha : gamma);
}
} else if ( (gamma < f11Min) || (gamma > f11Max) ) {
// two plausible roots; choose the one with smallest |D|
f11 = (fabs(beta - p1q1) <= fabs(alpha - p1q1) ? beta : alpha);
} else {
// three plausible roots; choose the one with smallest |D|
double minAB = (fabs(beta - p1q1) <= fabs(alpha - p1q1) ? beta : alpha);
f11 = (fabs(minAB - p1q1) <= fabs(gamma - p1q1) ? minAB : gamma);
}
}
} else { // Delta3 == 0; two different roots
double mu = cbrt(gammaN/(2.0*a));
double alpha = xN + mu;
double gamma = xN - 2.0*mu;
if ( (alpha < f11Min) || (alpha > f11Max) ) { // f11 cannot be greater than min(p1, q1)
if ( (gamma < f11Min) || (gamma > f11Max) ) {
rSq[iPop] = -9.0;
Dprime[iPop] = -9.0;
continue;
} else {
f11 = gamma;
}
} else {
if ( (gamma < f11Min) || (gamma > f11Max) ) { // impossible gamma; going with alpha
f11 = alpha;
} else { // both doable; conservatively choose the one minimzing |D|
f11 = (fabs(alpha - p1q1) <= fabs(gamma - p1q1) ? alpha : gamma);
}
}
}
D = f11 - p1q1;
p2q2 = (1.0-p1)*(1.0-q1);
rSq[iPop] = (D*D)/(p1q1*p2q2);
if (D < -10.0*EPS) {
double Dmax = ( p1q1 <= p2q2 ? -p1q1 : -p2q2 ); // (9) of Gaunt et al.
Dprime[iPop] = D/Dmax;
} else if (D > 10.0*EPS) {
p1q1 = p1*(1.0 - q1);
p2q2 = (1.0 - p1)*q1;
double Dmax = ( p1q1 <= p2q2 ? p1q1 : p2q2 ); // (9) of Gaunt et al.
Dprime[iPop] = D/Dmax;
} else {
Dprime[iPop] = 0.0;
}
}
}
}
void BedFileI::open(){
string bimName = _fileStub + ".bim";
string famName = _fileStub + ".fam";
try {
_varFile.open(_fileName.c_str(), ios::in | ios::binary);
if (!_varFile.is_open()) {
cerr << "ERROR: failed to open file " << _fileName << " for input" << endl;
exit(2);
}
} catch (system_error &error) {
cerr << "ERROR: cannot open BED file " << _fileName << " for input: " << error.code().message() << flush;
perror(" ");
exit(1);
}
// check the magic bytes and SNP-major status
char magic[3];
_varFile.read(magic, 3);
if ( (magic[0] != static_cast<char>(0x6C)) || (magic[1] != static_cast<char>(0x1B)) ) {
cerr << "ERROR: binary file " << _fileName << " not recognized as BED" << endl;
exit(2);
} else if (magic[2] != static_cast<char>(0x01)){
cerr << "ERROR: binary file " << _fileName << " not SNP-major. Run a newer version of plink to fix it." << endl;
exit(3);
}
try {
_bimFile.open(bimName.c_str(), ios::in);
if (!_bimFile.is_open()) {
cerr << "ERROR: failed to open .bim file " << bimName << " for input" << endl;
exit(2);