Debian Codegraph @

pgenlibr/src/pgenlibr.cpp

raw
1 #include "include/pgenlib_ffi_support.h"
2 #include "include/pgenlib_read.h"
3 #include "pvar.h" // includes Rcpp
4
5 class RPgenReader {
6 public:
7 // imitates Python/pgenlib.pyx
8 RPgenReader();
9
10 #if __cplusplus >= 201103L
11 RPgenReader(const RPgenReader&) = delete;
12 RPgenReader& operator=(const RPgenReader&) = delete;
13 #endif
14
15 void Load(String filename, Nullable<List> pvar, Nullable<int> raw_sample_ct,
16 Nullable<IntegerVector> sample_subset_1based);
17
18 uint32_t GetRawSampleCt() const;
19
20 uint32_t GetSubsetSize() const;
21
22 uint32_t GetVariantCt() const;
23
24 uint32_t GetAlleleCt(uint32_t variant_idx) const;
25
26 uint32_t GetMaxAlleleCt() const;
27
28 uint32_t GetVrtype(uint32_t variant_idx) const;
29
30 bool HardcallPhasePresent() const;
31
32 void ReadIntHardcalls(IntegerVector buf, int variant_idx, int allele_idx);
33
34 void ReadHardcalls(NumericVector buf, int variant_idx, int allele_idx);
35
36 void ReadIntMaybeSparseHardcalls(IntegerVector buf, int variant_idx, int allele_idx, int file_difflist_len_limit, IntegerVector* sample_nums_ptr, IntegerVector* allele_counts_ptr);
37
38 // void ReadMaybeSparseHardcalls(NumericVector buf, int variant_idx, int allele_idx, int file_difflist_len_limit, IntegerVector* sample_nums_ptr, NumericVector* allele_dosages_ptr);
39
40 void Read(NumericVector buf, int variant_idx, int allele_idx);
41
42 void ReadAlleles(IntegerMatrix acbuf,
43 Nullable<LogicalVector> phasepresent_buf, int variant_idx);
44
45 void ReadAllelesNumeric(NumericMatrix acbuf,
46 Nullable<LogicalVector> phasepresent_buf,
47 int variant_idx);
48
49 void ReadIntList(IntegerMatrix buf, IntegerVector variant_subset);
50
51 void ReadList(NumericMatrix buf, IntegerVector variant_subset, bool meanimpute);
52
53 void FillVariantScores(NumericVector result, NumericVector weights, Nullable<IntegerVector> variant_subset);
54
55 void Close();
56
57 ~RPgenReader();
58
59 private:
60 plink2::PgenFileInfo* _info_ptr;
61 plink2::RefcountedWptr* _allele_idx_offsetsp;
62 plink2::RefcountedWptr* _nonref_flagsp;
63 plink2::PgenReader* _state_ptr;
64 uintptr_t* _subset_include_vec;
65 uintptr_t* _subset_include_interleaved_vec;
66 uint32_t* _subset_cumulative_popcounts;
67 plink2::PgrSampleSubsetIndex _subset_index;
68 uint32_t _subset_size;
69
70 plink2::PgenVariant _pgv;
71
72 uintptr_t* _raregeno_buf;
73 uint32_t* _difflist_sample_ids_buf;
74
75 plink2::VecW* _transpose_batch_buf;
76 // kPglNypTransposeBatch (= 256) variants at a time, and then transpose
77 uintptr_t* _multivar_vmaj_geno_buf;
78 uintptr_t* _multivar_vmaj_phasepresent_buf;
79 uintptr_t* _multivar_vmaj_phaseinfo_buf;
80 uintptr_t* _multivar_smaj_geno_batch_buf;
81 uintptr_t* _multivar_smaj_phaseinfo_batch_buf;
82 uintptr_t* _multivar_smaj_phasepresent_batch_buf;
83
84 void SetSampleSubsetInternal(IntegerVector sample_subset_1based);
85
86 void ReadMaybeSparseHardcallsInternal(int variant_idx, int file_difflist_len_limit, uint32_t* difflist_common_geno_ptr, uint32_t* difflist_len_ptr);
87
88 void ReadAllelesPhasedInternal(int variant_idx);
89 };
90
91 RPgenReader::RPgenReader() : _info_ptr(nullptr),
92 _allele_idx_offsetsp(nullptr),
93 _nonref_flagsp(nullptr),
94 _state_ptr(nullptr) {
95 }
96
97 void RPgenReader::Load(String filename, Nullable<List> pvar,
98 Nullable<int> raw_sample_ct,
99 Nullable<IntegerVector> sample_subset_1based) {
100 if (_info_ptr) {
101 Close();
102 }
103 _info_ptr = static_cast<plink2::PgenFileInfo*>(malloc(sizeof(plink2::PgenFileInfo)));
104 if (!_info_ptr) {
105 stop("Out of memory");
106 }
107 plink2::PreinitPgfi(_info_ptr);
108 uint32_t cur_sample_ct = UINT32_MAX;
109 if (raw_sample_ct.isNotNull()) {
110 cur_sample_ct = as<int>(raw_sample_ct.get());
111 }
112 uint32_t cur_variant_ct = UINT32_MAX;
113 const char* fname = filename.get_cstring();
114 plink2::PgenHeaderCtrl header_ctrl;
115 uintptr_t pgfi_alloc_cacheline_ct;
116 char errstr_buf[plink2::kPglErrstrBufBlen];
117 if (plink2::PgfiInitPhase1(fname, nullptr, cur_variant_ct, cur_sample_ct, &header_ctrl, _info_ptr, &pgfi_alloc_cacheline_ct, errstr_buf) != plink2::kPglRetSuccess) {
118 stop(&(errstr_buf[7]));
119 }
120 const uint32_t raw_variant_ct = _info_ptr->raw_variant_ct;
121 if (pvar.isNotNull()) {
122 List pvarl = as<List>(pvar);
123 if (strcmp_r_c(pvarl[0], "pvar")) {
124 stop("pvar is not a pvar object");
125 }
126 XPtr<class RPvar> rp = as<XPtr<class RPvar> >(pvarl[1]);
127 if (rp->GetVariantCt() != raw_variant_ct) {
128 stop("pvar and pgen have different variant counts");
129 }
130 _allele_idx_offsetsp = rp->GetAlleleIdxOffsetsp();
131 if (_allele_idx_offsetsp) {
132 _info_ptr->allele_idx_offsets = _allele_idx_offsetsp->p;
133 }
134 _info_ptr->max_allele_ct = rp->GetMaxAlleleCt();
135 } else {
136 if (header_ctrl & 0x30) {
137 // no need to zero-initialize this
138 _allele_idx_offsetsp = plink2::CreateRefcountedWptr(raw_variant_ct + 1);
139 _info_ptr->allele_idx_offsets = _allele_idx_offsetsp->p;
140 // _info_ptr->max_allele_ct updated by PgfiInitPhase2() in this case
141 }
142 _info_ptr->max_allele_ct = 2;
143 }
144 if ((header_ctrl & 0xc0) == 0xc0) {
145 // todo: load this in pvar, to enable consistency check. we use a
146 // (manually implemented) shared_ptr in preparation for this.
147 const uintptr_t raw_variant_ctl = plink2::DivUp(raw_variant_ct, plink2::kBitsPerWord);
148 // no need to zero-initialize this
149 _nonref_flagsp = plink2::CreateRefcountedWptr(raw_variant_ctl + 1);
150 _info_ptr->nonref_flags = _nonref_flagsp->p;
151 }
152 const uint32_t file_sample_ct = _info_ptr->raw_sample_ct;
153 unsigned char* pgfi_alloc = nullptr;
154 if (plink2::cachealigned_malloc(pgfi_alloc_cacheline_ct * plink2::kCacheline, &pgfi_alloc)) {
155 stop("Out of memory");
156 }
157 uint32_t max_vrec_width;
158 uintptr_t pgr_alloc_cacheline_ct;
159 if (plink2::PgfiInitPhase2(header_ctrl, 1, 0, 0, 0, raw_variant_ct, &max_vrec_width, _info_ptr, pgfi_alloc, &pgr_alloc_cacheline_ct, errstr_buf)) {
160 if (pgfi_alloc && (!_info_ptr->vrtypes)) {
161 plink2::aligned_free(pgfi_alloc);
162 }
163 stop(&(errstr_buf[7]));
164 }
165 if ((!_allele_idx_offsetsp) && (_info_ptr->gflags & 4)) {
166 // Note that it's safe to be ignorant of multiallelic variants when
167 // phase and dosage info aren't present; GetAlleleCt() then always returns
168 // 2 when that isn't actually true, and all ALTs are treated as if they
169 // were ALT1, but otherwise everything works properly.
170 stop("Multiallelic variants and phase/dosage info simultaneously present; pvar required in this case");
171 }
172 _state_ptr = static_cast<plink2::PgenReader*>(malloc(sizeof(plink2::PgenReader)));
173 if (!_state_ptr) {
174 stop("Out of memory");
175 }
176 plink2::PreinitPgr(_state_ptr);
177 plink2::PgrSetFreadBuf(nullptr, _state_ptr);
178 const uintptr_t pgr_alloc_main_byte_ct = pgr_alloc_cacheline_ct * plink2::kCacheline;
179 const uintptr_t sample_subset_byte_ct = plink2::DivUp(file_sample_ct, plink2::kBitsPerVec) * plink2::kBytesPerVec;
180 const uintptr_t cumulative_popcounts_byte_ct = plink2::DivUp(file_sample_ct, plink2::kBitsPerWord * plink2::kInt32PerVec) * plink2::kBytesPerVec;
181 const uintptr_t genovec_byte_ct = plink2::DivUp(file_sample_ct, plink2::kNypsPerVec) * plink2::kBytesPerVec;
182 const uint32_t is_not_plink1_bed = (plink2::PgrGetVrtypes(_state_ptr) != nullptr);
183 uintptr_t raregeno_byte_ct = 0;
184 uintptr_t difflist_sample_ids_byte_ct = 0;
185 if (is_not_plink1_bed) {
186 const uint32_t max_simple_difflist_len = 2 * (file_sample_ct / plink2::kPglMaxDifflistLenDivisor);
187 raregeno_byte_ct = plink2::DivUp(max_simple_difflist_len, plink2::kNypsPerVec) * plink2::kBytesPerVec;
188 difflist_sample_ids_byte_ct = plink2::RoundUpPow2(max_simple_difflist_len * sizeof(int32_t), plink2::kBytesPerVec);
189 }
190 const uintptr_t ac_byte_ct = plink2::RoundUpPow2(file_sample_ct * sizeof(plink2::AlleleCode), plink2::kBytesPerVec);
191 const uintptr_t ac2_byte_ct = plink2::RoundUpPow2(file_sample_ct * 2 * sizeof(plink2::AlleleCode), plink2::kBytesPerVec);
192 uintptr_t multiallelic_hc_byte_ct = 0;
193 if (_info_ptr->max_allele_ct != 2) {
194 multiallelic_hc_byte_ct = 2 * sample_subset_byte_ct + ac_byte_ct + ac2_byte_ct;
195 }
196 const uintptr_t dosage_main_byte_ct = plink2::DivUp(file_sample_ct, (2 * plink2::kInt32PerVec)) * plink2::kBytesPerVec;
197 unsigned char* pgr_alloc;
198 if (plink2::cachealigned_malloc(pgr_alloc_main_byte_ct + (2 * plink2::kPglNypTransposeBatch + 5) * sample_subset_byte_ct + cumulative_popcounts_byte_ct + (1 + plink2::kPglNypTransposeBatch) * genovec_byte_ct + raregeno_byte_ct + difflist_sample_ids_byte_ct + multiallelic_hc_byte_ct + dosage_main_byte_ct + plink2::kPglBitTransposeBufbytes + 4 * (plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 8), &pgr_alloc)) {
199 stop("Out of memory");
200 }
201 plink2::PglErr reterr = plink2::PgrInit(fname, max_vrec_width, _info_ptr, _state_ptr, pgr_alloc);
202 if (reterr != plink2::kPglRetSuccess) {
203 if (!plink2::PgrGetFreadBuf(_state_ptr)) {
204 plink2::aligned_free(pgr_alloc);
205 }
206 snprintf(errstr_buf, plink2::kPglErrstrBufBlen, "PgrInit() error %d", static_cast<int>(reterr));
207 stop(errstr_buf);
208 }
209 unsigned char* pgr_alloc_iter = &(pgr_alloc[pgr_alloc_main_byte_ct]);
210 _subset_include_vec = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
211 pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]);
212 _subset_include_interleaved_vec = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
213 pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]);
214
215 #ifdef USE_AVX2
216 _subset_include_interleaved_vec[-3] = 0;
217 _subset_include_interleaved_vec[-2] = 0;
218 #endif
219 _subset_include_interleaved_vec[-1] = 0;
220
221 _subset_cumulative_popcounts = reinterpret_cast<uint32_t*>(pgr_alloc_iter);
222 pgr_alloc_iter = &(pgr_alloc_iter[cumulative_popcounts_byte_ct]);
223 _pgv.genovec = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
224 pgr_alloc_iter = &(pgr_alloc_iter[genovec_byte_ct]);
225 if (is_not_plink1_bed) {
226 _raregeno_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
227 pgr_alloc_iter = &(pgr_alloc_iter[raregeno_byte_ct]);
228 _difflist_sample_ids_buf = reinterpret_cast<uint32_t*>(pgr_alloc_iter);
229 pgr_alloc_iter = &(pgr_alloc_iter[difflist_sample_ids_byte_ct]);
230 } else {
231 _raregeno_buf = nullptr;
232 _difflist_sample_ids_buf = nullptr;
233 }
234 if (multiallelic_hc_byte_ct) {
235 _pgv.patch_01_set = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
236 pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]);
237 _pgv.patch_01_vals = reinterpret_cast<plink2::AlleleCode*>(pgr_alloc_iter);
238 pgr_alloc_iter = &(pgr_alloc_iter[ac_byte_ct]);
239 _pgv.patch_10_set = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
240 pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]);
241 _pgv.patch_10_vals = reinterpret_cast<plink2::AlleleCode*>(pgr_alloc_iter);
242 pgr_alloc_iter = &(pgr_alloc_iter[ac2_byte_ct]);
243 } else {
244 _pgv.patch_01_set = nullptr;
245 _pgv.patch_01_vals = nullptr;
246 _pgv.patch_10_set = nullptr;
247 _pgv.patch_10_vals = nullptr;
248 }
249 _pgv.phasepresent = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
250 pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]);
251 _pgv.phaseinfo = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
252 pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]);
253 _pgv.dosage_present = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
254 pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]);
255 _pgv.dosage_main = reinterpret_cast<uint16_t*>(pgr_alloc_iter);
256 pgr_alloc_iter = &(pgr_alloc_iter[dosage_main_byte_ct]);
257 if (sample_subset_1based.isNotNull()) {
258 SetSampleSubsetInternal(sample_subset_1based.get());
259 } else {
260 _subset_size = file_sample_ct;
261 }
262 _transpose_batch_buf = reinterpret_cast<plink2::VecW*>(pgr_alloc_iter);
263 pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglBitTransposeBufbytes]);
264 _multivar_vmaj_geno_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
265 pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * genovec_byte_ct]);
266 _multivar_vmaj_phasepresent_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
267 pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * sample_subset_byte_ct]);
268 _multivar_vmaj_phaseinfo_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
269 pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * sample_subset_byte_ct]);
270 _multivar_smaj_geno_batch_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
271 pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 4]);
272 _multivar_smaj_phaseinfo_batch_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
273 pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 8]);
274 _multivar_smaj_phasepresent_batch_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
275 // pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 8]);
276 }
277
278 uint32_t RPgenReader::GetRawSampleCt() const {
279 if (!_info_ptr) {
280 stop("pgen is closed");
281 }
282 return _info_ptr->raw_sample_ct;
283 }
284
285 uint32_t RPgenReader::GetSubsetSize() const {
286 return _subset_size;
287 }
288
289 uint32_t RPgenReader::GetVariantCt() const {
290 if (!_info_ptr) {
291 stop("pgen is closed");
292 }
293 return _info_ptr->raw_variant_ct;
294 }
295
296 uint32_t RPgenReader::GetAlleleCt(uint32_t variant_idx) const {
297 if (!_info_ptr) {
298 stop("pgen is closed");
299 }
300 if (variant_idx >= _info_ptr->raw_variant_ct) {
301 char errstr_buf[256];
302 snprintf(errstr_buf, 256, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct);
303 stop(errstr_buf);
304 }
305 if (!_allele_idx_offsetsp) {
306 return 2;
307 }
308 const uintptr_t* allele_idx_offsets = _allele_idx_offsetsp->p;
309 return allele_idx_offsets[variant_idx + 1] - allele_idx_offsets[variant_idx];
310 }
311
312 uint32_t RPgenReader::GetMaxAlleleCt() const {
313 if (!_info_ptr) {
314 stop("pgen is closed");
315 }
316 return _info_ptr->max_allele_ct;
317 }
318
319 uint32_t RPgenReader::GetVrtype(uint32_t variant_idx) const {
320 if (!_info_ptr) {
321 stop("pgen is closed");
322 }
323 if (variant_idx >= _info_ptr->raw_variant_ct) {
324 char errstr_buf[256];
325 snprintf(errstr_buf, 256, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct);
326 stop(errstr_buf);
327 }
328 return plink2::PgrGetVrtype(_state_ptr, variant_idx);
329 }
330
331 bool RPgenReader::HardcallPhasePresent() const {
332 if (!_info_ptr) {
333 stop("pgen is closed");
334 }
335 return ((_info_ptr->gflags & plink2::kfPgenGlobalHardcallPhasePresent) != 0);
336 }
337
338 static const int32_t kGenoRInt32Quads[1024] ALIGNV16 = QUAD_TABLE256(0, 1, 2, NA_INTEGER);
339
340 void RPgenReader::ReadIntHardcalls(IntegerVector buf, int variant_idx, int allele_idx) {
341 if (!_info_ptr) {
342 stop("pgen is closed");
343 }
344 if (static_cast<uint32_t>(variant_idx) >= _info_ptr->raw_variant_ct) {
345 char errstr_buf[256];
346 snprintf(errstr_buf, 256, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct);
347 stop(errstr_buf);
348 }
349 plink2::PglErr reterr = plink2::PgrGet1(_subset_include_vec, _subset_index, _subset_size, variant_idx, allele_idx, _state_ptr, _pgv.genovec);
350 if (reterr != plink2::kPglRetSuccess) {
351 char errstr_buf[256];
352 snprintf(errstr_buf, 256, "PgrGet1() error %d", static_cast<int>(reterr));
353 stop(errstr_buf);
354 }
355 plink2::GenoarrLookup256x4bx4(_pgv.genovec, kGenoRInt32Quads, _subset_size, &buf[0]);
356 }
357
358 static const double kGenoRDoublePairs[32] ALIGNV16 = PAIR_TABLE16(0.0, 1.0, 2.0, NA_REAL);
359
360 void RPgenReader::ReadHardcalls(NumericVector buf, int variant_idx, int allele_idx) {
361 if (!_info_ptr) {
362 stop("pgen is closed");
363 }
364 if (static_cast<uint32_t>(variant_idx) >= _info_ptr->raw_variant_ct) {
365 char errstr_buf[256];
366 snprintf(errstr_buf, 256, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct);
367 stop(errstr_buf);
368 }
369 if (buf.size() != _subset_size) {
370 using namespace plink2;
371 char errstr_buf[256];
372 char* write_iter = strcpya_k(errstr_buf, "buf has wrong length (");
373 write_iter = wtoa(buf.size(), write_iter);
374 write_iter = strcpya_k(write_iter, "; ");
375 write_iter = u32toa(_subset_size, write_iter);
376 strcpy_k(write_iter, " expected)");
377 stop(errstr_buf);
378 }
379 plink2::PglErr reterr = plink2::PgrGet1(_subset_include_vec, _subset_index, _subset_size, variant_idx, allele_idx, _state_ptr, _pgv.genovec);
380 if (reterr != plink2::kPglRetSuccess) {
381 char errstr_buf[256];
382 snprintf(errstr_buf, 256, "PgrGet1() error %d", static_cast<int>(reterr));
383 stop(errstr_buf);
384 }
385 plink2::GenoarrLookup16x8bx2(_pgv.genovec, kGenoRDoublePairs, _subset_size, &buf[0]);
386 }
387
388 void RPgenReader::ReadIntMaybeSparseHardcalls(IntegerVector buf, int variant_idx, int allele_idx, int file_difflist_len_limit, IntegerVector* sample_nums_ptr, IntegerVector* allele_counts_ptr) {
389 if (!_info_ptr) {
390 stop("pgen is closed");
391 }
392 const uint32_t raw_variant_ct = _info_ptr->raw_variant_ct;
393 if (static_cast<uint32_t>(variant_idx) >= raw_variant_ct) {
394 char errstr_buf[256];
395 snprintf(errstr_buf, 256, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct);
396 stop(errstr_buf);
397 }
398 uint32_t difflist_common_geno;
399 uint32_t difflist_len;
400 ReadMaybeSparseHardcallsInternal(variant_idx, file_difflist_len_limit, &difflist_common_geno, &difflist_len);
401 if (difflist_common_geno == UINT32_MAX) {
402 plink2::GenoarrLookup256x4bx4(_pgv.genovec, kGenoRInt32Quads, _subset_size, &buf[0]);
403 return;
404 }
405 // TODO
406 }
407
408 void RPgenReader::Read(NumericVector buf, int variant_idx, int allele_idx) {
409 if (!_info_ptr) {
410 stop("pgen is closed");
411 }
412 if (static_cast<uint32_t>(variant_idx) >= _info_ptr->raw_variant_ct) {
413 char errstr_buf[256];
414 snprintf(errstr_buf, 256, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct);
415 stop(errstr_buf);
416 }
417 if (buf.size() != _subset_size) {
418 using namespace plink2;
419 char errstr_buf[256];
420 char* write_iter = strcpya_k(errstr_buf, "buf has wrong length (");
421 write_iter = wtoa(buf.size(), write_iter);
422 write_iter = strcpya_k(write_iter, "; ");
423 write_iter = u32toa(_subset_size, write_iter);
424 strcpy_k(write_iter, " expected)");
425 stop(errstr_buf);
426 }
427 uint32_t dosage_ct;
428 plink2::PglErr reterr = plink2::PgrGet1D(_subset_include_vec, _subset_index, _subset_size, variant_idx, allele_idx, _state_ptr, _pgv.genovec, _pgv.dosage_present, _pgv.dosage_main, &dosage_ct);
429 if (reterr != plink2::kPglRetSuccess) {
430 char errstr_buf[256];
431 snprintf(errstr_buf, 256, "PgrGet1D() error %d", static_cast<int>(reterr));
432 stop(errstr_buf);
433 }
434 plink2::Dosage16ToDoubles(kGenoRDoublePairs, _pgv.genovec, _pgv.dosage_present, _pgv.dosage_main, _subset_size, dosage_ct, &buf[0]);
435 }
436
437 static const uint64_t kGenoToRIntcodeDPairs[32] ALIGNV16 = PAIR_TABLE16(0, 0x100000000LLU, 0x100000001LLU, 0x8000000080000000LLU);
438 static const int32_t kGenoToLogicalPhaseQuads[1024] ALIGNV16 = QUAD_TABLE256(1, 0, 1, NA_LOGICAL);
439
440 void RPgenReader::ReadAlleles(IntegerMatrix acbuf, Nullable<LogicalVector> phasepresent_buf, int variant_idx) {
441 if (!_info_ptr) {
442 stop("pgen is closed");
443 }
444 if ((acbuf.nrow() != 2) || (acbuf.ncol() != static_cast<int>(_subset_size))) {
445 char errstr_buf[256];
446 snprintf(errstr_buf, 256, "acbuf has wrong size (%dx%d; 2x%u expected)", acbuf.nrow(), acbuf.ncol(), _subset_size);
447 stop(errstr_buf);
448 }
449 ReadAllelesPhasedInternal(variant_idx);
450 plink2::GenoarrToAlleleCodes(kGenoToRIntcodeDPairs, _pgv.genovec, _subset_size, &acbuf[0]);
451 const uintptr_t* allele_idx_offsets = _info_ptr->allele_idx_offsets;
452 uint32_t cur_allele_ct = 2;
453 if (allele_idx_offsets) {
454 cur_allele_ct = allele_idx_offsets[variant_idx + 1] - allele_idx_offsets[variant_idx];
455 if (cur_allele_ct != 2) {
456 stop("multiallelic support under development");
457 }
458 }
459 const uintptr_t* phasepresent = _pgv.phasepresent;
460 const uintptr_t* phaseinfo = _pgv.phaseinfo;
461 const uint32_t phasepresent_ct = _pgv.phasepresent_ct;
462 uintptr_t sample_uidx_base = 0;
463 uintptr_t cur_bits = phasepresent[0];
464 if (!phasepresent_buf.isNotNull()) {
465 int32_t* allele_codes = &acbuf[0];
466 if (cur_allele_ct == 2) {
467 const uint64_t one = 1;
468 for (uint32_t phased_idx = 0; phased_idx != phasepresent_ct; ++phased_idx) {
469 const uintptr_t sample_uidx = plink2::BitIter1(phasepresent, &sample_uidx_base, &cur_bits);
470 if (plink2::IsSet(phaseinfo, sample_uidx)) {
471 // 1|0
472 memcpy(&(allele_codes[2 * sample_uidx]), &one, sizeof(int64_t));
473 }
474 }
475 } else {
476 for (uint32_t phased_idx = 0; phased_idx != phasepresent_ct; ++phased_idx) {
477 const uintptr_t sample_uidx = plink2::BitIter1(phasepresent, &sample_uidx_base, &cur_bits);
478 if (plink2::IsSet(phaseinfo, sample_uidx)) {
479 const int32_t tmpval = allele_codes[2 * sample_uidx];
480 allele_codes[2 * sample_uidx] = allele_codes[2 * sample_uidx + 1];
481 allele_codes[2 * sample_uidx + 1] = tmpval;
482 }
483 }
484 }
485 return;
486 }
487 // Unfortunately, we can't use GenoarrPhasedToAlleleCodes directly, since
488 // it's written for Python 1-byte bools instead of R 4-byte logical values.
489 // (probable todo: allow the no-phasepresent_buf part to be called
490 // separately)
491 //
492 // 0, 2 -> automatically phased. 3 -> NA_LOGICAL.
493 // 1 -> assume unphased; then change to phased as necessary when iterating
494 // over phasepresent.
495 int32_t* phasepresent_wbuf = &(as<LogicalVector>(phasepresent_buf)[0]);
496 plink2::GenoarrLookup256x4bx4(_pgv.genovec, kGenoToLogicalPhaseQuads, _subset_size, phasepresent_wbuf);
497 int32_t* allele_codes = &acbuf[0];
498 if (cur_allele_ct == 2) {
499 const uint64_t one = 1;
500 for (uint32_t phased_idx = 0; phased_idx != phasepresent_ct; ++phased_idx) {
501 const uintptr_t sample_uidx = plink2::BitIter1(phasepresent, &sample_uidx_base, &cur_bits);
502 phasepresent_wbuf[sample_uidx] = 1;
503 if (plink2::IsSet(phaseinfo, sample_uidx)) {
504 memcpy(&(allele_codes[2 * sample_uidx]), &one, sizeof(int64_t));
505 }
506 }
507 } else {
508 for (uint32_t phased_idx = 0; phased_idx != phasepresent_ct; ++phased_idx) {
509 const uintptr_t sample_uidx = plink2::BitIter1(phasepresent, &sample_uidx_base, &cur_bits);
510 phasepresent_wbuf[sample_uidx] = 1;
511 if (plink2::IsSet(phaseinfo, sample_uidx)) {
512 const int32_t tmpval = allele_codes[2 * sample_uidx];
513 allele_codes[2 * sample_uidx] = allele_codes[2 * sample_uidx + 1];
514 allele_codes[2 * sample_uidx + 1] = tmpval;
515 }
516 }
517 }
518 }
519
520 static const double kGenoToRNumcodePairs[8] ALIGNV16 = {0.0, 0.0, 0.0, 1.0, 1.0, 1.0, NA_REAL, NA_REAL};
521
522 void RPgenReader::ReadAllelesNumeric(NumericMatrix acbuf, Nullable<LogicalVector> phasepresent_buf, int variant_idx) {
523 if (!_info_ptr) {
524 stop("pgen is closed");
525 }
526 if ((acbuf.nrow() != 2) || (acbuf.ncol() != static_cast<int>(_subset_size))) {
527 char errstr_buf[256];
528 snprintf(errstr_buf, 256, "acbuf has wrong size (%dx%d; 2x%u expected)", acbuf.nrow(), acbuf.ncol(), _subset_size);
529 stop(errstr_buf);
530 }
531 ReadAllelesPhasedInternal(variant_idx);
532 double* allele_codes = &acbuf[0];
533 plink2::GenoarrLookup4x16b(_pgv.genovec, kGenoToRNumcodePairs, _subset_size, allele_codes);
534 const uintptr_t* allele_idx_offsets = _info_ptr->allele_idx_offsets;
535 uint32_t cur_allele_ct = 2;
536 if (allele_idx_offsets) {
537 cur_allele_ct = allele_idx_offsets[variant_idx + 1] - allele_idx_offsets[variant_idx];
538 if (cur_allele_ct != 2) {
539 stop("multiallelic support under development");
540 }
541 }
542 const uintptr_t* phasepresent = _pgv.phasepresent;
543 const uintptr_t* phaseinfo = _pgv.phaseinfo;
544 const uint32_t phasepresent_ct = _pgv.phasepresent_ct;
545 uintptr_t sample_uidx_base = 0;
546 uintptr_t cur_bits = phasepresent[0];
547 if (!phasepresent_buf.isNotNull()) {
548 if (cur_allele_ct == 2) {
549 for (uint32_t phased_idx = 0; phased_idx != phasepresent_ct; ++phased_idx) {
550 const uintptr_t sample_uidx = plink2::BitIter1(phasepresent, &sample_uidx_base, &cur_bits);
551 if (plink2::IsSet(phaseinfo, sample_uidx)) {
552 // 1|0
553 allele_codes[2 * sample_uidx] = 1.0;
554 allele_codes[2 * sample_uidx + 1] = 0.0;
555 }
556 }
557 } else {
558 for (uint32_t phased_idx = 0; phased_idx != phasepresent_ct; ++phased_idx) {
559 const uintptr_t sample_uidx = plink2::BitIter1(phasepresent, &sample_uidx_base, &cur_bits);
560 if (plink2::IsSet(phaseinfo, sample_uidx)) {
561 const double tmpval = allele_codes[2 * sample_uidx];
562 allele_codes[2 * sample_uidx] = allele_codes[2 * sample_uidx + 1];
563 allele_codes[2 * sample_uidx + 1] = tmpval;
564 }
565 }
566 }
567 return;
568 }
569 int32_t* phasepresent_wbuf = &(as<LogicalVector>(phasepresent_buf)[0]);
570 plink2::GenoarrLookup256x4bx4(_pgv.genovec, kGenoToLogicalPhaseQuads, _subset_size, phasepresent_wbuf);
571 if (cur_allele_ct == 2) {
572 for (uint32_t phased_idx = 0; phased_idx != phasepresent_ct; ++phased_idx) {
573 const uintptr_t sample_uidx = plink2::BitIter1(phasepresent, &sample_uidx_base, &cur_bits);
574 phasepresent_wbuf[sample_uidx] = 1;
575 if (plink2::IsSet(phaseinfo, sample_uidx)) {
576 allele_codes[2 * sample_uidx] = 1.0;
577 allele_codes[2 * sample_uidx + 1] = 0.0;
578 }
579 }
580 } else {
581 for (uint32_t phased_idx = 0; phased_idx != phasepresent_ct; ++phased_idx) {
582 const uintptr_t sample_uidx = plink2::BitIter1(phasepresent, &sample_uidx_base, &cur_bits);
583 phasepresent_wbuf[sample_uidx] = 1;
584 if (plink2::IsSet(phaseinfo, sample_uidx)) {
585 const double tmpval = allele_codes[2 * sample_uidx];
586 allele_codes[2 * sample_uidx] = allele_codes[2 * sample_uidx + 1];
587 allele_codes[2 * sample_uidx + 1] = tmpval;
588 }
589 }
590 }
591 }
592
593 void RPgenReader::ReadIntList(IntegerMatrix buf, IntegerVector variant_subset) {
594 if (!_info_ptr) {
595 stop("pgen is closed");
596 }
597 // assume that buf has the correct dimensions
598 const uintptr_t vsubset_size = variant_subset.size();
599 const uint32_t raw_variant_ct = _info_ptr->raw_variant_ct;
600 int32_t* buf_iter = &buf[0];
601 for (uintptr_t col_idx = 0; col_idx != vsubset_size; ++col_idx) {
602 uint32_t variant_idx = variant_subset[col_idx] - 1;
603 if (static_cast<uint32_t>(variant_idx) >= raw_variant_ct) {
604 char errstr_buf[256];
605 snprintf(errstr_buf, 256, "variant_subset element out of range (%d; must be 1..%u)", variant_idx + 1, raw_variant_ct);
606 stop(errstr_buf);
607 }
608 plink2::PglErr reterr = plink2::PgrGet(_subset_include_vec, _subset_index, _subset_size, variant_idx, _state_ptr, _pgv.genovec);
609 if (reterr != plink2::kPglRetSuccess) {
610 char errstr_buf[256];
611 snprintf(errstr_buf, 256, "PgrGet() error %d", static_cast<int>(reterr));
612 stop(errstr_buf);
613 }
614 plink2::GenoarrLookup256x4bx4(_pgv.genovec, kGenoRInt32Quads, _subset_size, buf_iter);
615 buf_iter = &(buf_iter[_subset_size]);
616 }
617 }
618
619 void RPgenReader::ReadList(NumericMatrix buf, IntegerVector variant_subset, bool meanimpute) {
620 if (!_info_ptr) {
621 stop("pgen is closed");
622 }
623 // assume that buf has the correct dimensions
624 const uintptr_t vsubset_size = variant_subset.size();
625 const uint32_t raw_variant_ct = _info_ptr->raw_variant_ct;
626 double* buf_iter = &buf[0];
627 for (uintptr_t col_idx = 0; col_idx != vsubset_size; ++col_idx) {
628 uint32_t variant_idx = variant_subset[col_idx] - 1;
629 if (static_cast<uint32_t>(variant_idx) >= raw_variant_ct) {
630 char errstr_buf[256];
631 snprintf(errstr_buf, 256, "variant_subset element out of range (%d; must be 1..%u)", variant_idx + 1, raw_variant_ct);
632 stop(errstr_buf);
633 }
634 uint32_t dosage_ct;
635 plink2::PglErr reterr = plink2::PgrGetD(_subset_include_vec, _subset_index, _subset_size, variant_idx, _state_ptr, _pgv.genovec, _pgv.dosage_present, _pgv.dosage_main, &dosage_ct);
636 if (reterr != plink2::kPglRetSuccess) {
637 char errstr_buf[256];
638 snprintf(errstr_buf, 256, "PgrGetD() error %d", static_cast<int>(reterr));
639 stop(errstr_buf);
640 }
641 if (!meanimpute) {
642 plink2::Dosage16ToDoubles(kGenoRDoublePairs, _pgv.genovec, _pgv.dosage_present, _pgv.dosage_main, _subset_size, dosage_ct, buf_iter);
643 } else {
644 plink2::ZeroTrailingNyps(_subset_size, _pgv.genovec);
645 if (plink2::Dosage16ToDoublesMeanimpute(_pgv.genovec, _pgv.dosage_present, _pgv.dosage_main, _subset_size, dosage_ct, buf_iter)) {
646 char errstr_buf[256];
647 snprintf(errstr_buf, 256, "variant %d has only missing dosages", variant_idx + 1);
648 stop(errstr_buf);
649 }
650 }
651 buf_iter = &(buf_iter[_subset_size]);
652 }
653 }
654
655 void RPgenReader::FillVariantScores(NumericVector result, NumericVector weights, Nullable<IntegerVector> variant_subset) {
656 if (!_info_ptr) {
657 stop("pgen is closed");
658 }
659 if (weights.size() != _subset_size) {
660 using namespace plink2;
661 char errstr_buf[256];
662 char* write_iter = strcpya_k(errstr_buf, "weights.size()=");
663 write_iter = wtoa(weights.size(), write_iter);
664 write_iter = strcpya_k(write_iter, " doesn't match pgen sample-subset size=");
665 write_iter = wtoa(_subset_size, write_iter);
666 *write_iter = '\0';
667 stop(errstr_buf);
668 }
669 const int raw_variant_ct = _info_ptr->raw_variant_ct;
670 const int* variant_idx_ints = nullptr;
671 uintptr_t variant_ct = raw_variant_ct;
672 if (variant_subset.isNotNull()) {
673 IntegerVector vs = as<IntegerVector>(variant_subset);
674 variant_idx_ints = &(vs[0]);
675 variant_ct = vs.size();
676 }
677 for (uintptr_t ulii = 0; ulii != variant_ct; ++ulii) {
678 int variant_idx = ulii;
679 if (variant_idx_ints) {
680 variant_idx = variant_idx_ints[ulii] - 1;
681 if ((variant_idx < 0) || (variant_idx >= raw_variant_ct)) {
682 char errstr_buf[256];
683 snprintf(errstr_buf, 256, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, raw_variant_ct);
684 stop(errstr_buf);
685 }
686 }
687 uint32_t dosage_ct;
688 plink2::PglErr reterr = plink2::PgrGetD(_subset_include_vec, _subset_index, _subset_size, variant_idx, _state_ptr, _pgv.genovec, _pgv.dosage_present, _pgv.dosage_main, &dosage_ct);
689 if (reterr != plink2::kPglRetSuccess) {
690 char errstr_buf[256];
691 snprintf(errstr_buf, 256, "PgrGetD() error %d", static_cast<int>(reterr));
692 stop(errstr_buf);
693 }
694 plink2::ZeroTrailingNyps(_subset_size, _pgv.genovec);
695 const double* wts = &(weights[0]);
696 result[ulii] = plink2::LinearCombinationMeanimpute(wts, _pgv.genovec, _pgv.dosage_present, _pgv.dosage_main, _subset_size, dosage_ct);
697 }
698 }
699
700 void RPgenReader::Close() {
701 // don't bother propagating file close errors for now
702 if (_info_ptr) {
703 CondReleaseRefcountedWptr(&_allele_idx_offsetsp);
704 CondReleaseRefcountedWptr(&_nonref_flagsp);
705 if (_info_ptr->vrtypes) {
706 plink2::aligned_free(_info_ptr->vrtypes);
707 }
708 plink2::PglErr reterr = plink2::kPglRetSuccess;
709 plink2::CleanupPgfi(_info_ptr, &reterr);
710 free(_info_ptr);
711 _info_ptr = nullptr;
712 }
713 if (_state_ptr) {
714 plink2::PglErr reterr = plink2::kPglRetSuccess;
715 plink2::CleanupPgr(_state_ptr, &reterr);
716 if (PgrGetFreadBuf(_state_ptr)) {
717 plink2::aligned_free(PgrGetFreadBuf(_state_ptr));
718 }
719 free(_state_ptr);
720 _state_ptr = nullptr;
721 }
722 _subset_size = 0;
723 }
724
725 void RPgenReader::SetSampleSubsetInternal(IntegerVector sample_subset_1based) {
726 const uint32_t raw_sample_ct = _info_ptr->raw_sample_ct;
727 const uint32_t raw_sample_ctv = plink2::DivUp(raw_sample_ct, plink2::kBitsPerVec);
728 const uint32_t raw_sample_ctaw = raw_sample_ctv * plink2::kWordsPerVec;
729 uintptr_t* sample_include = _subset_include_vec;
730 plink2::ZeroWArr(raw_sample_ctaw, sample_include);
731 const uint32_t subset_size = sample_subset_1based.size();
732 if (subset_size == 0) {
733 stop("Empty sample_subset is not currently permitted");
734 }
735 uint32_t sample_uidx = sample_subset_1based[0] - 1;
736 uint32_t idx = 0;
737 uint32_t next_uidx;
738 while (1) {
739 if (sample_uidx >= raw_sample_ct) {
740 char errstr_buf[256];
741 snprintf(errstr_buf, 256, "sample number out of range (%d; must be 1..%u)", static_cast<int>(sample_uidx + 1), raw_sample_ct);
742 stop(errstr_buf);
743 }
744 plink2::SetBit(sample_uidx, sample_include);
745 if (++idx == subset_size) {
746 break;
747 }
748 next_uidx = sample_subset_1based[idx] - 1;
749
750 // prohibit this since it implies that the caller expects genotypes to be
751 // returned in a different order
752 if (next_uidx <= sample_uidx) {
753 stop("sample_subset is not in strictly increasing order");
754 }
755 sample_uidx = next_uidx;
756 }
757 plink2::FillInterleavedMaskVec(sample_include, raw_sample_ctv, _subset_include_interleaved_vec);
758 const uint32_t raw_sample_ctl = plink2::DivUp(raw_sample_ct, plink2::kBitsPerWord);
759 plink2::FillCumulativePopcounts(sample_include, raw_sample_ctl, _subset_cumulative_popcounts);
760 plink2::PgrSetSampleSubsetIndex(_subset_cumulative_popcounts, _state_ptr, &_subset_index);
761 _subset_size = subset_size;
762 }
763
764 void RPgenReader::ReadMaybeSparseHardcallsInternal(int variant_idx, int file_difflist_len_limit, uint32_t* difflist_common_geno_ptr, uint32_t* difflist_len_ptr) {
765 // TODO
766 }
767
768 void RPgenReader::ReadAllelesPhasedInternal(int variant_idx) {
769 if (static_cast<uint32_t>(variant_idx) >= _info_ptr->raw_variant_ct) {
770 char errstr_buf[256];
771 snprintf(errstr_buf, 256, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct);
772 stop(errstr_buf);
773 }
774 plink2::PglErr reterr = plink2::PgrGetMP(_subset_include_vec, _subset_index, _subset_size, variant_idx, _state_ptr, &_pgv);
775 if (reterr != plink2::kPglRetSuccess) {
776 char errstr_buf[256];
777 snprintf(errstr_buf, 256, "PgrGetMP() error %d", static_cast<int>(reterr));
778 stop(errstr_buf);
779 }
780 }
781
782 RPgenReader::~RPgenReader() {
783 Close();
784 }
785
786 //' Opens a .pgen or PLINK 1 .bed file.
787 //'
788 //' @param filename .pgen/.bed file path.
789 //' @param pvar Object (see NewPvar()) corresponding to the .pgen's companion
790 //' .pvar; technically optional, but necessary for some functionality. In
791 //' particular, at multiallelic variants, all ALT alleles may be collapsed
792 //' together when .pvar information is not available.
793 //' @param raw_sample_ct Number of samples in file; required if it's a PLINK 1
794 //' .bed file, otherwise optional.
795 //' @param sample_subset List of 1-based positions of samples to load;
796 //' optional, all samples are loaded if this is not specified.
797 //' @return A pgen object, which can be queried for genotype/dosage data.
798 //' @export
799 // [[Rcpp::export]]
800 SEXP NewPgen(String filename, Nullable<List> pvar = R_NilValue,
801 Nullable<int> raw_sample_ct = R_NilValue,
802 Nullable<IntegerVector> sample_subset = R_NilValue) {
803 XPtr<class RPgenReader> pgen(new RPgenReader(), true);
804 pgen->Load(filename, pvar, raw_sample_ct, sample_subset);
805 return List::create(_["class"] = "pgen", _["pgen"] = pgen);
806 }
807
808 //' Returns the number of samples in the file.
809 //'
810 //' @param pgen Object returned by NewPgen().
811 //' @return Number of samples.
812 //' @export
813 // [[Rcpp::export]]
814 int GetRawSampleCt(List pgen) {
815 if (strcmp_r_c(pgen[0], "pgen")) {
816 stop("pgen is not a pgen object");
817 }
818 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
819 return rp->GetRawSampleCt();
820 }
821
822 //' Returns the number of variants in the file.
823 //'
824 //' @param pvar_or_pgen Object returned by NewPvar() or NewPgen().
825 //' @return Number of variants.
826 //' @export
827 // [[Rcpp::export]]
828 int GetVariantCt(List pvar_or_pgen) {
829 const char* c_str = as<String>(pvar_or_pgen[0]).get_cstring();
830 if (!strcmp(c_str, "pvar")) {
831 XPtr<class RPvar> rp = as<XPtr<class RPvar> >(pvar_or_pgen[1]);
832 return rp->GetVariantCt();
833 } else if (!strcmp(c_str, "pgen")) {
834 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pvar_or_pgen[1]);
835 return rp->GetVariantCt();
836 }
837 stop("pvar_or_pgen is not a pvar or pgen object");
838 }
839
840 // Throughout this codebase, _num indicates R 1-based indexing.
841
842 //' Returns the effective number of alleles for a variant. Note that if no
843 //' pvar was provided to the NewPgen() call, this function may return 2 even at
844 //' multiallelic variants, since the .pgen may not store allele-count
845 //' information.
846 //'
847 //' @param pvar_or_pgen Object returned by NewPvar() or NewPgen().
848 //' @param variant_num Variant index (1-based).
849 //' @return max(2, <number of alleles the variant_numth variant is known to
850 //' have>). Note that if no
851 //' @export
852 // [[Rcpp::export]]
853 int GetAlleleCt(List pvar_or_pgen, int variant_num) {
854 const char* c_str = as<String>(pvar_or_pgen[0]).get_cstring();
855 const uint32_t variant_idx = variant_num - 1;
856 if (!strcmp(c_str, "pvar")) {
857 XPtr<class RPvar> rp = as<XPtr<class RPvar> >(pvar_or_pgen[1]);
858 return rp->GetAlleleCt(variant_idx);
859 } else if (!strcmp(c_str, "pgen")) {
860 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pvar_or_pgen[1]);
861 return rp->GetAlleleCt(variant_idx);
862 }
863 stop("pvar_or_pgen is not a pvar or pgen object");
864 }
865
866 //' Returns the maximum GetAlleleCt() value across all variants in the file.
867 //'
868 //' @param pvar_or_pgen Object returned by NewPvar() or NewPgen().
869 //' @return Maximum GetAlleleCt() value across all variants.
870 //' @export
871 // [[Rcpp::export]]
872 int GetMaxAlleleCt(List pvar_or_pgen) {
873 const char* c_str = as<String>(pvar_or_pgen[0]).get_cstring();
874 if (!strcmp(c_str, "pvar")) {
875 XPtr<class RPvar> rp = as<XPtr<class RPvar> >(pvar_or_pgen[1]);
876 return rp->GetMaxAlleleCt();
877 } else if (!strcmp(c_str, "pgen")) {
878 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pvar_or_pgen[1]);
879 return rp->GetMaxAlleleCt();
880 }
881 stop("pvar_or_pgen is not a pvar or pgen object");
882 }
883
884 //' Returns whether explicitly phased hardcalls are present.
885 //'
886 //' @param pgen Object returned by NewPgen().
887 //' @return TRUE if the file contains at least one phased heterozygous
888 //' hardcall, FALSE otherwise.
889 //' @export
890 // [[Rcpp::export]]
891 bool HardcallPhasePresent(List pgen) {
892 if (strcmp_r_c(pgen[0], "pgen")) {
893 stop("pgen is not a pgen object");
894 }
895 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
896 return rp->HardcallPhasePresent();
897 }
898
899 //' Returns a numeric buffer that Read() or ReadHardcalls() can load to.
900 //'
901 //' @param pgen Object returned by NewPgen().
902 //' @return Numeric vector with appropriate length for Read() and
903 //' ReadHardcalls().
904 //' @export
905 // [[Rcpp::export]]
906 NumericVector Buf(List pgen) {
907 if (strcmp_r_c(pgen[0], "pgen")) {
908 stop("pgen is not a pgen object");
909 }
910 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
911 return NumericVector(rp->GetSubsetSize());
912 }
913
914 //' Returns an empty two-row numeric matrix that ReadAlleles() can load to.
915 //'
916 //' @param pgen Object returned by NewPgen().
917 //' @return Numeric matrix with two rows, and appropriate number of columns for
918 //' ReadAlleles().
919 //' @export
920 // [[Rcpp::export]]
921 NumericVector AlleleCodeBuf(List pgen) {
922 if (strcmp_r_c(pgen[0], "pgen")) {
923 stop("pgen is not a pgen object");
924 }
925 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
926 return NumericMatrix(2, rp->GetSubsetSize());
927 }
928
929 //' Returns an integer buffer that ReadHardcalls() can load to.
930 //'
931 //' @param pgen Object returned by NewPgen().
932 //' @return Integer vector with appropriate length for ReadHardcalls().
933 //' @export
934 // [[Rcpp::export]]
935 IntegerVector IntBuf(List pgen) {
936 if (strcmp_r_c(pgen[0], "pgen")) {
937 stop("pgen is not a pgen object");
938 }
939 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
940 return IntegerVector(rp->GetSubsetSize());
941 }
942
943 //' Returns an empty two-row integer matrix that ReadAlleles() can load to.
944 //'
945 //' @param pgen Object returned by NewPgen().
946 //' @return Integer matrix with two rows, and appropriate number of columns for
947 //' ReadAlleles().
948 //' @export
949 // [[Rcpp::export]]
950 IntegerVector IntAlleleCodeBuf(List pgen) {
951 if (strcmp_r_c(pgen[0], "pgen")) {
952 stop("pgen is not a pgen object");
953 }
954 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
955 return IntegerMatrix(2, rp->GetSubsetSize());
956 }
957
958 //' Returns a bool buffer that ReadAlleles() can load phasing information to.
959 //'
960 //' @param pgen Object returned by NewPgen().
961 //' @return Logical vector with appropriate length for ReadAlleles().
962 //' @export
963 // [[Rcpp::export]]
964 LogicalVector BoolBuf(List pgen) {
965 if (strcmp_r_c(pgen[0], "pgen")) {
966 stop("pgen is not a pgen object");
967 }
968 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
969 return LogicalVector(rp->GetSubsetSize());
970 }
971
972 //' Loads the variant_numth variant, and then fills buf with \{0, 1, 2, NA\}
973 //' values indicating the number of copies of the first ALT (or user-specified)
974 //' allele each sample has.
975 //'
976 //' This function treats the data as diploid; you can divide by 2, and then
977 //' treat 0.5 as NA, if it's actually haploid.
978 //'
979 //' @param pgen Object returned by NewPgen().
980 //' @param buf Buffer returned by Buf() or IntBuf().
981 //' @param variant_num Variant index (1-based).
982 //' @param allele_num Allele index; 1 corresponds to REF, 2 to the first ALT
983 //' allele, 3 to the second ALT allele if it exists, etc. Optional, defaults
984 //' to 2.
985 //' @return No return value, called for buf-filling side-effect.
986 //' @export
987 // [[Rcpp::export]]
988 void ReadHardcalls(List pgen, SEXP buf, int variant_num, int allele_num = 2) {
989 if (strcmp_r_c(pgen[0], "pgen")) {
990 stop("pgen is not a pgen object");
991 }
992 if (Rf_isMatrix(buf)) {
993 // otherwise the original buffer is not modified by Read[Int]Hardcalls
994 stop("buf must be a non-matrix vector");
995 }
996 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
997 const int variant_idx = variant_num - 1;
998 const int allele_idx = allele_num - 1;
999 if (TYPEOF(buf) == REALSXP) {
1000 rp->ReadHardcalls(buf, variant_idx, allele_idx);
1001 } else if (TYPEOF(buf) == INTSXP) {
1002 rp->ReadIntHardcalls(buf, variant_idx, allele_idx);
1003 } else {
1004 stop("Unsupported buf type");
1005 }
1006 }
1007
1008 //' Returns whether hardcalls for the variant_numth variant and given allele
1009 //' are represented in a sparse manner that is supported by
1010 //' ReadSparseHardcalls().
1011 //'
1012 //' @param pgen Object returned by NewPgen().
1013 //' @param variant_num Variant index (1-based).
1014 //' @param allele_num Allele index; 1 corresponds to REF, 2 to the first ALT
1015 //' allele, 3 to the second ALT allele if it exists, etc. Optional, defaults
1016 //' to 2.
1017 //' @return True iff the (variant, allele) pair has a sparse representation
1018 //' that can be returned by ReadSparseHardcalls().
1019 //' @export
1020 // [[Rcpp::export]]
1021 bool HasSparseHardcalls(List pgen, int variant_num, int allele_num = 2) {
1022 if (strcmp_r_c(pgen[0], "pgen")) {
1023 stop("pgen is not a pgen object");
1024 }
1025 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
1026 const int variant_idx = variant_num - 1;
1027 const uint32_t vrtype = rp->GetVrtype(variant_idx);
1028 // Don't support multiallelic variants outside the trivial REF case for now.
1029 if (allele_num == 1) {
1030 return ((vrtype & 7) == 6);
1031 } else if (allele_num == 2) {
1032 return ((vrtype & 15) == 4);
1033 } else {
1034 return false;
1035 }
1036 }
1037
1038 //' If HasSparseHardcalls() is true, returns a sparse representation for the
1039 //' (variant, allele) pair. If HasSparseHardcalls() is false, the function
1040 //' fails.
1041 //'
1042 //' @param pgen Object returned by NewPgen().
1043 //' @param variant_num Variant index (1-based).
1044 //' @param allele_num Allele index; 1 corresponds to REF, 2 to the first ALT
1045 //' allele, 3 to the second ALT allele if it exists, etc. Optional, defaults
1046 //' to 2.
1047 //' @param return_ints Whether to make the "counts" component of the return
1048 //' value an IntegerVector instead of a NumericVector; defaults to false.
1049 //' @return Either an empty list, in which case buf is filled in the same
1050 //' mannerObject where "sample_ids" is an increasing sequence of positive
1051 //' integers listing which samples have the allele, and "counts" is a vector
1052 //' listing the allele counts for those samples.
1053 //' @export
1054 // [[Rcpp::export]]
1055 List ReadSparseHardcalls(List pgen, int variant_num, int allele_num = 2, bool return_ints = false) {
1056 if (strcmp_r_c(pgen[0], "pgen")) {
1057 stop("pgen is not a pgen object");
1058 }
1059 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
1060 const int variant_idx = variant_num - 1;
1061 const uint32_t vrtype = rp->GetVrtype(variant_idx);
1062 const bool is_supported_sparse =
1063 ((allele_num == 1) && ((vrtype & 7) == 6)) ||
1064 ((allele_num == 2) && ((vrtype & 15) == 4));
1065 if (!is_supported_sparse) {
1066 stop("(variant, allele) does not have supported sparse representation");
1067 }
1068 stop("ReadSparseHardcalls() is under development");
1069 IntegerVector sample_ids(0);
1070 if (return_ints) {
1071 IntegerVector integer_counts(0);
1072 return List::create(
1073 _["sample_ids"] = sample_ids,
1074 _["counts"] = integer_counts
1075 );
1076 } else {
1077 NumericVector numeric_counts(0);
1078 return List::create(
1079 _["sample_ids"] = sample_ids,
1080 _["counts"] = numeric_counts
1081 );
1082 }
1083 }
1084
1085 //' Loads the variant_numth variant, and then fills buf with numeric dosages
1086 //' in [0, 2] indicating the dosages of the first ALT (or user-specified)
1087 //' allele for each sample, with missing values represented by NA.
1088 //'
1089 //' This function treats the data as diploid; divide by 2 to obtain haploid
1090 //' dosages.
1091 //'
1092 //' @param pgen Object returned by NewPgen().
1093 //' @param buf Buffer returned by Buf().
1094 //' @param variant_num Variant index (1-based).
1095 //' @param allele_num Allele index; 1 corresponds to REF, 2 to the first ALT
1096 //' allele, 3 to the second ALT allele if it exists, etc. Optional, defaults
1097 //' to 2.
1098 //' @return No return value, called for buf-filling side-effect.
1099 //' @export
1100 // [[Rcpp::export]]
1101 void Read(List pgen, NumericVector buf, int variant_num, int allele_num = 2) {
1102 if (strcmp_r_c(pgen[0], "pgen")) {
1103 stop("pgen is not a pgen object");
1104 }
1105 if (Rf_isMatrix(buf)) {
1106 stop("buf must be a non-matrix vector");
1107 }
1108 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
1109 rp->Read(buf, variant_num - 1, allele_num - 1);
1110 }
1111
1112 //' Loads the variant_numth variant, and then fills acbuf with integer allele
1113 //' codes, where each column of the buffer corresponds to a sample. An allele
1114 //' code of 0 corresponds to the REF allele, 1 to the first ALT, 2 to the
1115 //' second ALT, etc. Missing hardcalls are represented by a pair of NA codes.
1116 //'
1117 //' This function treats the data as diploid. If it's really haploid, you may
1118 //' want to compare the two rows, and then treat samples where the allele codes
1119 //' differ as missing values.
1120 //'
1121 //' @param pgen Object returned by NewPgen().
1122 //' @param acbuf Buffer returned by AlleleCodeBuf() or IntAlleleCodeBuf().
1123 //' @param variant_num Variant index (1-based).
1124 //' @param phasepresent_buf Buffer returned by BoolBuf(). Optional; if
1125 //' provided, elements are set to true when the sample has known phase. Most
1126 //' of these values will be TRUE even when the raw data is unphased, because
1127 //' homozygous genotypes always have known phase. (Missing genotypes are
1128 //' considered to have unknown phase.)
1129 //' @return No return value, called for acbuf-filling side-effect.
1130 //' @export
1131 // [[Rcpp::export]]
1132 void ReadAlleles(List pgen, SEXP acbuf, int variant_num, Nullable<LogicalVector> phasepresent_buf = R_NilValue) {
1133 if (strcmp_r_c(pgen[0], "pgen")) {
1134 stop("pgen is not a pgen object");
1135 }
1136 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
1137 const int variant_idx = variant_num - 1;
1138 // in this case, integer may be a more appropriate default than numeric?
1139 if (TYPEOF(acbuf) == INTSXP) {
1140 rp->ReadAlleles(acbuf, phasepresent_buf, variant_idx);
1141 } else if (TYPEOF(acbuf) == REALSXP) {
1142 rp->ReadAllelesNumeric(acbuf, phasepresent_buf, variant_idx);
1143 } else {
1144 stop("Unsupported acbuf type");
1145 }
1146 }
1147
1148 //' Load hardcalls for multiple variants as an integer matrix.
1149 //'
1150 //' This function treats the data as diploid; you can divide by 2, and then
1151 //' treat 0.5 as NA, if it's actually haploid.
1152 //'
1153 //' @param pgen Object returned by NewPgen().
1154 //' @param variant_subset Integer vector containing 1-based indexes of variants
1155 //' to load.
1156 //' @return Integer matrix, where rows correspond to samples, columns
1157 //' correspond to variant_subset, and values are in \{0, 1, 2, NA\} indicating
1158 //' the number of hardcall ALT allele copies. For multiallelic variants, all
1159 //' ALT alleles are combined.
1160 //' @export
1161 // [[Rcpp::export]]
1162 IntegerMatrix ReadIntList(List pgen, IntegerVector variant_subset) {
1163 // return value: rows = samples, columns = variants (from R's perspective)
1164 if (strcmp_r_c(pgen[0], "pgen")) {
1165 stop("pgen is not a pgen object");
1166 }
1167 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
1168 IntegerMatrix result(rp->GetSubsetSize(), variant_subset.size());
1169 rp->ReadIntList(result, variant_subset);
1170 return result;
1171 }
1172
1173 //' Load dosages for multiple variants as a numeric matrix.
1174 //'
1175 //' This function treats the data as diploid; divide by 2 to obtain haploid
1176 //' dosages.
1177 //'
1178 //' @param pgen Object returned by NewPgen().
1179 //' @param variant_subset Integer vector containing 1-based indexes of variants
1180 //' to load.
1181 //' @param meanimpute Optional; if true, missing values are mean-imputed
1182 //' instead of being represented by NA.
1183 //' @return Numeric matrix, where rows correspond to samples, and columns
1184 //' correspond to variant_subset. Values are in [0, 2] indicating ALT
1185 //' allele dosages, or NA for missing dosages. For multiallelic variants, all
1186 //' ALT alelles are combined.
1187 //' @export
1188 // [[Rcpp::export]]
1189 NumericMatrix ReadList(List pgen, IntegerVector variant_subset, bool meanimpute = false) {
1190 if (strcmp_r_c(pgen[0], "pgen")) {
1191 stop("pgen is not a pgen object");
1192 }
1193 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
1194 NumericMatrix result(rp->GetSubsetSize(), variant_subset.size());
1195 rp->ReadList(result, variant_subset, meanimpute);
1196 return result;
1197 }
1198
1199 //' Compute variant scores.
1200 //'
1201 //' This function treats the data as diploid; divide by 2 to obtain scores
1202 //' based on a haploid dosage matrix.
1203 //'
1204 //' @param pgen Object returned by NewPgen().
1205 //' @param weights Sample weights.
1206 //' @param variant_subset Integer vector containing 1-based indexes of variants
1207 //' to include in the dosage matrix. Optional; by default, all variants are
1208 //' included.
1209 //' @return Numeric vector, containing product of sample-weight vector and the
1210 //' specified subset of the dosage matrix.
1211 //' @export
1212 // [[Rcpp::export]]
1213 NumericVector VariantScores(List pgen, NumericVector weights,
1214 Nullable<IntegerVector> variant_subset = R_NilValue) {
1215 if (strcmp_r_c(pgen[0], "pgen")) {
1216 stop("pgen is not a pgen object");
1217 }
1218 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
1219 int variant_ct;
1220 if (variant_subset.isNotNull()) {
1221 variant_ct = as<IntegerVector>(variant_subset).size();
1222 } else {
1223 variant_ct = rp->GetVariantCt();
1224 }
1225 NumericVector result(variant_ct);
1226 rp->FillVariantScores(result, weights, variant_subset);
1227 return result;
1228 }
1229
1230 //' Closes a pgen object, releasing resources.
1231 //'
1232 //' @param pgen Object returned by NewPgen().
1233 //' @return No return value, called for side-effect.
1234 //' @export
1235 // [[Rcpp::export]]
1236 void ClosePgen(List pgen) {
1237 if (strcmp_r_c(pgen[0], "pgen")) {
1238 stop("pgen is not a pgen object");
1239 }
1240 XPtr<class RPgenReader> rp = as<XPtr<class RPgenReader> >(pgen[1]);
1241 rp->Close();
1242 }