Debian Codegraph @

include/pgenlib_read.cc

raw
1 // This library is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
2 // Christopher Chang.
3 //
4 // This library is free software: you can redistribute it and/or modify it
5 // under the terms of the GNU Lesser General Public License as published by the
6 // Free Software Foundation; either version 3 of the License, or (at your
7 // option) any later version.
8 //
9 // This library is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
12 // for more details.
13 //
14 // You should have received a copy of the GNU Lesser General Public License
15 // along with this library. If not, see <http://www.gnu.org/licenses/>.
16
17
18 #include "pgenlib_read.h"
19
20 #include <errno.h>
21
22 #ifdef __cplusplus
23 namespace plink2 {
24 #endif
25
26 static inline PgenReaderMain* GetPgrp(PgenReader* pgr_ptr) {
27 return &GET_PRIVATE(*pgr_ptr, m);
28 }
29
30 static inline const uint32_t* GetSicp(PgrSampleSubsetIndex pssi) {
31 return GET_PRIVATE(pssi, cumulative_popcounts);
32 }
33
34 // The subset of this codebase used by pgenlibr (which is compiled with
35 // -DNO_UNALIGNED and -DPGENLIB_NOPRINT) is now subject to additional
36 // restrictions. In particular:
37 // - No unaligned loads/stores/pointers, or other undefined behavior.
38 // - The PRI{d,u}PTR and PRI{d,u}64 printf format-specifiers cannot be used. I
39 // hope to remove this restriction later, but for now they make Windows
40 // compilation a clusterfuck.
41 // - No exit(), or printing to stdout/stderr.
42 // - No flexible array members.
43 // - Not a restriction yet, but we want to properly distinguish between
44 // __LP64__ and USE_SSE2.
45 #ifdef USE_SSE2
46 void SmallGenoarrCount3FreqIncr(const unsigned char* genoarrb_iter, uint32_t byte_ct, uint32_t* even_ctp, uint32_t* odd_ctp, uint32_t* bothset_ctp) {
47 for (uint32_t bytes_left = byte_ct; ; ) {
48 uintptr_t cur_geno_word;
49 if (bytes_left < kBytesPerWord) {
50 if (!bytes_left) {
51 return;
52 }
53 cur_geno_word = ProperSubwordLoad(genoarrb_iter, bytes_left);
54 bytes_left = 0;
55 } else {
56 CopyFromUnalignedIncrW(&cur_geno_word, &genoarrb_iter);
57 bytes_left -= kBytesPerWord;
58 }
59 const uintptr_t cur_geno_word_high = kMask5555 & (cur_geno_word >> 1);
60 *even_ctp += Popcount01Word(cur_geno_word & kMask5555);
61 *odd_ctp += Popcount01Word(cur_geno_word_high);
62 *bothset_ctp += Popcount01Word(cur_geno_word & cur_geno_word_high);
63 }
64 }
65 #endif
66
67 void GenoarrbCountFreqs(const unsigned char* genoarrb, uint32_t sample_ct, STD_ARRAY_REF(uint32_t, 4) genocounts) {
68 // does not read past the end of genoarrb
69 uint32_t even_ct = 0;
70 uint32_t odd_ct = 0;
71 uint32_t bothset_ct = 0;
72 #ifndef USE_SSE2
73 const uintptr_t* geno_firstw_start;
74 const uint32_t lead_byte_ct = AlignKToW(genoarrb, &geno_firstw_start);
75 uint32_t byte_ct = NypCtToByteCt(sample_ct);
76 uintptr_t cur_geno_word;
77 uint32_t fullword_ct;
78 uint32_t trail_byte_ct;
79 if (lead_byte_ct) {
80 if (lead_byte_ct >= byte_ct) {
81 cur_geno_word = ProperSubwordLoad(genoarrb, byte_ct);
82 goto GenoarrbCountFreqsLastWord;
83 }
84 cur_geno_word = ProperSubwordLoad(genoarrb, lead_byte_ct);
85 const uintptr_t cur_geno_word_high = kMask5555 & (cur_geno_word >> 1);
86 even_ct += Popcount01Word(cur_geno_word & kMask5555);
87 odd_ct += Popcount01Word(cur_geno_word_high);
88 bothset_ct += Popcount01Word(cur_geno_word & cur_geno_word_high);
89 byte_ct -= lead_byte_ct;
90 }
91 fullword_ct = byte_ct / kBytesPerWord;
92 for (uint32_t widx = 0; widx != fullword_ct; ++widx) {
93 cur_geno_word = geno_firstw_start[widx];
94 const uintptr_t cur_geno_word_high = kMask5555 & (cur_geno_word >> 1);
95 even_ct += Popcount01Word(cur_geno_word & kMask5555);
96 odd_ct += Popcount01Word(cur_geno_word_high);
97 bothset_ct += Popcount01Word(cur_geno_word & cur_geno_word_high);
98 }
99 trail_byte_ct = byte_ct % kBytesPerWord;
100 if (trail_byte_ct) {
101 cur_geno_word = ProperSubwordLoad(&(geno_firstw_start[fullword_ct]), trail_byte_ct);
102 GenoarrbCountFreqsLastWord:
103 const uintptr_t cur_geno_word_high = kMask5555 & (cur_geno_word >> 1);
104 even_ct += Popcount01Word(cur_geno_word & kMask5555);
105 odd_ct += Popcount01Word(cur_geno_word_high);
106 bothset_ct += Popcount01Word(cur_geno_word & cur_geno_word_high);
107 }
108 #else // USE_SSE2
109 const uint32_t lead_byte_ct = (-R_CAST(uintptr_t, genoarrb)) % kBytesPerVec;
110 const unsigned char* genoarrb_iter;
111 uint32_t trail_ct;
112 if (sample_ct >= lead_byte_ct * 4 + (6 * kNypsPerVec)) {
113 // Only enter this branch if we can execute at least one iteration of the
114 // main vectorized loop.
115 const uint32_t remaining_sample_ct = sample_ct - 4 * lead_byte_ct;
116 SmallGenoarrCount3FreqIncr(genoarrb, lead_byte_ct, &even_ct, &odd_ct, &bothset_ct);
117 genoarrb_iter = &(genoarrb[lead_byte_ct]); // now vector-aligned
118 const uint32_t remaining_full_vec_ct = remaining_sample_ct / kNypsPerVec;
119 uint32_t even_ct_incr;
120 uint32_t odd_ct_incr;
121 uint32_t bothset_ct_incr;
122 const uint32_t vec_ct = remaining_full_vec_ct - (remaining_full_vec_ct % 6);
123 Count3FreqVec6(genoarrb_iter, vec_ct, &even_ct_incr, &odd_ct_incr, &bothset_ct_incr);
124 even_ct += even_ct_incr;
125 odd_ct += odd_ct_incr;
126 bothset_ct += bothset_ct_incr;
127 genoarrb_iter = &(genoarrb_iter[kBytesPerVec * vec_ct]);
128 trail_ct = remaining_sample_ct - (vec_ct * kNypsPerVec);
129 } else {
130 genoarrb_iter = genoarrb;
131 trail_ct = sample_ct;
132 }
133 const uint32_t trail_byte_ct = NypCtToByteCt(trail_ct);
134 SmallGenoarrCount3FreqIncr(genoarrb_iter, trail_byte_ct, &even_ct, &odd_ct, &bothset_ct);
135 #endif
136 genocounts[0] = sample_ct + bothset_ct - even_ct - odd_ct;
137 genocounts[1] = even_ct - bothset_ct;
138 genocounts[2] = odd_ct - bothset_ct;
139 genocounts[3] = bothset_ct;
140 }
141
142 void GenoarrbCountSubsetFreqs(const unsigned char* genoarrb, const uintptr_t* __restrict sample_include_interleaved_vec, uint32_t raw_sample_ct, uint32_t sample_ct, STD_ARRAY_REF(uint32_t, 4) genocounts) {
143 // does not read past the end of genoarrb
144 const uint32_t raw_sample_ctv2 = NypCtToVecCt(raw_sample_ct);
145 uint32_t even_ct;
146 uint32_t odd_ct;
147 uint32_t bothset_ct;
148 uint32_t vec_idx = raw_sample_ctv2 - (raw_sample_ctv2 % 6);
149 CountSubset3FreqVec6(genoarrb, R_CAST(const VecW*, sample_include_interleaved_vec), vec_idx, &even_ct, &odd_ct, &bothset_ct);
150 const unsigned char* genoarrb_iter = &(genoarrb[kBytesPerVec * vec_idx]);
151 #ifdef __LP64__
152 const uintptr_t* interleaved_mask_iter = &(sample_include_interleaved_vec[vec_idx * (kWordsPerVec / 2)]);
153 #else
154 // bugfix (19 Jul 2018): (kWordsPerVec / 2) doesn't work in 32-bit case
155 const uintptr_t* interleaved_mask_iter = &(sample_include_interleaved_vec[(vec_idx * kWordsPerVec) / 2]);
156 #endif
157 #ifdef USE_AVX2
158 const uint32_t halfvec_idx_trail = (raw_sample_ct + 3) / (kBitsPerVec / 4);
159 uintptr_t mask_base1 = 0;
160 uintptr_t mask_base2 = 0;
161 uintptr_t mask_base3 = 0;
162 uintptr_t mask_base4 = 0;
163 for (; vec_idx != raw_sample_ctv2; ++vec_idx) {
164 uintptr_t mask_word1;
165 uintptr_t mask_word2;
166 uintptr_t mask_word3;
167 uintptr_t mask_word4;
168 if (!(vec_idx % 2)) {
169 mask_base1 = *interleaved_mask_iter++;
170 mask_base2 = *interleaved_mask_iter++;
171 mask_base3 = *interleaved_mask_iter++;
172 mask_base4 = *interleaved_mask_iter++;
173 mask_word1 = mask_base1 & kMask5555;
174 mask_word2 = mask_base2 & kMask5555;
175 mask_word3 = mask_base3 & kMask5555;
176 mask_word4 = mask_base4 & kMask5555;
177 } else {
178 mask_word1 = (mask_base1 >> 1) & kMask5555;
179 mask_word2 = (mask_base2 >> 1) & kMask5555;
180 mask_word3 = (mask_base3 >> 1) & kMask5555;
181 mask_word4 = (mask_base4 >> 1) & kMask5555;
182 }
183 uint32_t vechalf_idx = 0;
184 while (1) {
185 uintptr_t cur_geno_word1;
186 uintptr_t cur_geno_word2;
187 if (2 * vec_idx + vechalf_idx < halfvec_idx_trail) {
188 CopyFromUnalignedIncrW(&cur_geno_word1, &genoarrb_iter);
189 CopyFromUnalignedIncrW(&cur_geno_word2, &genoarrb_iter);
190 } else {
191 // bugfix (19 May 2022): this was in 0..31 when it needed to be in
192 // 0..15
193 const uint32_t remaining_byte_ct = NypCtToByteCt(raw_sample_ct) % (kBytesPerVec / 2);
194 // todo: check if this harms usual-case loop efficiency
195 vechalf_idx = 1;
196 if (remaining_byte_ct < kBytesPerWord) {
197 cur_geno_word1 = ProperSubwordLoad(genoarrb_iter, remaining_byte_ct);
198 cur_geno_word2 = 0;
199 } else {
200 CopyFromUnalignedIncrW(&cur_geno_word1, &genoarrb_iter);
201 cur_geno_word2 = ProperSubwordLoad(genoarrb_iter, remaining_byte_ct - kBytesPerWord);
202 }
203 }
204 const uintptr_t cur_geno_word1_high_masked = mask_word1 & (cur_geno_word1 >> 1);
205 const uintptr_t cur_geno_word2_high_masked = mask_word2 & (cur_geno_word2 >> 1);
206 even_ct += PopcountWord(((cur_geno_word1 & mask_word1) << 1) | (cur_geno_word2 & mask_word2));
207 odd_ct += PopcountWord((cur_geno_word1_high_masked << 1) | cur_geno_word2_high_masked);
208 bothset_ct += PopcountWord(((cur_geno_word1 & cur_geno_word1_high_masked) << 1) | (cur_geno_word2 & cur_geno_word2_high_masked));
209 if (vechalf_idx) {
210 break;
211 }
212 ++vechalf_idx;
213 mask_word1 = mask_word3;
214 mask_word2 = mask_word4;
215 }
216 }
217 #else // not USE_AVX2
218 const uint32_t vec_idx_trail = (raw_sample_ct + 3) / kNypsPerVec;
219 # ifdef USE_SSE2
220 uintptr_t mask_base1 = 0;
221 uintptr_t mask_base2 = 0;
222 for (; vec_idx != raw_sample_ctv2; ++vec_idx) {
223 uintptr_t mask_word1;
224 uintptr_t mask_word2;
225 if (!(vec_idx % 2)) {
226 mask_base1 = *interleaved_mask_iter++;
227 mask_base2 = *interleaved_mask_iter++;
228 mask_word1 = mask_base1 & kMask5555;
229 mask_word2 = mask_base2 & kMask5555;
230 } else {
231 mask_word1 = (mask_base1 >> 1) & kMask5555;
232 mask_word2 = (mask_base2 >> 1) & kMask5555;
233 }
234 uintptr_t cur_geno_word1;
235 uintptr_t cur_geno_word2;
236 if (vec_idx < vec_idx_trail) {
237 CopyFromUnalignedIncrW(&cur_geno_word1, &genoarrb_iter);
238 CopyFromUnalignedIncrW(&cur_geno_word2, &genoarrb_iter);
239 } else {
240 const uint32_t remaining_byte_ct = NypCtToByteCt(raw_sample_ct) % kBytesPerVec;
241 if (remaining_byte_ct < kBytesPerWord) {
242 cur_geno_word1 = ProperSubwordLoad(genoarrb_iter, remaining_byte_ct);
243 cur_geno_word2 = 0;
244 } else {
245 CopyFromUnalignedIncrW(&cur_geno_word1, &genoarrb_iter);
246 cur_geno_word2 = ProperSubwordLoad(genoarrb_iter, remaining_byte_ct - kBytesPerWord);
247 }
248 }
249 const uintptr_t cur_geno_word1_high_masked = mask_word1 & (cur_geno_word1 >> 1);
250 const uintptr_t cur_geno_word2_high_masked = mask_word2 & (cur_geno_word2 >> 1);
251 # ifdef USE_SSE42
252 even_ct += PopcountWord(((cur_geno_word1 & mask_word1) << 1) | (cur_geno_word2 & mask_word2));
253 odd_ct += PopcountWord((cur_geno_word1_high_masked << 1) | cur_geno_word2_high_masked);
254 bothset_ct += PopcountWord(((cur_geno_word1 & cur_geno_word1_high_masked) << 1) | (cur_geno_word2 & cur_geno_word2_high_masked));
255 # else
256 even_ct += NypsumWord((cur_geno_word1 & mask_word1) + (cur_geno_word2 & mask_word2));
257 odd_ct += NypsumWord(cur_geno_word1_high_masked + cur_geno_word2_high_masked);
258 bothset_ct += NypsumWord((cur_geno_word1 & cur_geno_word1_high_masked) + (cur_geno_word2 & cur_geno_word2_high_masked));
259 # endif
260 }
261 # else // not USE_SSE2
262 uintptr_t mask_base = 0;
263 for (; vec_idx != raw_sample_ctv2; ++vec_idx) {
264 uintptr_t mask_word;
265 if (!(vec_idx % 2)) {
266 mask_base = *interleaved_mask_iter++;
267 mask_word = mask_base & kMask5555;
268 } else {
269 mask_word = (mask_base >> 1) & kMask5555;
270 }
271 uintptr_t cur_geno_word;
272 if (vec_idx < vec_idx_trail) {
273 CopyFromUnalignedIncrW(&cur_geno_word, &genoarrb_iter);
274 } else {
275 const uint32_t remaining_byte_ct = NypCtToByteCt(raw_sample_ct) % kBytesPerVec;
276 cur_geno_word = ProperSubwordLoad(genoarrb_iter, remaining_byte_ct);
277 }
278 const uintptr_t cur_geno_word_high_masked = mask_word & (cur_geno_word >> 1);
279 even_ct += Popcount01Word(cur_geno_word & mask_word);
280 odd_ct += Popcount01Word(cur_geno_word_high_masked);
281 bothset_ct += Popcount01Word(cur_geno_word & cur_geno_word_high_masked);
282 }
283 # endif // not USE_SSE2
284 #endif // not USE_AVX2
285 genocounts[0] = sample_ct + bothset_ct - even_ct - odd_ct;
286 genocounts[1] = even_ct - bothset_ct;
287 genocounts[2] = odd_ct - bothset_ct;
288 genocounts[3] = bothset_ct;
289 }
290
291 void GenoarrCountFreqs(const uintptr_t* genoarr, uint32_t sample_ct, STD_ARRAY_REF(uint32_t, 4) genocounts) {
292 // this masks out trailing genoarr bits
293 const uint32_t sample_ct_remainder = sample_ct % kBitsPerWordD2;
294 GenoarrCountFreqsUnsafe(genoarr, sample_ct - sample_ct_remainder, genocounts);
295 if (sample_ct_remainder) {
296 uintptr_t cur_geno_word = bzhi(genoarr[sample_ct / kBitsPerWordD2], 2 * sample_ct_remainder);
297 const uintptr_t cur_geno_word_high = kMask5555 & (cur_geno_word >> 1);
298 const uint32_t even_ct = Popcount01Word(cur_geno_word & kMask5555);
299 const uint32_t odd_ct = Popcount01Word(cur_geno_word_high);
300 const uint32_t bothset_ct = Popcount01Word(cur_geno_word & cur_geno_word_high);
301 genocounts[0] += sample_ct_remainder + bothset_ct - even_ct - odd_ct;
302 genocounts[1] += even_ct - bothset_ct;
303 genocounts[2] += odd_ct - bothset_ct;
304 genocounts[3] += bothset_ct;
305 }
306 }
307
308 void GenovecNonmissingToZeroUnsafe(uint32_t sample_ct, uintptr_t* genovec) {
309 // sets 1 and 2 to zero; leaves 3s untouched.
310 const uint32_t vec_ct = NypCtToVecCt(sample_ct);
311 assert(IsVecAligned(genovec));
312 const VecW m1 = VCONST_W(kMask5555);
313 VecW* vptr = R_CAST(VecW*, genovec);
314 for (uint32_t vidx = 0; vidx != vec_ct; ++vidx) {
315 VecW cur_vec = vptr[vidx];
316 const VecW cur_vec_rshifted = vecw_srli(cur_vec, 1);
317 cur_vec = cur_vec & m1;
318 cur_vec = cur_vec & cur_vec_rshifted;
319 vptr[vidx] = cur_vec | vecw_slli(cur_vec, 1);
320 }
321 }
322
323 void GenovecNonzeroToMissingUnsafe(uint32_t sample_ct, uintptr_t* genovec) {
324 // converts 1s and 2s to 3s, leaves zeroes untouched.
325 const uint32_t vec_ct = NypCtToVecCt(sample_ct);
326 assert(IsVecAligned(genovec));
327 const VecW m1 = VCONST_W(kMask5555);
328 VecW* vptr = R_CAST(VecW*, genovec);
329 for (uint32_t vidx = 0; vidx != vec_ct; ++vidx) {
330 VecW cur_vec = vptr[vidx];
331 const VecW cur_vec_rshifted = vecw_srli(cur_vec, 1);
332 cur_vec = cur_vec | cur_vec_rshifted;
333 cur_vec = cur_vec & m1;
334 vptr[vidx] = cur_vec | vecw_slli(cur_vec, 1);
335 }
336 }
337
338 void GenovecNontwoToMissingUnsafe(uint32_t sample_ct, uintptr_t* genovec) {
339 // 0 -> 3, 1 -> 3.
340 const uint32_t vec_ct = NypCtToVecCt(sample_ct);
341 assert(IsVecAligned(genovec));
342 const VecW not_m1 = VCONST_W(kMaskAAAA);
343 VecW* vptr = R_CAST(VecW*, genovec);
344 for (uint32_t vidx = 0; vidx != vec_ct; ++vidx) {
345 const VecW cur_vec = vptr[vidx];
346 const VecW cur_vec_hi = vecw_and_notfirst(cur_vec, not_m1);
347 const VecW cur_or = cur_vec_hi | vecw_srli(cur_vec_hi, 1);
348 vptr[vidx] = cur_vec | cur_or;
349 }
350 }
351
352 void GenovecNonzeroToMissingThenInvertUnsafe(uint32_t sample_ct, uintptr_t* genovec) {
353 // 0 -> 2, 1 -> 3, 2 -> 3
354 const uint32_t vec_ct = NypCtToVecCt(sample_ct);
355 assert(IsVecAligned(genovec));
356 const VecW not_m1 = VCONST_W(kMaskAAAA);
357 VecW* vptr = R_CAST(VecW*, genovec);
358 for (uint32_t vidx = 0; vidx != vec_ct; ++vidx) {
359 const VecW cur_vec = vptr[vidx];
360 vptr[vidx] = cur_vec | vecw_srli(cur_vec, 1) | not_m1;
361 }
362 }
363
364 void GenovecInvertThenNonzeroToMissingUnsafe(uint32_t sample_ct, uintptr_t* genovec) {
365 // 0 -> 3, 1 -> 3, 2 -> 0
366 const uint32_t vec_ct = NypCtToVecCt(sample_ct);
367 assert(IsVecAligned(genovec));
368 const VecW m1 = VCONST_W(kMask5555);
369 VecW* vptr = R_CAST(VecW*, genovec);
370 for (uint32_t vidx = 0; vidx != vec_ct; ++vidx) {
371 const VecW cur_vec = vptr[vidx];
372 const VecW cur_vec_rshifted = vecw_srli(cur_vec, 1);
373 const VecW not2 = vecw_and_notfirst(vecw_and_notfirst(cur_vec, cur_vec_rshifted), m1);
374 vptr[vidx] = not2 | vecw_slli(not2, 1);
375 }
376 }
377
378 double BiallelicDiploidMinimac3R2(uint64_t alt1_dosage, uint64_t hap_alt1_ssq_x2, uint32_t nm_sample_ct) {
379 if (!nm_sample_ct) {
380 return (0.0 / 0.0);
381 }
382
383 const uint64_t nm_sample_ct_x32768 = nm_sample_ct * 0x8000LLU;
384 if (nm_sample_ct < 131072) {
385 const uint64_t alt1_dosage_sq = alt1_dosage * alt1_dosage;
386 const uint64_t observed_variance_times_2n = hap_alt1_ssq_x2 * nm_sample_ct - alt1_dosage * alt1_dosage;
387 const uint64_t expected_variance_times_2n = nm_sample_ct_x32768 * alt1_dosage - alt1_dosage_sq;
388 return S_CAST(double, observed_variance_times_2n) / S_CAST(double, expected_variance_times_2n);
389 }
390 // Need to avoid catastrophic cancellation here.
391 const double alt1_dosaged = u63tod(alt1_dosage);
392 const double expected_variance_times_2n = alt1_dosaged * u63tod(nm_sample_ct_x32768 - alt1_dosage);
393 const uint64_t hap_alt1_ssq_x2_hi = hap_alt1_ssq_x2 >> 32;
394 uint64_t left_lo = (hap_alt1_ssq_x2 & 0xffffffffLLU) * nm_sample_ct;
395 const uint64_t left_hi = (left_lo >> 32) + hap_alt1_ssq_x2_hi * nm_sample_ct;
396 left_lo &= 0xffffffffU;
397 const uint64_t alt1_dosage_lo = alt1_dosage & 0xffffffffLLU;
398 const uint64_t alt1_dosage_hi = alt1_dosage >> 32;
399 uint64_t right_lo = alt1_dosage_lo * alt1_dosage_lo;
400 const uint64_t right_hi = (right_lo >> 32) + (alt1_dosage_lo + alt1_dosage) * alt1_dosage_hi;
401 right_lo &= 0xffffffffU;
402 const double observed_variance_times_2n_hi = u63tod(left_hi - right_hi);
403 const int64_t observed_variance_times_2n_lo = S_CAST(int64_t, left_lo) - S_CAST(int64_t, right_lo);
404 const double observed_variance_times_2n = (observed_variance_times_2n_hi * 4294967296.0) + observed_variance_times_2n_lo;
405 return observed_variance_times_2n / expected_variance_times_2n;
406 }
407
408 // These two functions do not overread, but may write extra bytes up to the
409 // word boundary.
410 // They are likely to be moved to plink2_bits.
411 // bugfix (30 Oct 2023): given how we use this function, we have to drop the
412 // vector-alignment requirement for dst.
413 void Expand2bitTo8(const void* __restrict bytearr, uint32_t input_nyp_ct, uint32_t incr, void* __restrict dst) {
414 // Tried adding incr == 0 fast path, negligible performance difference in
415 // benchmark.
416 // GenoarrLookup256x1bx4 takes ~3-4x as long.
417 uint32_t input_byte_ct = DivUp(input_nyp_ct, 4);
418 #ifdef USE_SSE2
419 const unsigned char* src_iter = S_CAST(const unsigned char*, bytearr);
420 const uint32_t input_vec_ct = input_byte_ct / kBytesPerVec;
421 uintptr_t* dst_iter = S_CAST(uintptr_t*, dst);
422 if (input_vec_ct) {
423 const VecW mincr = VecUcToW(vecuc_set1(incr));
424 const VecW m03 = VCONST_W(kMask0303);
425 for (uint32_t vec_idx = 0; vec_idx != input_vec_ct; ++vec_idx) {
426 VecW cur_vec = vecw_loadu(src_iter);
427 src_iter = &(src_iter[kBytesPerVec]);
428 # ifdef USE_AVX2
429 // (todo: benchmark against just reading 8 bytes at a time and
430 // broadcasting.)
431 // midswapped_vec contains {0-1-2-3, 4-5-6-7, ..., 12-13-14-15,
432 // 32-33-34-35, ..., 44-45-46-47,
433 // 16-17-18-19, ..., 28-29-30-31,
434 // 48-49-50-51, ..., 60-61-62-63,
435 // 64-65-66-67, ..., 76-77-78-79,
436 // 96-97-98-99, ..., 108-109-110-111,
437 // 80-81-82-83, ..., 92-93-94-95,
438 // 112-113-114-115, ..., 124-125-126-127}
439 // 0xd8: {0, 2, 1, 3}
440 const __m256i midswapped_vec = _mm256_shuffle_epi32(WToVec(cur_vec), 0xd8);
441 // This operation is also used in FillInterleavedMaskVec().
442 // cur_vec now contains {0-1-2-3, 4-5-6-7, 8-9-10-11, 12-13-14-15,
443 // 32-33-34-35, ..., 44-45-46-47,
444 // 64-65-66-67, ..., 76-77-78-79,
445 // 96-97-98-99, ..., 108-109-110-111,
446 // 16-17-18-19, ..., 28-29-30-31,
447 // 48-49-50-51, ..., 60-61-62-63,
448 // 80-81-82-83, ..., 92-93-94-95,
449 // 112-113-114-115, ..., 124-125-126-127}
450 cur_vec = vecw_permute0xd8_if_avx2(VecToW(midswapped_vec));
451 # endif
452 // AVX2:
453 // vec_even contains {0-1, 4-5, 8-9, 12-13, 32-33, ..., 44-45,
454 // 64-65, ..., 76-77, 96-97, ..., 108-109,
455 // 16-17, ..., 28-29, 48-49, ..., 60-61,
456 // 80-81, ..., 92-93, 112-113, ..., 124-125}
457 // vec_odd contains {2-3, 6-7, 10-11, 14-15, 34-35, ..., 46-47,
458 // 66-67, ..., 78-79, 98-99, ..., 110-111,
459 // 18-19, ..., 30-31, 50-51, ..., 62-63,
460 // 82-83, ..., 94-95, 114-115, ..., 126-127}
461 // SSE2:
462 // vec_even contains {0-1, 4-5, 8-9, ..., 60-61}
463 // vec_odd contains {2-3, 6-7, 10-11, ..., 62-63}
464 const VecW vec_even = cur_vec;
465 const VecW vec_odd = vecw_srli(cur_vec, 4);
466
467 // AVX2:
468 // vec01 contains {0-1, 2-3, 4-5, ..., 14-15, 32-33, ..., 46-47,
469 // 16-17, ..., 30-31, 48-49, ..., 62-63}
470 // vec23 contains {64-65, 66-67, ..., 78-79, 96-97, ..., 110-111,
471 // 80-81, ..., 94-95, 112-113, ..., 126-127}
472 // SSE2:
473 // vec01 contains {0-1, 2-3, 4-5, 6-7, ..., 30-31}
474 // vec23 contains {32-33, 34-35, 36-37, 38-39, ..., 62-63}
475 // There's no m4 masking here, so we don't use vecw_lo_and_hi_nybbles.
476 const VecW vec01 = vecw_unpacklo8(vec_even, vec_odd);
477 const VecW vec23 = vecw_unpackhi8(vec_even, vec_odd);
478
479 // AVX2:
480 // vec01_even contains {0, 2, 4, ..., 14, 32, 34, ..., 46,
481 // 16, 18, ..., 30, 48, 50, ..., 62}
482 // vec01_odd contains {1, 3, 5, ..., 15, 33, 35, ..., 47,
483 // 17, 19, ..., 31, 49, 51, ..., 63}
484 // SSE2:
485 // vec01_even contains {0, 2, 4, 6, ..., 30}
486 // vec01_odd contains {1, 3, 5, 7, ..., 31}
487 const VecW vec01_even = vec01 & m03;
488 const VecW vec01_odd = vecw_srli(vec01, 2) & m03;
489
490 // AVX2:
491 // vecw_unpacklo8() contains {0, 1, ..., 15, 16, ..., 31}
492 // vecw_unpachhi8() contains {32, 33, ..., 47, 48, ..., 63}
493 // SSE2:
494 // vecw_unpacklo8() contains {0, 1, ..., 15}
495 // vecw_unpachhi8() contains {16, 17, ..., 31}
496 vecw_storeu(dst_iter, mincr + vecw_unpacklo8(vec01_even, vec01_odd));
497 dst_iter = &(dst_iter[kWordsPerVec]);
498 vecw_storeu(dst_iter, mincr + vecw_unpackhi8(vec01_even, vec01_odd));
499 dst_iter = &(dst_iter[kWordsPerVec]);
500 const VecW vec23_odd = vecw_srli(vec23, 2) & m03;
501 const VecW vec23_even = vec23 & m03;
502 vecw_storeu(dst_iter, mincr + vecw_unpacklo8(vec23_even, vec23_odd));
503 dst_iter = &(dst_iter[kWordsPerVec]);
504 vecw_storeu(dst_iter, mincr + vecw_unpackhi8(vec23_even, vec23_odd));
505 dst_iter = &(dst_iter[kWordsPerVec]);
506 }
507 }
508 input_byte_ct = input_byte_ct % kBytesPerVec;
509 if (!input_byte_ct) {
510 return;
511 }
512 const unsigned char* src_uc = src_iter;
513 uintptr_t* dstw = dst_iter;
514 #else // !USE_SSE2
515 const unsigned char* src_uc = S_CAST(const unsigned char*, bytearr);
516 uintptr_t* dstw = S_CAST(uintptr_t*, dst);
517 #endif
518 const uint32_t full_qw_ct = input_byte_ct / sizeof(Quarterword);
519 const uintptr_t incr_word = kMask0101 * incr;
520 for (uint32_t uii = 0; uii != full_qw_ct; ++uii) {
521 Quarterword cur_qw;
522 CopyFromUnalignedOffsetQW(&cur_qw, src_uc, uii);
523 dstw[uii] = incr_word + Unpack0303(cur_qw);
524 }
525 #ifdef __LP64__
526 if (input_byte_ct % 2) {
527 uintptr_t cur_byte = src_uc[input_byte_ct - 1];
528 # ifdef USE_AVX2
529 cur_byte = _pdep_u64(cur_byte, kMask0303);
530 # else
531 cur_byte = cur_byte | (cur_byte << 12);
532 cur_byte = (cur_byte | (cur_byte << 6)) & kMask0303;
533 # endif
534 dstw[full_qw_ct] = incr_word + cur_byte;
535 }
536 #endif
537 }
538
539 void Expand4bitTo8(const void* __restrict bytearr, uint32_t input_nybble_ct, uint32_t incr, void* __restrict dst) {
540 // Tried adding incr == 0 fast path, negligible performance difference in
541 // benchmark.
542 #ifdef USE_SSE2
543 uint32_t input_byte_ct = DivUp(input_nybble_ct, 2);
544 const unsigned char* src_iter = S_CAST(const unsigned char*, bytearr);
545 const uint32_t input_vec_ct = input_byte_ct / kBytesPerVec;
546 uintptr_t* dst_iter = S_CAST(uintptr_t*, dst);
547 if (input_vec_ct) {
548 const VecW mincr = VecUcToW(vecuc_set1(incr));
549 const VecW m4 = VCONST_W(kMask0F0F);
550 for (uint32_t vec_idx = 0; vec_idx != input_vec_ct; ++vec_idx) {
551 const VecW cur_vec = vecw_loadu(src_iter);
552 src_iter = &(src_iter[kBytesPerVec]);
553 VecW vec_lo;
554 VecW vec_hi;
555 vecw_lo_and_hi_nybbles(cur_vec, m4, &vec_lo, &vec_hi);
556 vecw_storeu(dst_iter, mincr + vec_lo);
557 dst_iter = &(dst_iter[kWordsPerVec]);
558 vecw_storeu(dst_iter, mincr + vec_hi);
559 dst_iter = &(dst_iter[kWordsPerVec]);
560 }
561 }
562 input_byte_ct = input_byte_ct % kBytesPerVec;
563 if (!input_byte_ct) {
564 return;
565 }
566 const unsigned char* src_uc = src_iter;
567 uintptr_t* dstw = dst_iter;
568 #else
569 if (!input_nybble_ct) {
570 return;
571 }
572 const unsigned char* src_uc = S_CAST(const unsigned char*, bytearr);
573 uintptr_t* dstw = S_CAST(uintptr_t*, dst);
574 const uint32_t input_byte_ct = DivUp(input_nybble_ct, 2);
575 #endif
576 const uint32_t hw_ct_m1 = (input_byte_ct - 1) / sizeof(Halfword);
577 const uintptr_t incr_word = kMask0101 * incr;
578 for (uint32_t hwidx = 0; ; ++hwidx) {
579 Halfword cur_hw;
580 if (hwidx >= hw_ct_m1) {
581 if (hwidx > hw_ct_m1) {
582 break;
583 }
584 cur_hw = SubHWLoad(&(src_uc[hwidx * sizeof(Halfword)]), ModNz(input_byte_ct, sizeof(Halfword)));
585 } else {
586 CopyFromUnalignedOffsetHW(&cur_hw, src_uc, hwidx);
587 }
588 dstw[hwidx] = incr_word + Unpack0F0F(cur_hw);
589 }
590 }
591
592 void PreinitPgfi(PgenFileInfo* pgfip) {
593 pgfip->shared_ff = nullptr;
594 pgfip->pgi_ff = nullptr;
595 pgfip->block_base = nullptr;
596 // we want this for proper handling of e.g. sites-only VCFs
597 pgfip->nonref_flags = nullptr;
598 }
599
600 uintptr_t CountPgfiAllocCachelinesRequired(uint32_t raw_variant_ct) {
601 // assumes variable-width variant records, otherwise pgfi.vrtypes and
602 // pgfi.vr_fpos can just be nullptr.
603
604 // vrtypes: 1 byte per entry, (raw_variant_ct + 1) entries
605 uintptr_t cachelines_required = 1 + (raw_variant_ct / kCacheline);
606
607 // var_fpos: 8 bytes per entry, (raw_variant_ct + 1) entries
608 cachelines_required += 1 + (raw_variant_ct / kInt64PerCacheline);
609 return cachelines_required;
610 }
611
612 uintptr_t CountPgrAllocCachelinesRequired(uint32_t raw_sample_ct, PgenGlobalFlags gflags, uint32_t max_allele_ct, uint32_t fread_buf_byte_ct) {
613 // ldbase_raw_genovec: always needed, 2 bits per entry, up to raw_sample_ct
614 // entries
615 const uint32_t genovec_cacheline_req = NypCtToCachelineCt(raw_sample_ct);
616 const uint32_t bitvec_cacheline_req = BitCtToCachelineCt(raw_sample_ct);
617 uintptr_t cachelines_required = genovec_cacheline_req;
618 // fread_buf. DivUp() won't overflow since fread_buf_byte_ct requirement
619 // can't exceed kPglMaxBytesPerVariant, which is sufficiently far from 2^32.
620 cachelines_required += DivUp(fread_buf_byte_ct, kCacheline);
621
622 const uint32_t ld_compression_present = (gflags / kfPgenGlobalLdCompressionPresent) & 1;
623 const uint32_t max_difflist_entry_ct_base = (raw_sample_ct / kPglMaxDifflistLenDivisor);
624 if ((gflags & kfPgenGlobalDifflistOrLdPresent) || (max_allele_ct > 2)) {
625 // workspace_difflist_sample_ids
626 // bugfix: must add 1 since several routines add a terminator element
627 cachelines_required += 1 + (max_difflist_entry_ct_base / kInt32PerCacheline);
628 }
629 if (gflags & kfPgenGlobalDifflistOrLdPresent) {
630 // const uint32_t max_difflist_entry_ct = max_difflist_entry_ct_base * (1 + ld_compression_present);
631 // workspace_raregeno_vec
632 cachelines_required += NypCtToCachelineCt(max_difflist_entry_ct_base);
633
634 // workspace_raregeno_tmp_loadbuf
635 cachelines_required += NypCtToCachelineCt(max_difflist_entry_ct_base);
636
637 if (ld_compression_present) {
638 // ldbase_genovec
639 cachelines_required += genovec_cacheline_req;
640
641 // ldbase_raregeno
642 cachelines_required += NypCtToCachelineCt(max_difflist_entry_ct_base);
643
644 // ldbase_difflist_sample_ids
645 cachelines_required += 1 + (max_difflist_entry_ct_base / kInt32PerCacheline);
646 }
647 }
648 const PgenGlobalFlags gflags_hphase_dosage = gflags & (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePresent);
649 if ((max_allele_ct > 2) || gflags_hphase_dosage) {
650 cachelines_required += genovec_cacheline_req; // workspace_vec
651 if (max_allele_ct > 2) {
652 // workspace_aux1x_present
653 cachelines_required += bitvec_cacheline_req;
654 // workspace_imp_r2
655 cachelines_required += Int64CtToCachelineCt(2 * max_allele_ct);
656 }
657 if (gflags & kfPgenGlobalHardcallPhasePresent) {
658 // workspace_all_hets, workspace_subset
659 cachelines_required += bitvec_cacheline_req * 2;
660 }
661 if (gflags & kfPgenGlobalDosagePresent) {
662 // aux track #3: usually bitarray tracking which samples have dosage info
663 // (may be stored on disk as a dosage list)
664 cachelines_required += bitvec_cacheline_req;
665 if (gflags & kfPgenGlobalDosagePhasePresent) {
666 // aux track #7: bitarray tracking which dosage entries are phased
667 cachelines_required += bitvec_cacheline_req;
668
669 // phased aux tracks #4,8: 2 bytes per sample
670 // There may be overflow risk here in the future.
671 // (commented out since caller always provides this buffer for now)
672 // cachelines_required += DivUp(2 * k1LU * raw_sample_ct, kCacheline);
673 }
674 // unphased aux track #4: 2 bytes per sample
675 // cachelines_required += DivUp(2 * k1LU * raw_sample_ct, kCacheline);
676
677 // may need deltalist64 workspace in multiallelic dosage case
678 }
679 }
680 return cachelines_required;
681 }
682
683 static_assert(kPglMaxAlleleCt == 255, "Need to update PgfiInitPhase1().");
684 PglErr PgfiInitPhase1(const char* fname, const char* pgi_fname, uint32_t raw_variant_ct, uint32_t raw_sample_ct, PgenHeaderCtrl* header_ctrl_ptr, PgenFileInfo* pgfip, uintptr_t* pgfi_alloc_cacheline_ct_ptr, char* errstr_buf) {
685 pgfip->var_fpos = nullptr;
686 pgfip->vrtypes = nullptr;
687 pgfip->allele_idx_offsets = nullptr;
688 pgfip->nonref_flags = nullptr;
689
690 // Caller is currently expected to reset max_allele_ct if allele_idx_offsets
691 // is preloaded... need to fix this interface.
692 pgfip->max_allele_ct = 2;
693 // pgfip->max_dosage_allele_ct = 0;
694 pgfip->extensions_present = 0;
695
696 pgfip->block_base = nullptr;
697 // this should force overflow when value is uninitialized.
698 pgfip->block_offset = 1LLU << 63;
699
700 uint64_t fsize;
701 const unsigned char* fread_ptr;
702 unsigned char small_readbuf[3];
703 FILE* shared_ff = fopen(fname, FOPEN_RB);
704 pgfip->shared_ff = shared_ff;
705 if (unlikely(!shared_ff)) {
706 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Failed to open %s : %s.\n", fname, strerror(errno));
707 return kPglRetOpenFail;
708 }
709 if (unlikely(fseeko(shared_ff, 0, SEEK_END))) {
710 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: %s read failure: %s.\n", fname, strerror(errno));
711 return kPglRetReadFail;
712 }
713 fsize = ftello(shared_ff);
714 if (unlikely(fsize < 4)) {
715 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: %s is too small to be a valid .pgen file.\n", fname);
716 return kPglRetMalformedInput;
717 }
718 rewind(shared_ff);
719 if (unlikely(!fread_unlocked(small_readbuf, 3, 1, shared_ff))) {
720 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: %s read failure: %s.\n", fname, strerror(errno));
721 return kPglRetReadFail;
722 }
723 fread_ptr = small_readbuf;
724 // deliberate underflow
725 if (unlikely(((raw_variant_ct - 1) > (kPglMaxVariantCt - 1)) && (raw_variant_ct != UINT32_MAX))) {
726 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid raw_variant_ct function parameter.\n");
727 return kPglRetImproperFunctionCall;
728 }
729 if (unlikely(((raw_sample_ct - 1) > (kPglMaxSampleCt - 1)) && (raw_sample_ct != UINT32_MAX))) {
730 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid raw_sample_ct function parameter.\n");
731 return kPglRetImproperFunctionCall;
732 }
733 if (unlikely(!memequal_k(fread_ptr, "l\x1b", 2))) {
734 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: %s is not a .pgen file (first two bytes don't match the magic number).\n", fname);
735 return kPglRetMalformedInput;
736 }
737 const uint32_t file_type_code = fread_ptr[2];
738 *header_ctrl_ptr = 0;
739 if (file_type_code < 2) {
740 // plink 1 binary
741 if (unlikely(!file_type_code)) {
742 // sample-major. validate file size here so we don't have to recheck it
743 if ((raw_sample_ct != UINT32_MAX) && (raw_variant_ct != UINT32_MAX)) {
744 const uint64_t fsize_expected = 3 + S_CAST(uint64_t, raw_sample_ct) * NypCtToByteCt(raw_variant_ct);
745 if (fsize != fsize_expected) {
746 char* write_iter = strcpya_k(errstr_buf, "Error: Unexpected PLINK 1 sample-major .bed file size (");
747 write_iter = i64toa(fsize_expected, write_iter);
748 strcpy_k(write_iter, " bytes expected).\n");
749 return kPglRetMalformedInput;
750 }
751 }
752 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: pgenlib does not directly support sample-major PLINK 1 .bed files.\n(However, PLINK 2 automatically transposes and compresses them for you.)\n");
753 return kPglRetSampleMajorBed;
754 }
755 if (unlikely(raw_sample_ct == UINT32_MAX)) {
756 // either .fam must be loaded first, or user must provide sample count
757 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: PgfiInitPhase1() must be called with an accurate raw_sample_ct value, since %s is a PLINK 1 .bed file.\n", fname);
758 return kPglRetImproperFunctionCall;
759 }
760 const uint32_t const_vrec_width = NypCtToByteCt(raw_sample_ct);
761 if (raw_variant_ct == UINT32_MAX) {
762 // allow raw_variant_ct to be inferred
763 uint64_t quotient = (fsize - 3) / const_vrec_width;
764 if (unlikely((quotient > kPglMaxSampleCt) || (quotient * const_vrec_width + 3 != fsize))) {
765 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Unexpected PLINK 1 .bed file size (since raw_sample_ct was %u, [file size - 3] should be divisible by %u and the quotient should be smaller than 2^31 - 1).\n", raw_sample_ct, const_vrec_width);
766 return kPglRetMalformedInput;
767 }
768 raw_variant_ct = quotient;
769 } else {
770 if (unlikely(S_CAST(uint64_t, raw_variant_ct) * const_vrec_width + 3 != fsize)) {
771 char* write_iter = strcpya_k(errstr_buf, "Error: Unexpected PLINK 1 .bed file size (expected ");
772 write_iter = i64toa(S_CAST(uint64_t, raw_variant_ct) * const_vrec_width + 3, write_iter);
773 strcpy_k(write_iter, " bytes).\n");
774 return kPglRetMalformedInput;
775 }
776 }
777 pgfip->raw_variant_ct = raw_variant_ct;
778 pgfip->raw_sample_ct = raw_sample_ct;
779 pgfip->const_fpos_offset = 3;
780
781 pgfip->const_vrtype = kPglVrtypePlink1;
782 pgfip->const_vrec_width = const_vrec_width;
783 pgfip->gflags = kfPgenGlobalAllNonref;
784 *pgfi_alloc_cacheline_ct_ptr = 0;
785 return kPglRetSuccess;
786 }
787
788 FILE* header_ff = shared_ff;
789 const char* header_fname = fname;
790
791 // Must declare here, rather than inside else{} block, since the buffer would
792 // otherwise be implicitly popped off the stack as soon as the else-block is
793 // exited, but we may still try to print this filename in an error message.
794 // This isn't Golang.
795 char pgi_fname_buf[kPglFnamesize];
796
797 if ((file_type_code & 0xfe) != 0x20) {
798 if (unlikely((file_type_code & 0xfe) == 0x30)) {
799 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: %s is a .pgen.pgi index file, rather than a .pgen file.\n", fname);
800 return kPglRetMalformedInput;
801 }
802 if (unlikely(fsize < 12)) {
803 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: %s is too small to be a valid .pgen file.\n", fname);
804 return kPglRetMalformedInput;
805 }
806 } else {
807 header_fname = pgi_fname;
808 if (!header_fname) {
809 const uint32_t fname_slen = strlen(fname);
810 // need space to append ".pgi" plus null-terminator
811 if (unlikely(fname_slen > kPglFnamesize - 5)) {
812 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: .pgen filename too long.\n");
813 return kPglRetMalformedInput;
814 }
815 char* fname_iter = memcpya(pgi_fname_buf, fname, fname_slen);
816 strcpy_k(fname_iter, ".pgi");
817 header_fname = pgi_fname_buf;
818 }
819 header_ff = fopen(header_fname, FOPEN_RB);
820 pgfip->pgi_ff = header_ff;
821 if (unlikely(!header_ff)) {
822 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Failed to open %s : %s.\n", header_fname, strerror(errno));
823 return kPglRetOpenFail;
824 }
825 if (unlikely(!fread_unlocked(small_readbuf, 3, 1, header_ff))) {
826 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: %s read failure: %s.\n", header_fname, strerror(errno));
827 return kPglRetReadFail;
828 }
829 if (unlikely((!memequal_k(small_readbuf, "l\x1b", 2)) || ((small_readbuf[2] & 0xfe) != 0x30))) {
830 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: %s is not a .pgen.pgi file (first three bytes don't match the magic number).\n", header_fname);
831 return kPglRetMalformedInput;
832 }
833 }
834 if (unlikely((!fread_unlocked(&(pgfip->raw_variant_ct), sizeof(int32_t), 1, header_ff)) ||
835 (!fread_unlocked(&(pgfip->raw_sample_ct), sizeof(int32_t), 1, header_ff)) ||
836 (!fread_unlocked(header_ctrl_ptr, 1, 1, header_ff)))) {
837 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: %s read failure: %s.\n", header_fname, strerror(errno));
838 return kPglRetReadFail;
839 }
840 const PgenHeaderCtrl header_ctrl = *header_ctrl_ptr;
841 if (raw_variant_ct == UINT32_MAX) {
842 raw_variant_ct = pgfip->raw_variant_ct;
843 // deliberate underflow
844 if (unlikely((raw_variant_ct - 1) > (kPglMaxVariantCt - 1))) {
845 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid variant count in .pgen%s file.\n", pgfip->pgi_ff? ".pgi" : "");
846 return kPglRetMalformedInput;
847 }
848 } else if (unlikely(raw_variant_ct != pgfip->raw_variant_ct)) {
849 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: PgfiInitPhase1() was called with raw_variant_ct == %u, but %s contains %u variant%s.\n", raw_variant_ct, fname, pgfip->raw_variant_ct, (pgfip->raw_variant_ct == 1)? "" : "s");
850 return kPglRetInconsistentInput;
851 }
852 if (raw_sample_ct == UINT32_MAX) {
853 raw_sample_ct = pgfip->raw_sample_ct;
854 // deliberate underflow
855 if (unlikely((raw_sample_ct - 1) > (kPglMaxSampleCt - 1))) {
856 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid sample count in .pgen%s file.\n", pgfip->pgi_ff? ".pgi" : "");
857 return kPglRetMalformedInput;
858 }
859 } else if (unlikely(raw_sample_ct != pgfip->raw_sample_ct)) {
860 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: PgfiInitPhase1() was called with raw_sample_ct == %u, but %s contains %u sample%s.\n", raw_sample_ct, fname, pgfip->raw_sample_ct, (pgfip->raw_sample_ct == 1)? "" : "s");
861 return kPglRetInconsistentInput;
862 }
863 pgfip->gflags = kfPgenGlobal0;
864
865 // explicit storage of "is this reference allele untrusted?"
866 // need caller to allocate this
867 uint32_t nonref_flags_storage = header_ctrl >> 6;
868 if (nonref_flags_storage == 2) {
869 pgfip->gflags |= kfPgenGlobalAllNonref;
870 }
871
872 if (file_type_code < 16) {
873 // plink 2 binary, single constant-width vrtype
874 pgfip->const_fpos_offset = 12;
875 if (nonref_flags_storage == 3) {
876 pgfip->const_fpos_offset += DivUp(raw_variant_ct, CHAR_BIT);
877 }
878 if (unlikely(file_type_code > 4)) {
879 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Third byte of %s does not correspond to a storage mode supported by this version of pgenlib.\n", fname);
880 return kPglRetNotYetSupported;
881 }
882 if (unlikely(header_ctrl & 63)) {
883 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Third byte of %s corresponds to a fixed-width storage mode, but twelfth byte is only consistent with a variable-width mode.\n", fname);
884 return kPglRetMalformedInput;
885 }
886 uint32_t vrtype = 0;
887 uintptr_t const_vrec_width = NypCtToByteCt(raw_sample_ct);
888 if (file_type_code == 3) {
889 vrtype = 0x40;
890 const_vrec_width += raw_sample_ct * 2;
891 pgfip->gflags |= kfPgenGlobalDosagePresent;
892 } else if (file_type_code == 4) {
893 vrtype = 0xc0;
894 const_vrec_width += raw_sample_ct * 4;
895 pgfip->gflags |= kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent;
896 }
897 if (unlikely(S_CAST(uint64_t, raw_variant_ct) * const_vrec_width + pgfip->const_fpos_offset != fsize)) {
898 char* write_iter = strcpya_k(errstr_buf, "Error: Unexpected .pgen file size (expected ");
899 write_iter = i64toa(S_CAST(uint64_t, raw_variant_ct) * const_vrec_width + pgfip->const_fpos_offset, write_iter);
900 strcpy_k(write_iter, " bytes).\n");
901 return kPglRetMalformedInput;
902 }
903 pgfip->const_vrtype = vrtype;
904 pgfip->const_vrec_width = const_vrec_width;
905 *pgfi_alloc_cacheline_ct_ptr = 0;
906 return kPglRetSuccess;
907 }
908 if (unlikely((file_type_code >= 0x12) && ((file_type_code & 0xfe) != 0x20))) {
909 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Third byte of %s does not correspond to a storage mode supported by this version of pgenlib.\n", fname);
910 return kPglRetNotYetSupported;
911 }
912 // plink 2 binary, general-purpose
913 pgfip->extensions_present = file_type_code & 1;
914 pgfip->const_fpos_offset = 0;
915 pgfip->const_vrtype = UINT32_MAX;
916 pgfip->const_vrec_width = 0;
917 const uintptr_t alt_allele_ct_byte_ct = (header_ctrl >> 4) & 3;
918 if (unlikely(alt_allele_ct_byte_ct > 1)) {
919 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: This version of pgenlib does not support >254 alternate alleles for a single variant.\n");
920 return kPglRetNotYetSupported;
921 }
922
923 if (header_ctrl & 8) {
924 // Special header_ctrl modes:
925 // 8: 1 bit per fused vrtype-length. Unset = vrtype 5, set = vrtype 0.
926 // 9: 2 bits, multiallelic. 0 = vrtype 5, 1 = vrtype 0, 2-3 = vrtype
927 // 8 with that many more bytes than vrtype 0. Note that this is
928 // limited to 16 ALT alleles.
929 // 10: 2 bits, phased. 0 = vrtype 5, 1 = vrtype 0, 2-3 = vrtype 16
930 // with that many minus 1 bytes beyond vrtype 0. While this is also
931 // aimed at the single-sample use case, it technically supports up to
932 // 15 always-phased or 7 partially-phased samples.
933 // 11: 4 bits, multiallelic + phased. 0 = vrtype 5, 1 = vrtype 0,
934 // 2-7 = vrtype 8 with that many bytes beyond vrtype 0, 9 = vrtype 16
935 // phase info requiring just 1 byte, 10-15 = vrtype 24 with (x-7)
936 // extra bytes required between multiallelic and phased tracks.
937 // 12: 2 bits, dosage, must be single-sample. 0 = vrtype 5,
938 // 1 = vrtype 0, 2 = vrtype 0x45 with 2 bytes, 3 = vrtype 0x40 with 3
939 // total bytes.
940 // 13: reserved for single-sample multiallelic + dosage.
941 // 14: 4 bits, phased + dosage, must be single-sample. 0 and 1 as usual,
942 // 3 = vrtype 16 with 1 phaseinfo byte, 4 = vrtype 0x45 with 2 bytes,
943 // 5 = vrtype 0x40 with 3 total bytes, 12 = vrtype 0xc5 with 4 total
944 // bytes, 13 = vrtype 0xc0 with 5 total bytes, 15 = vrtype 0xe0 with
945 // 6 total bytes
946 // 15: reserved for single-sample multiallelic + phased dosage.
947 const uint32_t header_ctrl_low3 = header_ctrl & 7;
948 // this can be a table lookup once 13/15 are implemented
949 if (unlikely((header_ctrl_low3 == 5) || (header_ctrl_low3 == 7))) {
950 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Twelfth byte of %s does not correspond to a format supported by this version of pgenlib.\n", header_fname);
951 return kPglRetNotYetSupported;
952 }
953 }
954 *pgfi_alloc_cacheline_ct_ptr = CountPgfiAllocCachelinesRequired(raw_variant_ct);
955 return kPglRetSuccess;
956 }
957
958 void FillPgenHeaderReadErrstrFromNzErrno(uint32_t is_pgi, char* errstr_buf) {
959 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: .pgen%s read failure: %s.\n", is_pgi? ".pgi" : "", strerror(errno));
960 }
961
962 void FillPgenReadErrstrFromNzErrno(char* errstr_buf) {
963 return FillPgenHeaderReadErrstrFromNzErrno(0, errstr_buf);
964 }
965
966 void FillPgenHeaderReadErrstrFromErrno(uint32_t is_pgi, char* errstr_buf) {
967 if (errno) {
968 FillPgenHeaderReadErrstrFromNzErrno(is_pgi, errstr_buf);
969 } else {
970 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: .pgen%s read failure: File appears to be corrupted.\n", is_pgi? ".pgi" : "");
971 }
972 }
973
974 void FillPgenReadErrstrFromErrno(char* errstr_buf) {
975 return FillPgenHeaderReadErrstrFromErrno(0, errstr_buf);
976 }
977
978 void FillPgenHeaderReadErrstr(FILE* ff, uint32_t is_pgi, char* errstr_buf) {
979 if (feof_unlocked(ff)) {
980 errno = 0;
981 }
982 FillPgenHeaderReadErrstrFromErrno(is_pgi, errstr_buf);
983 }
984
985 void FillPgenReadErrstr(FILE* ff, char* errstr_buf) {
986 FillPgenHeaderReadErrstr(ff, 0, errstr_buf);
987 }
988
989 // Assumes ff points to first byte of appropriate extension-set varint.
990 // For each exts_iter entry corresponding to a present extension, size is
991 // initialized to 0-based relative sequence number of extension. size is
992 // initialized to ~0LLU for each absent extension.
993 // If preprocessing header_exts, footer_fpos_ptr must be nullptr, and ff points
994 // to first byte of footer-extension-set varint on successful exit. If
995 // preprocessing footer_exts, footer_fpos_ptr must be non-null, will be filled
996 // if footer exists, and ff will be advanced past that on successful exit.
997 PglErr PgfiInitPhase2PreprocessExts(uint32_t is_pgi, FILE* ff, PgenExtensionLl* exts_iter, uint64_t* footer_fpos_ptr, char* errstr_buf) {
998 uint32_t cur_type_idx = exts_iter? exts_iter->type_idx : UINT32_MAX;
999 uint32_t type_idx_start = 0;
1000 uint32_t prev_ct = 0;
1001 while (1) {
1002 const uint32_t type_idx_stop = type_idx_start + 7;
1003 const int32_t ii = getc_unlocked(ff);
1004 if (unlikely(ii == EOF)) {
1005 if (ferror_unlocked(ff)) {
1006 FillPgenHeaderReadErrstrFromNzErrno(is_pgi, errstr_buf);
1007 return kPglRetReadFail;
1008 }
1009 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid .pgen%s.\n", is_pgi? ".pgi file" : " header");
1010 return kPglRetMalformedInput;
1011 }
1012 const uint32_t cur_byte = ii;
1013 while (cur_type_idx < type_idx_stop) {
1014 const uint32_t shifted_bit = 1 << (cur_type_idx - type_idx_start);
1015 if (cur_byte & shifted_bit) {
1016 exts_iter->size = prev_ct + PopcountByte(cur_byte & (shifted_bit - 1));
1017 } else {
1018 exts_iter->size = ~0LLU;
1019 }
1020 exts_iter = exts_iter->next;
1021 const uint32_t next_type_idx = exts_iter? exts_iter->type_idx : UINT32_MAX;
1022 if (unlikely(next_type_idx <= cur_type_idx)) {
1023 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: PgfiInitPhase2Ex() extension linked-lists must be ordered by increasing type_idx.\n");
1024 return kPglRetImproperFunctionCall;
1025 }
1026 cur_type_idx = next_type_idx;
1027 }
1028 if (unlikely((type_idx_start == 252) && (cur_byte & 0xf0))) {
1029 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid .pgen%s.\n", is_pgi? ".pgi file" : " header");
1030 return kPglRetMalformedInput;
1031 }
1032 if (!(cur_byte & 128)) {
1033 if (footer_fpos_ptr) {
1034 if (cur_byte || prev_ct) {
1035 if (unlikely(!fread_unlocked(footer_fpos_ptr, sizeof(int64_t), 1, ff))) {
1036 FillPgenHeaderReadErrstr(ff, is_pgi, errstr_buf);
1037 return kPglRetReadFail;
1038 }
1039 }
1040 }
1041 break;
1042 }
1043 type_idx_start = type_idx_stop;
1044 prev_ct += PopcountByte(cur_byte) - 1;
1045 }
1046 if (exts_iter) {
1047 while (1) {
1048 exts_iter->size = ~0LLU;
1049 exts_iter = exts_iter->next;
1050 if (!exts_iter) {
1051 break;
1052 }
1053 const uint32_t next_type_idx = exts_iter->type_idx;
1054 if (next_type_idx <= cur_type_idx) {
1055 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: PgfiInitPhase2Ex() extension linked-lists must be ordered by increasing type_idx.\n");
1056 return kPglRetImproperFunctionCall;
1057 }
1058 cur_type_idx = next_type_idx;
1059 }
1060 }
1061 return kPglRetSuccess;
1062 }
1063
1064 PglErr PgfiInitPhase2FillExtSizes(uint32_t is_pgi, FILE* ff, PgenExtensionLl* exts_iter, char* errstr_buf) {
1065 uint32_t next_seq_idx = 0;
1066 for (; exts_iter; exts_iter = exts_iter->next) {
1067 if (exts_iter->size == ~0LLU) {
1068 continue;
1069 }
1070 const uint32_t cur_seq_idx = exts_iter->size;
1071 for (; next_seq_idx < cur_seq_idx; ++next_seq_idx) {
1072 if (unlikely(FSkipVint(ff))) {
1073 goto PgfiInitPhase2FillExtSizes_error_or_eof;
1074 }
1075 }
1076 const uint64_t cur_size = FGetVint63(ff);
1077 if (unlikely(cur_size == (1LLU << 63))) {
1078 goto PgfiInitPhase2FillExtSizes_error_or_eof;
1079 }
1080 exts_iter->size = cur_size;
1081 next_seq_idx = cur_seq_idx + 1;
1082 }
1083 return kPglRetSuccess;
1084 PgfiInitPhase2FillExtSizes_error_or_eof:
1085 if (ferror_unlocked(ff)) {
1086 FillPgenHeaderReadErrstrFromNzErrno(is_pgi, errstr_buf);
1087 return kPglRetReadFail;
1088 }
1089 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid .pgen%s.\n", is_pgi? ".pgi file" : " header");
1090 return kPglRetMalformedInput;
1091 }
1092
1093 static_assert(kPglMaxAlleleCt == 255, "Need to update PgfiInitPhase2Ex().");
1094 PglErr PgfiInitPhase2Ex(PgenHeaderCtrl header_ctrl, uint32_t allele_cts_already_loaded, uint32_t nonref_flags_already_loaded, uint32_t use_blockload, uint32_t vblock_idx_start, uint32_t vidx_end, uint32_t* max_vrec_width_ptr, PgenFileInfo* pgfip, unsigned char* pgfi_alloc, PgenExtensionLl* header_exts, PgenExtensionLl* footer_exts, uintptr_t* pgr_alloc_cacheline_ct_ptr, char* errstr_buf) {
1095 // *max_vrec_width_ptr technically only needs to be set in single-variant
1096 // fread() mode, but its computation is not currently optimized out in the
1097 // other two modes.
1098
1099 // possible todo: add option to skip validation when allele_cts/nonref_flags
1100 // are already loaded. but let's play it safe for now.
1101 const uint32_t raw_variant_ct = pgfip->raw_variant_ct;
1102 const uint32_t const_vrec_width = pgfip->const_vrec_width;
1103 *pgr_alloc_cacheline_ct_ptr = 0;
1104
1105 // Note that this is a rather hefty stack allocation.
1106 unsigned char loadbuf[kPglVblockSize * 4];
1107
1108 uintptr_t* allele_idx_offsets_iter = pgfip->allele_idx_offsets;
1109 uintptr_t prev_allele_idx_offset = 0;
1110 if (allele_idx_offsets_iter) {
1111 if (!allele_cts_already_loaded) {
1112 *allele_idx_offsets_iter = 0;
1113 } else {
1114 prev_allele_idx_offset = *allele_idx_offsets_iter;
1115 }
1116 ++allele_idx_offsets_iter;
1117 }
1118 if (!raw_variant_ct) {
1119 return kPglRetSuccess;
1120 }
1121 const uint32_t nonref_flags_stored = ((header_ctrl >> 6) == 3);
1122 unsigned char* nonref_flags_iter = DowncastToUc(pgfip->nonref_flags);
1123 const unsigned char* fread_ptr = nullptr; // maybe-uninitialized warning
1124 FILE* header_ff = pgfip->pgi_ff;
1125 const uint32_t is_pgi = (header_ff != nullptr);
1126 if (!is_pgi) {
1127 header_ff = pgfip->shared_ff;
1128 assert(header_ff);
1129 }
1130 if (const_vrec_width) {
1131 assert(!is_pgi);
1132 // no allele counts to verify if fixed-width
1133 // always need ldbase_raw_genovec
1134 *pgr_alloc_cacheline_ct_ptr = NypCtToCachelineCt(pgfip->raw_sample_ct);
1135 *max_vrec_width_ptr = const_vrec_width;
1136 if (!use_blockload) {
1137 // using fread() single-variant-at-a-time, need pgr.fread_buf
1138 *pgr_alloc_cacheline_ct_ptr += DivUp(const_vrec_width, kCacheline);
1139 }
1140 if ((!(header_ctrl & 192)) || (pgfip->const_vrtype == kPglVrtypePlink1)) {
1141 return kPglRetSuccess;
1142 }
1143 if ((header_ctrl >> 6) == 1) {
1144 // all ref
1145 if (nonref_flags_already_loaded) {
1146 if (unlikely(!AllWordsAreZero(pgfip->nonref_flags, BitCtToWordCt(raw_variant_ct)))) {
1147 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Loaded nonref_flags do not match values in .pgen file.\n");
1148 return kPglRetInconsistentInput;
1149 }
1150 }
1151 return kPglRetSuccess;
1152 }
1153 if ((header_ctrl >> 6) == 2) {
1154 // all nonref
1155 if (nonref_flags_already_loaded) {
1156 if (unlikely(!AllBitsAreOne(pgfip->nonref_flags, raw_variant_ct))) {
1157 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Loaded nonref_flags do not match values in .pgen file.\n");
1158 return kPglRetInconsistentInput;
1159 }
1160 }
1161 return kPglRetSuccess;
1162 }
1163 // _last more useful than _end iff we just refer to the number of elements
1164 // in the block and have no use for a _stop pointer
1165 unsigned char* nonref_flags_last = &(nonref_flags_iter[((raw_variant_ct - 1) / (kPglVblockSize * 32)) * (kPglVblockSize * 4)]);
1166 uint32_t cur_byte_ct = kPglVblockSize * 4;
1167 for (; ; nonref_flags_iter = &(nonref_flags_iter[cur_byte_ct])) {
1168 if (nonref_flags_iter >= nonref_flags_last) {
1169 if (nonref_flags_iter > nonref_flags_last) {
1170 break;
1171 }
1172 cur_byte_ct = 1 + ((raw_variant_ct - 1) % (kPglVblockSize * 32)) / CHAR_BIT;
1173 }
1174 unsigned char* loadptr = nonref_flags_already_loaded? loadbuf : nonref_flags_iter;
1175 if (unlikely(!fread_unlocked(loadptr, cur_byte_ct, 1, header_ff))) {
1176 FillPgenHeaderReadErrstr(header_ff, is_pgi, errstr_buf);
1177 return kPglRetReadFail;
1178 }
1179 if (nonref_flags_already_loaded) {
1180 if (unlikely(!memequal(nonref_flags_iter, loadbuf, cur_byte_ct))) {
1181 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Loaded nonref_flags do not match values in .pgen file.\n");
1182 return kPglRetInconsistentInput;
1183 }
1184 }
1185 }
1186 return kPglRetSuccess;
1187 }
1188
1189 const uint32_t raw_sample_ct = pgfip->raw_sample_ct;
1190 unsigned char* vrtypes_iter = pgfi_alloc;
1191 pgfip->vrtypes = vrtypes_iter;
1192 uint64_t* var_fpos_iter = R_CAST(uint64_t*, &(vrtypes_iter[RoundUpPow2(raw_variant_ct + 1, kCacheline)]));
1193 pgfip->var_fpos = var_fpos_iter;
1194 uint32_t vblock_ct_m1 = (raw_variant_ct - 1) / kPglVblockSize;
1195 uint32_t max_vrec_width = 0;
1196 uint64_t variant_fpos;
1197 if (vblock_idx_start) {
1198 if (unlikely(fseeko(header_ff, vblock_idx_start * sizeof(int64_t), SEEK_CUR))) {
1199 FillPgenHeaderReadErrstrFromNzErrno(is_pgi, errstr_buf);
1200 return kPglRetReadFail;
1201 }
1202 }
1203 if (unlikely(!fread_unlocked(&variant_fpos, sizeof(int64_t), 1, header_ff))) {
1204 FillPgenHeaderReadErrstr(header_ff, is_pgi, errstr_buf);
1205 return kPglRetReadFail;
1206 }
1207 // May also need to load the rest of these values in the future, if we want
1208 // to support dynamic insertion into a memory-mapped file. But skip them
1209 // for now.
1210 if (unlikely(fseeko(header_ff, (vblock_ct_m1 - vblock_idx_start) * sizeof(int64_t), SEEK_CUR))) {
1211 FillPgenHeaderReadErrstrFromNzErrno(is_pgi, errstr_buf);
1212 return kPglRetReadFail;
1213 }
1214 const uint32_t vrtype_and_fpos_storage = header_ctrl & 15;
1215 const uint32_t alt_allele_ct_byte_ct = (header_ctrl >> 4) & 3;
1216 if (alt_allele_ct_byte_ct) {
1217 assert(alt_allele_ct_byte_ct == 1);
1218 if (unlikely(!allele_idx_offsets_iter)) {
1219 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: pgfip->allele_idx_offsets must be allocated before PgfiInitPhase2Ex() is called.\n");
1220 return kPglRetImproperFunctionCall;
1221 }
1222 }
1223 uint32_t vblock_idx = vblock_idx_start;
1224 vblock_ct_m1 = (vidx_end - 1) / kPglVblockSize;
1225 if (vblock_idx) {
1226 uintptr_t header_vblock_byte_ct = kPglVblockSize * alt_allele_ct_byte_ct;
1227 if (nonref_flags_stored) {
1228 header_vblock_byte_ct += kPglVblockSize / CHAR_BIT;
1229 }
1230 if (vrtype_and_fpos_storage & 8) {
1231 header_vblock_byte_ct += kPglVblockSize >> (10 - vrtype_and_fpos_storage);
1232 } else {
1233 if (!(vrtype_and_fpos_storage & 4)) {
1234 header_vblock_byte_ct += kPglVblockSize / 2;
1235 } else {
1236 header_vblock_byte_ct += kPglVblockSize;
1237 }
1238 header_vblock_byte_ct += kPglVblockSize * (1 + (vrtype_and_fpos_storage & 3));
1239 }
1240 if (unlikely(fseeko(header_ff, header_vblock_byte_ct * S_CAST(uint64_t, vblock_idx), SEEK_CUR))) {
1241 FillPgenHeaderReadErrstrFromNzErrno(is_pgi, errstr_buf);
1242 return kPglRetReadFail;
1243 }
1244 }
1245 uint32_t cur_vblock_variant_ct = kPglVblockSize;
1246 uint32_t max_allele_ct = pgfip->max_allele_ct;
1247 for (; ; ++vblock_idx) {
1248 if (vblock_idx >= vblock_ct_m1) {
1249 if (vblock_idx > vblock_ct_m1) {
1250 break;
1251 }
1252 cur_vblock_variant_ct = ModNz(vidx_end, kPglVblockSize);
1253 }
1254 // 1. handle vrtypes and var_fpos.
1255 if (vrtype_and_fpos_storage >= 8) {
1256 // Special encodings.
1257 uint32_t log2_entry_bit_width = 1;
1258 unsigned char vrtype_table[16];
1259 uint32_t vrec_len_table[16];
1260 vrtype_table[0] = 5;
1261 vrtype_table[1] = 0;
1262 vrec_len_table[0] = 0;
1263 const uint32_t raw_sample_ct4 = NypCtToByteCt(raw_sample_ct);
1264 vrec_len_table[1] = raw_sample_ct4;
1265 if (vrtype_and_fpos_storage == 8) {
1266 log2_entry_bit_width = 0;
1267 } else if (vrtype_and_fpos_storage == 9) {
1268 vrtype_table[2] = 8;
1269 vrtype_table[3] = 8;
1270 vrec_len_table[2] = raw_sample_ct4 + 2;
1271 vrec_len_table[3] = raw_sample_ct4 + 3;
1272 } else if (vrtype_and_fpos_storage == 10) {
1273 vrtype_table[2] = 16;
1274 vrtype_table[3] = 16;
1275 vrec_len_table[2] = raw_sample_ct4 + 1;
1276 vrec_len_table[3] = raw_sample_ct4 + 2;
1277 } else if (vrtype_and_fpos_storage == 11) {
1278 log2_entry_bit_width = 2;
1279 vrtype_table[2] = 8;
1280 vrtype_table[3] = 8;
1281 vrtype_table[4] = 8;
1282 vrtype_table[5] = 8;
1283 vrtype_table[6] = 8;
1284 vrtype_table[7] = 8;
1285 // 8 invalid
1286 vrtype_table[9] = 16;
1287 vrtype_table[10] = 24;
1288 vrtype_table[11] = 24;
1289 vrtype_table[12] = 24;
1290 vrtype_table[13] = 24;
1291 vrtype_table[14] = 24;
1292 vrtype_table[15] = 24;
1293 vrec_len_table[9] = raw_sample_ct4 + 1;
1294 for (uint32_t uii = 2; uii < 8; ++uii) {
1295 vrec_len_table[uii] = raw_sample_ct4 + uii;
1296 vrec_len_table[uii + 8] = raw_sample_ct4 + 1 + uii;
1297 }
1298 } else if (vrtype_and_fpos_storage == 12) {
1299 assert(raw_sample_ct == 1);
1300 vrtype_table[2] = 0x45;
1301 vrtype_table[3] = 0x40;
1302 vrec_len_table[2] = 2;
1303 vrec_len_table[3] = 3;
1304 } else {
1305 // 14 is only remaining possibility for now
1306 assert(raw_sample_ct == 1);
1307 log2_entry_bit_width = 2;
1308 vrtype_table[3] = 0x10;
1309 vrtype_table[4] = 0x45;
1310 vrtype_table[5] = 0x40;
1311 vrtype_table[12] = 0xc5;
1312 vrtype_table[13] = 0xc0;
1313 vrtype_table[15] = 0xe0;
1314 vrec_len_table[3] = 2;
1315 vrec_len_table[4] = 2;
1316 vrec_len_table[5] = 3;
1317 vrec_len_table[12] = 4;
1318 vrec_len_table[13] = 5;
1319 vrec_len_table[15] = 6;
1320 }
1321 const uint32_t entry_bit_width = 1 << log2_entry_bit_width;
1322 const uint32_t entry_mask = (1 << entry_bit_width) - 1;
1323 const uint32_t cur_byte_ct = 1 + ((cur_vblock_variant_ct - 1) >> (3 - log2_entry_bit_width));
1324 const unsigned char* loadbuf_biter;
1325 if (unlikely(!fread_unlocked(loadbuf, cur_byte_ct, 1, header_ff))) {
1326 FillPgenHeaderReadErrstr(header_ff, is_pgi, errstr_buf);
1327 return kPglRetReadFail;
1328 }
1329 loadbuf_biter = loadbuf;
1330 const uint32_t log2_entries_per_word = kBitsPerWordLog2 - log2_entry_bit_width;
1331 const uint32_t block_len = 1 << log2_entries_per_word;
1332 uint32_t cur_vblock_idx = 0;
1333 uint32_t cur_vblock_idx_stop = block_len;
1334 for (; ; cur_vblock_idx_stop += block_len) {
1335 if (cur_vblock_idx_stop > cur_vblock_variant_ct) {
1336 if (cur_vblock_idx == cur_vblock_variant_ct) {
1337 break;
1338 }
1339 cur_vblock_idx_stop = cur_vblock_variant_ct;
1340 }
1341 uintptr_t input_word;
1342 CopyFromUnalignedIncrW(&input_word, &loadbuf_biter);
1343 for (; cur_vblock_idx != cur_vblock_idx_stop; ++cur_vblock_idx) {
1344 const uint32_t input_word_masked = input_word & entry_mask;
1345 *vrtypes_iter++ = vrtype_table[input_word_masked];
1346 *var_fpos_iter++ = variant_fpos;
1347 variant_fpos += vrec_len_table[input_word_masked];
1348 input_word >>= entry_bit_width;
1349 }
1350 }
1351 } else {
1352 if (vrtype_and_fpos_storage < 4) {
1353 // no phase or dosage present, 4-bit vrtypes
1354 const uint32_t cur_byte_ct = DivUp(cur_vblock_variant_ct, 2);
1355 if (unlikely(!fread_unlocked(loadbuf, cur_byte_ct, 1, header_ff))) {
1356 FillPgenHeaderReadErrstr(header_ff, is_pgi, errstr_buf);
1357 return kPglRetReadFail;
1358 }
1359 fread_ptr = loadbuf;
1360 Expand4bitTo8(fread_ptr, cur_vblock_variant_ct, 0, vrtypes_iter);
1361 vrtypes_iter = &(vrtypes_iter[cur_vblock_variant_ct]);
1362 } else {
1363 // phase and dosage
1364 if (unlikely(!fread_unlocked(vrtypes_iter, cur_vblock_variant_ct, 1, header_ff))) {
1365 FillPgenHeaderReadErrstr(header_ff, is_pgi, errstr_buf);
1366 return kPglRetReadFail;
1367 }
1368 vrtypes_iter = &(vrtypes_iter[cur_vblock_variant_ct]);
1369 }
1370 const uint32_t vrec_len_byte_ct = 1 + (vrtype_and_fpos_storage & 3);
1371 const uint32_t cur_byte_ct = cur_vblock_variant_ct * vrec_len_byte_ct;
1372 if (unlikely(!fread_unlocked(loadbuf, cur_byte_ct, 1, header_ff))) {
1373 FillPgenHeaderReadErrstr(header_ff, is_pgi, errstr_buf);
1374 return kPglRetReadFail;
1375 }
1376 fread_ptr = loadbuf;
1377 if (vrec_len_byte_ct == 1) {
1378 for (uint32_t cur_vblock_vidx = 0; cur_vblock_vidx != cur_vblock_variant_ct; ++cur_vblock_vidx) {
1379 var_fpos_iter[cur_vblock_vidx] = variant_fpos;
1380 uint32_t cur_vrec_len = fread_ptr[cur_vblock_vidx];
1381 variant_fpos += cur_vrec_len;
1382 // no need for correct max_vrec_width
1383 }
1384 } else if (vrec_len_byte_ct == 2) {
1385 for (uint32_t cur_vblock_vidx = 0; cur_vblock_vidx != cur_vblock_variant_ct; ++cur_vblock_vidx) {
1386 var_fpos_iter[cur_vblock_vidx] = variant_fpos;
1387 uint16_t cur_vrec_len;
1388 CopyFromUnalignedU16(&cur_vrec_len, &(fread_ptr[cur_vblock_vidx * 2]));
1389 variant_fpos += cur_vrec_len;
1390 if (cur_vrec_len > max_vrec_width) {
1391 // todo: check whether we're better off just assuming 2^16 - 1
1392 max_vrec_width = cur_vrec_len;
1393 }
1394 }
1395 } else if (vrec_len_byte_ct == 3) {
1396 for (uint32_t cur_vblock_vidx = 0; cur_vblock_vidx != cur_vblock_variant_ct; ++cur_vblock_vidx) {
1397 var_fpos_iter[cur_vblock_vidx] = variant_fpos;
1398 uint32_t cur_vrec_len;
1399 // safe to read a byte past the end, since that's in loadbuf
1400 CopyFromUnalignedU32(&cur_vrec_len, &(fread_ptr[cur_vblock_vidx * 3]));
1401 cur_vrec_len &= 0xffffff;
1402 variant_fpos += cur_vrec_len;
1403 if (cur_vrec_len > max_vrec_width) {
1404 max_vrec_width = cur_vrec_len;
1405 }
1406 }
1407 } else {
1408 for (uint32_t cur_vblock_vidx = 0; cur_vblock_vidx != cur_vblock_variant_ct; ++cur_vblock_vidx) {
1409 var_fpos_iter[cur_vblock_vidx] = variant_fpos;
1410 uint32_t cur_vrec_len;
1411 CopyFromUnalignedU32(&cur_vrec_len, &(fread_ptr[cur_vblock_vidx * 4]));
1412 variant_fpos += cur_vrec_len;
1413 if (cur_vrec_len > max_vrec_width) {
1414 max_vrec_width = cur_vrec_len;
1415 }
1416 }
1417 #ifdef __LP64__
1418 if (unlikely(max_vrec_width > kPglMaxBytesPerVariant)) {
1419 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid .pgen%s.\n", is_pgi? ".pgi file" : " header");
1420 return kPglRetMalformedInput;
1421 }
1422 #else
1423 if (unlikely(max_vrec_width > kMaxBytesPerIO)) {
1424 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Variant records too large for 32-bit pgenlib.\n");
1425 return kPglRetNomem;
1426 }
1427 #endif
1428 }
1429 var_fpos_iter = &(var_fpos_iter[cur_vblock_variant_ct]);
1430 }
1431 // 2. allele counts?
1432 if (alt_allele_ct_byte_ct) {
1433 assert(alt_allele_ct_byte_ct == 1);
1434 if (unlikely(!fread_unlocked(loadbuf, cur_vblock_variant_ct * alt_allele_ct_byte_ct, 1, header_ff))) {
1435 FillPgenHeaderReadErrstr(header_ff, is_pgi, errstr_buf);
1436 return kPglRetReadFail;
1437 }
1438 fread_ptr = loadbuf;
1439 // max_allele_ct scan can probably be sped up with _mm{256}_max_epu8()?
1440 // probably can't do much for main loop (at least in sizeof(AlleleCode)
1441 // == 1 case)
1442 if (allele_cts_already_loaded) {
1443 // todo: update this for multibyte AlleleCode
1444 for (uint32_t cur_vblock_vidx = 0; cur_vblock_vidx != cur_vblock_variant_ct; ++cur_vblock_vidx) {
1445 const uintptr_t cur_allele_idx_offset = allele_idx_offsets_iter[cur_vblock_vidx];
1446 const uint32_t cur_allele_ct = fread_ptr[cur_vblock_vidx];
1447 if (unlikely((cur_allele_idx_offset - prev_allele_idx_offset) != cur_allele_ct)) {
1448 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Loaded allele_idx_offsets do not match values in .pgen%s file.\n", is_pgi? ".pgi" : "");
1449 return kPglRetInconsistentInput;
1450 }
1451 prev_allele_idx_offset = cur_allele_idx_offset;
1452 if (cur_allele_ct > max_allele_ct) {
1453 max_allele_ct = cur_allele_ct;
1454 }
1455 }
1456 } else {
1457 for (uint32_t cur_vblock_vidx = 0; cur_vblock_vidx != cur_vblock_variant_ct; ++cur_vblock_vidx) {
1458 const uint32_t cur_allele_ct = fread_ptr[cur_vblock_vidx];
1459 allele_idx_offsets_iter[cur_vblock_vidx] = prev_allele_idx_offset;
1460 prev_allele_idx_offset += cur_allele_ct;
1461 if (cur_allele_ct > max_allele_ct) {
1462 max_allele_ct = cur_allele_ct;
1463 }
1464 }
1465 }
1466 allele_idx_offsets_iter = &(allele_idx_offsets_iter[cur_vblock_variant_ct]);
1467 }
1468 // 3. nonref flags?
1469 if (nonref_flags_stored) {
1470 const uint32_t cur_byte_ct = DivUp(cur_vblock_variant_ct, CHAR_BIT);
1471 unsigned char* loadptr = nonref_flags_already_loaded? loadbuf : nonref_flags_iter;
1472 if (unlikely(!fread_unlocked(loadptr, cur_byte_ct, 1, header_ff))) {
1473 FillPgenHeaderReadErrstr(header_ff, is_pgi, errstr_buf);
1474 return kPglRetReadFail;
1475 }
1476 if (nonref_flags_already_loaded) {
1477 if (unlikely(!memequal(nonref_flags_iter, loadbuf, cur_byte_ct))) {
1478 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Loaded nonref_flags do not match values in .pgen%s file.\n", is_pgi? ".pgi" : "");
1479 return kPglRetInconsistentInput;
1480 }
1481 }
1482 nonref_flags_iter = &(nonref_flags_iter[cur_byte_ct]);
1483 }
1484 }
1485
1486 const uint32_t last_word_byte_ct = cur_vblock_variant_ct % kBytesPerWord;
1487 if (last_word_byte_ct) {
1488 ProperSubwordStore(0, kBytesPerWord - last_word_byte_ct, vrtypes_iter);
1489 } else {
1490 // must guarantee a trailing zero for is_ldbase check to work
1491 vrtypes_iter[0] = 0;
1492 }
1493
1494 uint64_t footer_extensions_fpos = 0;
1495 if (pgfip->extensions_present && (header_exts || footer_exts)) {
1496 if (vidx_end < raw_variant_ct) {
1497 const uint32_t vrec_len_byte_ct = 1 + (vrtype_and_fpos_storage & 3);
1498 const uint32_t phase_or_dosage_present = (vrtype_and_fpos_storage >= 4);
1499 const uint64_t ext_fpos = PglHeaderBaseEndOffset(raw_variant_ct, vrec_len_byte_ct, phase_or_dosage_present, nonref_flags_stored);
1500 if (unlikely(fseeko(header_ff, ext_fpos, SEEK_SET))) {
1501 FillPgenHeaderReadErrstrFromNzErrno(is_pgi, errstr_buf);
1502 return kPglRetReadFail;
1503 }
1504 }
1505 PglErr reterr = PgfiInitPhase2PreprocessExts(is_pgi, header_ff, header_exts, nullptr, errstr_buf);
1506 if (unlikely(reterr)) {
1507 return reterr;
1508 }
1509 reterr = PgfiInitPhase2PreprocessExts(is_pgi, header_ff, footer_exts, &footer_extensions_fpos, errstr_buf);
1510 if (unlikely(reterr)) {
1511 return reterr;
1512 }
1513 reterr = PgfiInitPhase2FillExtSizes(is_pgi, header_ff, header_exts, errstr_buf);
1514 if (unlikely(reterr)) {
1515 return reterr;
1516 }
1517 }
1518
1519 if (is_pgi && (!header_exts) && (!footer_exts)) {
1520 if (unlikely(fclose_null(&pgfip->pgi_ff))) {
1521 FillPgenHeaderReadErrstrFromNzErrno(1, errstr_buf);
1522 return kPglRetReadFail;
1523 }
1524 }
1525
1526 const uint64_t actual_fpos = ftello(pgfip->shared_ff);
1527 if (actual_fpos != pgfip->var_fpos[0]) {
1528 // now > instead of != to allow additional information to be stored between
1529 // header and first variant record (e.g. mode 0x11).
1530 if (unlikely(actual_fpos > pgfip->var_fpos[0])) {
1531 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid .pgen%s.\n", is_pgi? ".pgi file" : " header");
1532 return kPglRetMalformedInput;
1533 }
1534 if (unlikely(fseeko(pgfip->shared_ff, pgfip->var_fpos[0], SEEK_SET))) {
1535 FillPgenReadErrstrFromNzErrno(errstr_buf);
1536 return kPglRetReadFail;
1537 }
1538 }
1539 if (footer_extensions_fpos && footer_exts) {
1540 if (unlikely(fseeko(pgfip->shared_ff, footer_extensions_fpos, SEEK_SET))) {
1541 FillPgenReadErrstrFromNzErrno(errstr_buf);
1542 return kPglRetReadFail;
1543 }
1544 PglErr reterr = PgfiInitPhase2FillExtSizes(0, pgfip->shared_ff, footer_exts, errstr_buf);
1545 if (unlikely(reterr)) {
1546 return reterr;
1547 }
1548 if (unlikely(fseeko(pgfip->shared_ff, pgfip->var_fpos[0], SEEK_SET))) {
1549 FillPgenReadErrstrFromNzErrno(errstr_buf);
1550 return kPglRetReadFail;
1551 }
1552 }
1553 pgfip->var_fpos[vidx_end] = variant_fpos;
1554 pgfip->max_allele_ct = max_allele_ct;
1555 // if difflist/LD might be present, scan for them in a way that's likely to
1556 // terminate quickly
1557 PgenGlobalFlags new_gflags = kfPgenGlobal0;
1558 if (vrtype_and_fpos_storage != 8) {
1559 const uint32_t trailing_byte_ct = vidx_end & (kBytesPerVec - 1);
1560 if (trailing_byte_ct) {
1561 memset(&(pgfip->vrtypes[vidx_end]), 0, kBytesPerVec - trailing_byte_ct);
1562 }
1563 const VecW* vrtypes_alias_start = R_CAST(VecW*, pgfip->vrtypes);
1564 const VecW* vrtypes_alias_end = &(vrtypes_alias_start[DivUp(vidx_end, kBytesPerVec)]);
1565 if (vblock_idx_start) {
1566 vrtypes_alias_start = &(vrtypes_alias_start[vblock_idx_start * (kPglVblockSize / kBytesPerVec)]);
1567 }
1568 const VecW* vrtypes_alias_iter = vrtypes_alias_start;
1569 if (vrtype_and_fpos_storage < 8) {
1570 for (; vrtypes_alias_iter != vrtypes_alias_end; ++vrtypes_alias_iter) {
1571 const VecW cur_vvec = *vrtypes_alias_iter;
1572 #ifdef __LP64__
1573 // todo: better ARM implementation
1574 const VecW cur_vvec_bit2 = vecw_slli(cur_vvec, 5);
1575 const VecW cur_vvec_bit1 = vecw_slli(cur_vvec, 6);
1576 // check if any vrtype has bit 1 set and bit 2 clear
1577 if (vecw_movemask(vecw_and_notfirst(cur_vvec_bit2, cur_vvec_bit1))) {
1578 new_gflags |= kfPgenGlobalLdCompressionPresent | kfPgenGlobalDifflistOrLdPresent;
1579 break;
1580 }
1581 const VecW cur_vvec_bit0 = vecw_slli(cur_vvec, 7);
1582 if (vecw_movemask(cur_vvec_bit0 | cur_vvec_bit2)) {
1583 // this catches onebit
1584 new_gflags |= kfPgenGlobalDifflistOrLdPresent;
1585 }
1586 #else
1587 const uintptr_t cur_vvec_shifted = cur_vvec >> 1;
1588 // check if any vrtype has bit 1 set and bit 2 clear
1589 if (vecw_and_notfirst(cur_vvec_shifted, cur_vvec) & (2 * kMask0101)) {
1590 new_gflags |= kfPgenGlobalLdCompressionPresent | kfPgenGlobalDifflistOrLdPresent;
1591 break;
1592 }
1593 if (cur_vvec & (5 * kMask0101)) {
1594 // this catches onebit
1595 new_gflags |= kfPgenGlobalDifflistOrLdPresent;
1596 }
1597 #endif
1598 }
1599 }
1600 if (vrtype_and_fpos_storage >= 4) {
1601 // Likely for one of {hphase, dosage} to be present without the
1602 // other; make this scan faster in that case, at the cost of
1603 // failing to early-exit when both are present.
1604 // This is also suboptimal for the vrtype_and_fpos_storage > 8
1605 // special encodings.
1606 VecW or_vvec = vecw_setzero();
1607 for (vrtypes_alias_iter = vrtypes_alias_start; vrtypes_alias_iter != vrtypes_alias_end; ++vrtypes_alias_iter) {
1608 or_vvec |= *vrtypes_alias_iter;
1609 }
1610 #ifdef __LP64__
1611 const VecW or_vvec_bit3 = vecw_slli(or_vvec, 4);
1612 if (vecw_movemask(or_vvec_bit3)) {
1613 // note that, if no phase or dosage data is present, we don't
1614 // look for multiallelic hardcalls.
1615 new_gflags |= kfPgenGlobalMultiallelicHardcallFound;
1616 }
1617 const VecW or_vvec_bit4 = vecw_slli(or_vvec, 3);
1618 if (vecw_movemask(or_vvec_bit4)) {
1619 new_gflags |= kfPgenGlobalHardcallPhasePresent;
1620 }
1621 const VecW or_vvec_bit5 = vecw_slli(or_vvec, 2);
1622 const VecW or_vvec_bit6 = vecw_slli(or_vvec, 1);
1623 if (vecw_movemask(or_vvec_bit5 | or_vvec_bit6)) {
1624 new_gflags |= kfPgenGlobalDosagePresent;
1625 if (vecw_movemask(or_vvec)) {
1626 new_gflags |= kfPgenGlobalDosagePhasePresent;
1627 }
1628 }
1629 #else
1630 if (or_vvec & (8 * kMask0101)) {
1631 new_gflags |= kfPgenGlobalMultiallelicHardcallFound;
1632 }
1633 if (or_vvec & (0x10 * kMask0101)) {
1634 new_gflags |= kfPgenGlobalHardcallPhasePresent;
1635 }
1636 if (or_vvec & (0x60 * kMask0101)) {
1637 new_gflags |= kfPgenGlobalDosagePresent;
1638 if (or_vvec & (0x80 * kMask0101)) {
1639 new_gflags |= kfPgenGlobalDosagePhasePresent;
1640 }
1641 }
1642 #endif
1643 }
1644 if (vrtype_and_fpos_storage > 8) {
1645 if (vrtype_and_fpos_storage == 12) {
1646 max_vrec_width = 3;
1647 } else if (vrtype_and_fpos_storage == 14) {
1648 max_vrec_width = 6;
1649 } else {
1650 max_vrec_width = NypCtToByteCt(raw_sample_ct);
1651 if (vrtype_and_fpos_storage == 9) {
1652 max_vrec_width += 3;
1653 } else if (vrtype_and_fpos_storage == 10) {
1654 max_vrec_width += 2;
1655 } else {
1656 // 11
1657 max_vrec_width += 8;
1658 }
1659 // 13 and 15 not specified yet
1660 }
1661 } else if (!(vrtype_and_fpos_storage & 3)) {
1662 // 1 byte per vrec_len entry, don't bother to determine true
1663 // maximum
1664 max_vrec_width = 255;
1665 }
1666 pgfip->gflags |= new_gflags;
1667 } else {
1668 // vrtype_and_fpos_storage == 8.
1669 max_vrec_width = NypCtToByteCt(raw_sample_ct);
1670 }
1671 *pgr_alloc_cacheline_ct_ptr = CountPgrAllocCachelinesRequired(raw_sample_ct, new_gflags, max_allele_ct, use_blockload? 0 : max_vrec_width);
1672 *max_vrec_width_ptr = max_vrec_width;
1673 return kPglRetSuccess;
1674 }
1675
1676 PglErr PgfiInitReloadExtSet(uint32_t is_pgi, FILE* ff, uintptr_t* ext_bitarr, uint32_t* ext_bitarr_cumulative_popcounts, uint64_t* footer_fpos_ptr, uint32_t* word_ct_ptr, char* errstr_buf) {
1677 uintptr_t cur_output_word = 0;
1678 uintptr_t nonzero_present = 0;
1679 uint32_t write_idx_lowbits = 0;
1680 uint32_t widx = 0;
1681 ext_bitarr_cumulative_popcounts[0] = 0;
1682 while (1) {
1683 const int32_t ii = getc_unlocked(ff);
1684 if (unlikely(ii == EOF)) {
1685 if (ferror_unlocked(ff)) {
1686 FillPgenHeaderReadErrstrFromNzErrno(is_pgi, errstr_buf);
1687 return kPglRetReadFail;
1688 }
1689 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid .pgen%s.\n", is_pgi? ".pgi file" : " header");
1690 return kPglRetMalformedInput;
1691 }
1692 const uintptr_t cur_masked_bits = ii & 127;
1693 cur_output_word |= cur_masked_bits << write_idx_lowbits;
1694 uint32_t new_write_idx_lowbits = write_idx_lowbits + 7;
1695 if (new_write_idx_lowbits >= kBitsPerWord) {
1696 ext_bitarr[widx] = cur_output_word;
1697 nonzero_present |= cur_output_word;
1698 ++widx;
1699 ext_bitarr_cumulative_popcounts[widx] = PopcountWord(cur_output_word);
1700 cur_output_word = cur_masked_bits >> (kBitsPerWord - write_idx_lowbits);
1701 new_write_idx_lowbits -= kBitsPerWord;
1702 }
1703 write_idx_lowbits = new_write_idx_lowbits;
1704 if (!(ii & 128)) {
1705 break;
1706 }
1707 if (unlikely(widx == (256 / kBitsPerWord))) {
1708 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid .pgen%s.\n", is_pgi? ".pgi file" : " header");
1709 return kPglRetMalformedInput;
1710 }
1711 }
1712 ext_bitarr[widx] = cur_output_word;
1713 nonzero_present |= cur_output_word;
1714 *word_ct_ptr = widx + 1;
1715 if (footer_fpos_ptr && nonzero_present) {
1716 if (unlikely(!fread_unlocked(footer_fpos_ptr, sizeof(int64_t), 1, ff))) {
1717 FillPgenHeaderReadErrstr(ff, is_pgi, errstr_buf);
1718 return kPglRetReadFail;
1719 }
1720 }
1721 return kPglRetSuccess;
1722 }
1723
1724 PglErr PgfiInitFillExts(const uintptr_t* ext_bitarr, const uint32_t* ext_cumulative_popcounts, uint32_t word_ct, uint32_t is_pgi, FILE* ff, PgenExtensionLl* exts, char* errstr_buf) {
1725 {
1726 const uint32_t ext_ct = ext_cumulative_popcounts[word_ct - 1] + PopcountWord(ext_bitarr[word_ct - 1]);
1727 uint64_t sizes[256];
1728 for (uint32_t seq_idx = 0; seq_idx != ext_ct; ++seq_idx) {
1729 const uint64_t cur_size = FGetVint63(ff);
1730 if (unlikely(cur_size == (1LLU << 63))) {
1731 goto PgfiInitFillExts_error_or_eof;
1732 }
1733 sizes[seq_idx] = cur_size;
1734 }
1735 const uint32_t type_idx_limit = word_ct * kBitsPerWord;
1736 uint32_t next_seq_idx = 0;
1737 for (PgenExtensionLl* exts_iter = exts; exts_iter; exts_iter = exts_iter->next) {
1738 const uint32_t type_idx = exts_iter->type_idx;
1739 if (type_idx >= type_idx_limit) {
1740 break;
1741 }
1742 if ((exts_iter->size == ~0LLU) || (!IsSet(ext_bitarr, type_idx))) {
1743 continue;
1744 }
1745 const uint32_t seq_idx = RawToSubsettedPos(ext_bitarr, ext_cumulative_popcounts, type_idx);
1746 const uint64_t cur_size = sizes[seq_idx];
1747 if (unlikely(cur_size != exts_iter->size)) {
1748 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: PgfiInitLoadExts() extension byte-size mismatch.\n");
1749 return kPglRetImproperFunctionCall;
1750 }
1751 if (seq_idx > next_seq_idx) {
1752 uint64_t bytes_to_skip = 0;
1753 for (uint32_t uii = next_seq_idx; uii != seq_idx; ++uii) {
1754 bytes_to_skip += sizes[uii];
1755 }
1756 if (unlikely(fseeko(ff, bytes_to_skip, SEEK_CUR))) {
1757 FillPgenHeaderReadErrstrFromNzErrno(is_pgi, errstr_buf);
1758 return kPglRetReadFail;
1759 }
1760 }
1761 if (unlikely(fread_checked(exts_iter->contents, cur_size, ff))) {
1762 FillPgenHeaderReadErrstr(ff, is_pgi, errstr_buf);
1763 return kPglRetReadFail;
1764 }
1765 next_seq_idx = seq_idx + 1;
1766 }
1767 return kPglRetSuccess;
1768 }
1769 PgfiInitFillExts_error_or_eof:
1770 if (ferror_unlocked(ff)) {
1771 FillPgenHeaderReadErrstrFromNzErrno(is_pgi, errstr_buf);
1772 return kPglRetReadFail;
1773 }
1774 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid .pgen%s.\n", is_pgi? ".pgi file" : " header");
1775 return kPglRetMalformedInput;
1776 }
1777
1778 PglErr PgfiInitLoadExts(PgenHeaderCtrl header_ctrl, PgenFileInfo* pgfip, PgenExtensionLl* header_exts, PgenExtensionLl* footer_exts, char* errstr_buf) {
1779 const uint64_t starting_fpos = ftello(pgfip->shared_ff);
1780 FILE* header_ff = pgfip->pgi_ff;
1781 const uint32_t is_pgi = (header_ff != nullptr);
1782 if (!is_pgi) {
1783 header_ff = pgfip->shared_ff;
1784 assert(header_ff);
1785 }
1786 {
1787 const uint32_t vrtype_and_fpos_storage = header_ctrl & 15;
1788 const uint32_t vrec_len_byte_ct = 1 + (vrtype_and_fpos_storage & 3);
1789 const uint32_t phase_or_dosage_present = (vrtype_and_fpos_storage >= 4);
1790 const uint32_t nonref_flags_stored = ((header_ctrl >> 6) == 3);
1791 const uint64_t ext_fpos = PglHeaderBaseEndOffset(pgfip->raw_variant_ct, vrec_len_byte_ct, phase_or_dosage_present, nonref_flags_stored);
1792 if (unlikely(fseeko(header_ff, ext_fpos, SEEK_SET))) {
1793 FillPgenHeaderReadErrstrFromNzErrno(is_pgi, errstr_buf);
1794 return kPglRetReadFail;
1795 }
1796 }
1797 uintptr_t header_bitarr[(256 / kBitsPerWord) + 1];
1798 uint32_t header_bitarr_cumulative_popcounts[(256 / kBitsPerWord) + 1];
1799 uint32_t header_ext_word_ct;
1800 PglErr reterr = PgfiInitReloadExtSet(is_pgi, header_ff, header_bitarr, header_bitarr_cumulative_popcounts, nullptr, &header_ext_word_ct, errstr_buf);
1801 if (unlikely(reterr)) {
1802 return reterr;
1803 }
1804 uintptr_t footer_bitarr[(256 / kBitsPerWord) + 1];
1805 uint32_t footer_bitarr_cumulative_popcounts[(256 / kBitsPerWord) + 1];
1806 uint32_t footer_ext_word_ct;
1807 uint64_t footer_extensions_fpos;
1808 reterr = PgfiInitReloadExtSet(is_pgi, header_ff, footer_bitarr, footer_bitarr_cumulative_popcounts, &footer_extensions_fpos, &footer_ext_word_ct, errstr_buf);
1809 if (unlikely(reterr)) {
1810 return reterr;
1811 }
1812 if (header_exts) {
1813 reterr = PgfiInitFillExts(header_bitarr, header_bitarr_cumulative_popcounts, header_ext_word_ct, is_pgi, header_ff, header_exts, errstr_buf);
1814 if (unlikely(reterr)) {
1815 return reterr;
1816 }
1817 }
1818 if (is_pgi) {
1819 if (unlikely(fclose_null(&pgfip->pgi_ff))) {
1820 FillPgenHeaderReadErrstrFromNzErrno(1, errstr_buf);
1821 return kPglRetReadFail;
1822 }
1823 }
1824 if (footer_exts) {
1825 if (unlikely(fseeko(pgfip->shared_ff, footer_extensions_fpos, SEEK_SET))) {
1826 FillPgenReadErrstrFromNzErrno(errstr_buf);
1827 return kPglRetReadFail;
1828 }
1829 reterr = PgfiInitFillExts(footer_bitarr, footer_bitarr_cumulative_popcounts, footer_ext_word_ct, 0, pgfip->shared_ff, footer_exts, errstr_buf);
1830 if (unlikely(reterr)) {
1831 return reterr;
1832 }
1833 }
1834 if (unlikely(fseeko(pgfip->shared_ff, starting_fpos, SEEK_SET))) {
1835 FillPgenReadErrstrFromNzErrno(errstr_buf);
1836 return kPglRetReadFail;
1837 }
1838 return kPglRetSuccess;
1839 }
1840
1841 uint32_t GetLdbaseVidx(const unsigned char* vrtypes, uint32_t cur_vidx) {
1842 #ifdef __LP64__
1843 const VecW* vrtypes_valias = R_CAST(const VecW*, vrtypes);
1844 const uint32_t cur_vidx_orig_remainder = cur_vidx % kBytesPerVec;
1845 uint32_t vidx_vec_idx = cur_vidx / kBytesPerVec;
1846 Vec8thUint v8ui = 0;
1847 if (cur_vidx_orig_remainder) {
1848 const VecW cur_vvec = vrtypes_valias[vidx_vec_idx];
1849 // non-ld: ((bit 2) OR (NOT bit 1))
1850 // todo: better ARM implementation
1851 const VecW cur_vvec_bit2 = vecw_slli(cur_vvec, 5);
1852 const VecW inv_cur_vvec_bit1 = ~vecw_slli(cur_vvec, 6);
1853 v8ui = vecw_movemask(cur_vvec_bit2 | inv_cur_vvec_bit1);
1854 v8ui = bzhi(v8ui, cur_vidx_orig_remainder);
1855 }
1856 while (!v8ui) {
1857 const VecW cur_vvec = vrtypes_valias[--vidx_vec_idx];
1858 const VecW cur_vvec_bit2 = vecw_slli(cur_vvec, 5);
1859 const VecW inv_cur_vvec_bit1 = ~vecw_slli(cur_vvec, 6);
1860 v8ui = vecw_movemask(cur_vvec_bit2 | inv_cur_vvec_bit1);
1861 }
1862 return (vidx_vec_idx * kBytesPerVec) + bsru32(v8ui);
1863 #else
1864 const uintptr_t* vrtypes_walias = R_CAST(const uintptr_t*, vrtypes);
1865 const uint32_t cur_vidx_orig_remainder = cur_vidx % kBytesPerWord;
1866 uint32_t vidx_word_idx = (cur_vidx - 1) / kBytesPerWord;
1867 uintptr_t cur_vrtypes_word = vrtypes_walias[vidx_word_idx];
1868 if (cur_vidx_orig_remainder) {
1869 // make sure we don't detect a byte after the current position.
1870 cur_vrtypes_word = bzhi(cur_vrtypes_word, CHAR_BIT * cur_vidx_orig_remainder);
1871 cur_vrtypes_word |= (kMask0101 * 2) << (CHAR_BIT * cur_vidx_orig_remainder);
1872 }
1873 while (1) {
1874 // ((bit 2) OR (NOT bit 1)) for each byte. (possible experiment: see if
1875 // the same assembly is generated if this expression is rewritten to use
1876 // ands/nots.)
1877 const uintptr_t detect_non_ld_word = ((cur_vrtypes_word >> 1) | (~cur_vrtypes_word)) & (kMask0101 * 2);
1878 if (detect_non_ld_word) {
1879 // find the highest-order set bit in detect_non_ld_word; this corresponds
1880 // to the last non-LD-compressed byte (assuming little-endian).
1881 const uint32_t new_ldbase_vidx_loworder = bsrw(detect_non_ld_word) / CHAR_BIT;
1882 return (vidx_word_idx * kBytesPerWord) + new_ldbase_vidx_loworder;
1883 }
1884 // everything LD-compressed in the current block. move back 8 bytes in the
1885 // array (or 4-bytes for 32-bit build).
1886 cur_vrtypes_word = vrtypes_walias[--vidx_word_idx];
1887 }
1888 #endif
1889 }
1890
1891 uint64_t GetPgfiLdbaseFpos(const PgenFileInfo* pgfip, uintptr_t vidx) {
1892 if (!pgfip->var_fpos) {
1893 return pgfip->const_fpos_offset + pgfip->const_vrec_width * S_CAST(uint64_t, vidx);
1894 }
1895 if (pgfip->vrtypes && ((pgfip->vrtypes[vidx] & 6) == 2)) {
1896 vidx = GetLdbaseVidx(pgfip->vrtypes, vidx);
1897 }
1898 return pgfip->var_fpos[vidx];
1899 }
1900
1901 uint64_t PgfiMultireadGetCachelineReq(const uintptr_t* variant_include, const PgenFileInfo* pgfip, uint32_t variant_ct, uint32_t block_size) {
1902 // if block_size < kPglVblockSize, it's ideal for it to be a power of 2 (to
1903 // avoid unnecessary vblock crossing), but that's not required.
1904 const uint32_t raw_variant_ct = pgfip->raw_variant_ct;
1905 if (variant_ct == raw_variant_ct) {
1906 variant_include = nullptr;
1907 }
1908 uint32_t block_ct_m1 = 0;
1909 if (raw_variant_ct < block_size) {
1910 block_size = raw_variant_ct;
1911 } else {
1912 block_ct_m1 = (raw_variant_ct - 1) / block_size;
1913 }
1914 const uint64_t* var_fpos = pgfip->var_fpos;
1915 if ((!variant_include) && (!var_fpos)) {
1916 return DivUpU64(S_CAST(uint64_t, pgfip->const_vrec_width) * block_size, kCacheline);
1917 }
1918 uint64_t max_block_byte_ct = 0;
1919 uint32_t max_block_variant_ct = 0;
1920 for (uint32_t block_idx = 0; ; ++block_idx) {
1921 uint32_t variant_uidx_start = block_idx * block_size;
1922 uint32_t variant_uidx_end = variant_uidx_start + block_size;
1923 if (block_idx >= block_ct_m1) {
1924 if (block_idx > block_ct_m1) {
1925 break;
1926 }
1927 variant_uidx_end = raw_variant_ct;
1928 }
1929 if (variant_include) {
1930 variant_uidx_start = AdvBoundedTo1Bit(variant_include, variant_uidx_start, variant_uidx_end);
1931 if (variant_uidx_start == variant_uidx_end) {
1932 continue;
1933 }
1934 variant_uidx_end = 1 + FindLast1BitBefore(variant_include, variant_uidx_end);
1935 }
1936 if (var_fpos) {
1937 if (pgfip->vrtypes && ((pgfip->vrtypes[variant_uidx_start] & 6) == 2)) {
1938 // need to start loading from LD-buddy
1939 variant_uidx_start = GetLdbaseVidx(pgfip->vrtypes, variant_uidx_start);
1940 }
1941 uint64_t cur_block_byte_ct = var_fpos[variant_uidx_end] - var_fpos[variant_uidx_start];
1942 if (cur_block_byte_ct > max_block_byte_ct) {
1943 max_block_byte_ct = cur_block_byte_ct;
1944 }
1945 } else {
1946 // no LD compression here
1947 const uint32_t cur_block_variant_ct = variant_uidx_end - variant_uidx_start;
1948 if (cur_block_variant_ct > max_block_variant_ct) {
1949 max_block_variant_ct = cur_block_variant_ct;
1950 if (cur_block_variant_ct == block_size) {
1951 // no larger value possible, terminate search
1952 break;
1953 }
1954 }
1955 }
1956 }
1957 if (!var_fpos) {
1958 max_block_byte_ct = max_block_variant_ct * S_CAST(uint64_t, pgfip->const_vrec_width);
1959 }
1960 return DivUpU64(max_block_byte_ct, kCacheline);
1961 }
1962
1963 PglErr PgfiMultiread(const uintptr_t* variant_include, uint32_t variant_uidx_start, uint32_t variant_uidx_end, uint32_t load_variant_ct, PgenFileInfo* pgfip) {
1964 // we could permit 0, but that encourages lots of unnecessary thread wakeups
1965 assert(load_variant_ct);
1966 if (variant_include) {
1967 variant_uidx_start = AdvTo1Bit(variant_include, variant_uidx_start);
1968 }
1969 assert(variant_uidx_start < pgfip->raw_variant_ct);
1970 uint64_t block_offset;
1971 if (pgfip->vrtypes && ((pgfip->vrtypes[variant_uidx_start] & 6) == 2)) {
1972 // need to start loading from LD-buddy
1973 // assume for now that we can't skip any variants between the LD-buddy and
1974 // the actual first variant; should remove this assumption later
1975 block_offset = pgfip->var_fpos[GetLdbaseVidx(pgfip->vrtypes, variant_uidx_start)];
1976 } else {
1977 block_offset = GetPgfiFpos(pgfip, variant_uidx_start);
1978 }
1979 pgfip->block_offset = block_offset;
1980 uint64_t next_read_start_fpos = block_offset;
1981 // break this up into multiple freads whenever this lets us skip an entire
1982 // disk block
1983 // (possible todo: make the disk block size a parameter of this function)
1984 do {
1985 const uint64_t cur_read_start_fpos = next_read_start_fpos;
1986 uint32_t cur_read_uidx_end;
1987 uint64_t cur_read_end_fpos;
1988 while (1) {
1989 cur_read_uidx_end = variant_uidx_end;
1990 if (cur_read_uidx_end - variant_uidx_start == load_variant_ct) {
1991 cur_read_end_fpos = GetPgfiFpos(pgfip, cur_read_uidx_end);
1992 load_variant_ct = 0;
1993 break;
1994 }
1995 cur_read_uidx_end = AdvTo0Bit(variant_include, variant_uidx_start);
1996 cur_read_end_fpos = GetPgfiFpos(pgfip, cur_read_uidx_end);
1997 load_variant_ct -= cur_read_uidx_end - variant_uidx_start;
1998 if (!load_variant_ct) {
1999 break;
2000 }
2001 variant_uidx_start = AdvTo1Bit(variant_include, cur_read_uidx_end);
2002 next_read_start_fpos = GetPgfiFpos(pgfip, variant_uidx_start);
2003 if (pgfip->vrtypes && ((pgfip->vrtypes[variant_uidx_start] & 6) == 2)) {
2004 const uint32_t variant_read_uidx_start = GetLdbaseVidx(pgfip->vrtypes, variant_uidx_start);
2005 if (variant_read_uidx_start <= cur_read_uidx_end) {
2006 continue;
2007 }
2008 next_read_start_fpos = pgfip->var_fpos[variant_read_uidx_start];
2009 }
2010 // bugfix: can't use do..while, since previous "continue" needs to skip
2011 // this check
2012 if (RoundDownPow2U64(cur_read_end_fpos + kDiskBlockSize + 1LLU, kDiskBlockSize) < RoundDownPow2U64(next_read_start_fpos, kDiskBlockSize)) {
2013 // minor bugfix (7 Jul 2017): break, not continue
2014 break;
2015 }
2016 }
2017 if (unlikely(fseeko(pgfip->shared_ff, cur_read_start_fpos, SEEK_SET))) {
2018 return kPglRetReadFail;
2019 }
2020 uintptr_t len = cur_read_end_fpos - cur_read_start_fpos;
2021 if (unlikely(fread_checked(K_CAST(unsigned char*, &(pgfip->block_base[cur_read_start_fpos - block_offset])), len, pgfip->shared_ff))) {
2022 if (feof_unlocked(pgfip->shared_ff)) {
2023 errno = 0;
2024 }
2025 return kPglRetReadFail;
2026 }
2027 } while (load_variant_ct);
2028 return kPglRetSuccess;
2029 }
2030
2031
2032 void PreinitPgr(PgenReader* pgr_ptr) {
2033 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
2034 pgrp->ff = nullptr;
2035 }
2036
2037 PglErr PgrInit(const char* fname, uint32_t max_vrec_width, PgenFileInfo* pgfip, PgenReader* pgr_ptr, unsigned char* pgr_alloc) {
2038 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
2039 // See CountPgrAllocCachelinesRequired().
2040 // Could add a debug mode.
2041
2042 // Mode 1 (block-fread): block_base initialized, shared_ff != nullptr. fname
2043 // must be nullptr.
2044 // Mode 2 (per-variant fread): block_base == nullptr. fname must be
2045 // non-null, though it isn't actually referenced during the first
2046 // PgenReader initialization (instead shared_ff is moved).
2047 unsigned char* pgr_alloc_iter = pgr_alloc;
2048 if (pgfip->block_base != nullptr) {
2049 if (unlikely(fname != nullptr)) {
2050 return kPglRetImproperFunctionCall;
2051 }
2052 pgrp->ff = nullptr; // make sure CleanupPgr() doesn't break
2053 } else {
2054 if (pgfip->shared_ff != nullptr) {
2055 if (unlikely(fname == nullptr)) {
2056 return kPglRetImproperFunctionCall;
2057 }
2058 // move instead of close/reopen.
2059 pgrp->ff = pgfip->shared_ff;
2060 pgfip->shared_ff = nullptr;
2061 } else {
2062 pgrp->ff = fopen(fname, FOPEN_RB);
2063 if (unlikely(!pgrp->ff)) {
2064 return kPglRetOpenFail;
2065 }
2066 }
2067 // now that arbitrary info can be stored between header and first variant
2068 // record, always seek.
2069 uint64_t seek_pos;
2070 if (pgfip->var_fpos) {
2071 seek_pos = pgfip->var_fpos[0];
2072 } else {
2073 seek_pos = pgfip->const_fpos_offset;
2074 }
2075 if (unlikely(fseeko(pgrp->ff, seek_pos, SEEK_SET))) {
2076 return kPglRetReadFail;
2077 }
2078 }
2079 pgrp->fi = *pgfip; // struct copy
2080 if (fname) {
2081 // Mode 2 per-reader load buffer
2082 pgrp->fread_buf = pgr_alloc_iter;
2083 pgr_alloc_iter = &(pgr_alloc_iter[RoundUpPow2(max_vrec_width, kCacheline)]);
2084 }
2085 pgrp->fp_vidx = 0;
2086 pgrp->ldbase_vidx = UINT32_MAX;
2087 pgrp->ldbase_stypes = kfPgrLdcache0;
2088 pgrp->ldbase_genovec = nullptr;
2089 pgrp->ldbase_raregeno = nullptr;
2090 pgrp->ldbase_difflist_sample_ids = nullptr;
2091
2092 const PgenGlobalFlags gflags = pgrp->fi.gflags;
2093 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
2094 const uint32_t genovec_bytes_req = NypCtToCachelineCt(raw_sample_ct) * kCacheline;
2095 pgrp->ldbase_raw_genovec = S_CAST(uintptr_t*, arena_alloc_raw(genovec_bytes_req, &pgr_alloc_iter));
2096 const uint32_t bitvec_bytes_req = BitCtToCachelineCt(raw_sample_ct) * kCacheline;
2097 const uint32_t ld_compression_present = (gflags / kfPgenGlobalLdCompressionPresent) & 1;
2098 const uint32_t max_difflist_entry_ct_base = (raw_sample_ct / kPglMaxDifflistLenDivisor);
2099 const uint32_t max_allele_ct = pgrp->fi.max_allele_ct;
2100 pgrp->workspace_difflist_sample_ids = nullptr;
2101 if ((gflags & kfPgenGlobalDifflistOrLdPresent) || (max_allele_ct > 2)) {
2102 pgrp->workspace_difflist_sample_ids = S_CAST(uint32_t*, arena_alloc_raw_rd((max_difflist_entry_ct_base + 1) * sizeof(int32_t), &pgr_alloc_iter));
2103 }
2104 if (gflags & kfPgenGlobalDifflistOrLdPresent) {
2105 // const uint32_t max_difflist_entry_ct = max_difflist_entry_ct_base * (1 + ld_compression_present);
2106
2107 const uintptr_t raregeno_bytes_req = NypCtToCachelineCt(max_difflist_entry_ct_base) * kCacheline;
2108 pgrp->workspace_raregeno_vec = S_CAST(uintptr_t*, arena_alloc_raw(raregeno_bytes_req, &pgr_alloc_iter));
2109 pgrp->workspace_raregeno_tmp_loadbuf = S_CAST(uintptr_t*, arena_alloc_raw(raregeno_bytes_req, &pgr_alloc_iter));
2110
2111 if (ld_compression_present) {
2112 pgrp->ldbase_genovec = S_CAST(uintptr_t*, arena_alloc_raw(genovec_bytes_req, &pgr_alloc_iter));
2113
2114 pgrp->ldbase_raregeno = S_CAST(uintptr_t*, arena_alloc_raw(raregeno_bytes_req, &pgr_alloc_iter));
2115
2116 pgrp->ldbase_difflist_sample_ids = S_CAST(uint32_t*, arena_alloc_raw_rd((max_difflist_entry_ct_base + 1) * sizeof(int32_t), &pgr_alloc_iter));
2117 }
2118 } else {
2119 pgrp->workspace_raregeno_vec = nullptr;
2120 pgrp->workspace_raregeno_tmp_loadbuf = nullptr;
2121 }
2122 pgrp->workspace_vec = nullptr;
2123 pgrp->workspace_aux1x_present = nullptr;
2124 pgrp->workspace_imp_r2 = nullptr;
2125 pgrp->workspace_all_hets = nullptr;
2126 pgrp->workspace_subset = nullptr;
2127 const PgenGlobalFlags gflags_hphase_dosage = gflags & (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePresent);
2128 if ((max_allele_ct > 2) || gflags_hphase_dosage) {
2129 pgrp->workspace_vec = S_CAST(uintptr_t*, arena_alloc_raw(genovec_bytes_req, &pgr_alloc_iter));
2130 if (max_allele_ct > 2) {
2131 pgrp->workspace_aux1x_present = S_CAST(uintptr_t*, arena_alloc_raw(bitvec_bytes_req, &pgr_alloc_iter));
2132 pgrp->workspace_imp_r2 = S_CAST(uint64_t*, arena_alloc_raw_rd(2 * max_allele_ct * sizeof(int64_t), &pgr_alloc_iter));
2133 }
2134 if (gflags & kfPgenGlobalHardcallPhasePresent) {
2135 pgrp->workspace_all_hets = S_CAST(uintptr_t*, arena_alloc_raw(bitvec_bytes_req, &pgr_alloc_iter));
2136 pgrp->workspace_subset = S_CAST(uintptr_t*, arena_alloc_raw(bitvec_bytes_req, &pgr_alloc_iter));
2137 }
2138 pgrp->workspace_dosage_present = nullptr;
2139 pgrp->workspace_dphase_present = nullptr;
2140 if (gflags & kfPgenGlobalDosagePresent) {
2141 pgrp->workspace_dosage_present = S_CAST(uintptr_t*, arena_alloc_raw(bitvec_bytes_req, &pgr_alloc_iter));
2142 if (gflags & kfPgenGlobalDosagePhasePresent) {
2143 pgrp->workspace_dphase_present = S_CAST(uintptr_t*, arena_alloc_raw(bitvec_bytes_req, &pgr_alloc_iter));
2144 }
2145 }
2146 }
2147 return kPglRetSuccess;
2148 }
2149
2150 void PgrPlink1ToPlink2InplaceUnsafe(uint32_t sample_ct, uintptr_t* genovec) {
2151 // 00 -> 10, 01 -> 11, 10 -> 01, 11 -> 00
2152 // new low bit = [old low] ^ [old high]
2153 // new high bit = ~[old high]
2154 // "unsafe" because trailing bits are not zeroed out.
2155 const uint32_t vec_ct = NypCtToVecCt(sample_ct);
2156 const VecW m1 = VCONST_W(kMask5555);
2157 const VecW not_m1 = VCONST_W(kMaskAAAA);
2158 VecW* vptr = R_CAST(VecW*, genovec);
2159 for (uint32_t vidx = 0; vidx != vec_ct; vidx++) {
2160 const VecW not_cur_vec_high = vecw_and_notfirst(vptr[vidx], not_m1);
2161 vptr[vidx] = (vecw_and_notfirst(vptr[vidx], m1) ^ vecw_srli(not_cur_vec_high, 1)) | not_cur_vec_high;
2162 }
2163 }
2164
2165 void PgrPlink2ToPlink1InplaceUnsafe(uint32_t sample_ct, uintptr_t* genovec) {
2166 // 00 -> 11, 01 -> 10, 10 -> 00, 11 -> 01
2167 // new low bit = [old low] ^ (~[old high])
2168 // new high bit = ~[old high]
2169 const uint32_t vec_ct = NypCtToVecCt(sample_ct);
2170 const VecW not_m1 = VCONST_W(kMaskAAAA);
2171 VecW* vptr = R_CAST(VecW*, genovec);
2172 for (uint32_t vidx = 0; vidx != vec_ct; vidx++) {
2173 VecW cur_vec = vptr[vidx];
2174 VecW not_cur_vec_high = vecw_and_notfirst(cur_vec, not_m1);
2175 vptr[vidx] = (vecw_and_notfirst(not_m1, cur_vec) ^ vecw_srli(not_cur_vec_high, 1)) | not_cur_vec_high;
2176 }
2177 }
2178
2179 PglErr ParseDifflistHeader(const unsigned char* fread_end, uint32_t raw_sample_ct, const unsigned char** fread_pp, uintptr_t* raregeno_buf, const unsigned char** difflist_group_info_ptr, uint32_t* difflist_len_ptr) {
2180 // Can be used for deltalists as well: pass raregeno_buf == nullptr.
2181 // Trailing bits of raregeno may not be zeroed out.
2182 // Will need a separate 64-bit version of this for multiallelic dosages.
2183 const uint32_t difflist_len = GetVint31(fread_end, fread_pp);
2184 // moved here to address maybe-uninitialized warnings
2185 *difflist_group_info_ptr = *fread_pp;
2186 *difflist_len_ptr = difflist_len;
2187 if (!difflist_len) {
2188 return kPglRetSuccess;
2189 }
2190 if (unlikely(difflist_len > raw_sample_ct / kPglMaxDifflistLenDivisor)) {
2191 // automatically catches GetVint31() failure
2192 return kPglRetMalformedInput;
2193 }
2194 const uint32_t group_ct = DivUp(difflist_len, kPglDifflistGroupSize);
2195 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(raw_sample_ct);
2196 const uint32_t difflist_index_byte_ct = group_ct * (sample_id_byte_ct + 1) - 1;
2197 if (PtrAddCk(fread_end, difflist_index_byte_ct, fread_pp)) {
2198 return kPglRetMalformedInput;
2199 }
2200 if (!raregeno_buf) {
2201 // for sample ID lists without 2-bit genotype info, used for sparse dosage
2202 return kPglRetSuccess;
2203 }
2204 const uint32_t raregeno_byte_ct = NypCtToByteCt(difflist_len);
2205 const unsigned char* raregeno_start = *fread_pp;
2206 if (PtrAddCk(fread_end, raregeno_byte_ct, fread_pp)) {
2207 return kPglRetMalformedInput;
2208 }
2209 // possible todo: just return raregeno_start, and let the caller perform this
2210 // copy
2211 memcpy(raregeno_buf, raregeno_start, raregeno_byte_ct);
2212 return kPglRetSuccess;
2213 }
2214
2215 PglErr ParseAndSaveDifflist(const unsigned char* fread_end, uint32_t raw_sample_ct, const unsigned char** fread_pp, uintptr_t* __restrict raregeno, uint32_t* __restrict difflist_sample_ids, uint32_t* __restrict difflist_len_ptr) {
2216 // Appropriate when we need to iterate through the difflist multiple times.
2217 // Other functions are more efficient if we only need to process the list
2218 // once.
2219 // Trailing bits of raregeno may not be zeroed out.
2220 const unsigned char* group_info_iter;
2221 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, raregeno, &group_info_iter, difflist_len_ptr);
2222 uint32_t difflist_len = *difflist_len_ptr;
2223 // todo: check if difflist_len == 0 early exit is a net positive or negative
2224 // on a few test datasets
2225 if (reterr || (!difflist_len)) {
2226 return reterr;
2227 }
2228 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(raw_sample_ct);
2229 uint32_t* difflist_sample_ids_iter = difflist_sample_ids;
2230 for (uint32_t difflist_remaining = difflist_len; ; ) {
2231 const uint32_t* difflist_sample_ids_stop;
2232 if (difflist_remaining < kPglDifflistGroupSize) {
2233 if (!difflist_remaining) {
2234 return kPglRetSuccess;
2235 }
2236 difflist_sample_ids_stop = &(difflist_sample_ids_iter[difflist_remaining]);
2237 difflist_remaining = 0;
2238 } else {
2239 difflist_sample_ids_stop = &(difflist_sample_ids_iter[kPglDifflistGroupSize]);
2240 difflist_remaining -= kPglDifflistGroupSize;
2241 }
2242 // can't use uint32_t assignment trick for now since there's a corner case
2243 // where that would read past the end of the mapped address range
2244 uintptr_t raw_sample_idx = SubU32Load(group_info_iter, sample_id_byte_ct);
2245 group_info_iter = &(group_info_iter[sample_id_byte_ct]);
2246 while (1) {
2247 #ifndef __LP64__
2248 // perform more frequent checks in 32-bit build since raw_sample_idx may
2249 // overflow
2250 // misses "small negative" malformed input, but it'll catch data
2251 // corruption with very high probability
2252 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
2253 return kPglRetMalformedInput;
2254 }
2255 #endif
2256 *difflist_sample_ids_iter++ = raw_sample_idx;
2257 if (difflist_sample_ids_iter == difflist_sample_ids_stop) {
2258 break;
2259 }
2260 raw_sample_idx += GetVint31(fread_end, fread_pp);
2261 }
2262 #ifdef __LP64__
2263 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
2264 return kPglRetMalformedInput;
2265 }
2266 #endif
2267 }
2268 return kPglRetSuccess;
2269 }
2270
2271 PglErr ParseAndSaveDifflistProperSubset(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t raw_sample_ct, const unsigned char** fread_pp, uintptr_t* __restrict raregeno, uint32_t* __restrict difflist_sample_ids, uint32_t* __restrict difflist_len_ptr, uintptr_t* __restrict raregeno_workspace) {
2272 // Requires a PROPER subset. Might want to just merge this with
2273 // ParseAndSaveDifflist() and rename appropriately.
2274 // Trailing bits of raregeno are zeroed out.
2275 uint32_t raw_difflist_len;
2276 const unsigned char* group_info_iter;
2277 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, raregeno_workspace, &group_info_iter, &raw_difflist_len);
2278 if (reterr || (!raw_difflist_len)) {
2279 *difflist_len_ptr = 0;
2280 return reterr;
2281 }
2282 const uint32_t subgroup_idx_last = (raw_difflist_len - 1) / kBitsPerWordD2;
2283 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(raw_sample_ct);
2284 uintptr_t* raregeno_workspace_iter = raregeno_workspace;
2285 uintptr_t* raregeno_iter = raregeno;
2286 uint32_t* difflist_sample_ids_iter = difflist_sample_ids;
2287
2288 // technically doesn't need to be initialized, but I have principles
2289 uintptr_t raw_sample_idx = 0;
2290
2291 uintptr_t raregeno_word = 0;
2292 uint32_t subgroup_len_m1 = kBitsPerWordD2 - 1;
2293 uint32_t difflist_len_lowbits = 0;
2294 for (uint32_t subgroup_idx = 0; ; ++subgroup_idx) {
2295 if (subgroup_idx >= subgroup_idx_last) {
2296 if (subgroup_idx > subgroup_idx_last) {
2297 if (difflist_len_lowbits) {
2298 *raregeno_iter = raregeno_word;
2299 }
2300 *difflist_len_ptr = S_CAST(uintptr_t, difflist_sample_ids_iter - difflist_sample_ids) + difflist_len_lowbits;
2301 return kPglRetSuccess;
2302 }
2303 subgroup_len_m1 &= raw_difflist_len - 1;
2304 }
2305 // We need to consume a new rare genotype word every 32 entries, and pull a
2306 // raw sample index from the difflist header every 64 entries. So it's
2307 // best to make the inner loop have a period of 32 (call this a 'subgroup',
2308 // where 'group' refers to a set of 64 entries).
2309 if (!(subgroup_idx % (kPglDifflistGroupSize / kBitsPerWordD2))) {
2310 #ifdef __LP64__
2311 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
2312 return kPglRetMalformedInput;
2313 }
2314 #endif
2315 raw_sample_idx = SubU32Load(group_info_iter, sample_id_byte_ct);
2316 group_info_iter = &(group_info_iter[sample_id_byte_ct]);
2317 } else {
2318 raw_sample_idx += GetVint31(fread_end, fread_pp);
2319 }
2320 uintptr_t raregeno_workspace_word = *raregeno_workspace_iter++;
2321 for (uint32_t raw_difflist_idx_lowbits = 0; ; ++raw_difflist_idx_lowbits) {
2322 #ifndef __LP64__
2323 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
2324 return kPglRetMalformedInput;
2325 }
2326 #endif
2327 if (IsSet(sample_include, raw_sample_idx)) {
2328 raregeno_word |= ((raregeno_workspace_word >> (2 * raw_difflist_idx_lowbits)) & 3) << (difflist_len_lowbits * 2);
2329 difflist_sample_ids_iter[difflist_len_lowbits] = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, raw_sample_idx);
2330 if (difflist_len_lowbits++ == (kBitsPerWordD2 - 1)) {
2331 *raregeno_iter++ = raregeno_word;
2332 raregeno_word = 0;
2333 difflist_len_lowbits = 0;
2334 difflist_sample_ids_iter = &(difflist_sample_ids_iter[kBitsPerWordD2]);
2335 }
2336 }
2337 if (raw_difflist_idx_lowbits == subgroup_len_m1) {
2338 break;
2339 }
2340 raw_sample_idx += GetVint31(fread_end, fread_pp);
2341 }
2342 }
2343 }
2344
2345 PglErr ParseLdAndMergeDifflistSubset(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, const uintptr_t* __restrict ldbase_raregeno, const uint32_t* __restrict ldbase_difflist_sample_ids, uint32_t ldbase_difflist_len, uintptr_t ldbase_common_geno, uint32_t raw_sample_ct, uint32_t sample_ct, const unsigned char** fread_pp, uintptr_t* __restrict merged_raregeno, uint32_t* __restrict merged_difflist_sample_ids, uint32_t* __restrict merged_difflist_len_ptr, uintptr_t* __restrict diff_from_ldbase_raregeno_iter) {
2346 // Used when the ldbase variant was saved as a difflist, and it's useful to
2347 // process the current variant as a difflist.
2348 // * Assumes ldbase_difflist_sample_ids[ldbase_difflist_len]==sample_ct.
2349 // * Assumes sample_include == nullptr if no subsetting needed. (Otherwise,
2350 // it'll still work, but performance will be worse.)
2351 // Trailing bits of merged_raregeno may not be zeroed out.
2352 // Caller is responsible for inverting ldbase_common_geno and merged_raregeno
2353 // afterward if necessary.
2354 assert(ldbase_difflist_sample_ids[ldbase_difflist_len] == sample_ct);
2355 uint32_t diff_from_ldbase_len;
2356 const unsigned char* group_info_iter;
2357 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, diff_from_ldbase_raregeno_iter, &group_info_iter, &diff_from_ldbase_len);
2358 if (unlikely(reterr)) {
2359 return reterr;
2360 }
2361 if (!diff_from_ldbase_len) {
2362 memcpy(merged_difflist_sample_ids, ldbase_difflist_sample_ids, ldbase_difflist_len * sizeof(int32_t));
2363 *merged_difflist_len_ptr = ldbase_difflist_len;
2364 CopyNyparr(ldbase_raregeno, ldbase_difflist_len, merged_raregeno);
2365 return kPglRetSuccess;
2366 }
2367 const uint32_t subgroup_idx_last = (diff_from_ldbase_len - 1) / kBitsPerWordD2;
2368 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(raw_sample_ct);
2369 uintptr_t* merged_raregeno_iter = merged_raregeno;
2370 uint32_t* merged_difflist_sample_ids_iter = merged_difflist_sample_ids;
2371 uintptr_t merged_raregeno_word = 0;
2372 uintptr_t ldbase_raregeno_word = 0;
2373 uintptr_t diff_from_ldbase_raregeno_word = 0;
2374 uint32_t ldbase_sample_idx = ldbase_difflist_sample_ids[0];
2375 uintptr_t raw_sample_idx = 0;
2376 uintptr_t cur_geno = 0;
2377 uint32_t sample_idx = 0;
2378 uint32_t ldbase_difflist_idx = 0;
2379 uint32_t done = 0;
2380 uint32_t subgroup_len_m1 = kBitsPerWordD2 - 1;
2381 uint32_t merge_idx_lowbits = 0;
2382 for (uint32_t subgroup_idx = 0; ; ++subgroup_idx) {
2383 uint32_t diff_from_ldbase_idx_lowbits = 0;
2384 if (subgroup_idx >= subgroup_idx_last) {
2385 if (subgroup_idx > subgroup_idx_last) {
2386 done = 1;
2387 sample_idx = sample_ct;
2388 goto ParseLdAndMergeDifflistSubset_finish;
2389 }
2390 subgroup_len_m1 &= diff_from_ldbase_len - 1;
2391 }
2392 if (!(subgroup_idx % (kPglDifflistGroupSize / kBitsPerWordD2))) {
2393 raw_sample_idx = SubU32Load(group_info_iter, sample_id_byte_ct);
2394 group_info_iter = &(group_info_iter[sample_id_byte_ct]);
2395 } else {
2396 raw_sample_idx += GetVint31(fread_end, fread_pp);
2397 }
2398 diff_from_ldbase_raregeno_word = *diff_from_ldbase_raregeno_iter++;
2399 for (; ; ++diff_from_ldbase_idx_lowbits) {
2400 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
2401 return kPglRetMalformedInput;
2402 }
2403 cur_geno = diff_from_ldbase_raregeno_word & 3;
2404 if ((!sample_include) || IsSet(sample_include, raw_sample_idx)) {
2405 sample_idx = sample_include? RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, raw_sample_idx) : raw_sample_idx;
2406 ParseLdAndMergeDifflistSubset_finish:
2407 while (ldbase_sample_idx < sample_idx) {
2408 // replace with blocked copy?
2409 if (!(ldbase_difflist_idx % kBitsPerWordD2)) {
2410 ldbase_raregeno_word = ldbase_raregeno[ldbase_difflist_idx / kBitsPerWordD2];
2411 }
2412 *merged_difflist_sample_ids_iter++ = ldbase_sample_idx;
2413 merged_raregeno_word |= (ldbase_raregeno_word & 3) << (2 * merge_idx_lowbits);
2414 if (merge_idx_lowbits++ == (kBitsPerWordD2 - 1)) {
2415 *merged_raregeno_iter++ = merged_raregeno_word;
2416 merged_raregeno_word = 0;
2417 merge_idx_lowbits = 0;
2418 }
2419 ++ldbase_difflist_idx;
2420 ldbase_raregeno_word >>= 2;
2421 ldbase_sample_idx = ldbase_difflist_sample_ids[ldbase_difflist_idx];
2422 }
2423 if (ldbase_sample_idx == sample_idx) {
2424 if (done) {
2425 if (merge_idx_lowbits) {
2426 *merged_raregeno_iter = merged_raregeno_word;
2427 }
2428 *merged_difflist_len_ptr = merged_difflist_sample_ids_iter - merged_difflist_sample_ids;
2429 return kPglRetSuccess;
2430 }
2431 if (!(ldbase_difflist_idx % kBitsPerWordD2)) {
2432 ldbase_raregeno_word = ldbase_raregeno[ldbase_difflist_idx / kBitsPerWordD2];
2433 }
2434 ++ldbase_difflist_idx;
2435 ldbase_raregeno_word >>= 2;
2436 ldbase_sample_idx = ldbase_difflist_sample_ids[ldbase_difflist_idx];
2437 }
2438 if (cur_geno != ldbase_common_geno) {
2439 *merged_difflist_sample_ids_iter++ = sample_idx;
2440 merged_raregeno_word |= cur_geno << (2 * merge_idx_lowbits);
2441 if (merge_idx_lowbits++ == (kBitsPerWordD2 - 1)) {
2442 *merged_raregeno_iter++ = merged_raregeno_word;
2443 merged_raregeno_word = 0;
2444 merge_idx_lowbits = 0;
2445 }
2446 }
2447 }
2448 if (diff_from_ldbase_idx_lowbits == subgroup_len_m1) {
2449 break;
2450 }
2451 raw_sample_idx += GetVint31(fread_end, fread_pp);
2452 diff_from_ldbase_raregeno_word >>= 2;
2453 }
2454 }
2455 }
2456
2457 /*
2458 void PrunedDifflistToGenovecSubsetUnsafe(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, const uintptr_t* __restrict raregeno, const uint32_t* __restrict difflist_sample_ids, uint32_t sample_ct, uint32_t difflist_common_geno, uint32_t difflist_len, uintptr_t* __restrict genovec) {
2459 // Designed to be used after genovec subsetting. Assumes all difflist
2460 // entries are valid. Ok for trailing bits of raregeno to be nonzero. Does
2461 // not zero out trailing bits of genovec.
2462 const uint32_t vec_ct = NypCtToVecCt(sample_ct);
2463 vecset(genovec, difflist_common_geno * kMask5555, vec_ct);
2464 if (!difflist_len) {
2465 return;
2466 }
2467 const uintptr_t* raregeno_incr = raregeno;
2468 const uint32_t* difflist_sample_ids_iter = difflist_sample_ids;
2469 const uint32_t* difflist_sample_ids_end = &(difflist_sample_ids[difflist_len]);
2470 // don't think there's a point to separating out the
2471 // difflist_common_geno == 0 case here, since the RawToSubsettedPos
2472 // operation is a bit expensive
2473 while (1) {
2474 // er, get rid of this undefined behavior if we uncomment this function
2475 const uint32_t* difflist_sample_ids_stop = &(difflist_sample_ids_iter[kBitsPerWordD2]);
2476 uintptr_t raregeno_word = *raregeno_incr++;
2477 if (difflist_sample_ids_stop > difflist_sample_ids_end) {
2478 if (difflist_sample_ids_iter == difflist_sample_ids_end) {
2479 return;
2480 }
2481 difflist_sample_ids_stop = difflist_sample_ids_end;
2482 }
2483 while (1) {
2484 const uint32_t cur_sample_idx = *difflist_sample_ids_iter;
2485 const uint32_t cur_subsetted_pos = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, cur_sample_idx);
2486 AssignNyparrEntry(cur_subsetted_pos, raregeno_word & 3, genovec);
2487 if (difflist_sample_ids_iter++ == difflist_sample_ids_stop) {
2488 break;
2489 }
2490 raregeno_word >>= 2;
2491 }
2492 }
2493 }
2494 */
2495
2496 PglErr ParseAndApplyDifflist(const unsigned char* fread_end, const unsigned char** fread_pp, PgenReaderMain* pgrp, uintptr_t* __restrict genoarr) {
2497 // Side effects: uses pgr.workspace_raregeno_tmp_loadbuf.
2498 // Cannot occur after genoarr subsetting since the difflist sample indexes
2499 // will be incorrect.
2500 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
2501 uintptr_t* cur_raregeno_iter = pgrp->workspace_raregeno_tmp_loadbuf;
2502 const unsigned char* group_info_iter;
2503 uint32_t difflist_len;
2504 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, cur_raregeno_iter, &group_info_iter, &difflist_len);
2505 if (reterr || (!difflist_len)) {
2506 return reterr;
2507 }
2508 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(raw_sample_ct);
2509 const uint32_t subgroup_idx_last = (difflist_len - 1) / kBitsPerWordD2;
2510 uintptr_t raw_sample_idx = 0;
2511 for (uint32_t subgroup_idx = 0; ; ++subgroup_idx) {
2512 uint32_t remaining_deltas_in_subgroup = kBitsPerWordD2 - 1;
2513 if (subgroup_idx >= subgroup_idx_last) {
2514 if (subgroup_idx > subgroup_idx_last) {
2515 return kPglRetSuccess;
2516 }
2517 remaining_deltas_in_subgroup &= difflist_len - 1;
2518 }
2519 if (!(subgroup_idx % (kPglDifflistGroupSize / kBitsPerWordD2))) {
2520 raw_sample_idx = SubU32Load(group_info_iter, sample_id_byte_ct);
2521 group_info_iter = &(group_info_iter[sample_id_byte_ct]);
2522 } else {
2523 raw_sample_idx += GetVint31(fread_end, fread_pp);
2524 }
2525 uintptr_t cur_raregeno_word = *cur_raregeno_iter++;
2526 // This loop tends to be the decompression bottleneck. Tried to modify it
2527 // to process 4 entries at a time, but that didn't end up helping.
2528 for (; ; --remaining_deltas_in_subgroup) {
2529 // always check, since otherwise AssignNyparrEntry() can scribble
2530 // over arbitrary memory
2531 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
2532 return kPglRetMalformedInput;
2533 }
2534 const uintptr_t cur_geno = cur_raregeno_word & 3;
2535 AssignNyparrEntry(raw_sample_idx, cur_geno, genoarr);
2536 if (!remaining_deltas_in_subgroup) {
2537 break;
2538 }
2539 raw_sample_idx += GetVint31(fread_end, fread_pp);
2540 cur_raregeno_word >>= 2;
2541 }
2542 }
2543 }
2544
2545 // could merge ParseAndApplyDifflist() with this?
2546 PglErr ParseAndApplyDifflistSubset(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, const unsigned char** fread_pp, PgenReaderMain* pgrp, uintptr_t* __restrict genoarr) {
2547 // Side effects: uses pgr.workspace_raregeno_tmp_loadbuf.
2548 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
2549 if (sample_ct == raw_sample_ct) {
2550 return ParseAndApplyDifflist(fread_end, fread_pp, pgrp, genoarr);
2551 }
2552 uintptr_t* cur_raregeno_iter = pgrp->workspace_raregeno_tmp_loadbuf;
2553 const unsigned char* group_info_iter;
2554 uint32_t difflist_len;
2555 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, cur_raregeno_iter, &group_info_iter, &difflist_len);
2556 if (reterr || (!difflist_len)) {
2557 return reterr;
2558 }
2559 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(raw_sample_ct);
2560 const uint32_t subgroup_idx_last = (difflist_len - 1) / kBitsPerWordD2;
2561 uintptr_t raw_sample_idx = 0;
2562 for (uint32_t subgroup_idx = 0; ; ++subgroup_idx) {
2563 uint32_t remaining_deltas_in_subgroup = kBitsPerWordD2 - 1;
2564 if (subgroup_idx >= subgroup_idx_last) {
2565 if (subgroup_idx > subgroup_idx_last) {
2566 return kPglRetSuccess;
2567 }
2568 remaining_deltas_in_subgroup &= difflist_len - 1;
2569 }
2570 if (!(subgroup_idx % (kPglDifflistGroupSize / kBitsPerWordD2))) {
2571 raw_sample_idx = SubU32Load(group_info_iter, sample_id_byte_ct);
2572 group_info_iter = &(group_info_iter[sample_id_byte_ct]);
2573 } else {
2574 raw_sample_idx += GetVint31(fread_end, fread_pp);
2575 }
2576 uintptr_t cur_raregeno_word = *cur_raregeno_iter++;
2577 // This loop tends to be the decompression bottleneck. Tried to modify it
2578 // to process 4 entries at a time, but that didn't end up helping.
2579 for (; ; --remaining_deltas_in_subgroup) {
2580 // always check, since otherwise AssignNyparrEntry() can scribble
2581 // over arbitrary memory
2582 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
2583 return kPglRetMalformedInput;
2584 }
2585 if (IsSet(sample_include, raw_sample_idx)) {
2586 const uintptr_t cur_geno = cur_raregeno_word & 3;
2587 AssignNyparrEntry(RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, raw_sample_idx), cur_geno, genoarr);
2588 }
2589 if (!remaining_deltas_in_subgroup) {
2590 break;
2591 }
2592 raw_sample_idx += GetVint31(fread_end, fread_pp);
2593 cur_raregeno_word >>= 2;
2594 }
2595 }
2596 }
2597
2598 // vector-alignment preferred
2599 PglErr ParseOnebitUnsafe(const unsigned char* fread_end, const unsigned char** fread_pp, PgenReaderMain* pgrp, uintptr_t* __restrict genoarr) {
2600 // doesn't zero out trailing genoarr bits
2601 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
2602 const uint32_t common2_and_bitarray_byte_ct = (raw_sample_ct + 15) / CHAR_BIT;
2603 const unsigned char* onebit_main_iter = *fread_pp;
2604 if (PtrAddCk(fread_end, common2_and_bitarray_byte_ct, fread_pp)) {
2605 return kPglRetMalformedInput;
2606 }
2607 const uintptr_t common2_code = *onebit_main_iter++;
2608 const uintptr_t word_base = (common2_code / 4) * kMask5555;
2609 const uintptr_t common_code_delta = common2_code & 3;
2610 uint32_t genoarr_widx = 0;
2611 #if defined(__LP64__) && !defined(USE_AVX2)
2612 // this is slower in AVX2 case
2613 const uint32_t read_hw_ct = raw_sample_ct / kBitsPerWordD2;
2614 if (read_hw_ct >= 2 * kWordsPerVec) {
2615 const uint32_t read_vec_ct = raw_sample_ct / kBitsPerVec;
2616 const VecW m4 = VCONST_W(kMask0F0F);
2617 # ifdef USE_SHUFFLE8
2618 // 0, 1, 4, 5, 16, 17, 20, 21, 64, 65, 68, 69, 80, 81, 84, 85 if the codes
2619 // are 0 and 1
2620 const VecW lookup = {word_base + common_code_delta * 0x1514111005040100LLU,
2621 word_base + common_code_delta * 0x5554515045444140LLU};
2622 # else
2623 const VecW m1 = VCONST_W(kMask5555);
2624 const VecW m2 = VCONST_W(kMask3333);
2625 const VecW vec_base = VCONST_W(word_base);
2626 const VecW vec_delta = VCONST_W(common_code_delta * kMask5555);
2627 # endif
2628 for (uint32_t vidx = 0; vidx != read_vec_ct; ++vidx) {
2629 const VecW cur_vec = vecw_loadu(&(onebit_main_iter[vidx * kBytesPerVec]));
2630 VecW vec_lo;
2631 VecW vec_hi;
2632 vecw_lo_and_hi_nybbles(cur_vec, m4, &vec_lo, &vec_hi);
2633 # ifdef USE_SHUFFLE8
2634 vec_lo = vecw_shuffle8(lookup, vec_lo);
2635 vec_hi = vecw_shuffle8(lookup, vec_hi);
2636 # else
2637 // unpack bytes, then use as mask for vec_add.
2638 vec_lo = (vec_lo | vecw_slli(vec_lo, 2)) & m2;
2639 vec_hi = (vec_hi | vecw_slli(vec_hi, 2)) & m2;
2640 vec_lo = (vec_lo | vecw_slli(vec_lo, 1)) & m1;
2641 vec_hi = (vec_hi | vecw_slli(vec_hi, 1)) & m1;
2642 vec_lo = vec_lo | vecw_slli(vec_lo, 1);
2643 vec_hi = vec_hi | vecw_slli(vec_hi, 1);
2644 vec_lo = vec_base + (vec_delta & vec_lo);
2645 vec_hi = vec_base + (vec_delta & vec_hi);
2646 # endif
2647 vecw_storeu(&(genoarr[kWordsPerVec * 2 * vidx]), vec_lo);
2648 vecw_storeu(&(genoarr[kWordsPerVec * (2 * vidx + 1)]), vec_hi);
2649 }
2650 genoarr_widx = read_vec_ct * (2 * kWordsPerVec);
2651 }
2652 #endif
2653 const uint32_t genoarr_widx_trail = (raw_sample_ct + 7) / kBitsPerWordD2;
2654 const uint32_t genoarr_widx_end = NypCtToWordCt(raw_sample_ct);
2655 for (; ; ++genoarr_widx) {
2656 uintptr_t ww;
2657 if (genoarr_widx >= genoarr_widx_trail) {
2658 // might want to modify to not go here if last read is an entire halfword
2659 if (genoarr_widx == genoarr_widx_end) {
2660 break;
2661 }
2662 ww = ProperSubwordLoad(&(onebit_main_iter[genoarr_widx_trail * sizeof(Halfword)]), 1 + (((raw_sample_ct - 1) % kBitsPerWordD2) / CHAR_BIT));
2663 } else {
2664 Halfword hw;
2665 CopyFromUnalignedOffsetHW(&hw, onebit_main_iter, genoarr_widx);
2666 ww = hw;
2667 }
2668 // apply middle-out operation
2669 // 64-bit:
2670 // const uintptr_t middle_out_result = (ww | (ww << 31)) & kMask5555;
2671 // 32-bit:
2672 // *genoarr_iter++ = word_base + (ww & kMask5555) * common_code_delta;
2673 // *genoarr_iter++ = word_base + ((ww >> 1) & kMask5555) * common_code_delta;
2674 // (scrapped since the time savings don't seem to be worth the extra
2675 // end-of-vector corner cases, apparently the extra operations here are
2676 // sufficiently cheap, or even negative-cost in AVX2 case)
2677
2678 ww = UnpackHalfwordToWord(ww);
2679 genoarr[genoarr_widx] = word_base + ww * common_code_delta;
2680 }
2681 return ParseAndApplyDifflist(fread_end, fread_pp, pgrp, genoarr);
2682 }
2683
2684 // vector-alignment preferred
2685 PglErr Parse1or2bitGenoarrUnsafe(const unsigned char* fread_end, uint32_t vrtype, const unsigned char** fread_pp, PgenReaderMain* pgrp, uintptr_t* __restrict genoarr) {
2686 // Side effect: may use pgrp->workspace_raregeno_tmp_loadbuf.
2687 // Does not update fp_vidx, does not rotate plink1-formatted data (since it's
2688 // better to do that post-subsetting)
2689 if (vrtype & 3) {
2690 return ParseOnebitUnsafe(fread_end, fread_pp, pgrp, genoarr);
2691 }
2692 // uncompressed storage
2693 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
2694 const uint32_t genoarr_byte_ct = NypCtToByteCt(raw_sample_ct);
2695 const unsigned char* src_genodata = *fread_pp;
2696 if (PtrAddCk(fread_end, genoarr_byte_ct, fread_pp)) {
2697 return kPglRetMalformedInput;
2698 }
2699 memcpy(genoarr, src_genodata, genoarr_byte_ct);
2700 return kPglRetSuccess;
2701 }
2702
2703 PglErr ParseNonLdGenovecSubsetUnsafe(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vrtype, const unsigned char** fread_pp, PgenReaderMain* pgrp, uintptr_t* __restrict genovec) {
2704 // Side effects:
2705 // may use pgrp->workspace_raregeno_tmp_loadbuf
2706 // fills pgrp->ldbase_raw_genovec iff (!(vrtype & 4)) and
2707 // subsetting_required (does not update ldbase_stypes, caller's
2708 // responsibility to care)
2709 // See comments on Parse1or2bitGenoarrUnsafe().
2710 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
2711 if (!(vrtype & 4)) {
2712 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
2713 uintptr_t* raw_genovec = subsetting_required? pgrp->ldbase_raw_genovec : genovec;
2714 PglErr reterr = Parse1or2bitGenoarrUnsafe(fread_end, vrtype, fread_pp, pgrp, raw_genovec);
2715 if ((!subsetting_required) || reterr) {
2716 return reterr;
2717 }
2718 CopyNyparrNonemptySubset(raw_genovec, sample_include, raw_sample_ct, sample_ct, genovec);
2719 return kPglRetSuccess;
2720 }
2721 const uint32_t vrtype_low2 = vrtype & 3;
2722 if (vrtype_low2 != 1) {
2723 const uint32_t vec_ct = NypCtToVecCt(sample_ct);
2724
2725 // This memset is frequently the limiting operation. This suggests that we
2726 // should eventually make more use of the DifflistOrGenovec interface.
2727 vecset(genovec, vrtype_low2 * kMask5555, vec_ct);
2728 return ParseAndApplyDifflistSubset(fread_end, sample_include, sample_include_cumulative_popcounts, sample_ct, fread_pp, pgrp, genovec);
2729 }
2730 // all homozygous-ref special case
2731 ZeroWArr(NypCtToWordCt(sample_ct), genovec);
2732 return kPglRetSuccess;
2733 }
2734
2735 uint32_t LdLoadNecessary(uint32_t cur_vidx, PgenReaderMain* pgrp) {
2736 // Determines whether LD base variant needs to be loaded (in addition to the
2737 // current variant), assuming we need (possibly subsetted) hardcalls.
2738 // Important: this updates pgrp->ldbase_vidx when necessary, as a side
2739 // effect.
2740 // bugfix (22 May 2018): this only checked whether ldbase_stypes was nonzero;
2741 // there was an AllHets + cache-clear edge case where that's not good enough.
2742 // now that AllHets has been removed, though, it should be safe again.
2743 if (pgrp->ldbase_stypes && (cur_vidx == pgrp->fp_vidx)) {
2744 // ldbase variant guaranteed to be up-to-date if we didn't skip the last
2745 // variant, and cache wasn't cleared
2746 return 0;
2747 }
2748 // Find the last vrtypes[] value before vrtypes[cur_vidx] with bit 1 unset or
2749 // bit 2 set.
2750 const uint32_t old_ldbase_vidx = pgrp->ldbase_vidx;
2751 pgrp->ldbase_vidx = GetLdbaseVidx(pgrp->fi.vrtypes, cur_vidx);
2752 return (pgrp->ldbase_vidx != old_ldbase_vidx);
2753 }
2754
2755 BoolErr InitReadPtrs(uint32_t vidx, PgenReaderMain* pgrp, const unsigned char** fread_pp, const unsigned char** fread_endp) {
2756 const unsigned char* block_base = pgrp->fi.block_base;
2757 if (block_base != nullptr) {
2758 // possible todo: special handling of end of vblock
2759 const uint64_t block_offset = pgrp->fi.block_offset;
2760 *fread_pp = &(block_base[GetPgfiFpos(&(pgrp->fi), vidx) - block_offset]);
2761 *fread_endp = &(block_base[GetPgfiFpos(&(pgrp->fi), vidx + 1) - block_offset]);
2762
2763 // still a useful hint to LdLoadNecessary()
2764 pgrp->fp_vidx = vidx + 1;
2765
2766 return 0;
2767 }
2768 if (pgrp->fp_vidx != vidx) {
2769 if (unlikely(fseeko(pgrp->ff, GetPgfiFpos(&(pgrp->fi), vidx), SEEK_SET))) {
2770 return 1;
2771 }
2772 }
2773 const uintptr_t cur_vrec_width = GetPgfiVrecWidth(&(pgrp->fi), vidx);
2774 #ifdef __LP64__
2775 if (unlikely(fread_checked(pgrp->fread_buf, cur_vrec_width, pgrp->ff))) {
2776 if (feof_unlocked(pgrp->ff)) {
2777 errno = 0;
2778 }
2779 return 1;
2780 }
2781 #else
2782 // cur_vrec_width < 2^31 since otherwise we error out on initialization
2783 if (unlikely(!fread_unlocked(pgrp->fread_buf, cur_vrec_width, 1, pgrp->ff))) {
2784 if (feof_unlocked(pgrp->ff)) {
2785 errno = 0;
2786 }
2787 return 1;
2788 }
2789 #endif
2790 *fread_pp = pgrp->fread_buf;
2791 *fread_endp = &(pgrp->fread_buf[cur_vrec_width]);
2792 pgrp->fp_vidx = vidx + 1;
2793 return 0;
2794 }
2795
2796 // Fills dest with subsetted ldbase contents, and ensures ldcache is filled so
2797 // no explicit reload of ldbase is needed for next variant if we're extracting
2798 // the same sample subset. (Reload is occasionally needed if next variant is
2799 // multiallelic or phased, we only prevent that when convenient.)
2800 PglErr LdLoadAndCopyGenovecSubset(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, PgenReaderMain* pgrp, uintptr_t* dest) {
2801 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
2802 if (LdLoadNecessary(vidx, pgrp)) {
2803 const uint32_t ldbase_vidx = pgrp->ldbase_vidx;
2804 const unsigned char* fread_ptr;
2805 const unsigned char* fread_end;
2806 if (unlikely(InitReadPtrs(ldbase_vidx, pgrp, &fread_ptr, &fread_end))) {
2807 return kPglRetReadFail;
2808 }
2809 const uint32_t vrtype = pgrp->fi.vrtypes[ldbase_vidx];
2810 PglErr reterr = ParseNonLdGenovecSubsetUnsafe(fread_end, sample_include, sample_include_cumulative_popcounts, sample_ct, vrtype, &fread_ptr, pgrp, dest);
2811 pgrp->ldbase_stypes = ((sample_ct != raw_sample_ct) && (!(vrtype & 4)))? (kfPgrLdcacheNyp | kfPgrLdcacheRawNyp) : kfPgrLdcacheNyp;
2812 CopyNyparr(dest, sample_ct, pgrp->ldbase_genovec);
2813 return reterr;
2814 }
2815 if (pgrp->ldbase_stypes & kfPgrLdcacheNyp) {
2816 CopyNyparr(pgrp->ldbase_genovec, sample_ct, dest);
2817 } else {
2818 if ((pgrp->ldbase_stypes & kfPgrLdcacheRawNyp) && (sample_ct == raw_sample_ct)) {
2819 CopyNyparr(pgrp->ldbase_raw_genovec, sample_ct, dest);
2820 } else if (pgrp->ldbase_stypes & kfPgrLdcacheDifflist) {
2821 // rematerialize-from-difflist is cheap.
2822 PgrDifflistToGenovecUnsafe(pgrp->ldbase_raregeno, pgrp->ldbase_difflist_sample_ids, pgrp->fi.vrtypes[pgrp->ldbase_vidx] & 3, sample_ct, pgrp->ldbase_difflist_len, dest);
2823 } else {
2824 CopyNyparrNonemptySubset(pgrp->ldbase_raw_genovec, sample_include, pgrp->fi.raw_sample_ct, sample_ct, dest);
2825 CopyNyparr(dest, sample_ct, pgrp->ldbase_genovec);
2826 pgrp->ldbase_stypes |= kfPgrLdcacheNyp;
2827 }
2828 }
2829 return kPglRetSuccess;
2830 }
2831
2832 // fread_pp should be non-null iff this is being called by an internal function
2833 // as part of a more complex read.
2834 // in multiallelic case:
2835 // hom-ref = 0
2836 // het-ref = 1
2837 // two nonref = 2
2838 // missing = 3
2839 PglErr ReadGenovecSubsetUnsafe(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, PgenReaderMain* pgrp, const unsigned char** fread_pp, const unsigned char** fread_endp, uintptr_t* __restrict genovec) {
2840 // Side effects:
2841 // may use pgr.workspace_raregeno_tmp_loadbuf (any difflist)
2842 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
2843 const uint32_t maintrack_vrtype = vrtype & 7;
2844 if (VrtypeLdCompressed(maintrack_vrtype)) {
2845 // LD compression
2846 PglErr reterr = LdLoadAndCopyGenovecSubset(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, genovec);
2847 if (unlikely(reterr)) {
2848 return reterr;
2849 }
2850 const unsigned char* fread_ptr;
2851 const unsigned char* fread_end;
2852 if (unlikely(InitReadPtrs(vidx, pgrp, &fread_ptr, &fread_end))) {
2853 return kPglRetReadFail;
2854 }
2855 reterr = ParseAndApplyDifflistSubset(fread_end, sample_include, sample_include_cumulative_popcounts, sample_ct, &fread_ptr, pgrp, genovec);
2856 if (unlikely(reterr)) {
2857 return reterr;
2858 }
2859 if (maintrack_vrtype == 3) {
2860 GenovecInvertUnsafe(sample_ct, genovec);
2861 }
2862 if (fread_pp) {
2863 *fread_pp = fread_ptr;
2864 *fread_endp = fread_end;
2865 }
2866 return kPglRetSuccess;
2867 }
2868 const unsigned char* fread_ptr;
2869 const unsigned char* fread_end = nullptr; // maybe-uninitialized warning
2870 // tried inserting special-case code for the plink1 case to avoid a copy, and
2871 // it was actually slower
2872 if (unlikely(InitReadPtrs(vidx, pgrp, &fread_ptr, &fread_end))) {
2873 return kPglRetReadFail;
2874 }
2875 // tried to add more sophisticated caching, but turns out it isn't worth it
2876 PglErr reterr = ParseNonLdGenovecSubsetUnsafe(fread_end, sample_include, sample_include_cumulative_popcounts, sample_ct, maintrack_vrtype, &fread_ptr, pgrp, genovec);
2877 if (unlikely(reterr)) {
2878 return reterr;
2879 }
2880 if (vrtype == kPglVrtypePlink1) {
2881 PgrPlink1ToPlink2InplaceUnsafe(sample_ct, genovec);
2882 } else {
2883 const uint32_t is_ldbase = pgrp->fi.vrtypes && VrtypeLdCompressed(pgrp->fi.vrtypes[vidx + 1]);
2884 const uint32_t ldbase_raw_genovec_saved = (sample_ct != pgrp->fi.raw_sample_ct) && (!(maintrack_vrtype & 4));
2885 if (is_ldbase) {
2886 CopyNyparr(genovec, sample_ct, pgrp->ldbase_genovec);
2887 pgrp->ldbase_vidx = vidx;
2888 // may be better to just always set to kfPgrLdcacheNyp? this depends
2889 // on multiallelic code
2890 pgrp->ldbase_stypes = ldbase_raw_genovec_saved? (kfPgrLdcacheNyp | kfPgrLdcacheRawNyp) : kfPgrLdcacheNyp;
2891 } else if (ldbase_raw_genovec_saved) {
2892 // bugfix (22 Sep 2018): when accessing variants out of order, need to
2893 // note that we just clobbered the cache
2894 pgrp->ldbase_stypes &= ~kfPgrLdcacheRawNyp;
2895 }
2896 }
2897 if (fread_pp) {
2898 *fread_pp = fread_ptr;
2899 *fread_endp = fread_end;
2900 }
2901 return kPglRetSuccess;
2902 }
2903
2904 PglErr PgrGet(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, uintptr_t* __restrict genovec) {
2905 if (!sample_ct) {
2906 return kPglRetSuccess;
2907 }
2908 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
2909 assert(vidx < pgrp->fi.raw_variant_ct);
2910 return ReadGenovecSubsetUnsafe(sample_include, GetSicp(pssi), sample_ct, vidx, pgrp, nullptr, nullptr, genovec);
2911 }
2912
2913 // Fills dest with ldbase contents, and ensures ldcache is filled so no
2914 // explicit reload of ldbase is needed for next variant.
2915 PglErr LdLoadAndCopyRawGenovec(uint32_t subsetting_required, uint32_t vidx, PgenReaderMain* pgrp, uintptr_t* dest) {
2916 const uint32_t genovec_byte_ct = NypCtToVecCt(pgrp->fi.raw_sample_ct) * kBytesPerVec;
2917 if (LdLoadNecessary(vidx, pgrp) || (subsetting_required && (!(pgrp->ldbase_stypes & kfPgrLdcacheRawNyp)))) {
2918 const uint32_t ldbase_vidx = pgrp->ldbase_vidx;
2919 const unsigned char* fread_ptr;
2920 const unsigned char* fread_end;
2921 if (unlikely(InitReadPtrs(ldbase_vidx, pgrp, &fread_ptr, &fread_end))) {
2922 return kPglRetReadFail;
2923 }
2924 const uint32_t vrtype = pgrp->fi.vrtypes[ldbase_vidx];
2925 pgrp->ldbase_stypes = kfPgrLdcacheRawNyp;
2926 assert((vrtype & 7) != 5); // all-hom-ref can't be ldbase
2927 uintptr_t* raw_genovec = pgrp->ldbase_raw_genovec;
2928 PglErr reterr;
2929 if (!(vrtype & 4)) {
2930 reterr = Parse1or2bitGenoarrUnsafe(fread_end, vrtype, &fread_ptr, pgrp, raw_genovec);
2931 } else {
2932 const uint32_t vrtype_low2 = vrtype & 3;
2933 vecset(raw_genovec, vrtype_low2 * kMask5555, DivUp(genovec_byte_ct, kBytesPerVec));
2934 reterr = ParseAndApplyDifflist(fread_end, &fread_ptr, pgrp, raw_genovec);
2935 }
2936 memcpy(dest, raw_genovec, genovec_byte_ct);
2937 return reterr;
2938 }
2939 if (pgrp->ldbase_stypes & kfPgrLdcacheRawNyp) {
2940 memcpy(dest, pgrp->ldbase_raw_genovec, genovec_byte_ct);
2941 } else {
2942 // no subsetting, can use regular Ldcache entries
2943 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
2944 if (pgrp->ldbase_stypes & kfPgrLdcacheNyp) {
2945 memcpy(dest, pgrp->ldbase_genovec, genovec_byte_ct);
2946 } else {
2947 PgrDifflistToGenovecUnsafe(pgrp->ldbase_raregeno, pgrp->ldbase_difflist_sample_ids, pgrp->fi.vrtypes[pgrp->ldbase_vidx] & 3, raw_sample_ct, pgrp->ldbase_difflist_len, dest);
2948 }
2949 }
2950 return kPglRetSuccess;
2951 }
2952
2953 // Does not zero out trailing bits.
2954 // Requires fread_pp and fread_endp to be non-null for now.
2955 PglErr ReadRawGenovec(uint32_t subsetting_required, uint32_t vidx, PgenReaderMain* pgrp, const unsigned char** fread_pp, const unsigned char** fread_endp, uintptr_t* raw_genovec) {
2956 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
2957 const uint32_t maintrack_vrtype = vrtype & 7;
2958 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
2959 if (VrtypeLdCompressed(maintrack_vrtype)) {
2960 // LD compression
2961 PglErr reterr = LdLoadAndCopyRawGenovec(subsetting_required, vidx, pgrp, raw_genovec);
2962 if (unlikely(reterr)) {
2963 return reterr;
2964 }
2965 if (unlikely(InitReadPtrs(vidx, pgrp, fread_pp, fread_endp))) {
2966 return kPglRetReadFail;
2967 }
2968 reterr = ParseAndApplyDifflist(*fread_endp, fread_pp, pgrp, raw_genovec);
2969 if (unlikely(reterr)) {
2970 return reterr;
2971 }
2972 if (maintrack_vrtype == 3) {
2973 GenovecInvertUnsafe(raw_sample_ct, raw_genovec);
2974 }
2975 return kPglRetSuccess;
2976 }
2977 if (unlikely(InitReadPtrs(vidx, pgrp, fread_pp, fread_endp))) {
2978 return kPglRetReadFail;
2979 }
2980 const unsigned char* fread_end = *fread_endp;
2981 PglErr reterr;
2982 if (!(vrtype & 4)) {
2983 reterr = Parse1or2bitGenoarrUnsafe(fread_end, vrtype, fread_pp, pgrp, raw_genovec);
2984 } else {
2985 const uint32_t vrtype_low2 = vrtype & 3;
2986 if (vrtype_low2 == 1) {
2987 ZeroWArr(NypCtToWordCt(raw_sample_ct), raw_genovec);
2988 // all-hom-ref can't be ldbase
2989 return kPglRetSuccess;
2990 }
2991 const uint32_t vec_ct = NypCtToVecCt(raw_sample_ct);
2992 vecset(raw_genovec, vrtype_low2 * kMask5555, vec_ct);
2993 reterr = ParseAndApplyDifflist(fread_end, fread_pp, pgrp, raw_genovec);
2994 }
2995 if (vrtype == kPglVrtypePlink1) {
2996 PgrPlink1ToPlink2InplaceUnsafe(raw_sample_ct, raw_genovec);
2997 } else {
2998 const uint32_t is_ldbase = pgrp->fi.vrtypes && VrtypeLdCompressed(pgrp->fi.vrtypes[vidx + 1]);
2999 if (is_ldbase) {
3000 CopyNyparr(raw_genovec, raw_sample_ct, pgrp->ldbase_raw_genovec);
3001 pgrp->ldbase_vidx = vidx;
3002 pgrp->ldbase_stypes = kfPgrLdcacheRawNyp;
3003 }
3004 }
3005 return reterr;
3006 }
3007 /*
3008 void CopyAndSubsetDifflist(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, const uintptr_t* __restrict raw_raregeno, const uint32_t* __restrict raw_difflist_sample_ids, uint32_t raw_difflist_len, uintptr_t* __restrict new_raregeno, uint32_t* __restrict new_difflist_sample_ids, uint32_t* __restrict new_difflist_len_ptr) {
3009 // Trailing bits of new_raregeno are zeroed out.
3010 if (!raw_difflist_len) {
3011 *new_difflist_len_ptr = 0;
3012 return;
3013 }
3014 const uintptr_t* raw_raregeno_incr = raw_raregeno;
3015 const uint32_t* raw_difflist_sample_ids_iter = raw_difflist_sample_ids;
3016 const uint32_t* raw_difflist_sample_ids_last = &(raw_difflist_sample_ids[RoundDownPow2(raw_difflist_len - 1, kBitsPerWordD2)]);
3017 uintptr_t* new_raregeno_incr = new_raregeno;
3018 uintptr_t new_raregeno_word = 0;
3019 uint32_t new_difflist_len = 0;
3020 uint32_t block_len_m1 = kBitsPerWordD2 - 1;
3021 while (1) {
3022 if (raw_difflist_sample_ids_iter >= raw_difflist_sample_ids_last) {
3023 if (raw_difflist_sample_ids_iter > raw_difflist_sample_ids_last) {
3024 if (new_difflist_len % kBitsPerWordD2) {
3025 *new_raregeno_incr = new_raregeno_word;
3026 }
3027 *new_difflist_len_ptr = new_difflist_len;
3028 return;
3029 }
3030 block_len_m1 &= raw_difflist_len - 1;
3031 }
3032 uintptr_t raw_raregeno_word = *raw_raregeno_incr++;
3033 uint32_t raw_difflist_idx_lowbits = 0;
3034 while (1) {
3035 const uint32_t raw_sample_idx = raw_difflist_sample_ids_iter[raw_difflist_idx_lowbits];
3036 if (IsSet(sample_include, raw_sample_idx)) {
3037 new_difflist_sample_ids[new_difflist_len] = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, raw_sample_idx);
3038 new_raregeno_word |= ((raw_raregeno_word >> (2 * raw_difflist_idx_lowbits)) & 3) << (2 * (new_difflist_len % kBitsPerWordD2));
3039 ++new_difflist_len;
3040 if (!(new_difflist_len % kBitsPerWordD2)) {
3041 *new_raregeno_incr++ = new_raregeno_word;
3042 new_raregeno_word = 0;
3043 }
3044 }
3045 if (raw_difflist_idx_lowbits == block_len_m1) {
3046 break;
3047 }
3048 ++raw_difflist_idx_lowbits;
3049 }
3050 raw_difflist_sample_ids_iter = &(raw_difflist_sample_ids_iter[kBitsPerWordD2]);
3051 }
3052 }
3053 */
3054
3055 // Populates pgrp->ldbase_genovec or
3056 // pgrp->ldbase_{raregeno,difflist_sample_ids,difflist_len}, depending on
3057 // storage type.
3058 // Currently just called by ReadDifflistOrGenovecSubsetUnsafe().
3059 PglErr LdLoadMinimalSubsetIfNecessary(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, PgenReaderMain* pgrp) {
3060 if (!LdLoadNecessary(vidx, pgrp)) {
3061 return kPglRetSuccess;
3062 }
3063 const uint32_t ldbase_vidx = pgrp->ldbase_vidx;
3064 const uint64_t cur_vidx_fpos = pgrp->fi.var_fpos[ldbase_vidx];
3065 const uint32_t ldbase_vrtype = pgrp->fi.vrtypes[ldbase_vidx];
3066 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
3067 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
3068 uintptr_t* raw_genovec = subsetting_required? pgrp->ldbase_raw_genovec : pgrp->ldbase_genovec;
3069 const unsigned char* fread_ptr;
3070 const unsigned char* fread_end;
3071 const unsigned char* block_base = pgrp->fi.block_base;
3072 PglErr reterr = kPglRetSuccess;
3073 if (block_base != nullptr) {
3074 {
3075 const uint64_t block_offset = pgrp->fi.block_offset;
3076 fread_ptr = &(block_base[cur_vidx_fpos - block_offset]);
3077 fread_end = &(block_base[pgrp->fi.var_fpos[ldbase_vidx + 1] - block_offset]);
3078 }
3079 if (!(ldbase_vrtype & 4)) {
3080 reterr = Parse1or2bitGenoarrUnsafe(fread_end, ldbase_vrtype, &fread_ptr, pgrp, raw_genovec);
3081 LdLoadMinimalSubsetIfNecessary_genovec_finish:
3082 pgrp->ldbase_stypes = subsetting_required? (kfPgrLdcacheNyp | kfPgrLdcacheRawNyp) : kfPgrLdcacheNyp;
3083 if ((!subsetting_required) || reterr) {
3084 return reterr;
3085 }
3086 CopyNyparrNonemptySubset(raw_genovec, sample_include, raw_sample_ct, sample_ct, pgrp->ldbase_genovec);
3087 return kPglRetSuccess;
3088 }
3089 pgrp->fp_vidx = ldbase_vidx + 1;
3090 } else {
3091 if (unlikely(fseeko(pgrp->ff, pgrp->fi.var_fpos[ldbase_vidx], SEEK_SET))) {
3092 return kPglRetReadFail;
3093 }
3094 const uintptr_t cur_vrec_width = pgrp->fi.var_fpos[ldbase_vidx + 1] - cur_vidx_fpos;
3095 pgrp->fp_vidx = ldbase_vidx + 1;
3096 if (!(ldbase_vrtype & 7)) {
3097 // don't actually need to fread the whole record in this case
3098 const uint32_t raw_sample_ct4 = NypCtToByteCt(raw_sample_ct);
3099 if (unlikely(!fread_unlocked(raw_genovec, raw_sample_ct4, 1, pgrp->ff))) {
3100 if (feof_unlocked(pgrp->ff)) {
3101 errno = 0;
3102 }
3103 return kPglRetReadFail;
3104 }
3105 if (raw_sample_ct4 != cur_vrec_width) {
3106 // ensure this doesn't match
3107 pgrp->fp_vidx = 0;
3108 }
3109 goto LdLoadMinimalSubsetIfNecessary_genovec_finish;
3110 }
3111 if (unlikely(!fread_unlocked(pgrp->fread_buf, cur_vrec_width, 1, pgrp->ff))) {
3112 if (feof_unlocked(pgrp->ff)) {
3113 errno = 0;
3114 }
3115 return kPglRetReadFail;
3116 }
3117 fread_ptr = pgrp->fread_buf;
3118 fread_end = &(pgrp->fread_buf[cur_vrec_width]);
3119 if (!(ldbase_vrtype & 4)) {
3120 reterr = ParseOnebitUnsafe(fread_end, &fread_ptr, pgrp, raw_genovec);
3121 goto LdLoadMinimalSubsetIfNecessary_genovec_finish;
3122 }
3123 }
3124 uint32_t ldbase_difflist_len;
3125 if (!subsetting_required) {
3126 reterr = ParseAndSaveDifflist(fread_end, raw_sample_ct, &fread_ptr, pgrp->ldbase_raregeno, pgrp->ldbase_difflist_sample_ids, &ldbase_difflist_len);
3127 } else {
3128 reterr = ParseAndSaveDifflistProperSubset(fread_end, sample_include, sample_include_cumulative_popcounts, raw_sample_ct, &fread_ptr, pgrp->ldbase_raregeno, pgrp->ldbase_difflist_sample_ids, &ldbase_difflist_len, pgrp->workspace_raregeno_tmp_loadbuf);
3129 }
3130 if (unlikely(reterr)) {
3131 return reterr;
3132 }
3133 pgrp->ldbase_difflist_len = ldbase_difflist_len;
3134 pgrp->ldbase_difflist_sample_ids[ldbase_difflist_len] = sample_ct;
3135 pgrp->ldbase_stypes = kfPgrLdcacheDifflist;
3136 return kPglRetSuccess;
3137 }
3138
3139 PglErr ReadDifflistOrGenovecSubsetUnsafe(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t max_simple_difflist_len, uint32_t vidx, PgenReaderMain* pgrp, const unsigned char** fread_pp, const unsigned char** fread_endp, uintptr_t* __restrict genovec, uint32_t* difflist_common_geno_ptr, uintptr_t* __restrict main_raregeno, uint32_t* __restrict difflist_sample_ids, uint32_t* __restrict difflist_len_ptr) {
3140 assert(vidx < pgrp->fi.raw_variant_ct);
3141 assert(sample_ct);
3142 assert(max_simple_difflist_len < sample_ct);
3143 // Side effects:
3144 // may use pgr.workspace_raregeno_tmp_loadbuf
3145 // Trailing bits of genovec/main_raregeno may not be zeroed out.
3146 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
3147 const uint32_t maintrack_vrtype = vrtype & 7;
3148 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
3149 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
3150 // const uint32_t multiallelic_hc_present = fread_pp && VrtypeMultiallelic(vrtype);
3151 if (VrtypeLdCompressed(maintrack_vrtype)) {
3152 // LD compression
3153
3154 // note that this can currently load a difflist longer than
3155 // max_simple_difflist_len
3156 PglErr reterr = LdLoadMinimalSubsetIfNecessary(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp);
3157 if (unlikely(reterr)) {
3158 return reterr;
3159 }
3160 const unsigned char* fread_ptr;
3161 const unsigned char* fread_end;
3162 if (unlikely(InitReadPtrs(vidx, pgrp, &fread_ptr, &fread_end))) {
3163 return kPglRetReadFail;
3164 }
3165 const uint32_t ld_invert = (maintrack_vrtype == 3);
3166 if (pgrp->ldbase_stypes & kfPgrLdcacheDifflist) {
3167 const uint32_t ldbase_common_geno = pgrp->fi.vrtypes[pgrp->ldbase_vidx] & 3;
3168 // unnecessary for this to branch on LD difflist length, since that's
3169 // limited to 3/4 of the ldbase difflist length.
3170 *difflist_common_geno_ptr = ldbase_common_geno;
3171 reterr = ParseLdAndMergeDifflistSubset(fread_end, subsetting_required? sample_include : nullptr, sample_include_cumulative_popcounts, pgrp->ldbase_raregeno, pgrp->ldbase_difflist_sample_ids, pgrp->ldbase_difflist_len, ldbase_common_geno, raw_sample_ct, sample_ct, &fread_ptr, main_raregeno, difflist_sample_ids, difflist_len_ptr, pgrp->workspace_raregeno_tmp_loadbuf);
3172 if (unlikely(reterr)) {
3173 return reterr;
3174 }
3175 if (ld_invert) {
3176 *difflist_common_geno_ptr = (6 - ldbase_common_geno) & 3;
3177 GenovecInvertUnsafe(*difflist_len_ptr, main_raregeno);
3178 }
3179 return kPglRetSuccess;
3180 }
3181 if (pgrp->ldbase_stypes & kfPgrLdcacheNyp) {
3182 CopyNyparr(pgrp->ldbase_genovec, sample_ct, genovec);
3183 } else {
3184 assert(pgrp->ldbase_stypes & kfPgrLdcacheRawNyp);
3185 CopyNyparrNonemptySubset(pgrp->ldbase_raw_genovec, sample_include, raw_sample_ct, sample_ct, genovec);
3186 CopyNyparr(genovec, sample_ct, pgrp->ldbase_genovec);
3187 pgrp->ldbase_stypes |= kfPgrLdcacheNyp;
3188 }
3189 *difflist_common_geno_ptr = UINT32_MAX;
3190 reterr = ParseAndApplyDifflistSubset(fread_end, sample_include, sample_include_cumulative_popcounts, sample_ct, &fread_ptr, pgrp, genovec);
3191 if (unlikely(reterr)) {
3192 return reterr;
3193 }
3194 if (ld_invert) {
3195 GenovecInvertUnsafe(sample_ct, genovec);
3196 }
3197 if (fread_pp) {
3198 *fread_pp = fread_ptr;
3199 *fread_endp = fread_end;
3200 }
3201 return kPglRetSuccess;
3202 }
3203 const unsigned char* fread_ptr;
3204 const unsigned char* fread_end = nullptr; // maybe-uninitialized warning
3205 if (unlikely(InitReadPtrs(vidx, pgrp, &fread_ptr, &fread_end))) {
3206 return kPglRetReadFail;
3207 }
3208 const uint32_t is_ldbase = pgrp->fi.vrtypes && VrtypeLdCompressed(pgrp->fi.vrtypes[vidx + 1]);
3209 const uint32_t saved_difflist_len = VrtypeDifflist(vrtype)? PeekVint31(fread_ptr, fread_end) : raw_sample_ct;
3210 pgrp->ldbase_vidx = vidx;
3211 // no limit is slightly better than /16 but substantially worse than /32 on
3212 // the large test dataset (/64 is slightly worse than /32)
3213 // no limit is best on the small test dataset
3214 if (saved_difflist_len > max_simple_difflist_len) {
3215 *difflist_common_geno_ptr = UINT32_MAX;
3216 PglErr reterr = ParseNonLdGenovecSubsetUnsafe(fread_end, sample_include, sample_include_cumulative_popcounts, sample_ct, vrtype, &fread_ptr, pgrp, genovec);
3217 if (unlikely(reterr)) {
3218 return reterr;
3219 }
3220 const uint32_t ldbase_raw_genovec_saved = (subsetting_required && (!(vrtype & 4)));
3221 if (is_ldbase) {
3222 CopyNyparr(genovec, sample_ct, pgrp->ldbase_genovec);
3223 pgrp->ldbase_stypes = ldbase_raw_genovec_saved? (kfPgrLdcacheNyp | kfPgrLdcacheRawNyp) : kfPgrLdcacheNyp;
3224 } else if (ldbase_raw_genovec_saved) {
3225 // bugfix (22 Sep 2018)
3226 pgrp->ldbase_stypes &= ~kfPgrLdcacheRawNyp;
3227 }
3228 if (vrtype == kPglVrtypePlink1) {
3229 PgrPlink1ToPlink2InplaceUnsafe(sample_ct, genovec);
3230 }
3231 if (fread_pp) {
3232 *fread_pp = fread_ptr;
3233 *fread_endp = fread_end;
3234 }
3235 return kPglRetSuccess;
3236 }
3237 *difflist_common_geno_ptr = vrtype & 3;
3238 PglErr reterr;
3239 if (!subsetting_required) {
3240 reterr = ParseAndSaveDifflist(fread_end, raw_sample_ct, &fread_ptr, main_raregeno, difflist_sample_ids, difflist_len_ptr);
3241 } else {
3242 reterr = ParseAndSaveDifflistProperSubset(fread_end, sample_include, sample_include_cumulative_popcounts, raw_sample_ct, &fread_ptr, main_raregeno, difflist_sample_ids, difflist_len_ptr, pgrp->workspace_raregeno_tmp_loadbuf);
3243 }
3244 if (unlikely(reterr)) {
3245 return kPglRetMalformedInput;
3246 }
3247 if (is_ldbase) {
3248 const uint32_t difflist_len = *difflist_len_ptr;
3249 pgrp->ldbase_stypes = kfPgrLdcacheDifflist;
3250 pgrp->ldbase_difflist_len = difflist_len;
3251 CopyNyparr(main_raregeno, difflist_len, pgrp->ldbase_raregeno);
3252 memcpy(pgrp->ldbase_difflist_sample_ids, difflist_sample_ids, difflist_len * sizeof(int32_t));
3253 pgrp->ldbase_difflist_sample_ids[difflist_len] = sample_ct;
3254 }
3255 if (fread_pp) {
3256 *fread_pp = fread_ptr;
3257 *fread_endp = fread_end;
3258 }
3259 return kPglRetSuccess;
3260 }
3261
3262 PglErr PgrGetDifflistOrGenovec(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t max_simple_difflist_len, uint32_t vidx, PgenReader* pgr_ptr, uintptr_t* __restrict genovec, uint32_t* __restrict difflist_common_geno_ptr, uintptr_t* __restrict main_raregeno, uint32_t* __restrict difflist_sample_ids, uint32_t* __restrict difflist_len_ptr) {
3263 if (!sample_ct) {
3264 *difflist_common_geno_ptr = UINT32_MAX;
3265 return kPglRetSuccess;
3266 }
3267 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
3268 assert(vidx < pgrp->fi.raw_variant_ct);
3269 return ReadDifflistOrGenovecSubsetUnsafe(sample_include, GetSicp(pssi), sample_ct, max_simple_difflist_len, vidx, pgrp, nullptr, nullptr, genovec, difflist_common_geno_ptr, main_raregeno, difflist_sample_ids, difflist_len_ptr);
3270 }
3271
3272 PglErr LdSubsetAdjustGenocounts(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, const uintptr_t* __restrict ldbase_genovec, uint32_t raw_sample_ct, const unsigned char** fread_pp, STD_ARRAY_REF(uint32_t, 4) genocounts, uintptr_t* __restrict raregeno_workspace) {
3273 // * sample_include assumed to be nullptr if no subsetting required
3274 // * Assumes genocounts[] is initialized to the proper values for the LD
3275 // reference variant (including subsetting).
3276 // * Tried a hybrid implementation which allowed the base variant to be saved
3277 // as a difflist; turns out it's practically always better to unpack to a
3278 // genovec first.
3279 // * There are two modes:
3280 // 1. If sample_include is nullptr, we're not selecting a sample subset.
3281 // 2. If sample_include and sample_include_cumulative_popcounts are both
3282 // non-null, we're computing counts over a sample subset, and
3283 // ldbase_genovec is assumed to be subsetted.
3284 // Experimented with a third mode where ldbase_genovec was replaced with
3285 // ldbase_raw_genovec in the subsetted case, but that didn't seem to pay
3286 // off.
3287 // * This is the main frequency-counting bottleneck.
3288 uint32_t raw_difflist_len;
3289 const unsigned char* group_info_iter;
3290 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, raregeno_workspace, &group_info_iter, &raw_difflist_len);
3291 if (reterr || (!raw_difflist_len)) {
3292 return reterr;
3293 }
3294 const uint32_t subgroup_idx_last = (raw_difflist_len - 1) / kBitsPerWordD2;
3295 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(raw_sample_ct);
3296 uintptr_t* raregeno_workspace_iter = raregeno_workspace;
3297 uintptr_t raw_sample_idx = 0;
3298 STD_ARRAY_DECL(uint32_t, 16, delta_counts);
3299 STD_ARRAY_FILL0(delta_counts);
3300 for (uint32_t subgroup_idx = 0; ; ++subgroup_idx) {
3301 uint32_t remaining_deltas_in_subgroup = kBitsPerWordD2 - 1;
3302 if (subgroup_idx >= subgroup_idx_last) {
3303 if (subgroup_idx > subgroup_idx_last) {
3304 const int32_t incr0 = delta_counts[1] + delta_counts[2] + delta_counts[3] - delta_counts[4] - delta_counts[8] - delta_counts[12];
3305 const int32_t incr1 = delta_counts[4] + delta_counts[6] + delta_counts[7] - delta_counts[1] - delta_counts[9] - delta_counts[13];
3306 const int32_t incr2 = delta_counts[8] + delta_counts[9] + delta_counts[11] - delta_counts[2] - delta_counts[6] - delta_counts[14];
3307 genocounts[0] += incr0;
3308 genocounts[1] += incr1;
3309 genocounts[2] += incr2;
3310 genocounts[3] -= incr0 + incr1 + incr2;
3311 return kPglRetSuccess;
3312 }
3313 remaining_deltas_in_subgroup &= raw_difflist_len - 1;
3314 }
3315 if (!(subgroup_idx % (kPglDifflistGroupSize / kBitsPerWordD2))) {
3316 #ifdef __LP64__
3317 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
3318 return kPglRetMalformedInput;
3319 }
3320 #endif
3321 raw_sample_idx = SubU32Load(group_info_iter, sample_id_byte_ct);
3322 group_info_iter = &(group_info_iter[sample_id_byte_ct]);
3323 } else {
3324 raw_sample_idx += GetVint31(fread_end, fread_pp);
3325 }
3326 uintptr_t cur_raregeno_word = *raregeno_workspace_iter++;
3327 if (!sample_include) {
3328 for (; ; --remaining_deltas_in_subgroup) {
3329 #ifndef __LP64__
3330 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
3331 return kPglRetMalformedInput;
3332 }
3333 #endif
3334 const uintptr_t cur_geno = cur_raregeno_word & 3;
3335 delta_counts[cur_geno * 4 + GetNyparrEntry(ldbase_genovec, raw_sample_idx)] += 1;
3336 if (!remaining_deltas_in_subgroup) {
3337 break;
3338 }
3339 raw_sample_idx += GetVint31(fread_end, fread_pp);
3340 cur_raregeno_word >>= 2;
3341 }
3342 } else {
3343 for (; ; --remaining_deltas_in_subgroup) {
3344 #ifndef __LP64__
3345 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
3346 return kPglRetMalformedInput;
3347 }
3348 #endif
3349 if (IsSet(sample_include, raw_sample_idx)) {
3350 const uintptr_t cur_geno = cur_raregeno_word & 3;
3351 const uint32_t sample_idx = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, raw_sample_idx);
3352 delta_counts[cur_geno * 4 + GetNyparrEntry(ldbase_genovec, sample_idx)] += 1;
3353 }
3354 if (!remaining_deltas_in_subgroup) {
3355 break;
3356 }
3357 raw_sample_idx += GetVint31(fread_end, fread_pp);
3358 cur_raregeno_word >>= 2;
3359 }
3360 }
3361 }
3362 }
3363
3364 PglErr SkipDeltalistIds(const unsigned char* fread_end, const unsigned char* group_info, uint32_t difflist_len, uint32_t raw_sample_ct, uint32_t has_genotypes, const unsigned char** fread_pp) {
3365 assert(difflist_len);
3366 // fread_pp is a pure output parameter here
3367 const uint32_t group_ct = DivUp(difflist_len, kPglDifflistGroupSize);
3368 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(raw_sample_ct);
3369 const unsigned char* extra_byte_cts = &(group_info[group_ct * sample_id_byte_ct]);
3370 const uint32_t extra_byte_tot = BytesumArr(extra_byte_cts, group_ct - 1);
3371
3372 // (group_ct - 1) for extra_byte_cts
3373 // (difflist_len + 3) / 4 for raregeno
3374 // (group_ct - 1) * (kPglDifflistGroupSize - 1) + extra_byte_tot for
3375 // all but last ID block
3376 // total = (group_ct - 1) * kPglDifflistGroupSize + extra_byte_tot +
3377 // (difflist_len + 3) / 4
3378 const unsigned char* iddiff_start = &(extra_byte_cts[(group_ct - 1) * kPglDifflistGroupSize + extra_byte_tot]);
3379 if (has_genotypes) {
3380 iddiff_start = &(iddiff_start[NypCtToByteCt(difflist_len)]);
3381 }
3382 const unsigned char* fread_ptr = iddiff_start;
3383 const unsigned char* fread_loop_stop = &(fread_end[-S_CAST(int32_t, kBytesPerWord)]);
3384 uint32_t remaining_id_ct = (difflist_len - 1) % kPglDifflistGroupSize;
3385 #ifdef USE_SSE2
3386 while (remaining_id_ct >= kBytesPerVec) {
3387 if (unlikely(fread_ptr > fread_loop_stop)) {
3388 return kPglRetMalformedInput;
3389 }
3390 const VecW vv = vecw_loadu(fread_ptr);
3391 fread_ptr = &(fread_ptr[kBytesPerVec]);
3392 // todo: better ARM implementation
3393 const uint32_t highbits = vecw_movemask(vv);
3394 remaining_id_ct -= kBytesPerVec - PopcountVec8thUint(highbits);
3395 }
3396 #endif
3397 while (remaining_id_ct >= kBytesPerWord) {
3398 // scan a word at a time, count number of high bits set
3399 if (unlikely(fread_ptr > fread_loop_stop)) {
3400 return kPglRetMalformedInput;
3401 }
3402 #ifdef USE_SSE42
3403 uintptr_t ww;
3404 CopyFromUnalignedIncrW(&ww, &fread_ptr);
3405 ww &= 0x80 * kMask0101;
3406 remaining_id_ct -= kBytesPerWord - PopcountWord(ww);
3407 #else
3408 uintptr_t ww;
3409 CopyFromUnalignedIncrW(&ww, &fread_ptr);
3410 ww = (ww >> 7) & kMask0101;
3411 remaining_id_ct -= kBytesPerWord - ((ww * kMask0101) >> (kBitsPerWord - 8));
3412 #endif
3413 }
3414 if (!remaining_id_ct) {
3415 *fread_pp = fread_ptr;
3416 return kPglRetSuccess;
3417 }
3418 --remaining_id_ct;
3419 while (likely(fread_ptr < fread_end)) {
3420 if ((*fread_ptr++) <= 127) {
3421 if (!remaining_id_ct) {
3422 *fread_pp = fread_ptr;
3423 return kPglRetSuccess;
3424 }
3425 --remaining_id_ct;
3426 }
3427 }
3428 return kPglRetMalformedInput;
3429 }
3430
3431 PglErr CountparseDifflistSubset(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, uint32_t common_geno, uint32_t raw_sample_ct, uint32_t sample_ct, const unsigned char** fread_pp, STD_ARRAY_REF(uint32_t, 4) genocounts, uintptr_t* __restrict raregeno_workspace) {
3432 const unsigned char* group_info_iter;
3433 uint32_t difflist_len;
3434 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, raregeno_workspace, &group_info_iter, &difflist_len);
3435 STD_ARRAY_REF_FILL0(4, genocounts);
3436 if (reterr || (!difflist_len)) {
3437 genocounts[common_geno] = sample_ct;
3438 return reterr;
3439 }
3440 if (raw_sample_ct == sample_ct) {
3441 ZeroTrailingNyps(difflist_len, raregeno_workspace);
3442 GenoarrCountFreqsUnsafe(raregeno_workspace, difflist_len, genocounts);
3443 genocounts[common_geno] = sample_ct - difflist_len;
3444 // bugfix (26 Mar 2019): forgot to advance fread_pp
3445 return SkipDeltalistIds(fread_end, group_info_iter, difflist_len, raw_sample_ct, 1, fread_pp);
3446 }
3447 const uint32_t subgroup_idx_last = (difflist_len - 1) / kBitsPerWordD2;
3448 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(raw_sample_ct);
3449 uintptr_t* raregeno_workspace_iter = raregeno_workspace;
3450 uintptr_t raw_sample_idx = 0;
3451 for (uint32_t subgroup_idx = 0; ; ++subgroup_idx) {
3452 uint32_t remaining_deltas_in_subgroup = kBitsPerWordD2 - 1;
3453 if (subgroup_idx >= subgroup_idx_last) {
3454 if (subgroup_idx > subgroup_idx_last) {
3455 genocounts[common_geno] = sample_ct - genocounts[0] - genocounts[1] - genocounts[2] - genocounts[3];
3456 return kPglRetSuccess;
3457 }
3458 remaining_deltas_in_subgroup &= difflist_len - 1;
3459 }
3460 if (!(subgroup_idx % (kPglDifflistGroupSize / kBitsPerWordD2))) {
3461 #ifdef __LP64__
3462 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
3463 return kPglRetMalformedInput;
3464 }
3465 #endif
3466 raw_sample_idx = SubU32Load(group_info_iter, sample_id_byte_ct);
3467 group_info_iter = &(group_info_iter[sample_id_byte_ct]);
3468 } else {
3469 raw_sample_idx += GetVint31(fread_end, fread_pp);
3470 }
3471 uintptr_t cur_raregeno_word = *raregeno_workspace_iter++;
3472 for (; ; --remaining_deltas_in_subgroup) {
3473 #ifndef __LP64__
3474 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
3475 return kPglRetMalformedInput;
3476 }
3477 #endif
3478 if (IsSet(sample_include, raw_sample_idx)) {
3479 const uintptr_t cur_geno = cur_raregeno_word & 3;
3480 genocounts[cur_geno] += 1;
3481 }
3482 if (!remaining_deltas_in_subgroup) {
3483 break;
3484 }
3485 raw_sample_idx += GetVint31(fread_end, fread_pp);
3486 cur_raregeno_word >>= 2;
3487 }
3488 }
3489 }
3490
3491 // 1-bit, unsubsetted: count 1-bit array, then count raregeno
3492 // 1-bit, subsetted: count [1-bit array AND sample_include], iterate through
3493 // difflist
3494 PglErr CountparseOnebitSubset(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, uint32_t raw_sample_ct, uint32_t sample_ct, const unsigned char** fread_pp, STD_ARRAY_REF(uint32_t, 4) genocounts, uintptr_t* __restrict raregeno_workspace) {
3495 const uint32_t initial_bitarray_byte_ct = DivUp(raw_sample_ct, CHAR_BIT);
3496 const unsigned char* onebit_main_iter = *fread_pp;
3497 if (PtrAddCk(fread_end, initial_bitarray_byte_ct + 1, fread_pp)) {
3498 return kPglRetMalformedInput;
3499 }
3500 const uint32_t common2_code = *onebit_main_iter++;
3501 const uint32_t geno_code_low = common2_code / 4;
3502 const uint32_t geno_code_high = (common2_code & 3) + geno_code_low;
3503 uint32_t high_geno_ct;
3504 if (raw_sample_ct == sample_ct) {
3505 high_geno_ct = PopcountBytes(onebit_main_iter, initial_bitarray_byte_ct);
3506 } else {
3507 high_geno_ct = PopcountBytesMasked(onebit_main_iter, sample_include, initial_bitarray_byte_ct);
3508 }
3509 const unsigned char* group_info_iter;
3510 uint32_t difflist_len;
3511 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, raregeno_workspace, &group_info_iter, &difflist_len);
3512 STD_ARRAY_REF_FILL0(4, genocounts);
3513 if (reterr || (!difflist_len)) {
3514 genocounts[geno_code_low] = sample_ct - high_geno_ct;
3515 genocounts[geno_code_high] = high_geno_ct;
3516 return reterr;
3517 }
3518 if (raw_sample_ct == sample_ct) {
3519 ZeroTrailingNyps(difflist_len, raregeno_workspace);
3520 GenoarrCountFreqsUnsafe(raregeno_workspace, difflist_len, genocounts);
3521 genocounts[geno_code_low] = sample_ct - difflist_len - high_geno_ct;
3522 genocounts[geno_code_high] = high_geno_ct;
3523 // bugfix (26 Mar 2019): forgot to advance fread_pp
3524 return SkipDeltalistIds(fread_end, group_info_iter, difflist_len, raw_sample_ct, 1, fread_pp);
3525 }
3526 const uint32_t subgroup_idx_last = (difflist_len - 1) / kBitsPerWordD2;
3527 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(raw_sample_ct);
3528 uintptr_t* raregeno_workspace_iter = raregeno_workspace;
3529 uintptr_t raw_sample_idx = 0;
3530 for (uint32_t subgroup_idx = 0; ; ++subgroup_idx) {
3531 uint32_t remaining_deltas_in_subgroup = kBitsPerWordD2 - 1;
3532 if (subgroup_idx >= subgroup_idx_last) {
3533 if (subgroup_idx > subgroup_idx_last) {
3534 // avoid read-after-write dependency?
3535 genocounts[geno_code_low] = sample_ct - high_geno_ct - genocounts[0] - genocounts[1] - genocounts[2] - genocounts[3];
3536 genocounts[geno_code_high] = high_geno_ct;
3537 return kPglRetSuccess;
3538 }
3539 remaining_deltas_in_subgroup &= difflist_len - 1;
3540 }
3541 if (!(subgroup_idx % (kPglDifflistGroupSize / kBitsPerWordD2))) {
3542 #ifdef __LP64__
3543 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
3544 return kPglRetMalformedInput;
3545 }
3546 #endif
3547 raw_sample_idx = SubU32Load(group_info_iter, sample_id_byte_ct);
3548 group_info_iter = &(group_info_iter[sample_id_byte_ct]);
3549 } else {
3550 raw_sample_idx += GetVint31(fread_end, fread_pp);
3551 }
3552 uintptr_t cur_raregeno_word = *raregeno_workspace_iter++;
3553 for (; ; --remaining_deltas_in_subgroup) {
3554 #ifndef __LP64__
3555 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
3556 return kPglRetMalformedInput;
3557 }
3558 #endif
3559 if (IsSet(sample_include, raw_sample_idx)) {
3560 const uintptr_t cur_geno = cur_raregeno_word & 3;
3561 genocounts[cur_geno] += 1;
3562 high_geno_ct -= IsSetUnaligned(onebit_main_iter, raw_sample_idx);
3563 }
3564 if (!remaining_deltas_in_subgroup) {
3565 break;
3566 }
3567 raw_sample_idx += GetVint31(fread_end, fread_pp);
3568 cur_raregeno_word >>= 2;
3569 }
3570 }
3571 }
3572
3573 // loads ldbase variant if necessary, guarantees pgrp->ldbase_genovec is filled
3574 // on return
3575 // only called by GetBasicGenotypeCounts(), usually LdLoadAndCopy... is better
3576 PglErr LdLoadGenovecSubsetIfNecessary(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, PgenReaderMain* pgrp) {
3577 if (LdLoadNecessary(vidx, pgrp)) {
3578 const uint32_t ldbase_vidx = pgrp->ldbase_vidx;
3579 const unsigned char* fread_ptr;
3580 const unsigned char* fread_end;
3581 if (unlikely(InitReadPtrs(ldbase_vidx, pgrp, &fread_ptr, &fread_end))) {
3582 return kPglRetReadFail;
3583 }
3584 const uint32_t vrtype = pgrp->fi.vrtypes[ldbase_vidx];
3585 // bugfix (6 Mar 2019): ldbase_raw_genovec is only filled in (!difflist) &&
3586 // subsetting_required case; (!difflist) isn't enough
3587 pgrp->ldbase_stypes = ((vrtype & 4) || (sample_ct == pgrp->fi.raw_sample_ct))? kfPgrLdcacheNyp : (kfPgrLdcacheNyp | kfPgrLdcacheRawNyp);
3588 return ParseNonLdGenovecSubsetUnsafe(fread_end, sample_include, sample_include_cumulative_popcounts, sample_ct, vrtype, &fread_ptr, pgrp, pgrp->ldbase_genovec);
3589 }
3590 if (!(pgrp->ldbase_stypes & kfPgrLdcacheNyp)) {
3591 if (pgrp->ldbase_stypes & kfPgrLdcacheDifflist) {
3592 PgrDifflistToGenovecUnsafe(pgrp->ldbase_raregeno, pgrp->ldbase_difflist_sample_ids, pgrp->fi.vrtypes[pgrp->ldbase_vidx] & 3, sample_ct, pgrp->ldbase_difflist_len, pgrp->ldbase_genovec);
3593 } else {
3594 assert(pgrp->ldbase_stypes & kfPgrLdcacheRawNyp);
3595 CopyNyparrNonemptySubset(pgrp->ldbase_raw_genovec, sample_include, pgrp->fi.raw_sample_ct, sample_ct, pgrp->ldbase_genovec);
3596 }
3597 pgrp->ldbase_stypes |= kfPgrLdcacheNyp;
3598 }
3599 return kPglRetSuccess;
3600 }
3601
3602 PglErr GetBasicGenotypeCounts(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict sample_include_interleaved_vec, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, PgenReaderMain* pgrp, uint32_t* unphased_het_ctp, STD_ARRAY_REF(uint32_t, 4) genocounts) {
3603 // genocounts[0] := ref/ref, genocounts[1] := ref/altx,
3604 // genocounts[2] := altx/alty, genocounts[3] := missing
3605 // If unphased_het_ctp is non-null, this assumes multiallelic hardcalls are
3606 // not present, phased hardcalls are present, we aren't subsetting, and
3607 // unphased_het_ct is initialized to zero.
3608 assert(vidx < pgrp->fi.raw_variant_ct);
3609 assert(sample_ct);
3610 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
3611 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
3612 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
3613 const unsigned char* fread_ptr;
3614 const unsigned char* fread_end = nullptr; // maybe-uninitialized warning
3615 PglErr reterr;
3616 if (VrtypeLdCompressed(vrtype)) {
3617 // LD compression
3618 reterr = LdLoadGenovecSubsetIfNecessary(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp);
3619 if (unlikely(reterr)) {
3620 return reterr;
3621 }
3622 if (unlikely(InitReadPtrs(vidx, pgrp, &fread_ptr, &fread_end))) {
3623 return kPglRetReadFail;
3624 }
3625 if (!(pgrp->ldbase_stypes & kfPgrLdcacheBasicGenocounts)) {
3626 ZeroTrailingNyps(sample_ct, pgrp->ldbase_genovec);
3627 GenoarrCountFreqsUnsafe(pgrp->ldbase_genovec, sample_ct, pgrp->ldbase_basic_genocounts);
3628 assert(pgrp->ldbase_stypes);
3629 pgrp->ldbase_stypes |= kfPgrLdcacheBasicGenocounts;
3630 }
3631 STD_ARRAY_COPY(pgrp->ldbase_basic_genocounts, 4, genocounts);
3632 reterr = LdSubsetAdjustGenocounts(fread_end, subsetting_required? sample_include : nullptr, sample_include_cumulative_popcounts, pgrp->ldbase_genovec, raw_sample_ct, &fread_ptr, genocounts, pgrp->workspace_raregeno_tmp_loadbuf);
3633 if (vrtype & 1) {
3634 // inverted
3635 const uint32_t tmpval = genocounts[0];
3636 genocounts[0] = genocounts[2];
3637 genocounts[2] = tmpval;
3638 }
3639 } else {
3640 if (unlikely(InitReadPtrs(vidx, pgrp, &fread_ptr, &fread_end))) {
3641 return kPglRetReadFail;
3642 }
3643 const uint32_t is_ldbase = pgrp->fi.vrtypes && VrtypeLdCompressed(pgrp->fi.vrtypes[vidx + 1]);
3644 if (is_ldbase) {
3645 // difflists are very efficient to count directly when not subsetting
3646 // (since we can entirely ignore the sample IDs), but it's often better
3647 // to unpack them first when subsetting.
3648
3649 // ...er, the statement above is a lie, unpack-first almost always seems
3650 // to be better.
3651 pgrp->ldbase_vidx = vidx;
3652 // this may be slowed down by the LD caching change.
3653 reterr = ParseNonLdGenovecSubsetUnsafe(fread_end, sample_include, sample_include_cumulative_popcounts, sample_ct, vrtype, &fread_ptr, pgrp, pgrp->ldbase_genovec);
3654 ZeroTrailingNyps(sample_ct, pgrp->ldbase_genovec);
3655 GenoarrCountFreqsUnsafe(pgrp->ldbase_genovec, sample_ct, genocounts);
3656 STD_ARRAY_COPY(genocounts, 4, pgrp->ldbase_basic_genocounts);
3657 pgrp->ldbase_stypes = (subsetting_required && (!(vrtype & 4)))? (kfPgrLdcacheNyp | kfPgrLdcacheRawNyp | kfPgrLdcacheBasicGenocounts) : (kfPgrLdcacheNyp | kfPgrLdcacheBasicGenocounts);
3658 } else if (vrtype & 4) {
3659 const uint32_t vrtype_low2 = vrtype & 3;
3660 if (vrtype_low2 != 1) {
3661 reterr = CountparseDifflistSubset(fread_end, sample_include, vrtype & 3, raw_sample_ct, sample_ct, &fread_ptr, genocounts, pgrp->workspace_raregeno_tmp_loadbuf);
3662 } else {
3663 genocounts[0] = sample_ct;
3664 genocounts[1] = 0;
3665 genocounts[2] = 0;
3666 genocounts[3] = 0;
3667 reterr = kPglRetSuccess;
3668 }
3669 } else if (vrtype & 1) {
3670 reterr = CountparseOnebitSubset(fread_end, sample_include, raw_sample_ct, sample_ct, &fread_ptr, genocounts, pgrp->workspace_raregeno_tmp_loadbuf);
3671 } else {
3672 const uint32_t genovec_byte_ct = NypCtToByteCt(raw_sample_ct);
3673 const unsigned char* genoarrb = fread_ptr;
3674 if (PtrAddCk(fread_end, genovec_byte_ct, &fread_ptr)) {
3675 return kPglRetMalformedInput;
3676 }
3677 if (!subsetting_required) {
3678 const uint32_t genoarrb_is_unaligned = R_CAST(uintptr_t, genoarrb) % kBytesPerVec;
3679 if (genoarrb_is_unaligned) {
3680 GenoarrbCountFreqs(genoarrb, raw_sample_ct, genocounts);
3681 } else {
3682 GenoarrCountFreqs(R_CAST(const uintptr_t*, genoarrb), raw_sample_ct, genocounts);
3683 }
3684 } else {
3685 GenoarrbCountSubsetFreqs(genoarrb, sample_include_interleaved_vec, raw_sample_ct, sample_ct, genocounts);
3686 }
3687 if (vrtype == kPglVrtypePlink1) {
3688 // [3] -> [0]
3689 // [2] -> [1]
3690 // [1] -> [3]
3691 // [0] -> [2]
3692 const uint32_t save2 = genocounts[0];
3693 const uint32_t save3 = genocounts[1];
3694 genocounts[0] = genocounts[3];
3695 genocounts[1] = genocounts[2];
3696 genocounts[2] = save2;
3697 genocounts[3] = save3;
3698 }
3699 reterr = kPglRetSuccess;
3700 }
3701 }
3702 if ((!unphased_het_ctp) || reterr) {
3703 return reterr;
3704 }
3705 assert((!subsetting_required) && ((vrtype & 0x18) == 0x10));
3706 const uint32_t het_ct = genocounts[1];
3707 const uint32_t aux2_first_part_byte_ct = 1 + (het_ct / CHAR_BIT);
3708 if (PtrCheck(fread_end, fread_ptr, aux2_first_part_byte_ct)) {
3709 return kPglRetMalformedInput;
3710 }
3711 const uint32_t explicit_phasepresent = fread_ptr[0] & 1;
3712 if (explicit_phasepresent) {
3713 // otherwise initial value if 0 is correct
3714 *unphased_het_ctp = het_ct + 1 - PopcountBytes(fread_ptr, aux2_first_part_byte_ct);
3715 }
3716 return kPglRetSuccess;
3717 }
3718
3719 PglErr PgrGetCounts(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict sample_include_interleaved_vec, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, STD_ARRAY_REF(uint32_t, 4) genocounts) {
3720 if (!sample_ct) {
3721 STD_ARRAY_REF_FILL0(4, genocounts);
3722 return kPglRetSuccess;
3723 }
3724 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
3725 assert(vidx < pgrp->fi.raw_variant_ct);
3726 return GetBasicGenotypeCounts(sample_include, sample_include_interleaved_vec, GetSicp(pssi), sample_ct, vidx, pgrp, nullptr, genocounts);
3727 }
3728
3729 uint32_t CountNypVec6(const unsigned char* nyp_vvec_biter, uintptr_t nyp_word, uint32_t vec_ct) {
3730 assert(!(vec_ct % 6));
3731 const VecW m0 = vecw_setzero();
3732 const VecW m1 = VCONST_W(kMask5555);
3733 const VecW m2 = VCONST_W(kMask3333);
3734 const VecW m4 = VCONST_W(kMask0F0F);
3735 const VecW xor_vvec = vecw_set1(nyp_word);
3736 VecW prev_sad_result = vecw_setzero();
3737 VecW acc = vecw_setzero();
3738 uintptr_t cur_incr = 60;
3739 for (; ; vec_ct -= cur_incr) {
3740 if (vec_ct < 60) {
3741 if (!vec_ct) {
3742 acc = acc + prev_sad_result;
3743 return HsumW(acc);
3744 }
3745 cur_incr = vec_ct;
3746 }
3747 VecW inner_acc = vecw_setzero();
3748 const unsigned char* nyp_vvec_stop = &(nyp_vvec_biter[cur_incr * kBytesPerVec]);
3749 do {
3750 VecW loader1 = vecw_loadu(nyp_vvec_biter) ^ xor_vvec;
3751 nyp_vvec_biter += kBytesPerVec;
3752 VecW loader2 = vecw_loadu(nyp_vvec_biter) ^ xor_vvec;
3753 nyp_vvec_biter += kBytesPerVec;
3754 VecW count1 = vecw_and_notfirst(vecw_srli(loader1, 1) | loader1, m1);
3755 VecW count2 = vecw_and_notfirst(vecw_srli(loader2, 1) | loader2, m1);
3756
3757 loader1 = vecw_loadu(nyp_vvec_biter) ^ xor_vvec;
3758 nyp_vvec_biter += kBytesPerVec;
3759 loader2 = vecw_loadu(nyp_vvec_biter) ^ xor_vvec;
3760 nyp_vvec_biter += kBytesPerVec;
3761 count1 = count1 + vecw_and_notfirst(vecw_srli(loader1, 1) | loader1, m1);
3762 count2 = count2 + vecw_and_notfirst(vecw_srli(loader2, 1) | loader2, m1);
3763
3764 loader1 = vecw_loadu(nyp_vvec_biter) ^ xor_vvec;
3765 nyp_vvec_biter += kBytesPerVec;
3766 loader2 = vecw_loadu(nyp_vvec_biter) ^ xor_vvec;
3767 nyp_vvec_biter += kBytesPerVec;
3768 count1 = count1 + vecw_and_notfirst(vecw_srli(loader1, 1) | loader1, m1);
3769 count2 = count2 + vecw_and_notfirst(vecw_srli(loader2, 1) | loader2, m1);
3770
3771 count1 = (count1 & m2) + (vecw_srli(count1, 2) & m2);
3772 count1 = count1 + (count2 & m2) + (vecw_srli(count2, 2) & m2);
3773 inner_acc = inner_acc + (count1 & m4) + (vecw_srli(count1, 4) & m4);
3774 } while (nyp_vvec_biter < nyp_vvec_stop);
3775 acc = acc + prev_sad_result;
3776 prev_sad_result = vecw_bytesum(inner_acc, m0);
3777 }
3778 }
3779
3780 // Ok for nyparr to be unaligned. Ok if unsafe to read trailing bytes of
3781 // nyparr.
3782 uint32_t CountNyp(const void* nyparr, uintptr_t nyp_word, uint32_t nyp_ct) {
3783 const unsigned char* nyparr_uc = S_CAST(const unsigned char*, nyparr);
3784 const uint32_t fullword_ct = nyp_ct / kBitsPerWordD2;
3785 uint32_t word_idx = fullword_ct - (fullword_ct % (6 * kWordsPerVec));
3786 uint32_t tot = CountNypVec6(nyparr_uc, nyp_word, word_idx / kWordsPerVec);
3787 for (; word_idx != fullword_ct; ++word_idx) {
3788 uintptr_t cur_word;
3789 CopyFromUnalignedOffsetW(&cur_word, nyparr_uc, word_idx);
3790 tot += Popcount01Word(Word00(cur_word ^ nyp_word));
3791 }
3792 const uint32_t trailing_nyp_ct = nyp_ct % kBitsPerWordD2;
3793 if (trailing_nyp_ct) {
3794 const uint32_t trailing_byte_ct = DivUp(trailing_nyp_ct, (CHAR_BIT / 2));
3795 uintptr_t cur_word = SubwordLoad(&(nyparr_uc[fullword_ct * kBytesPerWord]), trailing_byte_ct) ^ nyp_word;
3796 cur_word = bzhi(Word00(cur_word), trailing_nyp_ct * 2);
3797 tot += Popcount01Word(cur_word);
3798 }
3799 return tot;
3800 }
3801
3802 /*
3803 uint32_t CountNypSubsetVec6(const VecW* __restrict nyp_vvec, const VecW* __restrict interleaved_mask_vvec, uintptr_t nyp_word, uint32_t vec_ct) {
3804 assert(!(vec_ct % 6));
3805 const VecW m0 = vecw_setzero();
3806 const VecW m1 = VCONST_W(kMask5555);
3807 const VecW m2 = VCONST_W(kMask3333);
3808 const VecW m4 = VCONST_W(kMask0F0F);
3809 const VecW xor_vvec = vecw_set1(nyp_word);
3810 const VecW* nyp_vvec_iter = nyp_vvec;
3811 const VecW* interleaved_mask_vvec_iter = interleaved_mask_vvec;
3812 VecW prev_sad_result = vecw_setzero();
3813 VecW acc = vecw_setzero();
3814 uintptr_t cur_incr = 60;
3815 while (1) {
3816 if (vec_ct < 60) {
3817 if (!vec_ct) {
3818 acc = acc + prev_sad_result;
3819 return HsumW(acc);
3820 }
3821 cur_incr = vec_ct;
3822 }
3823 VecW inner_acc = vecw_setzero();
3824 const VecW* nyp_vvec_stop = &(nyp_vvec_iter[cur_incr]);
3825 vec_ct -= cur_incr;
3826 do {
3827 VecW mask1 = *interleaved_mask_vvec_iter++;
3828 VecW loader1 = vecw_loadu(nyp_vvec_iter++) ^ xor_vvec;
3829 VecW mask2 = vecw_srli(mask1, 1) & m1;
3830 VecW loader2 = vecw_loadu(nyp_vvec_iter++) ^ xor_vvec;
3831 mask1 = mask1 & m1;
3832 VecW count1 = vecw_and_notfirst(vecw_srli(loader1, 1) | loader1, mask1);
3833 VecW count2 = vecw_and_notfirst(vecw_srli(loader2, 1) | loader2, mask2);
3834
3835 mask1 = *interleaved_mask_vvec_iter++;
3836 loader1 = vecw_loadu(nyp_vvec_iter++) ^ xor_vvec;
3837 mask2 = vecw_srli(mask1, 1) & m1;
3838 loader2 = vecw_loadu(nyp_vvec_iter++) ^ xor_vvec;
3839 mask1 = mask1 & m1;
3840 count1 = count1 + vecw_and_notfirst(vecw_srli(loader1, 1) | loader1, mask1);
3841 count2 = count2 + vecw_and_notfirst(vecw_srli(loader2, 1) | loader2, mask2);
3842
3843 mask1 = *interleaved_mask_vvec_iter++;
3844 loader1 = vecw_loadu(nyp_vvec_iter++) ^ xor_vvec;
3845 mask2 = vecw_srli(mask2, 1) & m1;
3846 loader2 = vecw_loadu(nyp_vvec_iter++) ^ xor_vvec;
3847 mask1 = mask1 & m1;
3848 count1 = count1 + vecw_and_notfirst(vecw_srli(loader1, 1) | loader1, mask1);
3849 count2 = count2 + vecw_and_notfirst(vecw_srli(loader2, 1) | loader2, mask2);
3850
3851 count1 = (count1 & m2) + (vecw_srli(count1, 2) & m2);
3852 count1 = count1 + (count2 & m2) + (vecw_srli(count2, 2) & m2);
3853 inner_acc = inner_acc + (count1 & m4) + (vecw_srli(count1, 4) & m4);
3854 } while (nyp_vvec_iter < nyp_vvec_stop);
3855 acc = acc + prev_sad_result;
3856 prev_sad_result = vecw_bytesum(inner_acc, m0);
3857 }
3858 }
3859
3860 uint32_t CountNypSubset(const uintptr_t* __restrict nypvec, const uintptr_t* __restrict interleaved_vec, uintptr_t nyp_word, uint32_t raw_nyp_ct) {
3861 // simplified GenoarrCountSubsetFreqs()
3862 const uint32_t raw_nyp_ctv2 = NypCtToVecCt(raw_nyp_ct);
3863 #ifdef __LP64__
3864 uint32_t vec_idx = raw_nyp_ctv2 - (raw_nyp_ctv2 % 6);
3865 uint32_t tot = CountNypSubsetVec6(R_CAST(const VecW*, nypvec), R_CAST(const VecW*, interleaved_vec), nyp_word, vec_idx);
3866 const uintptr_t* nypvec_iter = &(nypvec[kWordsPerVec * vec_idx]);
3867 const uintptr_t* interleaved_mask_iter = &(interleaved_vec[(kWordsPerVec / 2) * vec_idx]);
3868 # ifdef USE_AVX2
3869 uintptr_t mask_base1 = 0;
3870 uintptr_t mask_base2 = 0;
3871 uintptr_t mask_base3 = 0;
3872 uintptr_t mask_base4 = 0;
3873 for (; vec_idx != raw_nyp_ctv2; ++vec_idx) {
3874 uintptr_t mask_word1;
3875 uintptr_t mask_word2;
3876 uintptr_t mask_word3;
3877 uintptr_t mask_word4;
3878 if (!(vec_idx % 2)) {
3879 mask_base1 = *interleaved_mask_iter++;
3880 mask_base2 = *interleaved_mask_iter++;
3881 mask_base3 = *interleaved_mask_iter++;
3882 mask_base4 = *interleaved_mask_iter++;
3883 mask_word1 = mask_base1 & kMask5555;
3884 mask_word2 = mask_base2 & kMask5555;
3885 mask_word3 = mask_base3 & kMask5555;
3886 mask_word4 = mask_base4 & kMask5555;
3887 } else {
3888 mask_word1 = (mask_base1 >> 1) & kMask5555;
3889 mask_word2 = (mask_base2 >> 1) & kMask5555;
3890 mask_word3 = (mask_base3 >> 1) & kMask5555;
3891 mask_word4 = (mask_base4 >> 1) & kMask5555;
3892 }
3893 uint32_t uii = 0;
3894 while (1) {
3895 const uintptr_t cur_geno_word1 = (*nypvec_iter++) ^ nyp_word;
3896 const uintptr_t cur_geno_word2 = (*nypvec_iter++) ^ nyp_word;
3897 const uintptr_t masked1 = mask_word1 & (~(cur_geno_word1 | (cur_geno_word1 >> 1)));
3898 const uintptr_t masked2 = mask_word2 & (~(cur_geno_word2 | (cur_geno_word2 >> 1)));
3899 tot += PopcountWord((masked1 << 1) | masked2);
3900 if (uii) {
3901 break;
3902 }
3903 ++uii;
3904 mask_word1 = mask_word3;
3905 mask_word2 = mask_word4;
3906 }
3907 }
3908 # else // not USE_AVX2
3909 uintptr_t mask_base1 = 0;
3910 uintptr_t mask_base2 = 0;
3911 for (; vec_idx != raw_nyp_ctv2; ++vec_idx) {
3912 uintptr_t mask_word1;
3913 uintptr_t mask_word2;
3914 if (!(vec_idx % 2)) {
3915 mask_base1 = *interleaved_mask_iter++;
3916 mask_base2 = *interleaved_mask_iter++;
3917 mask_word1 = mask_base1 & kMask5555;
3918 mask_word2 = mask_base2 & kMask5555;
3919 } else {
3920 mask_word1 = (mask_base1 >> 1) & kMask5555;
3921 mask_word2 = (mask_base2 >> 1) & kMask5555;
3922 }
3923 const uintptr_t cur_geno_word1 = (*nypvec_iter++) ^ nyp_word;
3924 const uintptr_t cur_geno_word2 = (*nypvec_iter++) ^ nyp_word;
3925 const uintptr_t masked1 = mask_word1 & (~(cur_geno_word1 | (cur_geno_word1 >> 1)));
3926 const uintptr_t masked2 = mask_word2 & (~(cur_geno_word2 | (cur_geno_word2 >> 1)));
3927 # ifdef USE_SSE42
3928 tot += PopcountWord((masked1 << 1) | masked2);
3929 # else
3930 tot += NypsumWord(masked1 + masked2);
3931 # endif
3932 }
3933 # endif // not USE_AVX2
3934 #else // not __LP64__
3935 uint32_t word_idx = raw_nyp_ctv2 - (raw_nyp_ctv2 % 6);
3936 uint32_t tot = CountNypSubsetVec6(R_CAST(const VecW*, nypvec), R_CAST(const VecW*, interleaved_vec), nyp_word, word_idx);
3937 const uintptr_t* interleaved_mask_iter = &(interleaved_vec[word_idx / 2]);
3938 uintptr_t mask_base = 0;
3939 for (; word_idx != raw_nyp_ctv2; ++word_idx) {
3940 uintptr_t mask_word;
3941 if (!(word_idx % 2)) {
3942 mask_base = *interleaved_mask_iter++;
3943 mask_word = mask_base & kMask5555;
3944 } else {
3945 mask_word = (mask_base >> 1) & kMask5555;
3946 }
3947 const uintptr_t cur_geno_word = nypvec[word_idx] ^ nyp_word;
3948 const uintptr_t masked = mask_word & (~(cur_geno_word | (cur_geno_word >> 1)));
3949 tot += Popcount01Word(masked);
3950 }
3951 #endif
3952 return tot;
3953 }
3954 */
3955
3956 // similar to ParseAndSaveDifflist()
3957 PglErr ParseAndSaveDeltalist(const unsigned char* fread_end, uint32_t raw_sample_ct, const unsigned char** fread_pp, uint32_t* __restrict deltalist, uint32_t* __restrict deltalist_len_ptr) {
3958 const unsigned char* group_info_iter;
3959 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, nullptr, &group_info_iter, deltalist_len_ptr);
3960 const uint32_t deltalist_len = *deltalist_len_ptr;
3961 if (reterr || (!deltalist_len)) {
3962 return reterr;
3963 }
3964 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(raw_sample_ct);
3965 const uint32_t group_idx_last = (deltalist_len - 1) / kPglDifflistGroupSize;
3966 uint32_t* deltalist_iter = deltalist;
3967 uint32_t group_len_m1 = kPglDifflistGroupSize - 1;
3968 for (uint32_t group_idx = 0; ; ++group_idx) {
3969 if (group_idx >= group_idx_last) {
3970 if (group_idx > group_idx_last) {
3971 return kPglRetSuccess;
3972 }
3973 group_len_m1 &= deltalist_len - 1;
3974 }
3975 uintptr_t raw_sample_idx = SubU32Load(group_info_iter, sample_id_byte_ct);
3976 group_info_iter = &(group_info_iter[sample_id_byte_ct]);
3977 for (uint32_t raw_deltalist_idx_lowbits = 0; ; ++raw_deltalist_idx_lowbits) {
3978 // always check, otherwise we may scribble over arbitrary memory
3979 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
3980 return kPglRetMalformedInput;
3981 }
3982 deltalist_iter[raw_deltalist_idx_lowbits] = raw_sample_idx;
3983 if (raw_deltalist_idx_lowbits == group_len_m1) {
3984 break;
3985 }
3986 raw_sample_idx += GetVint31(fread_end, fread_pp);
3987 }
3988 deltalist_iter = &(deltalist_iter[group_len_m1 + 1]);
3989 }
3990 }
3991
3992 PglErr CountDeltalistIntersect(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, uint32_t raw_sample_ct, const unsigned char** fread_pp, uint32_t* __restrict intersect_ctp, uint32_t* __restrict raw_deltalist_len_ptr) {
3993 // Requires a PROPER subset.
3994 const unsigned char* group_info_iter;
3995 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, nullptr, &group_info_iter, raw_deltalist_len_ptr);
3996 const uint32_t raw_deltalist_len = *raw_deltalist_len_ptr;
3997 if (reterr || (!raw_deltalist_len)) {
3998 *intersect_ctp = 0;
3999 return reterr;
4000 }
4001 const uint32_t group_idx_last = (raw_deltalist_len - 1) / kPglDifflistGroupSize;
4002 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(raw_sample_ct);
4003 uintptr_t intersect_ct = 0;
4004
4005 // technically doesn't need to be initialized, but I have principles
4006 uintptr_t raw_sample_idx = 0;
4007
4008 uint32_t group_len_m1 = kPglDifflistGroupSize - 1;
4009 for (uint32_t group_idx = 0; ; ++group_idx) {
4010 if (group_idx >= group_idx_last) {
4011 if (group_idx > group_idx_last) {
4012 *intersect_ctp = intersect_ct;
4013 return kPglRetSuccess;
4014 }
4015 group_len_m1 &= raw_deltalist_len - 1;
4016 }
4017 // We need to pull a raw sample index from the deltalist header every 64
4018 // entries.
4019 #ifdef __LP64__
4020 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
4021 return kPglRetMalformedInput;
4022 }
4023 #endif
4024 raw_sample_idx = SubU32Load(group_info_iter, sample_id_byte_ct);
4025 group_info_iter = &(group_info_iter[sample_id_byte_ct]);
4026 for (uint32_t raw_deltalist_idx_lowbits = 0; ; ++raw_deltalist_idx_lowbits) {
4027 #ifndef __LP64__
4028 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
4029 return kPglRetMalformedInput;
4030 }
4031 #endif
4032 intersect_ct += IsSet(sample_include, raw_sample_idx);
4033 if (raw_deltalist_idx_lowbits == group_len_m1) {
4034 break;
4035 }
4036 raw_sample_idx += GetVint31(fread_end, fread_pp);
4037 }
4038 }
4039 }
4040
4041 uint32_t CountAux1aDense(const unsigned char* patch_01_fvals, uint32_t allele_ct, uint32_t allele_idx, uint32_t raw_01_ct, uint32_t rare01_ct) {
4042 // The 'f' in patch_01_fset/patch_01_fvals is to distinguish the in-file
4043 // representation from the returned AlleleCode*-based representation.
4044 if (allele_idx == 1) {
4045 // safe to ignore allele codes
4046 return raw_01_ct - rare01_ct;
4047 }
4048 if (allele_ct < 5) {
4049 if (allele_ct == 3) {
4050 return rare01_ct;
4051 }
4052 // need to count matches
4053 const uint32_t allele_code_byte_ct = DivUp(rare01_ct, 8);
4054 const uint32_t alt3_ct = PopcountBytes(patch_01_fvals, allele_code_byte_ct);
4055 if (allele_idx == 3) {
4056 return alt3_ct;
4057 }
4058 return rare01_ct - alt3_ct;
4059 }
4060 if (allele_ct < 19) {
4061 if (allele_ct < 7) {
4062 return CountNyp(patch_01_fvals, (allele_idx - 2) * kMask5555, rare01_ct);
4063 }
4064 return CountNybble(patch_01_fvals, (allele_idx - 2) * kMask1111, rare01_ct);
4065 }
4066 return CountByte(patch_01_fvals, allele_idx - 2, rare01_ct);
4067 }
4068
4069 uint32_t GetAux1aWidth(uint32_t allele_ct) {
4070 if (allele_ct < 7) {
4071 if (allele_ct < 5) {
4072 return allele_ct - 3;
4073 }
4074 return 2;
4075 }
4076 if (allele_ct < 19) {
4077 return 4;
4078 }
4079 return 8;
4080 }
4081
4082 // Returns allele_code_width. Other return values are inaccurate for allele_ct
4083 // == 3, since it's assumed that they're unused in that case.
4084 uint32_t GetAux1aConsts(uint32_t allele_ct, uintptr_t* detect_mask_hi_ptr, uintptr_t* detect_mask_lo_ptr, uint32_t* allele_code_logwidth_ptr) {
4085 if (allele_ct < 7) {
4086 if (allele_ct < 5) {
4087 *detect_mask_hi_ptr = ~k0LU;
4088 *detect_mask_lo_ptr = ~k0LU;
4089 *allele_code_logwidth_ptr = 0;
4090 return allele_ct - 3;
4091 }
4092 *detect_mask_hi_ptr = kMaskAAAA;
4093 *detect_mask_lo_ptr = kMask5555;
4094 *allele_code_logwidth_ptr = 1;
4095 return 2;
4096 }
4097 if (allele_ct < 19) {
4098 *detect_mask_hi_ptr = kMask1111 * 8;
4099 *detect_mask_lo_ptr = kMask1111;
4100 *allele_code_logwidth_ptr = 2;
4101 return 4;
4102 }
4103 *detect_mask_hi_ptr = kMask0101 * 0x80;
4104 *detect_mask_lo_ptr = kMask0101;
4105 *allele_code_logwidth_ptr = 3;
4106 return 8;
4107 }
4108
4109 // Advances *fread_pp past aux1a, and sets *het_ctp to the number of ref-altx
4110 // hets where x == allele_idx in sample_include. (If allele_idx == 1, *het_ctp
4111 // is raw_01_ct - [# of aux1a entries] when there's no subsetting.)
4112 // Note that raw_01_ct must be an un-subsetted count.
4113 // Ok for subsetted_01_ct to be uninitialized if not subsetting, or allele_idx
4114 // != 1.
4115 // sample_include assumed to be nullptr if no subsetting required
4116 PglErr CountAux1a(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uintptr_t* __restrict raw_genoarr, uint32_t aux1a_mode, uint32_t raw_sample_ct, uint32_t allele_ct, uint32_t allele_idx, uint32_t raw_01_ct, uint32_t subsetted_01_ct, const unsigned char** fread_pp, uint32_t* __restrict het_ctp, uint32_t* __restrict deltalist_workspace) {
4117 if (aux1a_mode == 15) {
4118 if (allele_idx == 1) {
4119 if (sample_include) {
4120 *het_ctp = subsetted_01_ct;
4121 } else {
4122 *het_ctp = raw_01_ct;
4123 }
4124 } else {
4125 *het_ctp = 0;
4126 }
4127 return kPglRetSuccess;
4128 }
4129 const uint32_t ignore_01_fvals = (allele_idx == 1) || (allele_ct == 3);
4130 uintptr_t detect_mask_hi;
4131 uintptr_t detect_mask_lo;
4132 uint32_t allele_code_logwidth;
4133 const uint32_t allele_code_width = GetAux1aConsts(allele_ct, &detect_mask_hi, &detect_mask_lo, &allele_code_logwidth);
4134 const uintptr_t xor_word = (allele_idx - 2) * detect_mask_lo;
4135 if (!aux1a_mode) {
4136 // 01-collapsed bitarray
4137 const uint32_t fset_byte_ct = DivUp(raw_01_ct, CHAR_BIT);
4138 const uint32_t rare01_ct = PopcountBytes(*fread_pp, fset_byte_ct);
4139 const unsigned char* patch_01_fset = *fread_pp;
4140 *fread_pp += fset_byte_ct;
4141 const unsigned char* patch_01_fvals = *fread_pp;
4142 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare01_ct) * allele_code_width, 8);
4143 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
4144 return kPglRetMalformedInput;
4145 }
4146 if (!sample_include) {
4147 *het_ctp = CountAux1aDense(patch_01_fvals, allele_ct, allele_idx, raw_01_ct, rare01_ct);
4148 return kPglRetSuccess;
4149 }
4150 const Halfword* sample_include_hw = DowncastKWToHW(sample_include);
4151 uintptr_t sample_hwidx = 0;
4152 uintptr_t cur_raw_genoarr_hets = Word01(raw_genoarr[0]);
4153 const uint32_t fset_word_ct_m1 = (fset_byte_ct - 1) / kBytesPerWord;
4154 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
4155 uintptr_t fvals_bits = 0;
4156 uint32_t fvals_widx = 0;
4157 uint32_t subsetted_hetx_ct = 0;
4158 uint32_t loop_len = kBitsPerWord;
4159 uint32_t rare01_lowbits = kBitsPerWord;
4160 for (uint32_t fset_widx = 0; ; ++fset_widx) {
4161 uintptr_t fset_bits;
4162 if (fset_widx >= fset_word_ct_m1) {
4163 if (fset_widx > fset_word_ct_m1) {
4164 break;
4165 }
4166 fset_bits = SubwordLoad(&(patch_01_fset[fset_word_ct_m1 * kBytesPerWord]), ModNz(fset_byte_ct, kBytesPerWord));
4167 loop_len = ModNz(raw_01_ct, kBitsPerWord);
4168 } else {
4169 CopyFromUnalignedOffsetW(&fset_bits, patch_01_fset, fset_widx);
4170 }
4171 // format 0, sample_include non-null
4172 if (ignore_01_fvals) {
4173 for (uint32_t uii = 0; uii != loop_len; ++uii) {
4174 while (!cur_raw_genoarr_hets) {
4175 cur_raw_genoarr_hets = Word01(raw_genoarr[++sample_hwidx]);
4176 }
4177 if (fset_bits & 1) {
4178 // Considered replacing cur_raw_genoarr_hets with the result of
4179 // two PackWordToHalfword() operations, since that keeps all
4180 // the sample word-indexes aligned. Couldn't justify it given
4181 // the expected sparsity of this case, though.
4182 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_hets) / 2;
4183 subsetted_hetx_ct += (sample_include_hw[sample_hwidx] >> sample_uidx_lowbits) & 1;
4184 }
4185 cur_raw_genoarr_hets &= cur_raw_genoarr_hets - 1;
4186 fset_bits = fset_bits >> 1;
4187 }
4188 } else {
4189 for (uint32_t uii = 0; uii != loop_len; ++uii) {
4190 while (!cur_raw_genoarr_hets) {
4191 cur_raw_genoarr_hets = Word01(raw_genoarr[++sample_hwidx]);
4192 }
4193 if (fset_bits & 1) {
4194 if (rare01_lowbits == kBitsPerWord) {
4195 if (fvals_widx == fvals_word_ct_m1) {
4196 fvals_bits = SubwordLoad(&(patch_01_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
4197 } else {
4198 CopyFromUnalignedOffsetW(&fvals_bits, patch_01_fvals, fvals_widx);
4199 }
4200 fvals_bits = fvals_bits ^ xor_word;
4201 fvals_bits = (detect_mask_hi & (~(fvals_bits | ((fvals_bits | detect_mask_hi) - detect_mask_lo)))) >> (allele_code_width - 1);
4202 // unnecessary to apply bzhi here
4203 ++fvals_widx;
4204 rare01_lowbits = 0;
4205 }
4206 if (fvals_bits & (k1LU << rare01_lowbits)) {
4207 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_hets) / 2;
4208 subsetted_hetx_ct += (sample_include_hw[sample_hwidx] >> sample_uidx_lowbits) & 1;
4209 }
4210 rare01_lowbits += allele_code_width;
4211 }
4212 cur_raw_genoarr_hets &= cur_raw_genoarr_hets - 1;
4213 fset_bits = fset_bits >> 1;
4214 }
4215 }
4216 }
4217 if (allele_idx == 1) {
4218 *het_ctp = subsetted_01_ct - subsetted_hetx_ct;
4219 } else {
4220 *het_ctp = subsetted_hetx_ct;
4221 }
4222 return kPglRetSuccess;
4223 }
4224 // mode 1: difflist.
4225 if (!sample_include) {
4226 const unsigned char* group_info_iter;
4227 uint32_t rare01_ct;
4228 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, nullptr, &group_info_iter, &rare01_ct);
4229 // rare01_ct == 0 should be impossible
4230 if (unlikely(reterr)) {
4231 return reterr;
4232 }
4233 reterr = SkipDeltalistIds(fread_end, group_info_iter, rare01_ct, raw_sample_ct, 1, fread_pp);
4234 if (unlikely(reterr)) {
4235 return reterr;
4236 }
4237 const unsigned char* patch_01_fvals = *fread_pp;
4238 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare01_ct) * allele_code_width, 8);
4239 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
4240 return kPglRetMalformedInput;
4241 }
4242
4243 *het_ctp = CountAux1aDense(patch_01_fvals, allele_ct, allele_idx, raw_01_ct, rare01_ct);
4244 return kPglRetSuccess;
4245 }
4246 if (ignore_01_fvals) {
4247 // Don't need to save deltalist contents in this case.
4248 uint32_t subsetted_hetx_ct;
4249 uint32_t rare01_ct;
4250 PglErr reterr = CountDeltalistIntersect(fread_end, sample_include, raw_sample_ct, fread_pp, &subsetted_hetx_ct, &rare01_ct);
4251 if (unlikely(reterr)) {
4252 return reterr;
4253 }
4254 if (allele_idx == 1) {
4255 *het_ctp = subsetted_01_ct - subsetted_hetx_ct;
4256 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare01_ct) * allele_code_width, 8);
4257 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
4258 return kPglRetMalformedInput;
4259 }
4260 } else {
4261 *het_ctp = subsetted_hetx_ct;
4262 }
4263 return kPglRetSuccess;
4264 }
4265 // Save deltalist elements, iterate.
4266 uint32_t rare01_ct;
4267 PglErr reterr = ParseAndSaveDeltalist(fread_end, raw_sample_ct, fread_pp, deltalist_workspace, &rare01_ct);
4268 if (unlikely(reterr)) {
4269 return reterr;
4270 }
4271 const unsigned char* patch_01_fvals = *fread_pp;
4272 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare01_ct) * allele_code_width, 8);
4273 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
4274 return kPglRetMalformedInput;
4275 }
4276 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
4277 uint32_t subsetted_hetx_ct = 0;
4278 for (uint32_t fvals_widx = 0; ; ++fvals_widx) {
4279 uintptr_t fvals_bits;
4280 if (fvals_widx >= fvals_word_ct_m1) {
4281 if (fvals_widx > fvals_word_ct_m1) {
4282 break;
4283 }
4284 fvals_bits = SubwordLoad(&(patch_01_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
4285 } else {
4286 CopyFromUnalignedOffsetW(&fvals_bits, patch_01_fvals, fvals_widx);
4287 }
4288 fvals_bits = fvals_bits ^ xor_word;
4289 fvals_bits = detect_mask_hi & (~(fvals_bits | ((fvals_bits | detect_mask_hi) - detect_mask_lo)));
4290 if (fvals_widx == fvals_word_ct_m1) {
4291 fvals_bits = bzhi_max(fvals_bits, ModNz(rare01_ct << allele_code_logwidth, kBitsPerWord));
4292 }
4293 if (!fvals_bits) {
4294 continue;
4295 }
4296 const uint32_t* cur_deltalist_base = &(deltalist_workspace[fvals_widx << (kBitsPerWordLog2 - allele_code_logwidth)]);
4297 do {
4298 const uint32_t rare01_idx_lowbits = ctzw(fvals_bits) >> allele_code_logwidth;
4299 const uint32_t sample_uidx = cur_deltalist_base[rare01_idx_lowbits];
4300 subsetted_hetx_ct += IsSet(sample_include, sample_uidx);
4301 fvals_bits &= fvals_bits - 1;
4302 } while (fvals_bits);
4303 }
4304 *het_ctp = subsetted_hetx_ct;
4305 return kPglRetSuccess;
4306 }
4307
4308 void CountAux1bDense(const unsigned char* patch_10_fvals, uint32_t allele_ct, uint32_t allele_idx_m1, uint32_t raw_10_ct, uint32_t rare10_ct, uint32_t* __restrict het_ctp, uint32_t* __restrict hom_ctp) {
4309 uint32_t matching_hom_ct = 0;
4310 uint32_t het_incr;
4311 if (allele_ct < 6) {
4312 if (allele_ct == 3) {
4313 const uint32_t allele_code_byte_ct = DivUp(rare10_ct, 8);
4314 matching_hom_ct = PopcountBytes(patch_10_fvals, allele_code_byte_ct);
4315 het_incr = rare10_ct - matching_hom_ct;
4316 } else {
4317 // 2+2 bits
4318 het_incr = CountNyp(patch_10_fvals, allele_idx_m1 * kMask5555, rare10_ct * 2);
4319 if (allele_idx_m1) {
4320 matching_hom_ct = CountNybble(patch_10_fvals, allele_idx_m1 * kMask5555, rare10_ct);
4321 }
4322 }
4323 } else {
4324 if (allele_ct < 18) {
4325 // 4+4 bits
4326 het_incr = CountNybble(patch_10_fvals, allele_idx_m1 * kMask1111, rare10_ct * 2);
4327 if (allele_idx_m1) {
4328 matching_hom_ct = CountByte(patch_10_fvals, allele_idx_m1 * 0x11, rare10_ct);
4329 }
4330 } else {
4331 // 8+8 bits
4332 het_incr = CountByte(patch_10_fvals, allele_idx_m1 * 0x11, rare10_ct * 2);
4333 if (allele_idx_m1) {
4334 matching_hom_ct = CountU16(patch_10_fvals, allele_idx_m1 * 0x1111, rare10_ct);
4335 }
4336 }
4337 }
4338 if (!allele_idx_m1) {
4339 *hom_ctp = raw_10_ct - rare10_ct;
4340 } else {
4341 het_incr -= 2 * matching_hom_ct;
4342 *hom_ctp = matching_hom_ct;
4343 }
4344 *het_ctp += het_incr;
4345 }
4346
4347 // Returns allele_code_logwidth.
4348 uint32_t GetAux1bConsts(uint32_t allele_ct, uintptr_t* detect_hom_mask_lo_ptr) {
4349 if (allele_ct < 6) {
4350 if (allele_ct == 3) {
4351 *detect_hom_mask_lo_ptr = ~k0LU;
4352 return 0;
4353 }
4354 *detect_hom_mask_lo_ptr = kMask1111;
4355 return 1;
4356 }
4357 if (allele_ct < 18) {
4358 *detect_hom_mask_lo_ptr = kMask0101;
4359 return 2;
4360 }
4361 *detect_hom_mask_lo_ptr = kMask0001;
4362 return 3;
4363 }
4364
4365 // Advances *fread_pp past aux1b; increments *het_ctp by the number of
4366 // altx-alty genotypes in aux1b and sample_include with one allele ==
4367 // allele_idx; and sets *hom_ctp to the number of such hom-allele_idx genotypes
4368 // present. (For allele_idx == 1, *hom_ctp is equal to raw_10_ct -
4369 // <# of aux1b entries> when there's no subsetting.)
4370 // Trailing bits of raw_genoarr must be cleared.
4371 // Ok for subsetted_10_ct to be uninitialized if not subsetting, or allele_idx
4372 // != 1.
4373 // sample_include assumed to be nullptr if no subsetting required
4374 PglErr CountAux1b(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uintptr_t* __restrict raw_genoarr, uint32_t aux1b_mode, uint32_t raw_sample_ct, uint32_t allele_ct, uint32_t allele_idx, uint32_t raw_10_ct, uint32_t subsetted_10_ct, const unsigned char** fread_pp, uint32_t* __restrict het_ctp, uint32_t* __restrict hom_ctp, uint32_t* __restrict deltalist_workspace) {
4375 if (aux1b_mode == 15) {
4376 if (allele_idx == 1) {
4377 if (sample_include) {
4378 *hom_ctp = subsetted_10_ct;
4379 } else {
4380 *hom_ctp = raw_10_ct;
4381 }
4382 } else {
4383 *hom_ctp = 0;
4384 }
4385 return kPglRetSuccess;
4386 }
4387 uintptr_t detect_hom_mask_lo;
4388 const uint32_t allele_code_logwidth = GetAux1bConsts(allele_ct, &detect_hom_mask_lo);
4389 const uint32_t allele_code_width = 1U << allele_code_logwidth;
4390 const uint32_t code10_logwidth = allele_code_logwidth + (allele_code_logwidth != 0);
4391 const uint32_t code10_width = 1U << code10_logwidth;
4392 const uint32_t allele_idx_m1 = allele_idx - 1;
4393 uint32_t rare10_lowbits = kBitsPerWord;
4394 if (!aux1b_mode) {
4395 // 10-collapsed bitarray
4396 const uint32_t fset_byte_ct = DivUp(raw_10_ct, CHAR_BIT);
4397 const uint32_t rare10_ct = PopcountBytes(*fread_pp, fset_byte_ct);
4398 const unsigned char* patch_10_fset = *fread_pp;
4399 *fread_pp += fset_byte_ct;
4400 const unsigned char* patch_10_fvals = *fread_pp;
4401 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare10_ct) * code10_width, 8);
4402 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
4403 return kPglRetMalformedInput;
4404 }
4405 if (!sample_include) {
4406 CountAux1bDense(patch_10_fvals, allele_ct, allele_idx_m1, raw_10_ct, rare10_ct, het_ctp, hom_ctp);
4407 return kPglRetSuccess;
4408 }
4409 const Halfword* sample_include_hw = DowncastKWToHW(sample_include);
4410 uintptr_t sample_hwidx = 0;
4411 uintptr_t cur_raw_genoarr_xys = Word10(raw_genoarr[0]);
4412 const uint32_t fset_word_ct_m1 = (fset_byte_ct - 1) / kBytesPerWord;
4413 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
4414 uintptr_t fvals_bits = 0;
4415 uint32_t fvals_widx = 0;
4416 uint32_t loop_len = kBitsPerWord;
4417 if ((!allele_idx_m1) || (allele_ct == 3)) {
4418 // bugfix (29 Dec 2019)
4419 const uintptr_t detect_alt1_mask_hi = detect_hom_mask_lo << (allele_code_width - 1);
4420 uint32_t subsetted_rare10_ct = 0;
4421 uint32_t het_1x_ct = 0;
4422 for (uint32_t fset_widx = 0; ; ++fset_widx) {
4423 uintptr_t fset_bits;
4424 if (fset_widx >= fset_word_ct_m1) {
4425 if (fset_widx > fset_word_ct_m1) {
4426 break;
4427 }
4428 fset_bits = SubwordLoad(&(patch_10_fset[fset_word_ct_m1 * kBytesPerWord]), ModNz(fset_byte_ct, kBytesPerWord));
4429 loop_len = ModNz(raw_10_ct, kBitsPerWord);
4430 } else {
4431 CopyFromUnalignedOffsetW(&fset_bits, patch_10_fset, fset_widx);
4432 }
4433 for (uint32_t uii = 0; uii != loop_len; ++uii) {
4434 while (!cur_raw_genoarr_xys) {
4435 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
4436 }
4437 if (fset_bits & 1) {
4438 if (rare10_lowbits == kBitsPerWord) {
4439 if (fvals_widx == fvals_word_ct_m1) {
4440 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
4441 } else {
4442 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
4443 }
4444 // This sets each fvals_bits entry to 1 iff the patch genotype is
4445 // ALT1-ALTx, i.e. the original low bits were zero.
4446 fvals_bits = (detect_alt1_mask_hi & (~(fvals_bits | ((fvals_bits | detect_alt1_mask_hi) - detect_hom_mask_lo)))) >> (allele_code_width - 1);
4447 // unnecessary to apply bzhi here
4448 ++fvals_widx;
4449 rare10_lowbits = 0;
4450 }
4451 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_xys) / 2;
4452 if (sample_include_hw[sample_hwidx] & (1U << sample_uidx_lowbits)) {
4453 ++subsetted_rare10_ct;
4454 het_1x_ct += (fvals_bits >> rare10_lowbits) & 1;
4455 }
4456 rare10_lowbits += code10_width;
4457 }
4458 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
4459 fset_bits = fset_bits >> 1;
4460 }
4461 }
4462 if (allele_ct == 3) {
4463 if (allele_idx_m1) {
4464 *hom_ctp = subsetted_rare10_ct - het_1x_ct;
4465 *het_ctp += het_1x_ct;
4466 return kPglRetSuccess;
4467 }
4468 }
4469 *hom_ctp = subsetted_10_ct - subsetted_rare10_ct;
4470 *het_ctp += het_1x_ct;
4471 return kPglRetSuccess;
4472 }
4473 // allele_idx > 1, allele_ct > 3
4474 const uintptr_t detect_all_mask_lo = detect_hom_mask_lo | (detect_hom_mask_lo << allele_code_width);
4475 const uintptr_t detect_all_mask_hi = detect_all_mask_lo << (allele_code_width - 1);
4476 const uintptr_t xor_word = allele_idx_m1 * detect_all_mask_lo;
4477 uint32_t matching_allele_ct = 0; // 2x hom + 1x het
4478 uint32_t matching_het_or_hom_ct = 0;
4479 for (uint32_t fset_widx = 0; ; ++fset_widx) {
4480 uintptr_t fset_bits;
4481 if (fset_widx >= fset_word_ct_m1) {
4482 if (fset_widx > fset_word_ct_m1) {
4483 break;
4484 }
4485 fset_bits = SubwordLoad(&(patch_10_fset[fset_word_ct_m1 * kBytesPerWord]), ModNz(fset_byte_ct, kBytesPerWord));
4486 loop_len = ModNz(raw_10_ct, kBitsPerWord);
4487 } else {
4488 CopyFromUnalignedOffsetW(&fset_bits, patch_10_fset, fset_widx);
4489 }
4490 for (uint32_t uii = 0; uii != loop_len; ++uii) {
4491 while (!cur_raw_genoarr_xys) {
4492 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
4493 }
4494 if (fset_bits & 1) {
4495 if (rare10_lowbits == kBitsPerWord) {
4496 if (fvals_widx == fvals_word_ct_m1) {
4497 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
4498 } else {
4499 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
4500 }
4501 fvals_bits ^= xor_word;
4502 fvals_bits = (detect_all_mask_hi & (~(fvals_bits | ((fvals_bits | detect_all_mask_hi) - detect_all_mask_lo)))) >> (allele_code_width - 1);
4503 // unnecessary to apply bzhi or detect_hom_mask_lo here
4504 fvals_bits = fvals_bits + (fvals_bits >> allele_code_width);
4505 ++fvals_widx;
4506 rare10_lowbits = 0;
4507 }
4508 const uintptr_t cur_hit_ct = (fvals_bits >> rare10_lowbits) & 3;
4509 rare10_lowbits += code10_width;
4510 if (cur_hit_ct) {
4511 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_xys) / 2;
4512 if (sample_include_hw[sample_hwidx] & (1U << sample_uidx_lowbits)) {
4513 ++matching_het_or_hom_ct;
4514 matching_allele_ct += cur_hit_ct;
4515 }
4516 }
4517 }
4518 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
4519 fset_bits = fset_bits >> 1;
4520 }
4521 }
4522 const uint32_t matching_hom_ct = matching_allele_ct - matching_het_or_hom_ct;
4523 *hom_ctp = matching_hom_ct;
4524 *het_ctp += matching_het_or_hom_ct - matching_hom_ct;
4525 return kPglRetSuccess;
4526 }
4527 // mode 1: difflist.
4528 if (!sample_include) {
4529 const unsigned char* group_info_iter;
4530 uint32_t rare10_ct;
4531 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, nullptr, &group_info_iter, &rare10_ct);
4532 // rare10_ct == 0 should be impossible
4533 if (unlikely(reterr)) {
4534 return reterr;
4535 }
4536 reterr = SkipDeltalistIds(fread_end, group_info_iter, rare10_ct, raw_sample_ct, 0, fread_pp);
4537 if (unlikely(reterr)) {
4538 return reterr;
4539 }
4540 const unsigned char* patch_10_fvals = *fread_pp;
4541 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare10_ct) << code10_logwidth, CHAR_BIT);
4542 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
4543 return kPglRetMalformedInput;
4544 }
4545 CountAux1bDense(patch_10_fvals, allele_ct, allele_idx_m1, raw_10_ct, rare10_ct, het_ctp, hom_ctp);
4546 return kPglRetSuccess;
4547 }
4548 // Save deltalist elements, iterate.
4549 uint32_t rare10_ct;
4550 PglErr reterr = ParseAndSaveDeltalist(fread_end, raw_sample_ct, fread_pp, deltalist_workspace, &rare10_ct);
4551 if (unlikely(reterr)) {
4552 return reterr;
4553 }
4554 const unsigned char* patch_10_fvals = *fread_pp;
4555 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare10_ct) << code10_logwidth, CHAR_BIT);
4556 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
4557 return kPglRetMalformedInput;
4558 }
4559 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
4560 if ((!allele_idx_m1) || (allele_ct == 3)) {
4561 const uintptr_t detect_alt1_mask_hi = detect_hom_mask_lo << (allele_code_width - 1);
4562 uint32_t subsetted_rare10_ct = 0;
4563 uint32_t het_1x_ct = 0;
4564 uint32_t loop_len = kBitsPerWord >> code10_logwidth;
4565 for (uint32_t fvals_widx = 0; ; ++fvals_widx) {
4566 uintptr_t fvals_bits;
4567 if (fvals_widx >= fvals_word_ct_m1) {
4568 if (fvals_widx > fvals_word_ct_m1) {
4569 break;
4570 }
4571 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
4572 loop_len = 1 + ((rare10_ct - 1) & ((kBitsPerWord >> code10_logwidth) - 1));
4573 } else {
4574 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
4575 }
4576 fvals_bits = (detect_alt1_mask_hi & (~(fvals_bits | ((fvals_bits | detect_alt1_mask_hi) - detect_hom_mask_lo)))) >> (allele_code_width - 1);
4577 const uint32_t* cur_deltalist_base = &(deltalist_workspace[fvals_widx << (kBitsPerWordLog2 - code10_logwidth)]);
4578 for (uint32_t uii = 0; uii != loop_len; ++uii) {
4579 const uint32_t sample_uidx = cur_deltalist_base[uii];
4580 if (IsSet(sample_include, sample_uidx)) {
4581 ++subsetted_rare10_ct;
4582 het_1x_ct += (fvals_bits >> (uii << code10_logwidth)) & 1;
4583 }
4584 }
4585 }
4586 if (allele_ct == 3) {
4587 if (allele_idx_m1) {
4588 *hom_ctp = subsetted_rare10_ct - het_1x_ct;
4589 *het_ctp += het_1x_ct;
4590 return kPglRetSuccess;
4591 }
4592 }
4593 *hom_ctp = subsetted_10_ct - subsetted_rare10_ct;
4594 *het_ctp += het_1x_ct;
4595 return kPglRetSuccess;
4596 }
4597 // allele_idx > 1, allele_ct > 3
4598 const uintptr_t detect_all_mask_lo = detect_hom_mask_lo | (detect_hom_mask_lo << allele_code_width);
4599 const uintptr_t detect_all_mask_hi = detect_all_mask_lo << (allele_code_width - 1);
4600 detect_hom_mask_lo = detect_hom_mask_lo * 3;
4601 const uintptr_t xor_word = allele_idx_m1 * detect_all_mask_lo;
4602 uint32_t matching_het_or_hom_ct = 0;
4603 uint32_t matching_hom_ct = 0;
4604 for (uint32_t fvals_widx = 0; ; ++fvals_widx) {
4605 uintptr_t fvals_bits;
4606 if (fvals_widx >= fvals_word_ct_m1) {
4607 if (fvals_widx > fvals_word_ct_m1) {
4608 break;
4609 }
4610 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
4611 } else {
4612 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
4613 }
4614 fvals_bits = fvals_bits ^ xor_word;
4615 fvals_bits = detect_all_mask_hi & (~(fvals_bits | ((fvals_bits | detect_all_mask_hi) - detect_all_mask_lo)));
4616 if (fvals_widx == fvals_word_ct_m1) {
4617 fvals_bits = bzhi_max(fvals_bits, ModNz(rare10_ct << code10_logwidth, kBitsPerWord));
4618 }
4619 if (!fvals_bits) {
4620 continue;
4621 }
4622 fvals_bits = fvals_bits >> (allele_code_width - 1);
4623 fvals_bits = (fvals_bits + (fvals_bits >> allele_code_width)) & detect_hom_mask_lo;
4624 const uint32_t* cur_deltalist_base = &(deltalist_workspace[fvals_widx << (kBitsPerWordLog2 - code10_logwidth)]);
4625 do {
4626 const uint32_t bit_idx = ctzw(fvals_bits);
4627 const uint32_t sample_uidx = cur_deltalist_base[bit_idx >> code10_logwidth];
4628 if (IsSet(sample_include, sample_uidx)) {
4629 ++matching_het_or_hom_ct;
4630 matching_hom_ct += bit_idx & 1;
4631 }
4632 fvals_bits &= fvals_bits - 1;
4633 } while (fvals_bits);
4634 }
4635 *hom_ctp = matching_hom_ct;
4636 *het_ctp += matching_het_or_hom_ct - matching_hom_ct;
4637 return kPglRetSuccess;
4638 }
4639
4640 PglErr PgrGetInv1Counts(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict sample_include_interleaved_vec, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReader* pgr_ptr, STD_ARRAY_REF(uint32_t, 4) genocounts) {
4641 // May use workspace_vec and workspace_difflist_sample_ids.
4642 if (!sample_ct) {
4643 STD_ARRAY_REF_FILL0(4, genocounts);
4644 return kPglRetSuccess;
4645 }
4646 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
4647 const uint32_t* sample_include_cumulative_popcounts = GetSicp(pssi);
4648 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
4649 PglErr reterr;
4650 if ((!allele_idx) || (!allele_idx_offsets)) {
4651 PgrGetInv1Counts_biallelic:
4652 reterr = GetBasicGenotypeCounts(sample_include, sample_include_interleaved_vec, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, nullptr, genocounts);
4653 if (allele_idx) {
4654 const uint32_t homref_ct = genocounts[0];
4655 genocounts[0] = genocounts[2];
4656 genocounts[2] = homref_ct;
4657 }
4658 return reterr;
4659 }
4660 const uint32_t allele_ct = allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx];
4661 if (allele_ct == 2) {
4662 goto PgrGetInv1Counts_biallelic;
4663 }
4664 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
4665 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
4666 uintptr_t* tmp_genovec = pgrp->workspace_vec;
4667 const unsigned char* fread_ptr;
4668 const unsigned char* fread_end;
4669 reterr = ReadRawGenovec(subsetting_required, vidx, pgrp, &fread_ptr, &fread_end, tmp_genovec);
4670 if (unlikely(reterr)) {
4671 return reterr;
4672 }
4673 ZeroTrailingNyps(raw_sample_ct, tmp_genovec);
4674 const uint32_t aux1_first_byte = *fread_ptr++;
4675 const uint32_t aux1a_mode = aux1_first_byte & 15;
4676 const uint32_t aux1b_mode = aux1_first_byte >> 4;
4677 // raw_01_ct not needed when aux1a uses difflist form and subsetting is
4678 // occurring; same applies to raw_10_ct.
4679 uint32_t raw_01_ct = 0;
4680 uint32_t raw_10_ct = 0;
4681 if ((!subsetting_required) || (!aux1a_mode) || (!aux1b_mode)) {
4682 GenoarrCountFreqsUnsafe(tmp_genovec, raw_sample_ct, genocounts);
4683 raw_01_ct = genocounts[1];
4684 raw_10_ct = genocounts[2];
4685 }
4686 uint32_t subsetted_01_ct = 0;
4687 uint32_t subsetted_10_ct = 0;
4688 if (subsetting_required) {
4689 // need accurate subsetted missing count for allele_idx > 1 case
4690 GenoarrCountSubsetFreqs(tmp_genovec, sample_include_interleaved_vec, raw_sample_ct, sample_ct, genocounts);
4691 subsetted_01_ct = genocounts[1];
4692 subsetted_10_ct = genocounts[2];
4693 } else {
4694 sample_include = nullptr;
4695 }
4696 uint32_t het_ct;
4697 reterr = CountAux1a(fread_end, sample_include, tmp_genovec, aux1a_mode, raw_sample_ct, allele_ct, allele_idx, raw_01_ct, subsetted_01_ct, &fread_ptr, &het_ct, pgrp->workspace_difflist_sample_ids);
4698 if (unlikely(reterr)) {
4699 return reterr;
4700 }
4701 uint32_t hom_ct;
4702 reterr = CountAux1b(fread_end, sample_include, tmp_genovec, aux1b_mode, raw_sample_ct, allele_ct, allele_idx, raw_10_ct, subsetted_10_ct, &fread_ptr, &het_ct, &hom_ct, pgrp->workspace_difflist_sample_ids);
4703 genocounts[0] = hom_ct;
4704 genocounts[1] = het_ct;
4705 genocounts[2] = sample_ct - genocounts[3] - hom_ct - het_ct;
4706 return reterr;
4707 }
4708
4709 // sample_include assumed to be nullptr if no subsetting required
4710 PglErr GenoarrAux1aUpdate(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, const uintptr_t* __restrict raw_genoarr, uint32_t aux1a_mode, uint32_t raw_sample_ct, uint32_t allele_ct, uint32_t allele_idx, uintptr_t lshifted_bit, uint32_t raw_01_ct, const unsigned char** fread_pp, uintptr_t* __restrict target_genoarr, uint32_t* __restrict deltalist_workspace) {
4711 if (aux1a_mode == 15) {
4712 return kPglRetSuccess;
4713 }
4714 const uint32_t ignore_01_fvals = (allele_idx == 1) || (allele_ct == 3);
4715 uintptr_t detect_mask_hi;
4716 uintptr_t detect_mask_lo;
4717 uint32_t allele_code_logwidth;
4718 const uint32_t allele_code_width = GetAux1aConsts(allele_ct, &detect_mask_hi, &detect_mask_lo, &allele_code_logwidth);
4719 const uintptr_t xor_word = (allele_idx - 2) * detect_mask_lo;
4720 if (!aux1a_mode) {
4721 const unsigned char* patch_01_fset = *fread_pp;
4722 const uint32_t fset_byte_ct = DivUp(raw_01_ct, 8);
4723 uint32_t rare01_ct = 0;
4724 if (allele_ct > 3) {
4725 rare01_ct = PopcountBytes(*fread_pp, fset_byte_ct);
4726 }
4727 *fread_pp += fset_byte_ct;
4728 const unsigned char* patch_01_fvals = *fread_pp;
4729 uintptr_t sample_hwidx = 0;
4730 uintptr_t cur_raw_genoarr_hets = Word01(raw_genoarr[0]);
4731 uint32_t loop_len = kBitsPerWord;
4732 const uintptr_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare01_ct) * allele_code_width, 8);
4733 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
4734 return kPglRetMalformedInput;
4735 }
4736 const uint32_t fset_word_ct_m1 = (fset_byte_ct - 1) / kBytesPerWord;
4737 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
4738 const uint32_t lshift = lshifted_bit - 1;
4739 uintptr_t fvals_bits = 0;
4740 uint32_t fvals_widx = 0;
4741 uint32_t rare01_lowbits = kBitsPerWord;
4742 for (uint32_t fset_widx = 0; ; ++fset_widx) {
4743 uintptr_t fset_bits;
4744 if (fset_widx >= fset_word_ct_m1) {
4745 if (fset_widx > fset_word_ct_m1) {
4746 return kPglRetSuccess;
4747 }
4748 fset_bits = SubwordLoad(&(patch_01_fset[fset_word_ct_m1 * kBytesPerWord]), ModNz(fset_byte_ct, kBytesPerWord));
4749 loop_len = ModNz(raw_01_ct, kBitsPerWord);
4750 } else {
4751 CopyFromUnalignedOffsetW(&fset_bits, patch_01_fset, fset_widx);
4752 }
4753 if (!sample_include) {
4754 if (ignore_01_fvals) {
4755 for (uint32_t uii = 0; uii != loop_len; ++uii) {
4756 while (!cur_raw_genoarr_hets) {
4757 cur_raw_genoarr_hets = Word01(raw_genoarr[++sample_hwidx]);
4758 }
4759 if (fset_bits & 1) {
4760 // ref/altx present for x>1. Change genovec entry from 01 to 11
4761 // (or 11 -> 01 in allele_idx == 2, allele_ct == 3 case; same xor
4762 // operation works for that)
4763 const uintptr_t lowbit = cur_raw_genoarr_hets & (-cur_raw_genoarr_hets);
4764 target_genoarr[sample_hwidx] ^= lowbit << lshift;
4765 }
4766 cur_raw_genoarr_hets &= cur_raw_genoarr_hets - 1;
4767 fset_bits = fset_bits >> 1;
4768 }
4769 } else {
4770 for (uint32_t uii = 0; uii != loop_len; ++uii) {
4771 while (!cur_raw_genoarr_hets) {
4772 cur_raw_genoarr_hets = Word01(raw_genoarr[++sample_hwidx]);
4773 }
4774 if (fset_bits & 1) {
4775 if (rare01_lowbits == kBitsPerWord) {
4776 if (fvals_widx == fvals_word_ct_m1) {
4777 fvals_bits = SubwordLoad(&(patch_01_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
4778 } else {
4779 CopyFromUnalignedOffsetW(&fvals_bits, patch_01_fvals, fvals_widx);
4780 }
4781 fvals_bits = fvals_bits ^ xor_word;
4782 fvals_bits = (detect_mask_hi & (~(fvals_bits | ((fvals_bits | detect_mask_hi) - detect_mask_lo)))) >> (allele_code_width - 1);
4783 // unnecessary to apply bzhi here
4784 ++fvals_widx;
4785 rare01_lowbits = 0;
4786 }
4787 if (fvals_bits & (k1LU << rare01_lowbits)) {
4788 const uintptr_t lowbit = cur_raw_genoarr_hets & (-cur_raw_genoarr_hets);
4789 target_genoarr[sample_hwidx] ^= lowbit << lshift;
4790 }
4791 rare01_lowbits += allele_code_width;
4792 }
4793 cur_raw_genoarr_hets &= cur_raw_genoarr_hets - 1;
4794 fset_bits = fset_bits >> 1;
4795 }
4796 }
4797 } else {
4798 // format 0, sample_include non-null
4799 if (ignore_01_fvals) {
4800 for (uint32_t uii = 0; uii != loop_len; ++uii) {
4801 while (!cur_raw_genoarr_hets) {
4802 cur_raw_genoarr_hets = Word01(raw_genoarr[++sample_hwidx]);
4803 }
4804 if (fset_bits & 1) {
4805 // Considered replacing cur_raw_genoarr_hets with the result of
4806 // two PackWordToHalfword() operations, since that keeps all
4807 // the sample word-indexes aligned. Couldn't justify it given
4808 // the expected sparsity of this case, though.
4809 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_hets) / 2;
4810 if ((DowncastKWToHW(sample_include)[sample_hwidx]) & (1U << sample_uidx_lowbits)) {
4811 const uint32_t sample_idx = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, sample_hwidx * kBitsPerWordD2 + sample_uidx_lowbits);
4812 target_genoarr[sample_idx / kBitsPerWordD2] ^= lshifted_bit << (2 * (sample_idx % kBitsPerWordD2));
4813 }
4814 }
4815 cur_raw_genoarr_hets &= cur_raw_genoarr_hets - 1;
4816 fset_bits = fset_bits >> 1;
4817 }
4818 } else {
4819 for (uint32_t uii = 0; uii != loop_len; ++uii) {
4820 while (!cur_raw_genoarr_hets) {
4821 cur_raw_genoarr_hets = Word01(raw_genoarr[++sample_hwidx]);
4822 }
4823 if (fset_bits & 1) {
4824 if (rare01_lowbits == kBitsPerWord) {
4825 if (fvals_widx == fvals_word_ct_m1) {
4826 fvals_bits = SubwordLoad(&(patch_01_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
4827 } else {
4828 CopyFromUnalignedOffsetW(&fvals_bits, patch_01_fvals, fvals_widx);
4829 }
4830 fvals_bits = fvals_bits ^ xor_word;
4831 fvals_bits = (detect_mask_hi & (~(fvals_bits | ((fvals_bits | detect_mask_hi) - detect_mask_lo)))) >> (allele_code_width - 1);
4832 // unnecessary to apply bzhi here
4833 ++fvals_widx;
4834 rare01_lowbits = 0;
4835 }
4836 if (fvals_bits & (k1LU << rare01_lowbits)) {
4837 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_hets) / 2;
4838 if ((DowncastKWToHW(sample_include)[sample_hwidx]) & (1U << sample_uidx_lowbits)) {
4839 const uint32_t sample_idx = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, sample_hwidx * kBitsPerWordD2 + sample_uidx_lowbits);
4840 target_genoarr[sample_idx / kBitsPerWordD2] ^= lshifted_bit << (2 * (sample_idx % kBitsPerWordD2));
4841 }
4842 }
4843 rare01_lowbits += allele_code_width;
4844 }
4845 cur_raw_genoarr_hets &= cur_raw_genoarr_hets - 1;
4846 fset_bits = fset_bits >> 1;
4847 }
4848 }
4849 }
4850 }
4851 }
4852 // aux1a_mode == 1
4853 uint32_t rare01_ct;
4854 // Might hardcode the ParseAndSaveDeltalist logic later, but lets get
4855 // this working first.
4856 PglErr reterr = ParseAndSaveDeltalist(fread_end, raw_sample_ct, fread_pp, deltalist_workspace, &rare01_ct);
4857 if (unlikely(reterr)) {
4858 return reterr;
4859 }
4860 const unsigned char* patch_01_fvals = *fread_pp;
4861 const uintptr_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare01_ct) * allele_code_width, 8);
4862 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
4863 return kPglRetMalformedInput;
4864 }
4865 if (ignore_01_fvals) {
4866 if (!sample_include) {
4867 for (uint32_t rare01_idx = 0; rare01_idx != rare01_ct; ++rare01_idx) {
4868 const uint32_t sample_uidx = deltalist_workspace[rare01_idx];
4869 // todo: benchmark against k1LU << (lshift + ...)
4870 target_genoarr[sample_uidx / kBitsPerWordD2] ^= lshifted_bit << (2 * (sample_uidx % kBitsPerWordD2));
4871 }
4872 return kPglRetSuccess;
4873 }
4874 for (uint32_t rare01_idx = 0; rare01_idx != rare01_ct; ++rare01_idx) {
4875 const uint32_t sample_uidx = deltalist_workspace[rare01_idx];
4876 // could wrap this boilerplate
4877 const uint32_t sample_widx = sample_uidx / kBitsPerWord;
4878 const uintptr_t lowbit = k1LU << (sample_uidx % kBitsPerWord);
4879 const uintptr_t sample_include_word = sample_include[sample_widx];
4880 if (sample_include_word & lowbit) {
4881 const uint32_t sample_idx = sample_include_cumulative_popcounts[sample_widx] + PopcountWord(sample_include_word & (lowbit - 1));
4882 target_genoarr[sample_idx / kBitsPerWordD2] ^= lshifted_bit << (2 * (sample_idx % kBitsPerWordD2));
4883 }
4884 }
4885 return kPglRetSuccess;
4886 }
4887 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
4888 for (uint32_t fvals_widx = 0; ; ++fvals_widx) {
4889 uintptr_t fvals_bits;
4890 if (fvals_widx >= fvals_word_ct_m1) {
4891 if (fvals_widx > fvals_word_ct_m1) {
4892 return kPglRetSuccess;
4893 }
4894 fvals_bits = SubwordLoad(&(patch_01_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
4895 } else {
4896 CopyFromUnalignedOffsetW(&fvals_bits, patch_01_fvals, fvals_widx);
4897 }
4898 fvals_bits = fvals_bits ^ xor_word;
4899 fvals_bits = detect_mask_hi & (~(fvals_bits | ((fvals_bits | detect_mask_hi) - detect_mask_lo)));
4900 if (fvals_widx == fvals_word_ct_m1) {
4901 fvals_bits = bzhi_max(fvals_bits, ModNz(rare01_ct << allele_code_logwidth, kBitsPerWord));
4902 }
4903 if (!fvals_bits) {
4904 continue;
4905 }
4906 const uint32_t* cur_deltalist_base = &(deltalist_workspace[fvals_widx << (kBitsPerWordLog2 - allele_code_logwidth)]);
4907 if (!sample_include) {
4908 do {
4909 const uint32_t rare01_idx_lowbits = ctzw(fvals_bits) >> allele_code_logwidth;
4910 const uint32_t sample_uidx = cur_deltalist_base[rare01_idx_lowbits];
4911 target_genoarr[sample_uidx / kBitsPerWordD2] ^= lshifted_bit << (2 * (sample_uidx % kBitsPerWordD2));
4912 fvals_bits &= fvals_bits - 1;
4913 } while (fvals_bits);
4914 } else {
4915 do {
4916 const uint32_t rare01_idx_lowbits = ctzw(fvals_bits) >> allele_code_logwidth;
4917 const uint32_t sample_uidx = cur_deltalist_base[rare01_idx_lowbits];
4918 const uint32_t sample_widx = sample_uidx / kBitsPerWord;
4919 const uintptr_t lowbit = k1LU << (sample_uidx % kBitsPerWord);
4920 const uintptr_t sample_include_word = sample_include[sample_widx];
4921 if (sample_include_word & lowbit) {
4922 const uint32_t sample_idx = sample_include_cumulative_popcounts[sample_widx] + PopcountWord(sample_include_word & (lowbit - 1));
4923 target_genoarr[sample_idx / kBitsPerWordD2] ^= lshifted_bit << (2 * (sample_idx % kBitsPerWordD2));
4924 }
4925 fvals_bits &= fvals_bits - 1;
4926 } while (fvals_bits);
4927 }
4928 }
4929 }
4930
4931 // sample_include assumed to be nullptr if no subsetting required
4932 PglErr GenoarrAux1bStandardUpdate(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, const uintptr_t* __restrict raw_genoarr, uint32_t aux1b_mode, uint32_t raw_sample_ct, uint32_t allele_ct, uint32_t allele_idx, uint32_t raw_10_ct, const unsigned char** fread_pp, uintptr_t* __restrict target_genoarr, uint32_t* __restrict deltalist_workspace) {
4933 if (aux1b_mode == 15) {
4934 return kPglRetSuccess;
4935 }
4936 const uint32_t allele_idx_m1 = allele_idx - 1;
4937 uintptr_t detect_hom_mask_lo;
4938 const uint32_t allele_code_logwidth = GetAux1bConsts(allele_ct, &detect_hom_mask_lo);
4939 const uint32_t allele_code_width = 1U << allele_code_logwidth;
4940 const uint32_t code10_logwidth = allele_code_logwidth + (allele_code_logwidth != 0);
4941 const uint32_t code10_width = 1U << code10_logwidth;
4942 uint32_t rare10_lowbits = kBitsPerWord;
4943 if (!aux1b_mode) {
4944 const unsigned char* patch_10_fset = *fread_pp;
4945 const uint32_t fset_byte_ct = DivUp(raw_10_ct, 8);
4946 const uint32_t fset_word_ct_m1 = (fset_byte_ct - 1) / kBytesPerWord;
4947 const uint32_t rare10_ct = PopcountBytes(*fread_pp, fset_byte_ct);
4948 *fread_pp += fset_byte_ct;
4949 uintptr_t sample_hwidx = 0;
4950 uintptr_t cur_raw_genoarr_xys = Word10(raw_genoarr[0]);
4951 const unsigned char* patch_10_fvals = *fread_pp;
4952 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare10_ct) * code10_width, CHAR_BIT);
4953 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
4954 return kPglRetMalformedInput;
4955 }
4956 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
4957 uintptr_t fvals_bits = 0;
4958 uint32_t fvals_widx = 0;
4959 uint32_t loop_len = kBitsPerWord;
4960 if ((!allele_idx_m1) || (allele_ct == 3)) {
4961 // bugfix (29 Dec 2019)
4962 const uintptr_t detect_alt1_mask_hi = detect_hom_mask_lo << (allele_code_width - 1);
4963 // If allele_ct == 3:
4964 // code10_width = 1
4965 // 0 -> 1/2, 1 -> 2/2
4966 // if allele_idx == 1:
4967 // we want to convert 2 -> 1 for 1/2 genotypes, and 2 -> 0 for 2/2.
4968 // if allele_idx == 2:
4969 // we want to convert 0 -> 1 for 1/2 genotypes, and 0 -> 2 for 2/2.
4970 // If allele_ct == 4 (allele_idx == 1 forced):
4971 // allele_code_width = 2
4972 // code10_width = 4
4973 // we want to convert 2 -> 1 for 1/x genotypes, and 2 -> 0 otherwise.
4974 const uint32_t lowcode_add = 2 - allele_idx_m1;
4975 for (uint32_t fset_widx = 0; ; ++fset_widx) {
4976 uintptr_t fset_bits;
4977 if (fset_widx >= fset_word_ct_m1) {
4978 if (fset_widx > fset_word_ct_m1) {
4979 break;
4980 }
4981 fset_bits = SubwordLoad(&(patch_10_fset[fset_word_ct_m1 * kBytesPerWord]), ModNz(fset_byte_ct, kBytesPerWord));
4982 loop_len = ModNz(raw_10_ct, kBitsPerWord);
4983 } else {
4984 CopyFromUnalignedOffsetW(&fset_bits, patch_10_fset, fset_widx);
4985 }
4986 if (!sample_include) {
4987 for (uint32_t uii = 0; uii != loop_len; ++uii) {
4988 while (!cur_raw_genoarr_xys) {
4989 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
4990 }
4991 if (fset_bits & 1) {
4992 if (rare10_lowbits == kBitsPerWord) {
4993 if (fvals_widx == fvals_word_ct_m1) {
4994 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
4995 } else {
4996 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
4997 }
4998 // modify to het 1/x = 1, otherwise 0, except in allele_idx ==
4999 // 2 special case.
5000 if (!allele_idx_m1) {
5001 fvals_bits = (detect_alt1_mask_hi & (~(fvals_bits | ((fvals_bits | detect_alt1_mask_hi) - detect_hom_mask_lo)))) >> (allele_code_width - 1);
5002 }
5003 // unnecessary to apply bzhi here
5004 ++fvals_widx;
5005 rare10_lowbits = 0;
5006 }
5007 const uint32_t cur_lowcode0 = (fvals_bits >> rare10_lowbits) & 1;
5008 rare10_lowbits += code10_width;
5009 const uintptr_t lowbit = cur_raw_genoarr_xys & (-cur_raw_genoarr_xys);
5010 target_genoarr[sample_hwidx] ^= lowbit * (lowcode_add + cur_lowcode0);
5011 }
5012 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
5013 fset_bits = fset_bits >> 1;
5014 }
5015 } else {
5016 // sample_include non-null
5017 for (uint32_t uii = 0; uii != loop_len; ++uii) {
5018 while (!cur_raw_genoarr_xys) {
5019 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
5020 }
5021 if (fset_bits & 1) {
5022 if (rare10_lowbits == kBitsPerWord) {
5023 if (fvals_widx == fvals_word_ct_m1) {
5024 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
5025 } else {
5026 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
5027 }
5028 // modify to het 1/x = 1, otherwise 0, except in allele_idx ==
5029 // 2 special case
5030 if (!allele_idx_m1) {
5031 fvals_bits = (detect_alt1_mask_hi & (~(fvals_bits | ((fvals_bits | detect_alt1_mask_hi) - detect_hom_mask_lo)))) >> (allele_code_width - 1);
5032 }
5033 // unnecessary to apply bzhi here
5034 ++fvals_widx;
5035 rare10_lowbits = 0;
5036 }
5037 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_xys) / 2;
5038 if ((DowncastKWToHW(sample_include)[sample_hwidx]) & (1U << sample_uidx_lowbits)) {
5039 const uint32_t sample_idx = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, sample_hwidx * kBitsPerWordD2 + sample_uidx_lowbits);
5040 const uintptr_t cur_lowcode0 = (fvals_bits >> rare10_lowbits) & 1;
5041 const uintptr_t shifted_xor_mult = (lowcode_add + cur_lowcode0) << (2 * (sample_idx % kBitsPerWordD2));
5042 target_genoarr[sample_idx / kBitsPerWordD2] ^= shifted_xor_mult;
5043 }
5044 rare10_lowbits += code10_width;
5045 }
5046 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
5047 fset_bits = fset_bits >> 1;
5048 }
5049 }
5050 }
5051 return kPglRetSuccess;
5052 }
5053 // allele_idx > 1, allele_ct > 3
5054 const uintptr_t detect_all_mask_lo = detect_hom_mask_lo | (detect_hom_mask_lo << allele_code_width);
5055 const uintptr_t detect_all_mask_hi = detect_all_mask_lo << (allele_code_width - 1);
5056 const uintptr_t xor_word = allele_idx_m1 * detect_all_mask_lo;
5057 for (uint32_t fset_widx = 0; ; ++fset_widx) {
5058 uintptr_t fset_bits;
5059 if (fset_widx >= fset_word_ct_m1) {
5060 if (fset_widx > fset_word_ct_m1) {
5061 break;
5062 }
5063 fset_bits = SubwordLoad(&(patch_10_fset[fset_word_ct_m1 * kBytesPerWord]), ModNz(fset_byte_ct, kBytesPerWord));
5064 loop_len = ModNz(raw_10_ct, kBitsPerWord);
5065 } else {
5066 CopyFromUnalignedOffsetW(&fset_bits, patch_10_fset, fset_widx);
5067 }
5068 if (!sample_include) {
5069 for (uint32_t uii = 0; uii != loop_len; ++uii) {
5070 while (!cur_raw_genoarr_xys) {
5071 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
5072 }
5073 if (fset_bits & 1) {
5074 if (rare10_lowbits == kBitsPerWord) {
5075 if (fvals_widx == fvals_word_ct_m1) {
5076 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
5077 } else {
5078 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
5079 }
5080 // modify to hom = 2, het = 1, neither = 0
5081 fvals_bits = fvals_bits ^ xor_word;
5082 fvals_bits = (detect_all_mask_hi & (~(fvals_bits | ((fvals_bits | detect_all_mask_hi) - detect_all_mask_lo)))) >> (allele_code_width - 1);
5083 // unnecessary to apply bzhi or detect_hom_mask_lo here
5084 fvals_bits = fvals_bits + (fvals_bits >> allele_code_width);
5085 ++fvals_widx;
5086 rare10_lowbits = 0;
5087 }
5088 const uintptr_t cur_hit_ct = (fvals_bits >> rare10_lowbits) & 3;
5089 rare10_lowbits += code10_width;
5090 if (cur_hit_ct) {
5091 const uintptr_t lowbit = cur_raw_genoarr_xys & (-cur_raw_genoarr_xys);
5092 target_genoarr[sample_hwidx] ^= lowbit * cur_hit_ct;
5093 }
5094 }
5095 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
5096 fset_bits = fset_bits >> 1;
5097 }
5098 } else {
5099 for (uint32_t uii = 0; uii != loop_len; ++uii) {
5100 while (!cur_raw_genoarr_xys) {
5101 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
5102 }
5103 if (fset_bits & 1) {
5104 if (rare10_lowbits == kBitsPerWord) {
5105 if (fvals_widx == fvals_word_ct_m1) {
5106 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
5107 } else {
5108 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
5109 }
5110 // modify to hom = 2, het = 1, neither = 0
5111 fvals_bits = fvals_bits ^ xor_word;
5112 fvals_bits = (detect_all_mask_hi & (~(fvals_bits | ((fvals_bits | detect_all_mask_hi) - detect_all_mask_lo)))) >> (allele_code_width - 1);
5113 if (fvals_widx == fvals_word_ct_m1) {
5114 fvals_bits = bzhi_max(fvals_bits, ModNz(rare10_ct * code10_width, kBitsPerWord));
5115 }
5116 fvals_bits = fvals_bits + (fvals_bits >> allele_code_width);
5117 ++fvals_widx;
5118 rare10_lowbits = 0;
5119 }
5120 const uintptr_t cur_hit_ct = (fvals_bits >> rare10_lowbits) & 3;
5121 rare10_lowbits += code10_width;
5122 if (cur_hit_ct) {
5123 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_xys) / 2;
5124 if ((DowncastKWToHW(sample_include)[sample_hwidx]) & (1U << sample_uidx_lowbits)) {
5125 const uint32_t sample_idx = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, sample_hwidx * kBitsPerWordD2 + sample_uidx_lowbits);
5126 target_genoarr[sample_idx / kBitsPerWordD2] ^= cur_hit_ct << (2 * (sample_idx % kBitsPerWordD2));
5127 }
5128 }
5129 }
5130 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
5131 fset_bits = fset_bits >> 1;
5132 }
5133 }
5134 }
5135 return kPglRetSuccess;
5136 }
5137 // aux1b_mode == 1
5138 uint32_t rare10_ct;
5139 PglErr reterr = ParseAndSaveDeltalist(fread_end, raw_sample_ct, fread_pp, deltalist_workspace, &rare10_ct);
5140 if (unlikely(reterr)) {
5141 return reterr;
5142 }
5143 const unsigned char* patch_10_fvals = *fread_pp;
5144 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare10_ct) << code10_logwidth, CHAR_BIT);
5145 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
5146 return kPglRetMalformedInput;
5147 }
5148 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
5149 if ((!allele_idx_m1) || (allele_ct == 3)) {
5150 // bugfix (29 Dec 2019)
5151 const uintptr_t detect_alt1_mask_hi = detect_hom_mask_lo << (allele_code_width - 1);
5152 const uintptr_t lowcode_add = 2 - allele_idx_m1;
5153 uint32_t loop_len = kBitsPerWord >> code10_logwidth;
5154 for (uint32_t fvals_widx = 0; ; ++fvals_widx) {
5155 uintptr_t fvals_bits;
5156 if (fvals_widx >= fvals_word_ct_m1) {
5157 if (fvals_widx > fvals_word_ct_m1) {
5158 break;
5159 }
5160 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
5161 loop_len = 1 + ((rare10_ct - 1) & ((kBitsPerWord >> code10_logwidth) - 1));
5162 } else {
5163 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
5164 }
5165 if (!allele_idx_m1) {
5166 fvals_bits = (detect_alt1_mask_hi & (~(fvals_bits | ((fvals_bits | detect_alt1_mask_hi) - detect_hom_mask_lo)))) >> (allele_code_width - 1);
5167 }
5168 const uint32_t* cur_deltalist_base = &(deltalist_workspace[fvals_widx << (kBitsPerWordLog2 - code10_logwidth)]);
5169 if (!sample_include) {
5170 for (uint32_t uii = 0; uii != loop_len; ++uii) {
5171 const uint32_t sample_uidx = cur_deltalist_base[uii];
5172 const uintptr_t cur_lowcode0 = fvals_bits & 1;
5173 const uintptr_t shifted_xor_mult = (lowcode_add + cur_lowcode0) << (2 * (sample_uidx % kBitsPerWordD2));
5174 target_genoarr[sample_uidx / kBitsPerWordD2] ^= shifted_xor_mult;
5175 fvals_bits = fvals_bits >> code10_width;
5176 }
5177 } else {
5178 for (uint32_t uii = 0; uii != loop_len; ++uii) {
5179 const uint32_t sample_uidx = cur_deltalist_base[uii];
5180 const uint32_t sample_widx = sample_uidx / kBitsPerWord;
5181 const uintptr_t lowbit = k1LU << (sample_uidx % kBitsPerWord);
5182 const uintptr_t sample_include_word = sample_include[sample_widx];
5183 if (sample_include_word & lowbit) {
5184 const uint32_t sample_idx = sample_include_cumulative_popcounts[sample_widx] + PopcountWord(sample_include_word & (lowbit - 1));
5185 const uintptr_t cur_lowcode0 = fvals_bits & 1;
5186 const uintptr_t shifted_xor_mult = (lowcode_add + cur_lowcode0) << (2 * (sample_idx % kBitsPerWordD2));
5187 target_genoarr[sample_idx / kBitsPerWordD2] ^= shifted_xor_mult;
5188 }
5189 fvals_bits = fvals_bits >> code10_width;
5190 }
5191 }
5192 }
5193 return kPglRetSuccess;
5194 }
5195 // allele_idx > 1, allele_ct > 3
5196 const uintptr_t detect_all_mask_lo = detect_hom_mask_lo | (detect_hom_mask_lo << allele_code_width);
5197 const uintptr_t detect_all_mask_hi = detect_all_mask_lo << (allele_code_width - 1);
5198 detect_hom_mask_lo = detect_hom_mask_lo * 3;
5199 const uintptr_t xor_word = allele_idx_m1 * detect_all_mask_lo;
5200 for (uint32_t fvals_widx = 0; ; ++fvals_widx) {
5201 uintptr_t fvals_bits;
5202 if (fvals_widx >= fvals_word_ct_m1) {
5203 if (fvals_widx > fvals_word_ct_m1) {
5204 break;
5205 }
5206 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
5207 } else {
5208 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
5209 }
5210 fvals_bits = fvals_bits ^ xor_word;
5211 fvals_bits = detect_all_mask_hi & (~(fvals_bits | ((fvals_bits | detect_all_mask_hi) - detect_all_mask_lo)));
5212 if (fvals_widx == fvals_word_ct_m1) {
5213 fvals_bits = bzhi_max(fvals_bits, ModNz(rare10_ct << code10_logwidth, kBitsPerWord));
5214 }
5215 if (!fvals_bits) {
5216 continue;
5217 }
5218 fvals_bits = fvals_bits >> (allele_code_width - 1);
5219 fvals_bits = (fvals_bits + (fvals_bits >> allele_code_width)) & detect_hom_mask_lo;
5220 const uint32_t* cur_deltalist_base = &(deltalist_workspace[fvals_widx << (kBitsPerWordLog2 - code10_logwidth)]);
5221 if (!sample_include) {
5222 do {
5223 const uint32_t bit_idx = ctzw(fvals_bits);
5224 const uint32_t sample_uidx = cur_deltalist_base[bit_idx >> code10_logwidth];
5225 target_genoarr[sample_uidx / kBitsPerWordD2] ^= k1LU << ((bit_idx % 2) + 2 * (sample_uidx % kBitsPerWordD2));
5226 fvals_bits &= fvals_bits - 1;
5227 } while (fvals_bits);
5228 } else {
5229 do {
5230 const uint32_t bit_idx = ctzw(fvals_bits);
5231 const uint32_t sample_uidx = cur_deltalist_base[bit_idx >> code10_logwidth];
5232 const uint32_t sample_widx = sample_uidx / kBitsPerWord;
5233 const uintptr_t lowbit = k1LU << (sample_uidx % kBitsPerWord);
5234 const uintptr_t sample_include_word = sample_include[sample_widx];
5235 if (sample_include_word & lowbit) {
5236 const uint32_t sample_idx = sample_include_cumulative_popcounts[sample_widx] + PopcountWord(sample_include_word & (lowbit - 1));
5237 target_genoarr[sample_idx / kBitsPerWordD2] ^= k1LU << ((bit_idx % 2) + 2 * (sample_idx % kBitsPerWordD2));
5238 }
5239 fvals_bits &= fvals_bits - 1;
5240 } while (fvals_bits);
5241 }
5242 }
5243 return kPglRetSuccess;
5244 }
5245
5246 // if aux1b_het_present is true, aux1b_hets becomes a 1-bit-per-sample bitarray
5247 // with the positions of altx/alty hets in aux1b.
5248 PglErr GetAux1bHets(const unsigned char* fread_end, const uintptr_t* __restrict raw_genoarr, uint32_t aux1b_mode, uint32_t raw_sample_ct, uint32_t allele_ct, uint32_t raw_10_ct, const unsigned char** fread_pp, uintptr_t* __restrict aux1b_hets, uint32_t* __restrict aux1b_het_presentp, uint32_t* __restrict deltalist_workspace) {
5249 if (aux1b_mode == 15) {
5250 *aux1b_het_presentp = 0;
5251 return kPglRetSuccess;
5252 }
5253 uintptr_t detect_hom_mask_lo;
5254 const uint32_t allele_code_logwidth = GetAux1bConsts(allele_ct, &detect_hom_mask_lo);
5255 const uint32_t code10_logwidth = allele_code_logwidth + (allele_code_logwidth != 0);
5256 const uint32_t code10_width = 1U << code10_logwidth;
5257 const uint32_t allele_code_width = 1U << allele_code_logwidth;
5258 const uintptr_t detect_all_mask_lo = detect_hom_mask_lo | (detect_hom_mask_lo << allele_code_width);
5259 const uintptr_t detect_all_mask_hi = detect_all_mask_lo << (allele_code_width - 1);
5260 Halfword* aux1b_hets_alias = DowncastWToHW(aux1b_hets);
5261 uint32_t rare10_lowbits = kBitsPerWord;
5262 uint32_t aux1b_het_present = 0;
5263 if (!aux1b_mode) {
5264 const unsigned char* patch_10_fset = *fread_pp;
5265 const uint32_t fset_byte_ct = DivUp(raw_10_ct, 8);
5266 const uint32_t fset_word_ct_m1 = (fset_byte_ct - 1) / kBytesPerWord;
5267 const uint32_t rare10_ct = PopcountBytes(*fread_pp, fset_byte_ct);
5268 *fread_pp += fset_byte_ct;
5269 uintptr_t sample_hwidx = 0;
5270 uintptr_t cur_raw_genoarr_xys = Word10(raw_genoarr[0]);
5271 const unsigned char* patch_10_fvals = *fread_pp;
5272 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare10_ct) * code10_width, CHAR_BIT);
5273 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
5274 return kPglRetMalformedInput;
5275 }
5276 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
5277 uintptr_t fvals_bits = 0;
5278 uint32_t fvals_widx = 0;
5279 uint32_t loop_len = kBitsPerWord;
5280 for (uint32_t fset_widx = 0; ; ++fset_widx) {
5281 uintptr_t fset_bits;
5282 if (fset_widx >= fset_word_ct_m1) {
5283 if (fset_widx > fset_word_ct_m1) {
5284 break;
5285 }
5286 fset_bits = SubwordLoad(&(patch_10_fset[fset_word_ct_m1 * kBytesPerWord]), ModNz(fset_byte_ct, kBytesPerWord));
5287 loop_len = ModNz(raw_10_ct, kBitsPerWord);
5288 } else {
5289 CopyFromUnalignedOffsetW(&fset_bits, patch_10_fset, fset_widx);
5290 }
5291 for (uint32_t uii = 0; uii != loop_len; ++uii) {
5292 while (!cur_raw_genoarr_xys) {
5293 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
5294 }
5295 if (fset_bits & 1) {
5296 if (rare10_lowbits == kBitsPerWord) {
5297 if (fvals_widx == fvals_word_ct_m1) {
5298 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
5299 } else {
5300 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
5301 }
5302 // allele_ct == 3: just invert raw fvals_bits
5303 // allele_ct > 3: shift by allele_code_width, xor with self so that
5304 // 0 == hom, detect nonzero by inverting the usual check
5305 if (allele_ct == 3) {
5306 fvals_bits = ~fvals_bits;
5307 } else {
5308 fvals_bits = fvals_bits ^ (fvals_bits << allele_code_width);
5309 // conveniently, removing a ~ here is equivalent to inverting the
5310 // relevant bits of the final result
5311 fvals_bits = detect_hom_mask_lo & ((fvals_bits | ((fvals_bits | detect_all_mask_hi) - detect_all_mask_lo)) >> (code10_width - 1));
5312 }
5313 // bzhi only relevant for detecting if there are any hets at all
5314 if (!aux1b_het_present) {
5315 if (fvals_widx == fvals_word_ct_m1) {
5316 fvals_bits = bzhi_max(fvals_bits, ModNz(rare10_ct * code10_width, kBitsPerWord));
5317 }
5318 if (fvals_bits) {
5319 // lazy-initialize
5320 aux1b_het_present = 1;
5321 ZeroHwArr(2 * BitCtToWordCt(raw_sample_ct), aux1b_hets_alias);
5322 }
5323 }
5324 ++fvals_widx;
5325 rare10_lowbits = 0;
5326 }
5327 if (fvals_bits & (k1LU << rare10_lowbits)) {
5328 const uint32_t bit_idx = ctzw(cur_raw_genoarr_xys) / 2;
5329 aux1b_hets_alias[sample_hwidx] |= 1U << bit_idx;
5330 }
5331 rare10_lowbits += code10_width;
5332 }
5333 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
5334 fset_bits = fset_bits >> 1;
5335 }
5336 }
5337 *aux1b_het_presentp = aux1b_het_present;
5338 return kPglRetSuccess;
5339 }
5340 // aux1b_mode == 1
5341 uint32_t rare10_ct;
5342 PglErr reterr = ParseAndSaveDeltalist(fread_end, raw_sample_ct, fread_pp, deltalist_workspace, &rare10_ct);
5343 if (unlikely(reterr)) {
5344 return reterr;
5345 }
5346 const unsigned char* patch_10_fvals = *fread_pp;
5347 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare10_ct) << code10_logwidth, CHAR_BIT);
5348 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
5349 return kPglRetMalformedInput;
5350 }
5351 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
5352 for (uint32_t fvals_widx = 0; ; ++fvals_widx) {
5353 uintptr_t fvals_bits;
5354 if (fvals_widx >= fvals_word_ct_m1) {
5355 if (fvals_widx > fvals_word_ct_m1) {
5356 break;
5357 }
5358 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
5359 } else {
5360 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
5361 }
5362 if (allele_ct == 3) {
5363 fvals_bits = ~fvals_bits;
5364 } else {
5365 fvals_bits = fvals_bits ^ (fvals_bits << allele_code_width);
5366 fvals_bits = detect_hom_mask_lo & ((fvals_bits | ((fvals_bits | detect_all_mask_hi) - detect_all_mask_lo)) >> (code10_width - 1));
5367 }
5368 if (fvals_widx == fvals_word_ct_m1) {
5369 fvals_bits = bzhi_max(fvals_bits, ModNz(rare10_ct << code10_logwidth, kBitsPerWord));
5370 }
5371 if (!fvals_bits) {
5372 continue;
5373 }
5374 if (!aux1b_het_present) {
5375 aux1b_het_present = 1;
5376 ZeroHwArr(2 * BitCtToWordCt(raw_sample_ct), aux1b_hets_alias);
5377 }
5378 const uint32_t* cur_deltalist_base = &(deltalist_workspace[fvals_widx << (kBitsPerWordLog2 - code10_logwidth)]);
5379 do {
5380 const uint32_t bit_idx = ctzw(fvals_bits);
5381 const uint32_t sample_uidx = cur_deltalist_base[bit_idx >> code10_logwidth];
5382 aux1b_hets_alias[sample_uidx / kBitsPerWordD2] |= 1U << (sample_uidx % kBitsPerWordD2);
5383 fvals_bits &= fvals_bits - 1;
5384 } while (fvals_bits);
5385 }
5386 *aux1b_het_presentp = aux1b_het_present;
5387 return kPglRetSuccess;
5388 }
5389
5390 static inline void SuppressHets00(const uintptr_t* allele_countvec, uintptr_t* subsetted_all_hets, uint32_t sample_ct, uintptr_t* subsetted_suppressed_hets) {
5391 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
5392 MaskWordsToHalfwordsInvmatch(allele_countvec, ~k0LU, sample_ctl2, subsetted_all_hets, subsetted_suppressed_hets);
5393 }
5394
5395 PglErr Get1Multiallelic(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReaderMain* pgrp, const unsigned char** fread_pp, const unsigned char** fread_endp, uintptr_t* __restrict all_hets, uintptr_t* __restrict allele_countvec, uintptr_t** subsetted_suppressed_hetp) {
5396 // sample_ct > 0; either allele_idx > 1 or ((allele_idx == 1) &&
5397 // multiallelic_hc_present)
5398 // subsetted_suppressed_het assumed to be initialized to nullptr, if present
5399 // at all
5400 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
5401 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
5402 uintptr_t* raw_genovec = pgrp->workspace_vec;
5403 const unsigned char* fread_ptr;
5404 const unsigned char* fread_end;
5405 PglErr reterr = ReadRawGenovec(subsetting_required, vidx, pgrp, &fread_ptr, &fread_end, raw_genovec);
5406 if (unlikely(reterr)) {
5407 return reterr;
5408 }
5409
5410 const uint32_t vrtype = pgrp->fi.vrtypes[vidx];
5411 const uint32_t multiallelic_hc_present = VrtypeMultiallelicHc(vrtype);
5412 CopyNyparrNonemptySubset(raw_genovec, sample_include, raw_sample_ct, sample_ct, allele_countvec);
5413 ZeroTrailingNyps(raw_sample_ct, raw_genovec);
5414 if (fread_pp) {
5415 *fread_endp = fread_end;
5416 if (all_hets) {
5417 PgrDetectGenoarrHets(raw_genovec, raw_sample_ct, all_hets);
5418 }
5419 }
5420 if (allele_idx != 1) {
5421 GenovecNonmissingToZeroUnsafe(sample_ct, allele_countvec);
5422 if (!multiallelic_hc_present) {
5423 if (fread_pp) {
5424 *fread_pp = fread_ptr;
5425 }
5426 return kPglRetSuccess;
5427 }
5428 }
5429 const uint32_t aux1_first_byte = *fread_ptr++;
5430 const uint32_t aux1a_mode = aux1_first_byte & 15;
5431 const uint32_t aux1b_mode = aux1_first_byte >> 4;
5432 // only need to initialize these in dense modes
5433 uint32_t raw_01_ct = 0;
5434 uint32_t raw_10_ct = 0;
5435 if ((!aux1a_mode) || (!aux1b_mode)) {
5436 GenovecCount12Unsafe(raw_genovec, raw_sample_ct, &raw_01_ct, &raw_10_ct);
5437 }
5438
5439 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
5440 const uint32_t allele_ct = allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx];
5441 if (!subsetting_required) {
5442 sample_include = nullptr;
5443 }
5444 // allele_idx == 1 case:
5445 // allele_countvec currently contains ALT counts; we want to reduce them to
5446 // ALT1 counts. This can be done with the following steps:
5447 // 1. For every element of patch_01_fset, reduce the value from 1 to 0. We
5448 // don't actually need to look at patch_01_fvals.
5449 // 2. For every element of patch_10_fset, reduce the value from 2 depending
5450 // on the low bit(s) of the patch_01_fvals entry (reduce to 0 unless low
5451 // bit(s) are all zero).
5452 // allele_idx > 1 case:
5453 // 1. For every element of patch_01_fset, set a 1 for each matching value
5454 // of patch_01_fvals.
5455 // 2. For every element of patch_10_fset, set a 1 for each het-matching
5456 // value of patch_10_fvals, and a 2 for each hom-match.
5457 uint32_t* deltalist_workspace = pgrp->workspace_difflist_sample_ids;
5458 // Two cases:
5459 // - If allele_idx == 1, convert all aux1a entries from 01 to 00.
5460 // - Otherwise, for each matching aux1a entry, convert from 00 to 01.
5461 reterr = GenoarrAux1aUpdate(fread_end, sample_include, sample_include_cumulative_popcounts, raw_genovec, aux1a_mode, raw_sample_ct, allele_ct, allele_idx, 1, raw_01_ct, &fread_ptr, allele_countvec, deltalist_workspace);
5462 if (unlikely(reterr)) {
5463 return reterr;
5464 }
5465 const unsigned char* aux1b_start = fread_ptr;
5466 reterr = GenoarrAux1bStandardUpdate(fread_end, sample_include, sample_include_cumulative_popcounts, raw_genovec, aux1b_mode, raw_sample_ct, allele_ct, allele_idx, raw_10_ct, &fread_ptr, allele_countvec, deltalist_workspace);
5467 if ((!fread_pp) || reterr) {
5468 return reterr;
5469 }
5470 *fread_pp = fread_ptr;
5471 if (all_hets) {
5472 // can merge this with GenovecAux1bStandardUpdate if this is ever a
5473 // significant bottleneck
5474 uintptr_t* aux1b_hets = pgrp->workspace_aux1x_present;
5475 uint32_t aux1b_het_present;
5476 reterr = GetAux1bHets(fread_end, raw_genovec, aux1b_mode, raw_sample_ct, allele_ct, raw_10_ct, &aux1b_start, aux1b_hets, &aux1b_het_present, deltalist_workspace);
5477 if (unlikely(reterr)) {
5478 return reterr;
5479 }
5480 if (aux1b_het_present) {
5481 BitvecOr(aux1b_hets, BitCtToWordCt(raw_sample_ct), all_hets);
5482 }
5483 // We now want to make subsetted_suppressed_het flag all hets where neither
5484 // allele is equal to allele_idx, i.e. the allele_countvec value is 0 yet
5485 // the all_hets bit is set.
5486 // This was done incorrectly before 17 Aug 2023.
5487 if ((allele_idx > 1) || aux1b_het_present) {
5488 // We can now clobber the contents of pgrp->workspace_vec (raw_genovec)
5489 // and pgrp->workspace_aux1x_present (aux1b_hets).
5490 // We use the former as the subsetted_suppressed_het return buffer.
5491 uintptr_t* all_hets_subsetted = all_hets;
5492 if (subsetting_required) {
5493 all_hets_subsetted = aux1b_hets;
5494 CopyBitarrSubset(all_hets, sample_include, sample_ct, all_hets_subsetted);
5495 }
5496 *subsetted_suppressed_hetp = raw_genovec;
5497 SuppressHets00(allele_countvec, all_hets_subsetted, sample_ct, raw_genovec);
5498 }
5499 }
5500 return kPglRetSuccess;
5501 }
5502
5503 PglErr IMPLPgrGet1(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReaderMain* pgrp, uintptr_t* __restrict allele_countvec) {
5504 if (!sample_ct) {
5505 return kPglRetSuccess;
5506 }
5507 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
5508 const uint32_t multiallelic_hc_present = VrtypeMultiallelicHc(vrtype);
5509 if ((!allele_idx) || ((allele_idx == 1) && (!multiallelic_hc_present))) {
5510 PglErr reterr = ReadGenovecSubsetUnsafe(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, nullptr, nullptr, allele_countvec);
5511 if (unlikely(reterr)) {
5512 return reterr;
5513 }
5514 if (!allele_idx) {
5515 GenovecInvertUnsafe(sample_ct, allele_countvec);
5516 }
5517 return kPglRetSuccess;
5518 }
5519 return Get1Multiallelic(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx, pgrp, nullptr, nullptr, nullptr, allele_countvec, nullptr);
5520 }
5521
5522 PglErr IMPLPgrGetInv1(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReaderMain* pgrp, uintptr_t* __restrict allele_invcountvec) {
5523 if (!sample_ct) {
5524 return kPglRetSuccess;
5525 }
5526 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
5527 const uint32_t multiallelic_hc_present = VrtypeMultiallelicHc(vrtype);
5528 if ((!allele_idx) || ((allele_idx == 1) && (!multiallelic_hc_present))) {
5529 PglErr reterr = ReadGenovecSubsetUnsafe(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, nullptr, nullptr, allele_invcountvec);
5530 if (unlikely(reterr)) {
5531 return reterr;
5532 }
5533 if (allele_idx) {
5534 GenovecInvertUnsafe(sample_ct, allele_invcountvec);
5535 }
5536 return kPglRetSuccess;
5537 }
5538 PglErr reterr = Get1Multiallelic(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx, pgrp, nullptr, nullptr, nullptr, allele_invcountvec, nullptr);
5539 GenovecInvertUnsafe(sample_ct, allele_invcountvec);
5540 return reterr;
5541 }
5542
5543 PglErr IMPLPgrGetInv1DifflistOrGenovec(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t max_simple_difflist_len, uint32_t vidx, uint32_t allele_idx, PgenReaderMain* pgrp, uintptr_t* __restrict allele_invcountvec, uint32_t* __restrict difflist_common_geno_ptr, uintptr_t* __restrict main_raregeno, uint32_t* __restrict difflist_sample_ids, uint32_t* __restrict difflist_len_ptr) {
5544 if (!sample_ct) {
5545 *difflist_common_geno_ptr = UINT32_MAX;
5546 return kPglRetSuccess;
5547 }
5548 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
5549 const uint32_t multiallelic_hc_present = VrtypeMultiallelicHc(vrtype);
5550 if ((!allele_idx) || ((allele_idx == 1) && (!multiallelic_hc_present))) {
5551 PglErr reterr = ReadDifflistOrGenovecSubsetUnsafe(sample_include, sample_include_cumulative_popcounts, sample_ct, max_simple_difflist_len, vidx, pgrp, nullptr, nullptr, allele_invcountvec, difflist_common_geno_ptr, main_raregeno, difflist_sample_ids, difflist_len_ptr);
5552 if (unlikely(reterr)) {
5553 return reterr;
5554 }
5555 if (allele_idx) {
5556 if (*difflist_common_geno_ptr == UINT32_MAX) {
5557 GenovecInvertUnsafe(sample_ct, allele_invcountvec);
5558 } else {
5559 const uint32_t orig_common_geno = *difflist_common_geno_ptr;
5560 GenovecInvertUnsafe(*difflist_len_ptr, main_raregeno);
5561 if (orig_common_geno != 3) {
5562 *difflist_common_geno_ptr = 2 - orig_common_geno;
5563 }
5564 }
5565 }
5566 return kPglRetSuccess;
5567 }
5568 *difflist_common_geno_ptr = UINT32_MAX;
5569 PglErr reterr = Get1Multiallelic(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx, pgrp, nullptr, nullptr, nullptr, allele_invcountvec, nullptr);
5570 GenovecInvertUnsafe(sample_ct, allele_invcountvec);
5571 return reterr;
5572 }
5573
5574 // Assumes allele_idx0 < allele_idx1, and allele_idx0 < 2. Rotates hardcalls
5575 // such that, if no multiallelic hardcalls are present, 0 = 0/0, 1 = 0/1,
5576 // 2 = 1/1, and 3 = anything else.
5577 void Rotate2(uint32_t allele_idx0, uint32_t allele_idx1, uint32_t sample_ct, uintptr_t* genovec) {
5578 if (!allele_idx0) {
5579 if (allele_idx1 > 1) {
5580 GenovecNonzeroToMissingUnsafe(sample_ct, genovec);
5581 }
5582 } else {
5583 GenovecInvertThenNonzeroToMissingUnsafe(sample_ct, genovec);
5584 }
5585 }
5586
5587 PglErr SkipAux1a(const unsigned char* fread_end, uint32_t aux1a_mode, uint32_t raw_sample_ct, uint32_t allele_ct, uint32_t raw_01_ct, const unsigned char** fread_pp) {
5588 if (aux1a_mode == 15) {
5589 return kPglRetSuccess;
5590 }
5591 uint32_t rare01_ct;
5592 if (!aux1a_mode) {
5593 const uint32_t fset_byte_ct = DivUp(raw_01_ct, CHAR_BIT);
5594 rare01_ct = PopcountBytes(*fread_pp, fset_byte_ct);
5595 *fread_pp += fset_byte_ct;
5596 } else {
5597 const unsigned char* group_info_iter;
5598 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, nullptr, &group_info_iter, &rare01_ct);
5599 if (unlikely(reterr)) {
5600 return reterr;
5601 }
5602 reterr = SkipDeltalistIds(fread_end, group_info_iter, rare01_ct, raw_sample_ct, 0, fread_pp);
5603 if (unlikely(reterr)) {
5604 return reterr;
5605 }
5606 }
5607 const uint32_t fvals_byte_ct = GetAux1aAlleleEntryByteCt(allele_ct, rare01_ct);
5608 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
5609 return kPglRetMalformedInput;
5610 }
5611 return kPglRetSuccess;
5612 }
5613
5614 // sample_include assumed to be nullptr if no subsetting required
5615 PglErr GenoarrAux1bUpdate2(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, const uintptr_t* __restrict raw_genoarr, uint32_t aux1b_mode, uint32_t raw_sample_ct, uint32_t allele_ct, uint32_t allele_idx0, uint32_t allele_idx1, uint32_t raw_10_ct, const unsigned char** fread_pp, uintptr_t* __restrict target_genoarr, uint32_t* __restrict deltalist_workspace) {
5616 // Possible aux1b updates:
5617 // - allele_idx0 == 0:
5618 // allele_idx1 == 1: all altx/alty including a rarealt from 10 to 11
5619 // allele_idx1 > 1: set one rarealtx/rarealtx from 11 to 10
5620 //
5621 // - allele_idx0 == 1: change all alt1/rarealtx from 00 to 01,
5622 // rarealtx/rarealtx from 00 to 10, and all other aux1b entries to missing.
5623 // This can use the same driver as Get1Multiallelic.
5624 //
5625 // - allele_idx0 > 1: change all rarealtx/rarealtx from missing to 00,
5626 // rarealtx/rarealty to 01, and rarealty/rarealty to 10.
5627 if (aux1b_mode == 15) {
5628 return kPglRetSuccess;
5629 }
5630 if (allele_idx0 == 1) {
5631 return GenoarrAux1bStandardUpdate(fread_end, sample_include, sample_include_cumulative_popcounts, raw_genoarr, aux1b_mode, raw_sample_ct, allele_ct, allele_idx1, raw_10_ct, fread_pp, target_genoarr, deltalist_workspace);
5632 }
5633 uintptr_t detect_hom_mask_lo;
5634 const uint32_t allele_code_logwidth = GetAux1bConsts(allele_ct, &detect_hom_mask_lo);
5635 const uint32_t code10_logwidth = allele_code_logwidth + (allele_code_logwidth != 0);
5636 const uint32_t code10_width = 1U << code10_logwidth;
5637 const uintptr_t detect_hom_mask_hi = detect_hom_mask_lo << (code10_width - 1);
5638 uintptr_t xor_word2 = allele_idx1 - 1;
5639 // fortunately, this sequence of operations happens to work for allele_ct ==
5640 // 3
5641 xor_word2 = xor_word2 | (xor_word2 << (code10_width / 2));
5642 xor_word2 = xor_word2 * detect_hom_mask_lo;
5643 uint32_t rare10_lowbits = kBitsPerWord;
5644 if (!aux1b_mode) {
5645 const unsigned char* patch_10_fset = *fread_pp;
5646 const uint32_t fset_byte_ct = DivUp(raw_10_ct, 8);
5647 const uint32_t fset_word_ct_m1 = (fset_byte_ct - 1) / kBytesPerWord;
5648 const uint32_t rare10_ct = PopcountBytes(*fread_pp, fset_byte_ct);
5649 *fread_pp += fset_byte_ct;
5650 uintptr_t sample_hwidx = 0;
5651 uintptr_t cur_raw_genoarr_xys = Word10(raw_genoarr[0]);
5652 const unsigned char* patch_10_fvals = *fread_pp;
5653 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare10_ct) * code10_width, CHAR_BIT);
5654 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
5655 return kPglRetMalformedInput;
5656 }
5657 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
5658 uintptr_t fvals_bits = 0;
5659 uint32_t fvals_widx = 0;
5660 uint32_t loop_len = kBitsPerWord;
5661 if (!allele_idx0) {
5662 for (uint32_t fset_widx = 0; ; ++fset_widx) {
5663 uintptr_t fset_bits;
5664 if (fset_widx >= fset_word_ct_m1) {
5665 if (fset_widx > fset_word_ct_m1) {
5666 return kPglRetSuccess;
5667 }
5668 fset_bits = SubwordLoad(&(patch_10_fset[fset_word_ct_m1 * kBytesPerWord]), ModNz(fset_byte_ct, kBytesPerWord));
5669 loop_len = ModNz(raw_10_ct, kBitsPerWord);
5670 } else {
5671 CopyFromUnalignedOffsetW(&fset_bits, patch_10_fset, fset_widx);
5672 }
5673 if (!sample_include) {
5674 if (allele_idx1 == 1) {
5675 // All aux1b 10 -> 11. Ignore aux1b_fvals.
5676 for (uint32_t uii = 0; uii != loop_len; ++uii) {
5677 while (!cur_raw_genoarr_xys) {
5678 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
5679 }
5680 if (fset_bits & 1) {
5681 const uintptr_t lowbit = cur_raw_genoarr_xys & (-cur_raw_genoarr_xys);
5682 target_genoarr[sample_hwidx] ^= lowbit;
5683 }
5684 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
5685 fset_bits = fset_bits >> 1;
5686 }
5687 } else {
5688 // hom-altx 11 -> 10.
5689 for (uint32_t uii = 0; uii != loop_len; ++uii) {
5690 while (!cur_raw_genoarr_xys) {
5691 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
5692 }
5693 if (fset_bits & 1) {
5694 if (rare10_lowbits == kBitsPerWord) {
5695 if (fvals_widx == fvals_word_ct_m1) {
5696 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
5697 } else {
5698 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
5699 }
5700 fvals_bits = fvals_bits ^ xor_word2;
5701 fvals_bits = (detect_hom_mask_hi & (~(fvals_bits | ((fvals_bits | detect_hom_mask_hi) - detect_hom_mask_lo)))) >> (code10_width - 1);
5702 // unnecessary to apply bzhi here
5703 ++fvals_widx;
5704 rare10_lowbits = 0;
5705 }
5706 if (fvals_bits & (k1LU << rare10_lowbits)) {
5707 const uintptr_t lowbit = cur_raw_genoarr_xys & (-cur_raw_genoarr_xys);
5708 target_genoarr[sample_hwidx] ^= lowbit;
5709 }
5710 rare10_lowbits += code10_width;
5711 }
5712 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
5713 fset_bits = fset_bits >> 1;
5714 }
5715 }
5716 } else {
5717 // sample_include non-null
5718 if (allele_idx1 == 1) {
5719 for (uint32_t uii = 0; uii != loop_len; ++uii) {
5720 while (!cur_raw_genoarr_xys) {
5721 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
5722 }
5723 if (fset_bits & 1) {
5724 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_xys) / 2;
5725 if ((DowncastKWToHW(sample_include)[sample_hwidx]) & (1U << sample_uidx_lowbits)) {
5726 const uint32_t sample_idx = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, sample_hwidx * kBitsPerWordD2 + sample_uidx_lowbits);
5727 target_genoarr[sample_idx / kBitsPerWordD2] ^= k1LU << (2 * (sample_idx % kBitsPerWordD2));
5728 }
5729 rare10_lowbits += code10_width;
5730 }
5731 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
5732 fset_bits = fset_bits >> 1;
5733 }
5734 } else {
5735 for (uint32_t uii = 0; uii != loop_len; ++uii) {
5736 while (!cur_raw_genoarr_xys) {
5737 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
5738 }
5739 if (fset_bits & 1) {
5740 if (rare10_lowbits == kBitsPerWord) {
5741 if (fvals_widx == fvals_word_ct_m1) {
5742 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
5743 } else {
5744 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
5745 }
5746 fvals_bits = fvals_bits ^ xor_word2;
5747 fvals_bits = (detect_hom_mask_hi & (~(fvals_bits | ((fvals_bits | detect_hom_mask_hi) - detect_hom_mask_lo)))) >> (code10_width - 1);
5748 // unnecessary to apply bzhi here
5749 ++fvals_widx;
5750 rare10_lowbits = 0;
5751 }
5752 if (fvals_bits & (k1LU << rare10_lowbits)) {
5753 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_xys) / 2;
5754 if ((DowncastKWToHW(sample_include)[sample_hwidx]) & (1U << sample_uidx_lowbits)) {
5755 const uint32_t sample_idx = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, sample_hwidx * kBitsPerWordD2 + sample_uidx_lowbits);
5756 target_genoarr[sample_idx / kBitsPerWordD2] ^= k1LU << (2 * (sample_idx % kBitsPerWordD2));
5757 }
5758 }
5759 rare10_lowbits += code10_width;
5760 }
5761 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
5762 fset_bits = fset_bits >> 1;
5763 }
5764 }
5765 }
5766 }
5767 }
5768 // 2 <= allele_idx0 < allele_idx1 (so allele_ct > 3 guaranteed)
5769 uintptr_t xor_word1 = allele_idx1 - 1;
5770 uintptr_t xor_word0 = allele_idx0 - 1;
5771 xor_word1 = xor_word0 | (xor_word1 << (code10_width / 2));
5772 xor_word0 = xor_word0 | (xor_word0 << (code10_width / 2));
5773 xor_word1 *= detect_hom_mask_lo;
5774 xor_word0 *= detect_hom_mask_lo;
5775 for (uint32_t fset_widx = 0; ; ++fset_widx) {
5776 uintptr_t fset_bits;
5777 if (fset_widx >= fset_word_ct_m1) {
5778 if (fset_widx > fset_word_ct_m1) {
5779 return kPglRetSuccess;
5780 }
5781 fset_bits = SubwordLoad(&(patch_10_fset[fset_word_ct_m1 * kBytesPerWord]), ModNz(fset_byte_ct, kBytesPerWord));
5782 loop_len = ModNz(raw_10_ct, kBitsPerWord);
5783 } else {
5784 CopyFromUnalignedOffsetW(&fset_bits, patch_10_fset, fset_widx);
5785 }
5786 if (!sample_include) {
5787 for (uint32_t uii = 0; uii != loop_len; ++uii) {
5788 while (!cur_raw_genoarr_xys) {
5789 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
5790 }
5791 if (fset_bits & 1) {
5792 if (rare10_lowbits == kBitsPerWord) {
5793 if (fvals_widx == fvals_word_ct_m1) {
5794 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
5795 } else {
5796 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
5797 }
5798 uintptr_t match0 = fvals_bits ^ xor_word0;
5799 uintptr_t match1 = fvals_bits ^ xor_word1;
5800 uintptr_t match2 = fvals_bits ^ xor_word2;
5801 match0 = detect_hom_mask_hi & (~(match0 | ((match0 | detect_hom_mask_hi) - detect_hom_mask_lo)));
5802 match1 = detect_hom_mask_hi & (~(match1 | ((match1 | detect_hom_mask_hi) - detect_hom_mask_lo)));
5803 match2 = detect_hom_mask_hi & (~(match2 | ((match2 | detect_hom_mask_hi) - detect_hom_mask_lo)));
5804 // Now want match0 -> 11, match1 -> 10, and match2 -> 01.
5805 fvals_bits = ((match0 | match1) >> (code10_width - 2)) | ((match0 | match2) >> (code10_width - 1));
5806 // unnecessary to apply bzhi here
5807 ++fvals_widx;
5808 rare10_lowbits = 0;
5809 }
5810 const uintptr_t xor_val = (fvals_bits >> rare10_lowbits) & 3;
5811 if (xor_val) {
5812 const uintptr_t lowbit = cur_raw_genoarr_xys & (-cur_raw_genoarr_xys);
5813 target_genoarr[sample_hwidx] ^= lowbit * xor_val;
5814 }
5815 rare10_lowbits += code10_width;
5816 }
5817 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
5818 fset_bits = fset_bits >> 1;
5819 }
5820 } else {
5821 // sample_include non-null
5822 for (uint32_t uii = 0; uii != loop_len; ++uii) {
5823 while (!cur_raw_genoarr_xys) {
5824 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
5825 }
5826 if (fset_bits & 1) {
5827 if (rare10_lowbits == kBitsPerWord) {
5828 if (fvals_widx == fvals_word_ct_m1) {
5829 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
5830 } else {
5831 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
5832 }
5833 uintptr_t match0 = fvals_bits ^ xor_word0;
5834 uintptr_t match1 = fvals_bits ^ xor_word1;
5835 uintptr_t match2 = fvals_bits ^ xor_word2;
5836 match0 = detect_hom_mask_hi & (~(match0 | ((match0 | detect_hom_mask_hi) - detect_hom_mask_lo)));
5837 match1 = detect_hom_mask_hi & (~(match1 | ((match1 | detect_hom_mask_hi) - detect_hom_mask_lo)));
5838 match2 = detect_hom_mask_hi & (~(match2 | ((match2 | detect_hom_mask_hi) - detect_hom_mask_lo)));
5839 fvals_bits = ((match0 | match1) >> (code10_width - 2)) | ((match0 | match2) >> (code10_width - 1));
5840 // unnecessary to apply bzhi here
5841 ++fvals_widx;
5842 rare10_lowbits = 0;
5843 }
5844 const uintptr_t xor_val = (fvals_bits >> rare10_lowbits) & 3;
5845 if (xor_val) {
5846 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_xys) / 2;
5847 if ((DowncastKWToHW(sample_include)[sample_hwidx]) & (1U << sample_uidx_lowbits)) {
5848 const uint32_t sample_idx = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, sample_hwidx * kBitsPerWordD2 + sample_uidx_lowbits);
5849 target_genoarr[sample_idx / kBitsPerWordD2] ^= xor_val << (2 * (sample_idx % kBitsPerWordD2));
5850 }
5851 }
5852 rare10_lowbits += code10_width;
5853 }
5854 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
5855 fset_bits = fset_bits >> 1;
5856 }
5857 }
5858 }
5859 }
5860 // aux1b_mode == 1
5861 uint32_t rare10_ct;
5862 PglErr reterr = ParseAndSaveDeltalist(fread_end, raw_sample_ct, fread_pp, deltalist_workspace, &rare10_ct);
5863 if (unlikely(reterr)) {
5864 return reterr;
5865 }
5866 const unsigned char* patch_10_fvals = *fread_pp;
5867 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare10_ct) << code10_logwidth, CHAR_BIT);
5868 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
5869 return kPglRetMalformedInput;
5870 }
5871 if (allele_idx1 == 1) {
5872 if (!sample_include) {
5873 for (uint32_t rare10_idx = 0; rare10_idx != rare10_ct; ++rare10_idx) {
5874 const uint32_t sample_uidx = deltalist_workspace[rare10_idx];
5875 target_genoarr[sample_uidx / kBitsPerWordD2] ^= k1LU << (2 * (sample_uidx % kBitsPerWordD2));
5876 }
5877 return kPglRetSuccess;
5878 }
5879 for (uint32_t rare10_idx = 0; rare10_idx != rare10_ct; ++rare10_idx) {
5880 const uint32_t sample_uidx = deltalist_workspace[rare10_idx];
5881 const uint32_t sample_widx = sample_uidx / kBitsPerWord;
5882 const uintptr_t lowbit = k1LU << (sample_uidx % kBitsPerWord);
5883 const uintptr_t sample_include_word = sample_include[sample_widx];
5884 if (sample_include_word & lowbit) {
5885 const uint32_t sample_idx = sample_include_cumulative_popcounts[sample_widx] + PopcountWord(sample_include_word & (lowbit - 1));
5886 target_genoarr[sample_idx / kBitsPerWordD2] ^= k1LU << (2 * (sample_idx % kBitsPerWordD2));
5887 }
5888 }
5889 return kPglRetSuccess;
5890 }
5891 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
5892 if (!allele_idx0) {
5893 for (uint32_t fvals_widx = 0; ; ++fvals_widx) {
5894 uintptr_t fvals_bits;
5895 if (fvals_widx >= fvals_word_ct_m1) {
5896 if (fvals_widx > fvals_word_ct_m1) {
5897 return kPglRetSuccess;
5898 }
5899 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
5900 } else {
5901 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
5902 }
5903 fvals_bits = fvals_bits ^ xor_word2;
5904 fvals_bits = detect_hom_mask_hi & (~(fvals_bits | ((fvals_bits | detect_hom_mask_hi) - detect_hom_mask_lo)));
5905 if (fvals_widx == fvals_word_ct_m1) {
5906 fvals_bits = bzhi_max(fvals_bits, ModNz(rare10_ct << code10_logwidth, kBitsPerWord));
5907 }
5908 if (!fvals_bits) {
5909 continue;
5910 }
5911 const uint32_t* cur_deltalist_base = &(deltalist_workspace[fvals_widx << (kBitsPerWordLog2 - code10_logwidth)]);
5912 if (!sample_include) {
5913 do {
5914 const uint32_t bit_idx = ctzw(fvals_bits);
5915 const uint32_t sample_uidx = cur_deltalist_base[bit_idx >> code10_logwidth];
5916 target_genoarr[sample_uidx / kBitsPerWordD2] ^= k1LU << (2 * (sample_uidx % kBitsPerWordD2));
5917 fvals_bits &= fvals_bits - 1;
5918 } while (fvals_bits);
5919 } else {
5920 do {
5921 const uint32_t bit_idx = ctzw(fvals_bits);
5922 const uint32_t sample_uidx = cur_deltalist_base[bit_idx >> code10_logwidth];
5923 const uint32_t sample_widx = sample_uidx / kBitsPerWord;
5924 const uintptr_t lowbit = k1LU << (sample_uidx % kBitsPerWord);
5925 const uintptr_t sample_include_word = sample_include[sample_widx];
5926 if (sample_include_word & lowbit) {
5927 const uint32_t sample_idx = sample_include_cumulative_popcounts[sample_widx] + PopcountWord(sample_include_word & (lowbit - 1));
5928 target_genoarr[sample_idx / kBitsPerWordD2] ^= k1LU << (2 * (sample_idx % kBitsPerWordD2));
5929 }
5930 fvals_bits &= fvals_bits - 1;
5931 } while (fvals_bits);
5932 }
5933 }
5934 }
5935 // 2 <= allele_idx0 < allele_idx1
5936 uintptr_t xor_word1 = allele_idx1 - 1;
5937 uintptr_t xor_word0 = allele_idx0 - 1;
5938 xor_word1 = xor_word0 | (xor_word1 << (code10_width / 2));
5939 xor_word0 = xor_word0 | (xor_word0 << (code10_width / 2));
5940 xor_word1 *= detect_hom_mask_lo;
5941 xor_word0 *= detect_hom_mask_lo;
5942 for (uint32_t fvals_widx = 0; ; ++fvals_widx) {
5943 uintptr_t fvals_bits;
5944 if (fvals_widx >= fvals_word_ct_m1) {
5945 if (fvals_widx > fvals_word_ct_m1) {
5946 return kPglRetSuccess;
5947 }
5948 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
5949 } else {
5950 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
5951 }
5952 uintptr_t match0 = fvals_bits ^ xor_word0;
5953 uintptr_t match1 = fvals_bits ^ xor_word1;
5954 uintptr_t match2 = fvals_bits ^ xor_word2;
5955 match0 = detect_hom_mask_hi & (~(match0 | ((match0 | detect_hom_mask_hi) - detect_hom_mask_lo)));
5956 match1 = detect_hom_mask_hi & (~(match1 | ((match1 | detect_hom_mask_hi) - detect_hom_mask_lo)));
5957 match2 = detect_hom_mask_hi & (~(match2 | ((match2 | detect_hom_mask_hi) - detect_hom_mask_lo)));
5958 // since code10_width >= 4, we can use match0 == 3 (mod 4), match1 == 2
5959 // (mod 4), match2 == 1 (mod 4) representation.
5960 fvals_bits = (match0 >> (code10_width - 4)) | (match1 >> (code10_width - 3)) | (match2 >> (code10_width - 2));
5961 if (fvals_widx == fvals_word_ct_m1) {
5962 fvals_bits = bzhi_max(fvals_bits, ModNz(rare10_ct << code10_logwidth, kBitsPerWord));
5963 }
5964 if (!fvals_bits) {
5965 continue;
5966 }
5967 const uint32_t* cur_deltalist_base = &(deltalist_workspace[fvals_widx << (kBitsPerWordLog2 - code10_logwidth)]);
5968 if (!sample_include) {
5969 do {
5970 const uintptr_t bit_idx = ctzw(fvals_bits);
5971 const uint32_t sample_uidx = cur_deltalist_base[bit_idx >> code10_logwidth];
5972 target_genoarr[sample_uidx / kBitsPerWordD2] ^= (bit_idx & 3) << (2 * (sample_uidx % kBitsPerWordD2));
5973 fvals_bits &= fvals_bits - 1;
5974 } while (fvals_bits);
5975 } else {
5976 do {
5977 const uintptr_t bit_idx = ctzw(fvals_bits);
5978 const uint32_t sample_uidx = cur_deltalist_base[bit_idx >> code10_logwidth];
5979 const uint32_t sample_widx = sample_uidx / kBitsPerWord;
5980 const uintptr_t lowbit = k1LU << (sample_uidx % kBitsPerWord);
5981 const uintptr_t sample_include_word = sample_include[sample_widx];
5982 if (sample_include_word & lowbit) {
5983 const uint32_t sample_idx = sample_include_cumulative_popcounts[sample_widx] + PopcountWord(sample_include_word & (lowbit - 1));
5984 target_genoarr[sample_idx / kBitsPerWordD2] ^= (bit_idx & 3) << (2 * (sample_idx % kBitsPerWordD2));
5985 }
5986 fvals_bits &= fvals_bits - 1;
5987 } while (fvals_bits);
5988 }
5989 }
5990 }
5991
5992 PglErr IMPLPgrGet2(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx0, uint32_t allele_idx1, PgenReaderMain* pgrp, uintptr_t* __restrict genovec) {
5993 assert(allele_idx0 != allele_idx1);
5994 if (!sample_ct) {
5995 return kPglRetSuccess;
5996 }
5997 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
5998 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
5999 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
6000 const uint32_t multiallelic_hc_present = VrtypeMultiallelicHc(vrtype);
6001 if (!multiallelic_hc_present) {
6002 if ((allele_idx0 > 1) && (allele_idx1 > 1)) {
6003 // Trivial all-missing case.
6004 SetAllBits(2 * sample_ct, genovec);
6005 return kPglRetSuccess;
6006 }
6007 PglErr reterr = ReadGenovecSubsetUnsafe(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, nullptr, nullptr, genovec);
6008 if (unlikely(reterr)) {
6009 return reterr;
6010 }
6011 if (allele_idx0 < allele_idx1) {
6012 Rotate2(allele_idx0, allele_idx1, sample_ct, genovec);
6013 return kPglRetSuccess;
6014 }
6015 if (allele_idx0 == 1) {
6016 GenovecInvertUnsafe(sample_ct, genovec);
6017 return kPglRetSuccess;
6018 }
6019 if (!allele_idx1) {
6020 GenovecNonzeroToMissingThenInvertUnsafe(sample_ct, genovec);
6021 return kPglRetSuccess;
6022 }
6023 GenovecNontwoToMissingUnsafe(sample_ct, genovec);
6024 return kPglRetSuccess;
6025 }
6026 uintptr_t* raw_genovec = pgrp->workspace_vec;
6027 const unsigned char* fread_ptr;
6028 const unsigned char* fread_end;
6029 PglErr reterr = ReadRawGenovec(subsetting_required, vidx, pgrp, &fread_ptr, &fread_end, raw_genovec);
6030 if (unlikely(reterr)) {
6031 return reterr;
6032 }
6033 ZeroTrailingNyps(raw_sample_ct, raw_genovec);
6034
6035 uint32_t invert = 0;
6036 if (allele_idx0 > allele_idx1) {
6037 const uint32_t swap = allele_idx0;
6038 allele_idx0 = allele_idx1;
6039 allele_idx1 = swap;
6040 invert = 1;
6041 }
6042 if (allele_idx0 > 1) {
6043 SetAllBits(2 * sample_ct, genovec);
6044 } else {
6045 CopyNyparrNonemptySubset(raw_genovec, sample_include, raw_sample_ct, sample_ct, genovec);
6046 Rotate2(allele_idx0, allele_idx1, sample_ct, genovec);
6047 }
6048 const uint32_t aux1_first_byte = *fread_ptr++;
6049 const uint32_t aux1a_mode = aux1_first_byte & 15;
6050 const uint32_t aux1b_mode = aux1_first_byte >> 4;
6051 uint32_t raw_01_ct = 0;
6052 uint32_t raw_10_ct = 0;
6053 if ((!aux1a_mode) || (!aux1b_mode)) {
6054 GenovecCount12Unsafe(raw_genovec, raw_sample_ct, &raw_01_ct, &raw_10_ct);
6055 }
6056 if (!subsetting_required) {
6057 sample_include = nullptr;
6058 }
6059 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
6060 const uint32_t allele_ct = allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx];
6061 uint32_t* deltalist_workspace = pgrp->workspace_difflist_sample_ids;
6062 if (!allele_idx0) {
6063 // Two cases:
6064 // - If allele_idx == 1, convert all aux1a entries from 01 to 11.
6065 // - Otherwise, for each matching aux1a entry, convert from 11 to 01.
6066 reterr = GenoarrAux1aUpdate(fread_end, sample_include, sample_include_cumulative_popcounts, raw_genovec, aux1a_mode, raw_sample_ct, allele_ct, allele_idx1, 2, raw_01_ct, &fread_ptr, genovec, deltalist_workspace);
6067 } else {
6068 reterr = SkipAux1a(fread_end, aux1a_mode, raw_sample_ct, allele_ct, raw_01_ct, &fread_ptr);
6069 }
6070 if (unlikely(reterr)) {
6071 return reterr;
6072 }
6073 reterr = GenoarrAux1bUpdate2(fread_end, sample_include, sample_include_cumulative_popcounts, raw_genovec, aux1b_mode, raw_sample_ct, allele_ct, allele_idx0, allele_idx1, raw_10_ct, &fread_ptr, genovec, deltalist_workspace);
6074 if (unlikely(reterr)) {
6075 return reterr;
6076 }
6077 if (invert) {
6078 GenovecInvertUnsafe(sample_ct, genovec);
6079 }
6080 return kPglRetSuccess;
6081 }
6082
6083 void PreinitPgv(PgenVariant* pgvp) {
6084 pgvp->genovec = nullptr;
6085 pgvp->patch_01_set = nullptr;
6086 pgvp->patch_01_vals = nullptr;
6087 pgvp->patch_10_set = nullptr;
6088 pgvp->patch_10_vals = nullptr;
6089 pgvp->phasepresent = nullptr;
6090 pgvp->phaseinfo = nullptr;
6091 pgvp->dosage_present = nullptr;
6092 pgvp->dosage_main = nullptr;
6093 pgvp->multidosage_present = nullptr;
6094 pgvp->multidosage_cts = nullptr;
6095 pgvp->multidosage_codes = nullptr;
6096 pgvp->multidosage_vals = nullptr;
6097 pgvp->dphase_present = nullptr;
6098 pgvp->dphase_delta = nullptr;
6099 pgvp->multidphase_present = nullptr;
6100 pgvp->multidphase_cts = nullptr;
6101 pgvp->multidphase_codes = nullptr;
6102 pgvp->multidphase_delta = nullptr;
6103
6104 pgvp->patch_01_ct = 0;
6105 pgvp->patch_10_ct = 0;
6106 pgvp->phasepresent_ct = 0;
6107 pgvp->dosage_ct = 0;
6108 pgvp->multidosage_sample_ct = 0;
6109 pgvp->dphase_ct = 0;
6110 pgvp->multidphase_sample_ct = 0;
6111 }
6112
6113 // similar to ParseAndSaveDifflist()
6114 PglErr ParseAndSaveDeltalistAsBitarr(const unsigned char* fread_end, uint32_t raw_sample_ct, const unsigned char** fread_pp, uintptr_t* deltalist_include, uint32_t* deltalist_len_ptr) {
6115 const unsigned char* group_info_iter;
6116 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, nullptr, &group_info_iter, deltalist_len_ptr);
6117 const uint32_t deltalist_len = *deltalist_len_ptr;
6118 if (reterr || (!deltalist_len)) {
6119 return reterr;
6120 }
6121 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(raw_sample_ct);
6122 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
6123 const uint32_t group_idx_last = (deltalist_len - 1) / kPglDifflistGroupSize;
6124 ZeroWArr(raw_sample_ctl, deltalist_include);
6125 uint32_t group_len_m1 = kPglDifflistGroupSize - 1;
6126 for (uint32_t group_idx = 0; ; ++group_idx) {
6127 if (group_idx >= group_idx_last) {
6128 if (group_idx > group_idx_last) {
6129 return kPglRetSuccess;
6130 }
6131 group_len_m1 &= deltalist_len - 1;
6132 }
6133 uintptr_t raw_sample_idx = SubU32Load(group_info_iter, sample_id_byte_ct);
6134 group_info_iter = &(group_info_iter[sample_id_byte_ct]);
6135 for (uint32_t raw_deltalist_idx_lowbits = 0; ; ++raw_deltalist_idx_lowbits) {
6136 // always check, otherwise we may scribble over arbitrary memory
6137 if (unlikely(raw_sample_idx >= raw_sample_ct)) {
6138 return kPglRetMalformedInput;
6139 }
6140 SetBit(raw_sample_idx, deltalist_include);
6141 if (raw_deltalist_idx_lowbits == group_len_m1) {
6142 break;
6143 }
6144 raw_sample_idx += GetVint31(fread_end, fread_pp);
6145 }
6146 }
6147 }
6148
6149 static_assert(sizeof(AlleleCode) == 1, "GetAux1aCodes() must be updated.");
6150 // read-buffer patch_01_vals, patch_10_vals, etc. assumed to be word-aligned.
6151 PglErr GetAux1aCodes(const unsigned char* fread_end, uint32_t rare01_ct, uint32_t allele_ct, const unsigned char** fread_pp, AlleleCode* __restrict patch_01_vals) {
6152 if (allele_ct == 3) {
6153 memset(patch_01_vals, 2, rare01_ct);
6154 return kPglRetSuccess;
6155 }
6156 const unsigned char* patch_01_fvals = *fread_pp;
6157 if (allele_ct == 4) {
6158 const uint32_t patch_01_fvals_byte_ct = DivUp(rare01_ct, CHAR_BIT);
6159 if (PtrAddCk(fread_end, patch_01_fvals_byte_ct, fread_pp)) {
6160 return kPglRetMalformedInput;
6161 }
6162 Expand1bitTo8(patch_01_fvals, rare01_ct, 2, patch_01_vals);
6163 return kPglRetSuccess;
6164 }
6165 if (allele_ct < 7) {
6166 const uint32_t patch_01_fvals_byte_ct = DivUp(rare01_ct, 4);
6167 if (PtrAddCk(fread_end, patch_01_fvals_byte_ct, fread_pp)) {
6168 return kPglRetMalformedInput;
6169 }
6170 Expand2bitTo8(patch_01_fvals, rare01_ct, 2, patch_01_vals);
6171 return kPglRetSuccess;
6172 }
6173 if (allele_ct < 19) {
6174 const uint32_t patch_01_fvals_byte_ct = DivUp(rare01_ct, 2);
6175 if (PtrAddCk(fread_end, patch_01_fvals_byte_ct, fread_pp)) {
6176 return kPglRetMalformedInput;
6177 }
6178 Expand4bitTo8(patch_01_fvals, rare01_ct, 2, patch_01_vals);
6179 return kPglRetSuccess;
6180 }
6181 if (PtrAddCk(fread_end, rare01_ct, fread_pp)) {
6182 return kPglRetMalformedInput;
6183 }
6184 // todo: verify the compiler recognizes this
6185 for (uint32_t uii = 0; uii < rare01_ct; ++uii) {
6186 patch_01_vals[uii] = patch_01_fvals[uii] + 2;
6187 }
6188 return kPglRetSuccess;
6189 }
6190
6191 // Assumes aux1a_mode != 15.
6192 PglErr ExportAux1a(const unsigned char* fread_end, const uintptr_t* __restrict raw_genoarr, uint32_t aux1a_mode, uint32_t raw_sample_ct, uint32_t allele_ct, uint32_t raw_01_ct, const unsigned char** fread_pp, uintptr_t* __restrict patch_01_set, AlleleCode* __restrict patch_01_vals, uint32_t* __restrict rare01_ctp) {
6193 uint32_t rare01_ct;
6194 if (!aux1a_mode) {
6195 const unsigned char* patch_01_fset = *fread_pp;
6196 const uint32_t fset_byte_ct = DivUp(raw_01_ct, CHAR_BIT);
6197 if (PtrAddCk(fread_end, fset_byte_ct, fread_pp)) {
6198 return kPglRetMalformedInput;
6199 }
6200 rare01_ct = PopcountBytes(patch_01_fset, fset_byte_ct);
6201 ExpandBytearrFromGenoarr(patch_01_fset, raw_genoarr, kMask5555, NypCtToWordCt(raw_sample_ct), raw_01_ct, 0, patch_01_set);
6202 } else {
6203 if (unlikely(ParseAndSaveDeltalistAsBitarr(fread_end, raw_sample_ct, fread_pp, patch_01_set, &rare01_ct))) {
6204 return kPglRetMalformedInput;
6205 }
6206 }
6207 *rare01_ctp = rare01_ct;
6208 return GetAux1aCodes(fread_end, rare01_ct, allele_ct, fread_pp, patch_01_vals);
6209 }
6210
6211 PglErr ExportAux1aProperSubset(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, const uintptr_t* __restrict raw_genoarr, uint32_t aux1a_mode, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t allele_ct, uint32_t raw_01_ct, const unsigned char** fread_pp, uintptr_t* __restrict dst_01_set, AlleleCode* __restrict dst_01_vals, uint32_t* __restrict rare01_ctp, uint32_t* __restrict deltalist_workspace) {
6212 const uint32_t allele_code_width = GetAux1aWidth(allele_ct);
6213 const uintptr_t allele_code_mask = (1U << allele_code_width) - 1;
6214 memset(dst_01_set, 0, BitCtToWordCt(sample_ct) * sizeof(intptr_t));
6215 AlleleCode* dst_01_vals_iter = dst_01_vals;
6216 if (!aux1a_mode) {
6217 // similar to GenoarrAux1aUpdate()
6218 const unsigned char* patch_01_fset = *fread_pp;
6219 const uint32_t fset_byte_ct = DivUp(raw_01_ct, CHAR_BIT);
6220 const uint32_t rare01_ct = PopcountBytes(patch_01_fset, fset_byte_ct);
6221 if (PtrAddCk(fread_end, fset_byte_ct, fread_pp)) {
6222 return kPglRetMalformedInput;
6223 }
6224 const unsigned char* patch_01_fvals = *fread_pp;
6225 uintptr_t sample_hwidx = 0;
6226 uintptr_t cur_raw_genoarr_hets = Word01(raw_genoarr[0]);
6227 uint32_t loop_len = kBitsPerWord;
6228 const uintptr_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare01_ct) * allele_code_width, 8);
6229 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
6230 return kPglRetMalformedInput;
6231 }
6232 const uint32_t fset_word_ct_m1 = (fset_byte_ct - 1) / kBytesPerWord;
6233 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
6234 uintptr_t fvals_bits = 0;
6235 uint32_t fvals_widx = 0;
6236 uint32_t rare01_lowbits = kBitsPerWord;
6237 for (uint32_t fset_widx = 0; ; ++fset_widx) {
6238 uintptr_t fset_bits;
6239 if (fset_widx >= fset_word_ct_m1) {
6240 if (fset_widx > fset_word_ct_m1) {
6241 break;
6242 }
6243 fset_bits = SubwordLoad(&(patch_01_fset[fset_word_ct_m1 * kBytesPerWord]), ModNz(fset_byte_ct, kBytesPerWord));
6244 loop_len = ModNz(raw_01_ct, kBitsPerWord);
6245 } else {
6246 CopyFromUnalignedOffsetW(&fset_bits, patch_01_fset, fset_widx);
6247 }
6248 if (allele_ct == 3) {
6249 for (uint32_t uii = 0; uii != loop_len; ++uii) {
6250 while (!cur_raw_genoarr_hets) {
6251 cur_raw_genoarr_hets = Word01(raw_genoarr[++sample_hwidx]);
6252 }
6253 if (fset_bits & 1) {
6254 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_hets) / 2;
6255 if ((DowncastKWToHW(sample_include)[sample_hwidx]) & (1U << sample_uidx_lowbits)) {
6256 const uint32_t sample_idx = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, sample_hwidx * kBitsPerWordD2 + sample_uidx_lowbits);
6257 SetBit(sample_idx, dst_01_set);
6258 *dst_01_vals_iter++ = 2;
6259 }
6260 }
6261 cur_raw_genoarr_hets &= cur_raw_genoarr_hets - 1;
6262 fset_bits = fset_bits >> 1;
6263 }
6264 } else {
6265 for (uint32_t uii = 0; uii != loop_len; ++uii) {
6266 while (!cur_raw_genoarr_hets) {
6267 cur_raw_genoarr_hets = Word01(raw_genoarr[++sample_hwidx]);
6268 }
6269 if (fset_bits & 1) {
6270 if (rare01_lowbits == kBitsPerWord) {
6271 if (fvals_widx == fvals_word_ct_m1) {
6272 fvals_bits = SubwordLoad(&(patch_01_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
6273 } else {
6274 CopyFromUnalignedOffsetW(&fvals_bits, patch_01_fvals, fvals_widx);
6275 }
6276 // unnecessary to apply bzhi here
6277 ++fvals_widx;
6278 rare01_lowbits = 0;
6279 }
6280 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_hets) / 2;
6281 if ((DowncastKWToHW(sample_include)[sample_hwidx]) & (1U << sample_uidx_lowbits)) {
6282 const uint32_t sample_idx = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, sample_hwidx * kBitsPerWordD2 + sample_uidx_lowbits);
6283 SetBit(sample_idx, dst_01_set);
6284 *dst_01_vals_iter++ = 2 + ((fvals_bits >> rare01_lowbits) & allele_code_mask);
6285 }
6286 rare01_lowbits += allele_code_width;
6287 }
6288 cur_raw_genoarr_hets &= cur_raw_genoarr_hets - 1;
6289 fset_bits = fset_bits >> 1;
6290 }
6291 }
6292 }
6293 *rare01_ctp = dst_01_vals_iter - dst_01_vals;
6294 return kPglRetSuccess;
6295 }
6296 // aux1a_mode == 1
6297 uint32_t rare01_ct;
6298 PglErr reterr = ParseAndSaveDeltalist(fread_end, raw_sample_ct, fread_pp, deltalist_workspace, &rare01_ct);
6299 if (unlikely(reterr)) {
6300 return reterr;
6301 }
6302 const unsigned char* patch_01_fvals = *fread_pp;
6303 const uintptr_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare01_ct) * allele_code_width, 8);
6304 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
6305 return kPglRetMalformedInput;
6306 }
6307 if (allele_ct == 3) {
6308 for (uint32_t rare01_idx = 0; rare01_idx != rare01_ct; ++rare01_idx) {
6309 const uint32_t sample_uidx = deltalist_workspace[rare01_idx];
6310 // could wrap this boilerplate
6311 const uint32_t sample_widx = sample_uidx / kBitsPerWord;
6312 const uintptr_t lowbit = k1LU << (sample_uidx % kBitsPerWord);
6313 const uintptr_t sample_include_word = sample_include[sample_widx];
6314 if (sample_include_word & lowbit) {
6315 const uint32_t sample_idx = sample_include_cumulative_popcounts[sample_widx] + PopcountWord(sample_include_word & (lowbit - 1));
6316 SetBit(sample_idx, dst_01_set);
6317 *dst_01_vals_iter++ = 2;
6318 }
6319 }
6320 *rare01_ctp = dst_01_vals_iter - dst_01_vals;
6321 return kPglRetSuccess;
6322 }
6323 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
6324 const uint32_t allele_code_logwidth = ctzu32(allele_code_width);
6325 uint32_t loop_len = kBitsPerWord >> allele_code_logwidth;
6326 for (uint32_t fvals_widx = 0; ; ++fvals_widx) {
6327 uintptr_t fvals_bits;
6328 if (fvals_widx >= fvals_word_ct_m1) {
6329 if (fvals_widx > fvals_word_ct_m1) {
6330 break;
6331 }
6332 fvals_bits = SubwordLoad(&(patch_01_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
6333 loop_len = 1 + ((rare01_ct - 1) & (loop_len - 1));
6334 } else {
6335 CopyFromUnalignedOffsetW(&fvals_bits, patch_01_fvals, fvals_widx);
6336 }
6337 const uint32_t* cur_deltalist_base = &(deltalist_workspace[fvals_widx << (kBitsPerWordLog2 - allele_code_logwidth)]);
6338 for (uint32_t uii = 0; uii != loop_len; ++uii) {
6339 const uint32_t sample_uidx = cur_deltalist_base[uii];
6340 const uint32_t sample_widx = sample_uidx / kBitsPerWord;
6341 const uintptr_t lowbit = k1LU << (sample_uidx % kBitsPerWord);
6342 const uintptr_t sample_include_word = sample_include[sample_widx];
6343 if (sample_include_word & lowbit) {
6344 const uint32_t sample_idx = sample_include_cumulative_popcounts[sample_widx] + PopcountWord(sample_include_word & (lowbit - 1));
6345 SetBit(sample_idx, dst_01_set);
6346 *dst_01_vals_iter++ = 2 + ((fvals_bits >> (uii << allele_code_logwidth)) & allele_code_mask);
6347 }
6348 }
6349 }
6350 *rare01_ctp = dst_01_vals_iter - dst_01_vals;
6351 return kPglRetSuccess;
6352 }
6353
6354 static_assert(sizeof(AlleleCode) == 1, "GetAux1bCodes() must be updated.");
6355 PglErr GetAux1bCodes(const unsigned char* fread_end, uint32_t rare10_ct, uint32_t allele_ct, const unsigned char** fread_pp, AlleleCode* __restrict patch_10_vals) {
6356 const unsigned char* patch_10_fvals = *fread_pp;
6357 if (allele_ct == 3) {
6358 // 1 bit, distinguishes between 0x0201 and 0x0202
6359 const uint32_t patch_10_fvals_byte_ct = DivUp(rare10_ct, CHAR_BIT);
6360 if (PtrAddCk(fread_end, patch_10_fvals_byte_ct, fread_pp)) {
6361 return kPglRetMalformedInput;
6362 }
6363 Expand1bitTo16(patch_10_fvals, rare10_ct, 0x0201, patch_10_vals);
6364 return kPglRetSuccess;
6365 }
6366 const uint32_t rare10_ct_x2 = rare10_ct * 2;
6367 if (allele_ct < 6) {
6368 // 2+2 bits, add 1
6369 const uint32_t patch_10_fvals_byte_ct = DivUp(rare10_ct, 2);
6370 if (PtrAddCk(fread_end, patch_10_fvals_byte_ct, fread_pp)) {
6371 return kPglRetMalformedInput;
6372 }
6373 Expand2bitTo8(patch_10_fvals, rare10_ct_x2, 1, patch_10_vals);
6374 return kPglRetSuccess;
6375 }
6376 if (allele_ct < 18) {
6377 // 4+4 bits
6378 if (PtrAddCk(fread_end, rare10_ct, fread_pp)) {
6379 return kPglRetMalformedInput;
6380 }
6381 Expand4bitTo8(patch_10_fvals, rare10_ct_x2, 1, patch_10_vals);
6382 return kPglRetSuccess;
6383 }
6384 if (PtrAddCk(fread_end, rare10_ct_x2, fread_pp)) {
6385 return kPglRetMalformedInput;
6386 }
6387 // todo: verify the compiler recognizes this
6388 for (uint32_t uii = 0; uii < rare10_ct_x2; ++uii) {
6389 patch_10_vals[uii] = patch_10_fvals[uii] + 1;
6390 }
6391 return kPglRetSuccess;
6392 }
6393
6394 // Assumes aux1b_mode != 15.
6395 PglErr ExportAux1b(const unsigned char* fread_end, const uintptr_t* __restrict raw_genoarr, uint32_t aux1b_mode, uint32_t raw_sample_ct, uint32_t allele_ct, uint32_t raw_10_ct, const unsigned char** fread_pp, uintptr_t* __restrict patch_10_set, AlleleCode* __restrict patch_10_vals, uint32_t* __restrict rare10_ctp) {
6396 uint32_t rare10_ct;
6397 if (!aux1b_mode) {
6398 const unsigned char* patch_10_fset = *fread_pp;
6399 const uint32_t fset_byte_ct = DivUp(raw_10_ct, CHAR_BIT);
6400 if (PtrAddCk(fread_end, fset_byte_ct, fread_pp)) {
6401 return kPglRetMalformedInput;
6402 }
6403 rare10_ct = PopcountBytes(patch_10_fset, fset_byte_ct);
6404 ExpandBytearrFromGenoarr(patch_10_fset, raw_genoarr, kMaskAAAA, NypCtToWordCt(raw_sample_ct), raw_10_ct, 0, patch_10_set);
6405 } else {
6406 if (unlikely(ParseAndSaveDeltalistAsBitarr(fread_end, raw_sample_ct, fread_pp, patch_10_set, &rare10_ct))) {
6407 return kPglRetMalformedInput;
6408 }
6409 }
6410 *rare10_ctp = rare10_ct;
6411 return GetAux1bCodes(fread_end, rare10_ct, allele_ct, fread_pp, patch_10_vals);
6412 }
6413
6414 PglErr ExportAux1bProperSubset(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, const uintptr_t* __restrict raw_genoarr, uint32_t aux1b_mode, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t allele_ct, uint32_t raw_10_ct, const unsigned char** fread_pp, uintptr_t* __restrict dst_10_set, AlleleCode* __restrict dst_10_vals, uint32_t* __restrict rare10_ctp, uint32_t* __restrict deltalist_workspace) {
6415 uintptr_t detect_hom_mask_lo; // unused
6416 const uint32_t allele_code_logwidth = GetAux1bConsts(allele_ct, &detect_hom_mask_lo);
6417 const uint32_t allele_code_width = 1U << allele_code_logwidth;
6418 const uintptr_t allele_code_mask = (1U << allele_code_width) - 1;
6419 const uint32_t code10_logwidth = allele_code_logwidth + (allele_code_logwidth != 0);
6420 const uint32_t code10_width = 1U << code10_logwidth;
6421 memset(dst_10_set, 0, BitCtToWordCt(sample_ct) * sizeof(intptr_t));
6422 AlleleCode* dst_10_vals_iter = dst_10_vals;
6423 if (!aux1b_mode) {
6424 const unsigned char* patch_10_fset = *fread_pp;
6425 const uint32_t fset_byte_ct = DivUp(raw_10_ct, CHAR_BIT);
6426 const uint32_t rare10_ct = PopcountBytes(patch_10_fset, fset_byte_ct);
6427 if (PtrAddCk(fread_end, fset_byte_ct, fread_pp)) {
6428 return kPglRetMalformedInput;
6429 }
6430 const unsigned char* patch_10_fvals = *fread_pp;
6431 uintptr_t sample_hwidx = 0;
6432 uintptr_t cur_raw_genoarr_xys = Word10(raw_genoarr[0]);
6433 uint32_t loop_len = kBitsPerWord;
6434 const uintptr_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare10_ct) * code10_width, 8);
6435 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
6436 return kPglRetMalformedInput;
6437 }
6438 const uint32_t fset_word_ct_m1 = (fset_byte_ct - 1) / kBytesPerWord;
6439 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
6440 uintptr_t fvals_bits = 0;
6441 uint32_t fvals_widx = 0;
6442 uint32_t rare10_lowbits = kBitsPerWord;
6443 for (uint32_t fset_widx = 0; ; ++fset_widx) {
6444 uintptr_t fset_bits;
6445 if (fset_widx >= fset_word_ct_m1) {
6446 if (fset_widx > fset_word_ct_m1) {
6447 break;
6448 }
6449 fset_bits = SubwordLoad(&(patch_10_fset[fset_word_ct_m1 * kBytesPerWord]), ModNz(fset_byte_ct, kBytesPerWord));
6450 loop_len = ModNz(raw_10_ct, kBitsPerWord);
6451 } else {
6452 CopyFromUnalignedOffsetW(&fset_bits, patch_10_fset, fset_widx);
6453 }
6454 if (allele_ct == 3) {
6455 for (uint32_t uii = 0; uii != loop_len; ++uii) {
6456 while (!cur_raw_genoarr_xys) {
6457 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
6458 }
6459 if (fset_bits & 1) {
6460 if (rare10_lowbits == kBitsPerWord) {
6461 if (fvals_widx == fvals_word_ct_m1) {
6462 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
6463 } else {
6464 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
6465 }
6466 // unnecessary to apply bzhi here
6467 ++fvals_widx;
6468 rare10_lowbits = 0;
6469 }
6470 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_xys) / 2;
6471 if ((DowncastKWToHW(sample_include)[sample_hwidx]) & (1U << sample_uidx_lowbits)) {
6472 const uint32_t sample_idx = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, sample_hwidx * kBitsPerWordD2 + sample_uidx_lowbits);
6473 SetBit(sample_idx, dst_10_set);
6474 *dst_10_vals_iter++ = 1 + ((fvals_bits >> rare10_lowbits) & 1);
6475 *dst_10_vals_iter++ = 2;
6476 }
6477 ++rare10_lowbits;
6478 }
6479 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
6480 fset_bits = fset_bits >> 1;
6481 }
6482 } else {
6483 for (uint32_t uii = 0; uii != loop_len; ++uii) {
6484 while (!cur_raw_genoarr_xys) {
6485 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
6486 }
6487 if (fset_bits & 1) {
6488 if (rare10_lowbits == kBitsPerWord) {
6489 if (fvals_widx == fvals_word_ct_m1) {
6490 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
6491 } else {
6492 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
6493 }
6494 // unnecessary to apply bzhi here
6495 ++fvals_widx;
6496 rare10_lowbits = 0;
6497 }
6498 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_xys) / 2;
6499 if ((DowncastKWToHW(sample_include)[sample_hwidx]) & (1U << sample_uidx_lowbits)) {
6500 const uint32_t sample_idx = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, sample_hwidx * kBitsPerWordD2 + sample_uidx_lowbits);
6501 SetBit(sample_idx, dst_10_set);
6502 const uintptr_t cur_code_pair = fvals_bits >> rare10_lowbits;
6503 const uint32_t cur_code_hi = (cur_code_pair >> allele_code_width) & allele_code_mask;
6504 const uint32_t cur_code_lo = cur_code_pair & allele_code_mask;
6505 *dst_10_vals_iter++ = 1 + cur_code_lo;
6506 *dst_10_vals_iter++ = 1 + cur_code_hi;
6507 }
6508 rare10_lowbits += code10_width;
6509 }
6510 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
6511 fset_bits = fset_bits >> 1;
6512 }
6513 }
6514 }
6515 *rare10_ctp = S_CAST(uintptr_t, dst_10_vals_iter - dst_10_vals) / 2;
6516 return kPglRetSuccess;
6517 }
6518 // aux1b_mode == 1
6519 uint32_t rare10_ct;
6520 PglErr reterr = ParseAndSaveDeltalist(fread_end, raw_sample_ct, fread_pp, deltalist_workspace, &rare10_ct);
6521 if (unlikely(reterr)) {
6522 return reterr;
6523 }
6524 const unsigned char* patch_10_fvals = *fread_pp;
6525 const uintptr_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare10_ct) << code10_logwidth, 8);
6526 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
6527 return kPglRetMalformedInput;
6528 }
6529 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
6530 uint32_t loop_len = kBitsPerWord >> code10_logwidth;
6531 for (uint32_t fvals_widx = 0; ; ++fvals_widx) {
6532 uintptr_t fvals_bits;
6533 if (fvals_widx >= fvals_word_ct_m1) {
6534 if (fvals_widx > fvals_word_ct_m1) {
6535 break;
6536 }
6537 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
6538 loop_len = 1 + ((rare10_ct - 1) & (loop_len - 1));
6539 } else {
6540 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
6541 }
6542 const uint32_t* cur_deltalist_base = &(deltalist_workspace[fvals_widx << (kBitsPerWordLog2 - code10_logwidth)]);
6543 if (allele_ct == 3) {
6544 for (uint32_t uii = 0; uii != loop_len; ++uii) {
6545 const uint32_t sample_uidx = cur_deltalist_base[uii];
6546 const uint32_t sample_widx = sample_uidx / kBitsPerWord;
6547 const uintptr_t lowbit = k1LU << (sample_uidx % kBitsPerWord);
6548 const uintptr_t sample_include_word = sample_include[sample_widx];
6549 if (sample_include_word & lowbit) {
6550 const uint32_t sample_idx = sample_include_cumulative_popcounts[sample_widx] + PopcountWord(sample_include_word & (lowbit - 1));
6551 SetBit(sample_idx, dst_10_set);
6552 *dst_10_vals_iter++ = 1 + ((fvals_bits >> uii) & 1);
6553 *dst_10_vals_iter++ = 2;
6554 }
6555 }
6556 } else {
6557 for (uint32_t uii = 0; uii != loop_len; ++uii) {
6558 const uint32_t sample_uidx = cur_deltalist_base[uii];
6559 const uint32_t sample_widx = sample_uidx / kBitsPerWord;
6560 const uintptr_t lowbit = k1LU << (sample_uidx % kBitsPerWord);
6561 const uintptr_t sample_include_word = sample_include[sample_widx];
6562 if (sample_include_word & lowbit) {
6563 const uint32_t sample_idx = sample_include_cumulative_popcounts[sample_widx] + PopcountWord(sample_include_word & (lowbit - 1));
6564 SetBit(sample_idx, dst_10_set);
6565 const uintptr_t cur_code_pair = fvals_bits >> (uii << code10_logwidth);
6566 const uint32_t cur_code_hi = (cur_code_pair >> allele_code_width) & allele_code_mask;
6567 const uint32_t cur_code_lo = cur_code_pair & allele_code_mask;
6568 *dst_10_vals_iter++ = 1 + cur_code_lo;
6569 *dst_10_vals_iter++ = 1 + cur_code_hi;
6570 }
6571 }
6572 }
6573 }
6574 *rare10_ctp = S_CAST(uintptr_t, dst_10_vals_iter - dst_10_vals) / 2;
6575 return kPglRetSuccess;
6576 }
6577
6578 // Assumes sample_ct > 0, multiallelic-hc track is present, and patch_01_ct and
6579 // patch_10_ct are zero-initialized.
6580 PglErr GetMultiallelicCodes(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, PgenReaderMain* pgrp, const unsigned char** fread_pp, const unsigned char** fread_endp, uintptr_t* __restrict all_hets, PgenVariant* pgvp) {
6581 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
6582 uint32_t subsetting_required = (sample_ct != raw_sample_ct);
6583 uintptr_t* raw_genovec = pgrp->workspace_vec;
6584 const unsigned char* fread_ptr;
6585 const unsigned char* fread_end;
6586 PglErr reterr = ReadRawGenovec(subsetting_required, vidx, pgrp, &fread_ptr, &fread_end, raw_genovec);
6587 if (unlikely(reterr)) {
6588 return reterr;
6589 }
6590 CopyNyparrNonemptySubset(raw_genovec, sample_include, raw_sample_ct, sample_ct, pgvp->genovec);
6591 ZeroTrailingNyps(raw_sample_ct, raw_genovec);
6592 const uint32_t aux1_first_byte = *fread_ptr++;
6593 const uint32_t aux1a_mode = aux1_first_byte & 15;
6594 const uint32_t aux1b_mode = aux1_first_byte >> 4;
6595 uint32_t raw_01_ct = 0;
6596 uint32_t raw_10_ct = 0;
6597 if ((!aux1a_mode) || (!aux1b_mode)) {
6598 GenovecCount12Unsafe(raw_genovec, raw_sample_ct, &raw_01_ct, &raw_10_ct);
6599 }
6600 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
6601 const uint32_t allele_ct = allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx];
6602 uint32_t* deltalist_workspace = pgrp->workspace_difflist_sample_ids;
6603 if (aux1a_mode != 15) {
6604 if (!subsetting_required) {
6605 reterr = ExportAux1a(fread_end, raw_genovec, aux1a_mode, raw_sample_ct, allele_ct, raw_01_ct, &fread_ptr, pgvp->patch_01_set, pgvp->patch_01_vals, &(pgvp->patch_01_ct));
6606 } else {
6607 reterr = ExportAux1aProperSubset(fread_end, sample_include, sample_include_cumulative_popcounts, raw_genovec, aux1a_mode, raw_sample_ct, sample_ct, allele_ct, raw_01_ct, &fread_ptr, pgvp->patch_01_set, pgvp->patch_01_vals, &(pgvp->patch_01_ct), deltalist_workspace);
6608 }
6609 if (unlikely(reterr)) {
6610 return reterr;
6611 }
6612 }
6613 const unsigned char* aux1b_start = fread_ptr;
6614 if (aux1b_mode != 15) {
6615 if (!subsetting_required) {
6616 reterr = ExportAux1b(fread_end, raw_genovec, aux1b_mode, raw_sample_ct, allele_ct, raw_10_ct, &fread_ptr, pgvp->patch_10_set, pgvp->patch_10_vals, &(pgvp->patch_10_ct));
6617 } else {
6618 reterr = ExportAux1bProperSubset(fread_end, sample_include, sample_include_cumulative_popcounts, raw_genovec, aux1b_mode, raw_sample_ct, sample_ct, allele_ct, raw_10_ct, &fread_ptr, pgvp->patch_10_set, pgvp->patch_10_vals, &(pgvp->patch_10_ct), deltalist_workspace);
6619 }
6620 if (unlikely(reterr)) {
6621 return reterr;
6622 }
6623 }
6624 if (fread_pp) {
6625 *fread_pp = fread_ptr;
6626 *fread_endp = fread_end;
6627 if (all_hets) {
6628 PgrDetectGenoarrHets(raw_genovec, raw_sample_ct, all_hets);
6629 if (aux1b_mode != 15) {
6630 // can merge this with ExportAux1b functions later
6631 uintptr_t* aux1b_hets = pgrp->workspace_aux1x_present;
6632 uint32_t aux1b_het_present;
6633 reterr = GetAux1bHets(fread_end, raw_genovec, aux1b_mode, raw_sample_ct, allele_ct, raw_10_ct, &aux1b_start, aux1b_hets, &aux1b_het_present, deltalist_workspace);
6634 if (unlikely(reterr)) {
6635 return reterr;
6636 }
6637 if (aux1b_het_present) {
6638 BitvecOr(aux1b_hets, BitCtToWordCt(raw_sample_ct), all_hets);
6639 }
6640 }
6641 }
6642 }
6643 return kPglRetSuccess;
6644 }
6645
6646 PglErr PgrGetM(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, PgenVariant* pgvp) {
6647 pgvp->patch_01_ct = 0;
6648 pgvp->patch_10_ct = 0;
6649 if (!sample_ct) {
6650 return kPglRetSuccess;
6651 }
6652 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
6653 const uint32_t* sample_include_cumulative_popcounts = GetSicp(pssi);
6654 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
6655 const uint32_t multiallelic_hc_present = VrtypeMultiallelicHc(vrtype);
6656 if (!multiallelic_hc_present) {
6657 return ReadGenovecSubsetUnsafe(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, nullptr, nullptr, pgvp->genovec);
6658 }
6659 return GetMultiallelicCodes(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, nullptr, nullptr, nullptr, pgvp);
6660 }
6661
6662 void PgrDetectGenoarrHetsMultiallelic(const uintptr_t* __restrict genoarr, const uintptr_t* __restrict patch_10_set, const AlleleCode* __restrict patch_10_vals, uint32_t raw_sample_ct, uintptr_t* __restrict all_hets) {
6663 const Halfword* patch_10_set_alias = DowncastKWToHW(patch_10_set);
6664 const AlleleCode* patch_10_vals_iter = patch_10_vals;
6665 const uint32_t word_ct_m1 = (raw_sample_ct - 1) / kBitsPerWordD2;
6666 Halfword* all_hets_hw = DowncastWToHW(all_hets);
6667 for (uint32_t widx = 0; ; ++widx) {
6668 uintptr_t cur_geno_word;
6669 if (widx >= word_ct_m1) {
6670 if (widx > word_ct_m1) {
6671 if (widx % 2) {
6672 all_hets_hw[widx] = 0;
6673 }
6674 return;
6675 }
6676 const uint32_t final_ct = ModNz(raw_sample_ct, kBitsPerWordD2);
6677 cur_geno_word = bzhi_max(genoarr[widx], 2 * final_ct);
6678 } else {
6679 cur_geno_word = genoarr[widx];
6680 }
6681 uint32_t patch_10_hw = patch_10_set_alias[widx];
6682 uint32_t cur_hets = Pack01ToHalfword(cur_geno_word);
6683 while (patch_10_hw) {
6684 const AlleleCode code1 = *patch_10_vals_iter++;
6685 const AlleleCode code2 = *patch_10_vals_iter++;
6686 const uint32_t lowbit = patch_10_hw & (-patch_10_hw);
6687 if (code1 != code2) {
6688 cur_hets |= lowbit;
6689 }
6690 patch_10_hw ^= lowbit;
6691 }
6692 all_hets_hw[widx] = cur_hets;
6693 }
6694 }
6695
6696 PglErr SkipAux1b(const unsigned char* fread_end, uint32_t aux1b_mode, uint32_t raw_sample_ct, uint32_t allele_ct, uint32_t raw_10_ct, const unsigned char** fread_pp) {
6697 if (aux1b_mode == 15) {
6698 return kPglRetSuccess;
6699 }
6700 uint32_t rare10_ct;
6701 if (!aux1b_mode) {
6702 const uint32_t fset_byte_ct = DivUp(raw_10_ct, CHAR_BIT);
6703 rare10_ct = PopcountBytes(*fread_pp, fset_byte_ct);
6704 *fread_pp += fset_byte_ct;
6705 } else {
6706 const unsigned char* group_info_iter;
6707 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, nullptr, &group_info_iter, &rare10_ct);
6708 if (unlikely(reterr)) {
6709 return reterr;
6710 }
6711 reterr = SkipDeltalistIds(fread_end, group_info_iter, rare10_ct, raw_sample_ct, 0, fread_pp);
6712 if (unlikely(reterr)) {
6713 return reterr;
6714 }
6715 }
6716 const uint32_t fvals_byte_ct = GetAux1bAlleleEntryByteCt(allele_ct, rare10_ct);
6717 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
6718 return kPglRetMalformedInput;
6719 }
6720 return kPglRetSuccess;
6721 }
6722
6723 PglErr SkipAux1(const unsigned char* fread_end, const uintptr_t* __restrict raw_genovec, uint32_t raw_sample_ct, uint32_t allele_ct, const unsigned char** fread_pp) {
6724 const uint32_t aux1_first_byte = **fread_pp;
6725 (*fread_pp) += 1;
6726 const uint32_t aux1a_mode = aux1_first_byte & 15;
6727 const uint32_t aux1b_mode = aux1_first_byte >> 4;
6728 uint32_t raw_01_ct = 0;
6729 uint32_t raw_10_ct = 0;
6730 if ((!aux1a_mode) || (!aux1b_mode)) {
6731 GenovecCount12Unsafe(raw_genovec, raw_sample_ct, &raw_01_ct, &raw_10_ct);
6732 }
6733 PglErr reterr = SkipAux1a(fread_end, aux1a_mode, raw_sample_ct, allele_ct, raw_01_ct, fread_pp);
6734 if (unlikely(reterr)) {
6735 return reterr;
6736 }
6737 return SkipAux1b(fread_end, aux1b_mode, raw_sample_ct, allele_ct, raw_10_ct, fread_pp);
6738 }
6739
6740 // sample_include assumed to be nullptr if no subsetting required
6741 // subsetted_suppressed_het should only be provided when you explicitly want to
6742 // exclude those phase entries
6743 // set phasepresent == phaseinfo == nullptr if you want to skip the entire
6744 // track; ok for phasepresent_ct_ptr to be nullptr too in that case
6745 // (also see SkipAux2() and GetPhasepresentAndSkipPhaseinfo() below)
6746 PglErr ParseAux2Subset(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uintptr_t* __restrict all_hets, const uintptr_t* __restrict subsetted_suppressed_het, uint32_t raw_sample_ct, uint32_t sample_ct, const unsigned char** fread_pp, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo, uint32_t* __restrict phasepresent_ct_ptr, uintptr_t* __restrict workspace_subset) {
6747 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
6748 const uint32_t het_ct = PopcountWords(all_hets, raw_sample_ctl);
6749 if (unlikely(!het_ct)) {
6750 // there shouldn't be a hphase track at all in this case, het_ct is not
6751 // computed off a subset
6752 return kPglRetMalformedInput;
6753 }
6754 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
6755 const unsigned char* aux2_start = *fread_pp;
6756 if (!(aux2_start[0] & 1)) {
6757 // phase always present
6758 if (PtrAddCk(fread_end, 1 + (het_ct / CHAR_BIT), fread_pp)) {
6759 return kPglRetMalformedInput;
6760 }
6761 if (!phaseinfo) {
6762 // for internal callers which just want to skip aux2
6763 return kPglRetSuccess;
6764 }
6765 if (!sample_include) {
6766 memcpy(phasepresent, all_hets, raw_sample_ctl * kBytesPerWord);
6767 ExpandBytearr(aux2_start, all_hets, raw_sample_ctl, het_ct, 1, phaseinfo);
6768 if (!subsetted_suppressed_het) {
6769 *phasepresent_ct_ptr = het_ct;
6770 return kPglRetSuccess;
6771 }
6772 } else {
6773 CopyBitarrSubset(all_hets, sample_include, sample_ct, phasepresent);
6774 if (AllWordsAreZero(phasepresent, sample_ctl)) {
6775 *phasepresent_ct_ptr = 0;
6776 // bugfix (7 Dec 2017): clear sample_ctl words here, not raw_sample_ctl
6777 ZeroWArr(sample_ctl, phaseinfo);
6778 return kPglRetSuccess;
6779 }
6780 ExpandThenSubsetBytearr(aux2_start, all_hets, sample_include, het_ct, sample_ct, 1, phaseinfo);
6781 }
6782 // bugfix (25 Feb 2020): forgot to mask out subsetted_suppressed_het here
6783 } else {
6784 const uint32_t het_ctdl = het_ct / kBitsPerWord;
6785
6786 // explicit phasepresent
6787 uintptr_t* aux2_first_part_copy = workspace_subset;
6788 aux2_first_part_copy[het_ctdl] = 0;
6789 memcpy(aux2_first_part_copy, aux2_start, 1 + (het_ct / CHAR_BIT));
6790 const uint32_t raw_phasepresent_ct = PopcountWords(aux2_first_part_copy, het_ctdl + 1) - 1;
6791 if (unlikely(!raw_phasepresent_ct)) {
6792 // there shouldn't be a hphase track at all in this case
6793 return kPglRetMalformedInput;
6794 }
6795 const unsigned char* aux2_second_part = &(aux2_start[1 + (het_ct / CHAR_BIT)]);
6796 *fread_pp = aux2_second_part;
6797 if (PtrAddCk(fread_end, DivUp(raw_phasepresent_ct, CHAR_BIT), fread_pp)) {
6798 return kPglRetMalformedInput;
6799 }
6800 if (!phaseinfo) {
6801 return kPglRetSuccess;
6802 }
6803 if (!sample_include) {
6804 ExpandBytearrNested(aux2_second_part, aux2_first_part_copy, all_hets, sample_ctl, raw_phasepresent_ct, 1, phasepresent, phaseinfo);
6805 if (!subsetted_suppressed_het) {
6806 *phasepresent_ct_ptr = raw_phasepresent_ct;
6807 return kPglRetSuccess;
6808 }
6809 } else {
6810 // could skip if intersection of phasepresent with sample_include is
6811 // empty, but this function call should be fast enough there anyway?
6812 ExpandThenSubsetBytearrNested(aux2_second_part, aux2_first_part_copy, all_hets, sample_include, sample_ct, raw_phasepresent_ct, 1, phasepresent, phaseinfo);
6813 }
6814 }
6815 if (subsetted_suppressed_het) {
6816 BitvecInvmask(subsetted_suppressed_het, sample_ctl, phasepresent);
6817 }
6818 *phasepresent_ct_ptr = PopcountWords(phasepresent, sample_ctl);
6819 return kPglRetSuccess;
6820 }
6821
6822 PglErr SkipAux2(const unsigned char* fread_end, uint32_t het_ct, const unsigned char** fread_pp, uint32_t* __restrict phasepresent_ctp) {
6823 const unsigned char* aux2_start = *fread_pp;
6824 const uint32_t aux2_first_part_byte_ct = 1 + (het_ct / CHAR_BIT);
6825 if (PtrAddCk(fread_end, aux2_first_part_byte_ct, fread_pp)) {
6826 return kPglRetMalformedInput;
6827 }
6828 if (!(aux2_start[0] & 1)) {
6829 if (phasepresent_ctp) {
6830 *phasepresent_ctp = het_ct;
6831 }
6832 return kPglRetSuccess;
6833 }
6834 const uint32_t phasepresent_ct = PopcountBytes(aux2_start, aux2_first_part_byte_ct) - 1;
6835 if (phasepresent_ctp) {
6836 *phasepresent_ctp = phasepresent_ct;
6837 }
6838 if (PtrAddCk(fread_end, DivUp(phasepresent_ct, CHAR_BIT), fread_pp)) {
6839 return kPglRetMalformedInput;
6840 }
6841 return kPglRetSuccess;
6842 }
6843
6844 // If fread_pp/fread_endp are non-null, this always moves fread_ptr to the end
6845 // of aux2. Set phasepresent/phaseinfo to nullptr when you don't actually care
6846 // about the contents of aux2.
6847 // In multiallelic case, this guarantees phasepresent bits are only set at
6848 // ref/altx hets, not at altx/alty hets. (We don't currently guarantee this
6849 // for phaseinfo, since popcounts on that array are meaningless.) Yes, this is
6850 // mildly annoying, but the code would be messier if the ordering of
6851 // multiallelic-hardcall and hardcall-phase info were swapped.
6852 PglErr ReadGenovecHphaseSubsetUnsafe(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, PgenReaderMain* pgrp, const unsigned char** fread_pp, const unsigned char** fread_endp, uintptr_t* __restrict genovec, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo, uint32_t* phasepresent_ct_ptr) {
6853 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
6854 if ((!(vrtype & 0x18)) || ((!fread_pp) && (!VrtypeHphase(vrtype)))) {
6855 *phasepresent_ct_ptr = 0;
6856 return ReadGenovecSubsetUnsafe(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, fread_pp, fread_endp, genovec);
6857 }
6858 // Either hphase track is present; or if it's absent, multiallelic track is
6859 // present and we were asked to advance fread_ptr to the end of aux2.
6860 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
6861 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
6862 uintptr_t* raw_genovec = (subsetting_required || VrtypeMultiallelicHc(vrtype))? pgrp->workspace_vec : genovec;
6863 const unsigned char* fread_ptr;
6864 const unsigned char* fread_end;
6865 PglErr reterr = ReadRawGenovec(subsetting_required, vidx, pgrp, &fread_ptr, &fread_end, raw_genovec);
6866 if (unlikely(reterr)) {
6867 return reterr;
6868 }
6869 ZeroTrailingNyps(raw_sample_ct, raw_genovec);
6870 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
6871 const uint32_t allele_ct = allele_idx_offsets? (allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx]) : 2;
6872 if (raw_genovec != genovec) {
6873 CopyNyparrNonemptySubset(raw_genovec, sample_include, raw_sample_ct, sample_ct, genovec);
6874 if (!VrtypeHphase(vrtype)) {
6875 // only possible if multiallelic track present and fread_ptr must be
6876 // advanced to end of aux2
6877 *fread_pp = fread_ptr;
6878 *fread_endp = fread_end;
6879 return SkipAux1(fread_end, raw_genovec, raw_sample_ct, allele_ct, fread_pp);
6880 }
6881 }
6882 uintptr_t* all_hets = pgrp->workspace_all_hets;
6883 PgrDetectGenoarrHets(raw_genovec, raw_sample_ct, all_hets);
6884 uintptr_t* subsetted_suppressed_het = nullptr;
6885 if (VrtypeMultiallelicHc(vrtype)) {
6886 const uint32_t aux1_first_byte = *fread_ptr++;
6887 const uint32_t aux1a_mode = aux1_first_byte & 15;
6888 const uint32_t aux1b_mode = aux1_first_byte >> 4;
6889 uint32_t raw_01_ct = 0;
6890 uint32_t raw_10_ct = 0;
6891 if ((!aux1a_mode) || (!aux1b_mode)) {
6892 GenovecCount12Unsafe(raw_genovec, raw_sample_ct, &raw_01_ct, &raw_10_ct);
6893 }
6894 reterr = SkipAux1a(fread_end, aux1a_mode, raw_sample_ct, allele_ct, raw_01_ct, &fread_ptr);
6895 if (unlikely(reterr)) {
6896 return reterr;
6897 }
6898 // 1. fill workspace_aux1x_present with aux1b
6899 // 2. clear bit for each hom-altx call in aux1b
6900 // 3. bitvec-or to set new workspace_all_hets bits
6901 // 4. if not subsetting, set subsetted_suppressed_het := workspace_all_hets
6902 // if subsetting, copy-subset to pgrp->workspace_vec and set to that
6903 // if AllWordsAreZero, keep as nullptr
6904 uintptr_t* aux1b_hets = pgrp->workspace_aux1x_present;
6905 uint32_t* deltalist_workspace = pgrp->workspace_difflist_sample_ids;
6906 uint32_t aux1b_het_present;
6907 reterr = GetAux1bHets(fread_end, raw_genovec, aux1b_mode, raw_sample_ct, allele_ct, raw_10_ct, &fread_ptr, aux1b_hets, &aux1b_het_present, deltalist_workspace);
6908 if (unlikely(reterr)) {
6909 return reterr;
6910 }
6911 if (aux1b_het_present) {
6912 BitvecOr(aux1b_hets, BitCtToWordCt(raw_sample_ct), all_hets);
6913 if (!subsetting_required) {
6914 subsetted_suppressed_het = aux1b_hets;
6915 } else {
6916 // Don't need raw_genovec any more.
6917 CopyBitarrSubset(aux1b_hets, sample_include, sample_ct, raw_genovec);
6918 subsetted_suppressed_het = raw_genovec;
6919 }
6920 }
6921 }
6922 reterr = ParseAux2Subset(fread_end, subsetting_required? sample_include : nullptr, all_hets, subsetted_suppressed_het, raw_sample_ct, sample_ct, &fread_ptr, phasepresent, phaseinfo, phasepresent_ct_ptr, pgrp->workspace_subset);
6923 if (fread_pp) {
6924 *fread_pp = fread_ptr;
6925 *fread_endp = fread_end;
6926 }
6927 return reterr;
6928 }
6929
6930 PglErr PgrGetP(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, uintptr_t* __restrict genovec, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo, uint32_t* __restrict phasepresent_ct_ptr) {
6931 if (!sample_ct) {
6932 *phasepresent_ct_ptr = 0;
6933 return kPglRetSuccess;
6934 }
6935 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
6936 assert(vidx < pgrp->fi.raw_variant_ct);
6937 return ReadGenovecHphaseSubsetUnsafe(sample_include, GetSicp(pssi), sample_ct, vidx, pgrp, nullptr, nullptr, genovec, phasepresent, phaseinfo, phasepresent_ct_ptr);
6938 }
6939
6940 // eventually want to return fread_ptr/fread_end, but not relevant until
6941 // multiallelic dosage working
6942 PglErr Get1MP(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReaderMain* pgrp, uintptr_t* __restrict allele_countvec, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo, uint32_t* __restrict phasepresent_ct_ptr) {
6943 // sample_ct > 0; either allele_idx > 1 or ((allele_idx == 1) &&
6944 // multiallelic_hc_present)
6945 const uint32_t vrtype = pgrp->fi.vrtypes[vidx];
6946 if (!VrtypeHphase(vrtype)) {
6947 *phasepresent_ct_ptr = 0;
6948 return IMPLPgrGet1(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx, pgrp, allele_countvec);
6949 }
6950 uintptr_t* all_hets = pgrp->workspace_all_hets;
6951 uintptr_t* subsetted_suppressed_het = nullptr;
6952 const unsigned char* fread_ptr;
6953 const unsigned char* fread_end;
6954 PglErr reterr = Get1Multiallelic(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx, pgrp, &fread_ptr, &fread_end, all_hets, allele_countvec, &subsetted_suppressed_het);
6955 if (unlikely(reterr)) {
6956 return reterr;
6957 }
6958 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
6959 reterr = ParseAux2Subset(fread_end, (sample_ct != raw_sample_ct)? sample_include : nullptr, all_hets, subsetted_suppressed_het, raw_sample_ct, sample_ct, &fread_ptr, phasepresent, phaseinfo, phasepresent_ct_ptr, pgrp->workspace_subset);
6960 // bugfix (7 Sep 2018): Need to postprocess phasepresent when collapsing
6961 // multiple alleles.
6962 if (reterr || (!(*phasepresent_ct_ptr))) {
6963 return reterr;
6964 }
6965
6966 // Might want to make this its own function.
6967 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
6968 MaskWordsToHalfwordsInvmatch(allele_countvec, kMaskAAAA, sample_ctl2, phasepresent, phasepresent);
6969 *phasepresent_ct_ptr = PopcountWords(phasepresent, BitCtToWordCt(sample_ct));
6970
6971 return kPglRetSuccess;
6972 }
6973
6974 PglErr PgrGet1P(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReader* pgr_ptr, uintptr_t* __restrict allele_countvec, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo, uint32_t* __restrict phasepresent_ct_ptr) {
6975 if (!sample_ct) {
6976 *phasepresent_ct_ptr = 0;
6977 return kPglRetSuccess;
6978 }
6979 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
6980 const uint32_t* sample_include_cumulative_popcounts = GetSicp(pssi);
6981 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
6982 const uint32_t multiallelic_hc_present = VrtypeMultiallelicHc(vrtype);
6983 if ((!allele_idx) || ((allele_idx == 1) && (!multiallelic_hc_present))) {
6984 PglErr reterr = ReadGenovecHphaseSubsetUnsafe(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, nullptr, nullptr, allele_countvec, phasepresent, phaseinfo, phasepresent_ct_ptr);
6985 if (allele_idx) {
6986 GenovecInvertUnsafe(sample_ct, allele_countvec);
6987 if (*phasepresent_ct_ptr) {
6988 BitvecInvert(BitCtToWordCt(sample_ct), phaseinfo);
6989 }
6990 }
6991 return reterr;
6992 }
6993 return Get1MP(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx, pgrp, allele_countvec, phasepresent, phaseinfo, phasepresent_ct_ptr);
6994 }
6995
6996 PglErr IMPLPgrGetInv1P(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReaderMain* pgrp, uintptr_t* __restrict allele_invcountvec, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo, uint32_t* __restrict phasepresent_ct_ptr) {
6997 if (!sample_ct) {
6998 *phasepresent_ct_ptr = 0;
6999 return kPglRetSuccess;
7000 }
7001 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
7002 const uint32_t multiallelic_hc_present = VrtypeMultiallelicHc(vrtype);
7003 if ((!allele_idx) || ((allele_idx == 1) && (!multiallelic_hc_present))) {
7004 PglErr reterr = ReadGenovecHphaseSubsetUnsafe(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, nullptr, nullptr, allele_invcountvec, phasepresent, phaseinfo, phasepresent_ct_ptr);
7005 if (!allele_idx) {
7006 GenovecInvertUnsafe(sample_ct, allele_invcountvec);
7007 if (*phasepresent_ct_ptr) {
7008 BitvecInvert(BitCtToWordCt(sample_ct), phaseinfo);
7009 }
7010 }
7011 return reterr;
7012 }
7013 PglErr reterr = Get1MP(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx, pgrp, allele_invcountvec, phasepresent, phaseinfo, phasepresent_ct_ptr);
7014 if (unlikely(reterr)) {
7015 return reterr;
7016 }
7017 GenovecInvertUnsafe(sample_ct, allele_invcountvec);
7018 if (*phasepresent_ct_ptr) {
7019 BitvecInvert(BitCtToWordCt(sample_ct), phaseinfo);
7020 }
7021 return kPglRetSuccess;
7022 }
7023
7024 void SuppressHets11(const uintptr_t* genovec, uintptr_t* subsetted_all_hets, uint32_t sample_ct, uintptr_t* subsetted_suppressed_hets) {
7025 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
7026 MaskWordsToHalfwordsInvmatch(genovec, 0, sample_ctl2, subsetted_all_hets, subsetted_suppressed_hets);
7027 }
7028
7029 PglErr PgrGet2P(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx0, uint32_t allele_idx1, PgenReader* pgr_ptr, uintptr_t* __restrict genovec, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo, uint32_t* __restrict phasepresent_ct_ptr) {
7030 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
7031 const uint32_t* sample_include_cumulative_popcounts = GetSicp(pssi);
7032 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
7033 if (!VrtypeHphase(vrtype)) {
7034 *phasepresent_ct_ptr = 0;
7035 return IMPLPgrGet2(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx0, allele_idx1, pgrp, genovec);
7036 }
7037 if (!sample_ct) {
7038 *phasepresent_ct_ptr = 0;
7039 return kPglRetSuccess;
7040 }
7041 if (allele_idx0 + allele_idx1 == 1) {
7042 PglErr reterr = ReadGenovecHphaseSubsetUnsafe(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, nullptr, nullptr, genovec, phasepresent, phaseinfo, phasepresent_ct_ptr);
7043 if (allele_idx0) {
7044 GenovecInvertUnsafe(sample_ct, genovec);
7045 if (*phasepresent_ct_ptr) {
7046 BitvecInvert(BitCtToWordCt(sample_ct), phaseinfo);
7047 }
7048 }
7049 return reterr;
7050 }
7051 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
7052 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
7053 uintptr_t* raw_genovec = pgrp->workspace_vec;
7054 const unsigned char* fread_ptr;
7055 const unsigned char* fread_end;
7056 PglErr reterr = ReadRawGenovec(subsetting_required, vidx, pgrp, &fread_ptr, &fread_end, raw_genovec);
7057 if (unlikely(reterr)) {
7058 return reterr;
7059 }
7060 ZeroTrailingNyps(raw_sample_ct, raw_genovec);
7061
7062 uint32_t invert = 0;
7063 if (allele_idx0 > allele_idx1) {
7064 const uint32_t swap = allele_idx0;
7065 allele_idx0 = allele_idx1;
7066 allele_idx1 = swap;
7067 invert = 1;
7068 }
7069 if (allele_idx0 > 1) {
7070 SetAllBits(2 * sample_ct, genovec);
7071 } else {
7072 CopyNyparrNonemptySubset(raw_genovec, sample_include, raw_sample_ct, sample_ct, genovec);
7073 // allele_idx1 > 1 guaranteed
7074 if (!allele_idx0) {
7075 GenovecNonzeroToMissingUnsafe(sample_ct, genovec);
7076 } else {
7077 GenovecInvertThenNonzeroToMissingUnsafe(sample_ct, genovec);
7078 }
7079 }
7080 uintptr_t* all_hets = pgrp->workspace_all_hets;
7081 PgrDetectGenoarrHets(raw_genovec, raw_sample_ct, all_hets);
7082 uintptr_t* subsetted_suppressed_het = nullptr;
7083 if (!subsetting_required) {
7084 sample_include = nullptr;
7085 }
7086
7087 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
7088 const uint32_t allele_ct = allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx];
7089 if (VrtypeMultiallelicHc(vrtype)) {
7090 // This combines ReadGenovecHphaseSubsetUnsafe() and Get2()'s logic.
7091 const uint32_t aux1_first_byte = *fread_ptr++;
7092 const uint32_t aux1a_mode = aux1_first_byte & 15;
7093 const uint32_t aux1b_mode = aux1_first_byte >> 4;
7094 uint32_t raw_01_ct = 0;
7095 uint32_t raw_10_ct = 0;
7096 if ((!aux1a_mode) || (!aux1b_mode)) {
7097 GenovecCount12Unsafe(raw_genovec, raw_sample_ct, &raw_01_ct, &raw_10_ct);
7098 }
7099 uint32_t* deltalist_workspace = pgrp->workspace_difflist_sample_ids;
7100 if (!allele_idx0) {
7101 // Two cases:
7102 // - If allele_idx == 1, convert all aux1a entries from 01 to 11.
7103 // - Otherwise, for each matching aux1a entry, convert from 11 to 01.
7104 reterr = GenoarrAux1aUpdate(fread_end, sample_include, sample_include_cumulative_popcounts, raw_genovec, aux1a_mode, raw_sample_ct, allele_ct, allele_idx1, 2, raw_01_ct, &fread_ptr, genovec, deltalist_workspace);
7105 } else {
7106 reterr = SkipAux1a(fread_end, aux1a_mode, raw_sample_ct, allele_ct, raw_01_ct, &fread_ptr);
7107 }
7108 if (unlikely(reterr)) {
7109 return reterr;
7110 }
7111 const unsigned char* aux1b_start = fread_ptr;
7112 reterr = GenoarrAux1bUpdate2(fread_end, sample_include, sample_include_cumulative_popcounts, raw_genovec, aux1b_mode, raw_sample_ct, allele_ct, allele_idx0, allele_idx1, raw_10_ct, &fread_ptr, genovec, deltalist_workspace);
7113 if (unlikely(reterr)) {
7114 return reterr;
7115 }
7116 // Can have a modified version of GenoarrAux1bUpdate2() which only requires
7117 // one pass, but let's keep the logic simpler for now since I don't expect
7118 // this function to be used frequently.
7119 uintptr_t* aux1b_hets = pgrp->workspace_aux1x_present;
7120 uint32_t aux1b_het_present;
7121 reterr = GetAux1bHets(fread_end, raw_genovec, aux1b_mode, raw_sample_ct, allele_ct, raw_10_ct, &aux1b_start, aux1b_hets, &aux1b_het_present, deltalist_workspace);
7122 if (unlikely(reterr)) {
7123 return reterr;
7124 }
7125 if (aux1b_het_present) {
7126 BitvecOr(aux1b_hets, BitCtToWordCt(raw_sample_ct), all_hets);
7127 }
7128 if ((allele_idx0 + allele_idx1 != 1) || aux1b_het_present) {
7129 // We can now clobber the contents of pgrp->workspace_vec (raw_genovec)
7130 // and pgrp->workspace_aux1x_present (aux1b_hets).
7131 // We use the former as the subsetted_suppressed_het return buffer.
7132 uintptr_t* all_hets_subsetted = all_hets;
7133 if (sample_include) {
7134 all_hets_subsetted = aux1b_hets;
7135 CopyBitarrSubset(all_hets, sample_include, sample_ct, all_hets_subsetted);
7136 }
7137 subsetted_suppressed_het = raw_genovec;
7138 SuppressHets11(genovec, all_hets_subsetted, sample_ct, raw_genovec);
7139 }
7140 }
7141 reterr = ParseAux2Subset(fread_end, sample_include, all_hets, subsetted_suppressed_het, raw_sample_ct, sample_ct, &fread_ptr, phasepresent, phaseinfo, phasepresent_ct_ptr, pgrp->workspace_subset);
7142 if (unlikely(reterr)) {
7143 return reterr;
7144 }
7145 if (VrtypeMultiallelicHc(vrtype) && (*phasepresent_ct_ptr)) {
7146 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
7147 MaskWordsToHalfwordsInvmatch(genovec, kMaskAAAA, sample_ctl2, phasepresent, phasepresent);
7148 *phasepresent_ct_ptr = PopcountWords(phasepresent, BitCtToWordCt(sample_ct));
7149 }
7150 if (invert) {
7151 GenovecInvertUnsafe(sample_ct, genovec);
7152 if (*phasepresent_ct_ptr) {
7153 BitvecInvert(BitCtToWordCt(sample_ct), phaseinfo);
7154 }
7155 }
7156 return kPglRetSuccess;
7157 }
7158
7159 PglErr PgrGetMP(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, PgenVariant* pgvp) {
7160 pgvp->patch_01_ct = 0;
7161 pgvp->patch_10_ct = 0;
7162 if (!sample_ct) {
7163 pgvp->phasepresent_ct = 0;
7164 return kPglRetSuccess;
7165 }
7166 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
7167 const uint32_t* sample_include_cumulative_popcounts = GetSicp(pssi);
7168 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
7169 const uint32_t multiallelic_hc_present = VrtypeMultiallelicHc(vrtype);
7170 if (!multiallelic_hc_present) {
7171 return ReadGenovecHphaseSubsetUnsafe(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, nullptr, nullptr, pgvp->genovec, pgvp->phasepresent, pgvp->phaseinfo, &(pgvp->phasepresent_ct));
7172 }
7173 const unsigned char* fread_ptr;
7174 const unsigned char* fread_end;
7175 uintptr_t* all_hets = VrtypeHphase(vrtype)? pgrp->workspace_all_hets : nullptr;
7176 PglErr reterr = GetMultiallelicCodes(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, all_hets? (&fread_ptr) : nullptr, all_hets? (&fread_end) : nullptr, all_hets, pgvp);
7177 if (reterr || (!all_hets)) {
7178 // bugfix (17 Apr 2023): need to zero out phasepresent_ct in this case
7179 pgvp->phasepresent_ct = 0;
7180 return reterr;
7181 }
7182 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
7183 return ParseAux2Subset(fread_end, (sample_ct != raw_sample_ct)? sample_include : nullptr, all_hets, nullptr, raw_sample_ct, sample_ct, &fread_ptr, pgvp->phasepresent, pgvp->phaseinfo, &(pgvp->phasepresent_ct), pgrp->workspace_subset);
7184 }
7185
7186 // ok for sample_include to be nullptr if not subsetting, though this is not
7187 // required
7188 PglErr ParseDosage16(const unsigned char* fread_ptr, const unsigned char* fread_end, const uintptr_t* __restrict sample_include, uint32_t sample_ct, uint32_t vidx, uint32_t allele_ct, PgenReaderMain* pgrp, uint32_t* __restrict dosage_ct_ptr, uintptr_t* __restrict dphase_present, int16_t* dphase_delta, uint32_t* __restrict dphase_ct_ptr, uintptr_t* __restrict dosage_present, uint16_t* dosage_main) {
7189 // Side effect: may use pgrp->workspace_dosage_present and
7190 // pgrp->workspace_dphase_present
7191 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
7192 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
7193 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
7194 uintptr_t* raw_dosage_present = subsetting_required? pgrp->workspace_dosage_present : dosage_present;
7195 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
7196 const uint32_t is_unconditional_dosage = ((vrtype & 0x60) == 0x40);
7197 uint32_t raw_dosage_ct;
7198 if ((vrtype & 0x60) == 0x20) {
7199 // case 1: dosage list
7200 if (unlikely(ParseAndSaveDeltalistAsBitarr(fread_end, raw_sample_ct, &fread_ptr, raw_dosage_present, &raw_dosage_ct))) {
7201 return kPglRetMalformedInput;
7202 }
7203 if ((!raw_dosage_ct) && (!dosage_ct_ptr)) {
7204 // bugfix (7 Oct 2024)
7205 ZeroWArr(raw_sample_ctl, raw_dosage_present);
7206 }
7207 } else if (is_unconditional_dosage) {
7208 // case 2: unconditional dosage. handle separately from other two cases
7209 // since missing values may be present.
7210 SetAllBits(raw_sample_ct, raw_dosage_present);
7211 raw_dosage_ct = raw_sample_ct;
7212 } else {
7213 // case 3: dosage bitarray
7214 raw_dosage_present[raw_sample_ctl - 1] = 0;
7215 const uint32_t raw_sample_ctb = DivUp(raw_sample_ct, CHAR_BIT);
7216 memcpy(raw_dosage_present, fread_ptr, raw_sample_ctb);
7217 fread_ptr = &(fread_ptr[raw_sample_ctb]);
7218 raw_dosage_ct = PopcountWords(raw_dosage_present, raw_sample_ctl);
7219 }
7220 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
7221 uint32_t dosage_ct;
7222 if (subsetting_required) {
7223 CopyBitarrSubset(raw_dosage_present, sample_include, sample_ct, dosage_present);
7224 dosage_ct = PopcountWords(dosage_present, sample_ctl);
7225 } else {
7226 dosage_ct = raw_dosage_ct;
7227 }
7228 if (dosage_ct_ptr) {
7229 *dosage_ct_ptr = dosage_ct;
7230 }
7231 if (!dosage_ct) {
7232 if (dphase_ct_ptr) {
7233 *dphase_ct_ptr = 0;
7234 }
7235 return kPglRetSuccess;
7236 }
7237 const unsigned char* dosage_main_read_biter = fread_ptr;
7238 uint16_t* dosage_main_write_iter = dosage_main;
7239 uint32_t raw_dphase_ct = 0;
7240 uint32_t dphase_ct = 0;
7241 uintptr_t* raw_dphase_present = nullptr;
7242 if (dphase_present && (vrtype & 0x80)) {
7243 fread_ptr = &(fread_ptr[raw_dosage_ct * 2]);
7244 if (!is_unconditional_dosage) {
7245 const unsigned char* file_dphase_present = fread_ptr;
7246 fread_ptr = &(fread_ptr[DivUp(raw_dosage_ct, CHAR_BIT)]);
7247 raw_dphase_present = subsetting_required? pgrp->workspace_dphase_present : dphase_present;
7248 ExpandBytearr(file_dphase_present, raw_dosage_present, raw_sample_ctl, raw_dosage_ct, 0, raw_dphase_present);
7249 raw_dphase_ct = PopcountWords(raw_dphase_present, raw_sample_ctl);
7250 dphase_ct = raw_dphase_ct;
7251 if (subsetting_required) {
7252 CopyBitarrSubset(raw_dphase_present, sample_include, sample_ct, dphase_present);
7253 dphase_ct = PopcountWords(dphase_present, sample_ctl);
7254 }
7255 } else {
7256 // raw_dphase_present = raw_dosage_present;
7257 dphase_ct = dosage_ct;
7258 SetAllBits(sample_ct, dphase_present);
7259 }
7260 }
7261 if (!dphase_ct) {
7262 if (allele_ct == 2) {
7263 if (!is_unconditional_dosage) {
7264 if (dosage_ct == raw_dosage_ct) {
7265 memcpy(dosage_main_write_iter, dosage_main_read_biter, dosage_ct * sizeof(int16_t));
7266 } else {
7267 // bugfix (22 May 2017): dosage_entry_idx needs to iterate up to
7268 // raw_dosage_ct, not dosage_ct
7269 uintptr_t widx = ~k0LU;
7270 uint32_t dosage_entry_idx = 0;
7271 do {
7272 uintptr_t cur_bits;
7273 do {
7274 cur_bits = raw_dosage_present[++widx];
7275 } while (!cur_bits);
7276 const uintptr_t sample_include_word = sample_include[widx];
7277 do {
7278 const uintptr_t low_bit = cur_bits & (-cur_bits);
7279 if (sample_include_word & low_bit) {
7280 CopyFromUnalignedOffsetU16(dosage_main_write_iter, dosage_main_read_biter, dosage_entry_idx);
7281 ++dosage_main_write_iter;
7282 }
7283 ++dosage_entry_idx;
7284 cur_bits ^= low_bit;
7285 } while (cur_bits);
7286 } while (dosage_entry_idx != raw_dosage_ct);
7287 }
7288 } else {
7289 if (!subsetting_required) {
7290 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
7291 uint16_t cur_dosage;
7292 CopyFromUnalignedIncrU16(&cur_dosage, &dosage_main_read_biter);
7293 if (cur_dosage != 65535) {
7294 *dosage_main_write_iter++ = cur_dosage;
7295 } else {
7296 ClearBit(sample_idx, dosage_present);
7297 }
7298 }
7299 } else {
7300 uintptr_t widx = ~k0LU;
7301 uint32_t sample_idx = 0;
7302 do {
7303 uintptr_t cur_bits;
7304 do {
7305 cur_bits = sample_include[++widx];
7306 } while (!cur_bits);
7307 const uintptr_t sample_uidx_base = widx * kBitsPerWord;
7308 const unsigned char* dosage_main_readp = &(dosage_main_read_biter[sample_uidx_base * sizeof(int16_t)]);
7309 do {
7310 const uint32_t sample_uidx_lowbits = ctzw(cur_bits);
7311 uint16_t cur_dosage;
7312 CopyFromUnalignedOffsetU16(&cur_dosage, dosage_main_readp, sample_uidx_lowbits);
7313 if (cur_dosage != 65535) {
7314 *dosage_main_write_iter++ = cur_dosage;
7315 } else {
7316 ClearBit(sample_idx, dosage_present);
7317 }
7318 ++sample_idx;
7319 cur_bits &= cur_bits - 1;
7320 } while (cur_bits);
7321 } while (sample_idx != sample_ct);
7322 }
7323 if (dosage_ct_ptr) {
7324 *dosage_ct_ptr = dosage_main_write_iter - dosage_main;
7325 }
7326 }
7327 } else {
7328 // todo: multiallelic dosage
7329 // need to support downcode to ref/nonref as well as raw load
7330 // (dosage_ct_ptr should be nullptr iff we're doing a raw load)
7331 #ifndef PGENLIB_NOPRINT
7332 fputs("multiallelic variants not yet supported by ParseDosage16()\n", stderr);
7333 #endif
7334 return kPglRetNotYetSupported;
7335 }
7336 if (dphase_ct_ptr) {
7337 *dphase_ct_ptr = 0;
7338 }
7339 } else {
7340 // phased dosage
7341 if (allele_ct == 2) {
7342 if (!is_unconditional_dosage) {
7343 // bugfix (15 Sep 2023): dphase_ct == raw_dphase_ct doesn't guarantee
7344 // dosage_ct == raw_dosage_ct
7345 if (dosage_ct == raw_dosage_ct) {
7346 memcpy(dosage_main_write_iter, dosage_main_read_biter, dosage_ct * sizeof(int16_t));
7347 } else {
7348 uintptr_t widx = ~k0LU;
7349 uint32_t dosage_entry_idx = 0;
7350 do {
7351 uintptr_t cur_bits;
7352 do {
7353 cur_bits = raw_dosage_present[++widx];
7354 } while (!cur_bits);
7355 const uintptr_t sample_include_word = sample_include[widx];
7356 do {
7357 const uintptr_t low_bit = cur_bits & (-cur_bits);
7358 if (sample_include_word & low_bit) {
7359 CopyFromUnalignedOffsetU16(dosage_main_write_iter, dosage_main_read_biter, dosage_entry_idx);
7360 ++dosage_main_write_iter;
7361 }
7362 ++dosage_entry_idx;
7363 cur_bits ^= low_bit;
7364 } while (cur_bits);
7365 } while (dosage_entry_idx != raw_dosage_ct);
7366 }
7367 if (dphase_ct == raw_dphase_ct) {
7368 memcpy(dphase_delta, fread_ptr, dphase_ct * sizeof(int16_t));
7369 if (dphase_ct_ptr) {
7370 *dphase_ct_ptr = dphase_ct;
7371 }
7372 } else {
7373 uintptr_t widx = ~k0LU;
7374 uint32_t dphase_entry_idx = 0;
7375 const unsigned char* dphase_delta_read = fread_ptr;
7376 int16_t* dphase_delta_write_iter = dphase_delta;
7377 do {
7378 uintptr_t cur_bits;
7379 do {
7380 cur_bits = raw_dphase_present[++widx];
7381 } while (!cur_bits);
7382 const uintptr_t sample_include_word = sample_include[widx];
7383 do {
7384 const uintptr_t low_bit = cur_bits & (-cur_bits);
7385 if (sample_include_word & low_bit) {
7386 CopyFromUnalignedOffsetI16(dphase_delta_write_iter, dphase_delta_read, dphase_entry_idx);
7387 ++dphase_delta_write_iter;
7388 }
7389 ++dphase_entry_idx;
7390 cur_bits ^= low_bit;
7391 } while (cur_bits);
7392 } while (dphase_entry_idx != raw_dphase_ct);
7393 if (dphase_ct_ptr) {
7394 *dphase_ct_ptr = dphase_delta_write_iter - dphase_delta;
7395 }
7396 }
7397 } else {
7398 const unsigned char* dphase_delta_read = fread_ptr;
7399 int16_t* dphase_delta_write_iter = dphase_delta;
7400 if (!subsetting_required) {
7401 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
7402 uint16_t cur_dosage;
7403 CopyFromUnalignedIncrU16(&cur_dosage, &dosage_main_read_biter);
7404 if (cur_dosage != 65535) {
7405 *dosage_main_write_iter++ = cur_dosage;
7406 int16_t dphase_delta_val;
7407 CopyFromUnalignedOffsetI16(&dphase_delta_val, dphase_delta_read, sample_idx);
7408 if (dphase_delta_val) {
7409 *dphase_delta_write_iter++ = dphase_delta_val;
7410 } else {
7411 ClearBit(sample_idx, dphase_present);
7412 }
7413 } else {
7414 // assert(dphase_delta_read[sample_idx] == -32768);
7415 ClearBit(sample_idx, dosage_present);
7416 }
7417 }
7418 } else {
7419 uintptr_t sample_uidx_base = 0;
7420 uintptr_t sample_include_bits = sample_include[0];
7421 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
7422 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &sample_include_bits);
7423 uint16_t cur_dosage;
7424 CopyFromUnalignedOffsetU16(&cur_dosage, dosage_main_read_biter, sample_uidx);
7425 if (cur_dosage != 65535) {
7426 *dosage_main_write_iter++ = cur_dosage;
7427 int16_t dphase_delta_val;
7428 CopyFromUnalignedOffsetI16(&dphase_delta_val, dphase_delta_read, sample_uidx);
7429 if (dphase_delta_val) {
7430 *dphase_delta_write_iter++ = dphase_delta_val;
7431 } else {
7432 ClearBit(sample_idx, dphase_present);
7433 }
7434 } else {
7435 // assert(dphase_delta_read[sample_uidx] == -32768);
7436 ClearBit(sample_idx, dosage_present);
7437 }
7438 }
7439 }
7440 dosage_ct = dosage_main_write_iter - dosage_main;
7441 if (dosage_ct != sample_ct) {
7442 BitvecAnd(dosage_present, sample_ctl, dphase_present);
7443 }
7444 if (dosage_ct_ptr) {
7445 *dosage_ct_ptr = dosage_ct;
7446 }
7447 if (dphase_ct_ptr) {
7448 *dphase_ct_ptr = dphase_delta_write_iter - dphase_delta;
7449 }
7450 }
7451 } else {
7452 // multiallelic subcase
7453 #ifndef PGENLIB_NOPRINT
7454 fputs("multiallelic variants not yet supported by ParseDosage16()\n", stderr);
7455 #endif
7456 return kPglRetNotYetSupported;
7457 }
7458 }
7459 return kPglRetSuccess;
7460 }
7461
7462 PglErr IMPLPgrGetD(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, PgenReaderMain* pgrp, uintptr_t* __restrict genovec, uintptr_t* __restrict dosage_present, uint16_t* dosage_main, uint32_t* dosage_ct_ptr) {
7463 assert(vidx < pgrp->fi.raw_variant_ct);
7464 if (!sample_ct) {
7465 *dosage_ct_ptr = 0;
7466 return kPglRetSuccess;
7467 }
7468 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
7469 if ((!VrtypeDosage(vrtype)) || (!dosage_present)) {
7470 *dosage_ct_ptr = 0;
7471 return ReadGenovecSubsetUnsafe(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, nullptr, nullptr, genovec);
7472 }
7473 const unsigned char* fread_ptr = nullptr;
7474 const unsigned char* fread_end = nullptr;
7475 uint32_t phasepresent_ct;
7476 PglErr reterr = ReadGenovecHphaseSubsetUnsafe(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, &fread_ptr, &fread_end, genovec, nullptr, nullptr, &phasepresent_ct);
7477 if (unlikely(reterr)) {
7478 return reterr;
7479 }
7480 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
7481 const uint32_t allele_ct = allele_idx_offsets? (allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx]) : 2;
7482 return ParseDosage16(fread_ptr, fread_end, sample_include, sample_ct, vidx, allele_ct, pgrp, dosage_ct_ptr, nullptr, nullptr, nullptr, dosage_present, dosage_main);
7483 }
7484
7485 PglErr PgrGet1D(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, AlleleCode allele_idx, PgenReader* pgr_ptr, uintptr_t* __restrict allele_countvec, uintptr_t* __restrict dosage_present, uint16_t* dosage_main, uint32_t* dosage_ct_ptr) {
7486 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
7487 const uint32_t* sample_include_cumulative_popcounts = GetSicp(pssi);
7488 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
7489 const uint32_t allele_ct = allele_idx_offsets? (allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx]) : 2;
7490 if ((allele_ct == 2) || (!allele_idx)) {
7491 uint32_t dosage_ct;
7492 PglErr reterr = IMPLPgrGetD(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, allele_countvec, dosage_present, dosage_main, &dosage_ct);
7493 if (!allele_idx) {
7494 GenovecInvertUnsafe(sample_ct, allele_countvec);
7495 if (dosage_ct) {
7496 BiallelicDosage16Invert(dosage_ct, dosage_main);
7497 }
7498 }
7499 *dosage_ct_ptr = dosage_ct;
7500 return reterr;
7501 }
7502 const uint32_t vrtype = pgrp->fi.vrtypes[vidx];
7503 if (!VrtypeDosage(vrtype)) {
7504 *dosage_ct_ptr = 0;
7505 return IMPLPgrGet1(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx, pgrp, allele_countvec);
7506 }
7507 #ifndef PGENLIB_NOPRINT
7508 fputs("multiallelic variants not yet supported by PgrGet1D()\n", stderr);
7509 #endif
7510 return kPglRetNotYetSupported;
7511 }
7512
7513 PglErr PgrGetInv1D(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, AlleleCode allele_idx, PgenReader* pgr_ptr, uintptr_t* __restrict allele_invcountvec, uintptr_t* __restrict dosage_present, uint16_t* dosage_main, uint32_t* dosage_ct_ptr) {
7514 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
7515 const uint32_t* sample_include_cumulative_popcounts = GetSicp(pssi);
7516 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
7517 const uint32_t allele_ct = allele_idx_offsets? (allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx]) : 2;
7518 if ((allele_ct == 2) || (!allele_idx)) {
7519 uint32_t dosage_ct;
7520 PglErr reterr = IMPLPgrGetD(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, allele_invcountvec, dosage_present, dosage_main, &dosage_ct);
7521 if (allele_idx) {
7522 GenovecInvertUnsafe(sample_ct, allele_invcountvec);
7523 if (dosage_ct) {
7524 BiallelicDosage16Invert(dosage_ct, dosage_main);
7525 }
7526 }
7527 *dosage_ct_ptr = dosage_ct;
7528 return reterr;
7529 }
7530 const uint32_t vrtype = pgrp->fi.vrtypes[vidx];
7531 if (!VrtypeDosage(vrtype)) {
7532 *dosage_ct_ptr = 0;
7533 return IMPLPgrGetInv1(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx, pgrp, allele_invcountvec);
7534 }
7535 #ifndef PGENLIB_NOPRINT
7536 fputs("multiallelic variants not yet supported by PgrGetInv1D()\n", stderr);
7537 #endif
7538 return kPglRetNotYetSupported;
7539 }
7540
7541 PglErr GetAux1bHetIncr(const unsigned char* fread_end, uint32_t aux1b_mode, uint32_t raw_sample_ct, uint32_t allele_ct, uint32_t raw_10_ct, const unsigned char** fread_pp, uint32_t* __restrict raw_het_ctp) {
7542 if (aux1b_mode == 15) {
7543 return kPglRetSuccess;
7544 }
7545 uint32_t rare10_ct;
7546 if (!aux1b_mode) {
7547 const uint32_t fset_byte_ct = DivUp(raw_10_ct, 8);
7548 rare10_ct = PopcountBytes(*fread_pp, fset_byte_ct);
7549 *fread_pp += fset_byte_ct;
7550 } else {
7551 // aux1b_mode == 1
7552 const unsigned char* group_info_iter;
7553 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, nullptr, &group_info_iter, &rare10_ct);
7554 if (unlikely(reterr)) {
7555 return reterr;
7556 }
7557 reterr = SkipDeltalistIds(fread_end, group_info_iter, rare10_ct, raw_sample_ct, 0, fread_pp);
7558 if (unlikely(reterr)) {
7559 return reterr;
7560 }
7561 }
7562 uintptr_t detect_hom_mask_lo;
7563 const uint32_t allele_code_logwidth = GetAux1bConsts(allele_ct, &detect_hom_mask_lo);
7564 const uint32_t code10_logwidth = allele_code_logwidth + (allele_code_logwidth != 0);
7565 const unsigned char* patch_10_fvals = *fread_pp;
7566 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare10_ct) << code10_logwidth, CHAR_BIT);
7567 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
7568 return kPglRetMalformedInput;
7569 }
7570 if (allele_ct == 3) {
7571 const uint32_t hom22_ct = PopcountBytes(patch_10_fvals, fvals_byte_ct);
7572 *raw_het_ctp += rare10_ct - hom22_ct;
7573 return kPglRetSuccess;
7574 }
7575 // possible todo: vectorized het-counter, analogous to CountAux1bDense()
7576 const uint32_t code10_width = 1U << code10_logwidth;
7577 const uint32_t allele_code_width = 1U << allele_code_logwidth;
7578 const uintptr_t detect_all_mask_lo = detect_hom_mask_lo | (detect_hom_mask_lo << allele_code_width);
7579 const uintptr_t detect_all_mask_hi = detect_all_mask_lo << (allele_code_width - 1);
7580 const uintptr_t detect_hom_mask_hi = detect_hom_mask_lo << (code10_width - 1);
7581 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
7582 uint32_t het_incr = 0;
7583 for (uint32_t fvals_widx = 0; ; ++fvals_widx) {
7584 uintptr_t fvals_bits;
7585 if (fvals_widx >= fvals_word_ct_m1) {
7586 if (fvals_widx > fvals_word_ct_m1) {
7587 break;
7588 }
7589 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
7590 } else {
7591 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
7592 }
7593 // allele_ct > 3 guaranteed
7594 fvals_bits = fvals_bits ^ (fvals_bits << allele_code_width);
7595 fvals_bits = detect_hom_mask_hi & (fvals_bits | ((fvals_bits | detect_all_mask_hi) - detect_all_mask_lo));
7596 if (fvals_widx == fvals_word_ct_m1) {
7597 fvals_bits = bzhi_max(fvals_bits, ModNz(rare10_ct << code10_logwidth, kBitsPerWord));
7598 }
7599 het_incr += PopcountWord(fvals_bits);
7600 }
7601 *raw_het_ctp += het_incr;
7602 return kPglRetSuccess;
7603 }
7604
7605 uint64_t U16VecSum(const uint16_t* __restrict uint16_vec, uint32_t entry_ct) {
7606 #ifdef USE_SSE2
7607 // UniVecHsum32() could overflow once we exceed this
7608 const uint32_t max_loop_len = (131072 / kInt32PerVec) - 1;
7609
7610 const VecW m16 = VCONST_W(kMask0000FFFF);
7611 const VecW* uint16_vvec_iter = R_CAST(const VecW*, uint16_vec);
7612 uint64_t sum = 0;
7613 for (uint32_t full_vecs_remaining = entry_ct / (kBytesPerVec / sizeof(int16_t)); ; ) {
7614 UniVec acc_even;
7615 UniVec acc_odd;
7616 acc_even.vw = vecw_setzero();
7617 acc_odd.vw = vecw_setzero();
7618 const VecW* uint16_vvec_stop;
7619 if (full_vecs_remaining < max_loop_len) {
7620 if (!full_vecs_remaining) {
7621 const uint32_t trail_ct = entry_ct % (kBytesPerVec / sizeof(int16_t));
7622 uint16_vec = DowncastKVecWToU16(uint16_vvec_iter);
7623 for (uint32_t uii = 0; uii != trail_ct; ++uii) {
7624 sum += uint16_vec[uii];
7625 }
7626 return sum;
7627 }
7628 uint16_vvec_stop = &(uint16_vvec_iter[full_vecs_remaining]);
7629 full_vecs_remaining = 0;
7630 } else {
7631 uint16_vvec_stop = &(uint16_vvec_iter[max_loop_len]);
7632 full_vecs_remaining -= max_loop_len;
7633 }
7634 do {
7635 const VecW cur_vec = *uint16_vvec_iter++;
7636 acc_even.vw = acc_even.vw + (cur_vec & m16);
7637 acc_odd.vw = acc_odd.vw + (vecw_srli(cur_vec, 16) & m16);
7638 } while (uint16_vvec_iter < uint16_vvec_stop);
7639 sum += UniVecHsum32(acc_even);
7640 sum += UniVecHsum32(acc_odd);
7641 }
7642 #else
7643 uint64_t sum = 0;
7644 for (uint32_t uii = 0; uii != entry_ct; ++uii) {
7645 sum += uint16_vec[uii];
7646 }
7647 return sum;
7648 #endif
7649 }
7650
7651 PglErr GetPhasepresentAndSkipPhaseinfo(const unsigned char* fread_end, const uintptr_t* __restrict all_hets, uint32_t raw_sample_ct, uint32_t het_ct, const unsigned char** fread_pp, uintptr_t* __restrict phasepresent, uint32_t* __restrict phasepresent_ctp) {
7652 const unsigned char* aux2_start = *fread_pp;
7653 const uint32_t aux2_first_part_byte_ct = 1 + (het_ct / CHAR_BIT);
7654 if (PtrAddCk(fread_end, aux2_first_part_byte_ct, fread_pp)) {
7655 return kPglRetMalformedInput;
7656 }
7657 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
7658 if (!(aux2_start[0] & 1)) {
7659 memcpy(phasepresent, all_hets, raw_sample_ctl * kBytesPerWord);
7660 *phasepresent_ctp = het_ct;
7661 return kPglRetSuccess;
7662 }
7663 const uint32_t phasepresent_ct = PopcountBytes(aux2_start, aux2_first_part_byte_ct) - 1;
7664 if (PtrAddCk(fread_end, DivUp(phasepresent_ct, CHAR_BIT), fread_pp)) {
7665 return kPglRetMalformedInput;
7666 }
7667 *phasepresent_ctp = phasepresent_ct;
7668 ExpandBytearr(aux2_start, all_hets, raw_sample_ctl, het_ct, 1, phasepresent);
7669 return kPglRetSuccess;
7670 }
7671
7672 PglErr GetUnphasedBiallelicHetCt(const uintptr_t* __restrict sample_include, const uintptr_t* raw_genoarr, const unsigned char* fread_ptr, const unsigned char* fread_end, uint32_t subsetted_het_ct, PgenReaderMain* pgrp, uint32_t* unphased_het_ctp) {
7673 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
7674 uint32_t raw_het_ct;
7675 if (!sample_include) {
7676 raw_het_ct = subsetted_het_ct;
7677 } else {
7678 raw_het_ct = CountNyp(raw_genoarr, kMask5555, raw_sample_ct);
7679 }
7680 const uint32_t aux2_first_part_byte_ct = 1 + (raw_het_ct / CHAR_BIT);
7681 if (PtrCheck(fread_end, fread_ptr, aux2_first_part_byte_ct)) {
7682 return kPglRetMalformedInput;
7683 }
7684 const uint32_t explicit_phasepresent = fread_ptr[0] & 1;
7685 if (!explicit_phasepresent) {
7686 // initial value of 0 is correct
7687 return kPglRetSuccess;
7688 }
7689 if (raw_het_ct == subsetted_het_ct) {
7690 *unphased_het_ctp = raw_het_ct + 1 - PopcountBytes(fread_ptr, aux2_first_part_byte_ct);
7691 return kPglRetSuccess;
7692 }
7693 // A dedicated counting function would be faster, but this case
7694 // should rarely come up.
7695 uintptr_t* all_hets = pgrp->workspace_all_hets;
7696 PgrDetectGenoarrHets(raw_genoarr, raw_sample_ct, all_hets);
7697 uintptr_t* raw_phasepresent = pgrp->workspace_subset;
7698 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
7699 // todo: compare against ExpandThenSubsetBytearr followed by simple popcount
7700 ExpandBytearr(fread_ptr, all_hets, raw_sample_ctl, raw_het_ct, 1, raw_phasepresent);
7701 *unphased_het_ctp = subsetted_het_ct - PopcountWordsIntersect(raw_phasepresent, sample_include, raw_sample_ctl);
7702 return kPglRetSuccess;
7703 }
7704
7705 PglErr GetPhasedBiallelicGenotypeSubsetCounts(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict sample_include_interleaved_vec, uint32_t sample_ct, uint32_t vidx, PgenReaderMain* pgrp, uint32_t* unphased_het_ctp, STD_ARRAY_REF(uint32_t, 4) genocounts) {
7706 // Currently much less optimized than the other count functions. (This case
7707 // shouldn't come up much, the user has to be computing minimac-r2 on a file
7708 // with no dosages...)
7709 uintptr_t* raw_genovec = pgrp->workspace_vec;
7710 const unsigned char* fread_ptr;
7711 const unsigned char* fread_end;
7712 PglErr reterr = ReadRawGenovec(1, vidx, pgrp, &fread_ptr, &fread_end, raw_genovec);
7713 if (unlikely(reterr)) {
7714 return reterr;
7715 }
7716 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
7717 ZeroTrailingNyps(raw_sample_ct, raw_genovec);
7718 GenoarrCountSubsetFreqs(raw_genovec, sample_include_interleaved_vec, raw_sample_ct, sample_ct, genocounts);
7719 return GetUnphasedBiallelicHetCt(sample_include, raw_genovec, fread_ptr, fread_end, genocounts[1], pgrp, unphased_het_ctp);
7720 }
7721
7722 // Imputation r^2 computation:
7723 // * This function assumes the biallelic diploid case. Divide by two to get
7724 // the biallelic haploid value, for whatever that's worth.
7725 // * chrX requires sex information, so that's handled directly in
7726 // LoadAlleleAndGenoCountsThread()... er, actually, we just give up on that
7727 // for now.
7728 // * See PgrGetMDCounts() support functions below for multiallelic-diploid
7729 // notes.
7730 PglErr GetBasicGenotypeCountsAndDosage16s(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict sample_include_interleaved_vec, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, uint32_t is_minimac3_r2, PgenReaderMain* pgrp, double* imp_r2_ptr, STD_ARRAY_REF(uint32_t, 4) genocounts, uint64_t* __restrict all_dosages) {
7731 // genocounts[0] := ref/ref, genocounts[1] := ref/altx,
7732 // genocounts[2] := altx/alty, genocounts[3] := missing
7733 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
7734 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
7735 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
7736 uint32_t unphased_het_ct = 0;
7737 // To avoid LD cache thrashing, we try to either always keep a subsetted
7738 // cache, or never do so. (Always, when only hardcalls are present;
7739 // otherwise never.)
7740 if ((!(pgrp->fi.gflags & kfPgenGlobalDosagePresent)) ||
7741 ((!(vrtype & 0x60)) && (!subsetting_required))) {
7742 {
7743 const uint32_t need_unphased_het_ct = is_minimac3_r2 && VrtypeHphase(vrtype);
7744 PglErr reterr;
7745 if (!(subsetting_required && need_unphased_het_ct)) {
7746 reterr = GetBasicGenotypeCounts(sample_include, sample_include_interleaved_vec, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, need_unphased_het_ct? (&unphased_het_ct) : nullptr, genocounts);
7747 } else {
7748 reterr = GetPhasedBiallelicGenotypeSubsetCounts(sample_include, sample_include_interleaved_vec, sample_ct, vidx, pgrp, &unphased_het_ct, genocounts);
7749 }
7750 if (unlikely(reterr)) {
7751 return reterr;
7752 }
7753 }
7754 GetBasicGenotypeCountsAndDosage16s_basic_finish:
7755 all_dosages[0] = (genocounts[0] * 2 + genocounts[1]) * 16384LLU;
7756 all_dosages[1] = (genocounts[2] * 2 + genocounts[1]) * 16384LLU;
7757 if (!imp_r2_ptr) {
7758 return kPglRetSuccess;
7759 }
7760 // yeah, it's sinful to implement imputation r2 here...
7761 const uint32_t nm_sample_ct = sample_ct - genocounts[3];
7762 const uint64_t alt1_dosage = genocounts[2] * 0x8000LLU + genocounts[1] * 0x4000LLU;
7763 uint64_t hap_alt1_ssq_x2 = genocounts[2] * 0x40000000LLU + genocounts[1] * 0x10000000LLU;
7764 if (is_minimac3_r2) {
7765 if (!VrtypeHphase(vrtype)) {
7766 unphased_het_ct = genocounts[1];
7767 }
7768 hap_alt1_ssq_x2 += (genocounts[1] - unphased_het_ct) * 0x10000000LLU;
7769 }
7770 *imp_r2_ptr = BiallelicDiploidMinimac3R2(alt1_dosage, hap_alt1_ssq_x2, nm_sample_ct);
7771 if (!is_minimac3_r2) {
7772 *imp_r2_ptr *= 2;
7773 }
7774 return kPglRetSuccess;
7775 }
7776 uintptr_t* raw_genovec = pgrp->workspace_vec;
7777 const unsigned char* fread_ptr;
7778 const unsigned char* fread_end;
7779 PglErr reterr = ReadRawGenovec(subsetting_required, vidx, pgrp, &fread_ptr, &fread_end, raw_genovec);
7780 if (unlikely(reterr)) {
7781 return reterr;
7782 }
7783 ZeroTrailingNyps(raw_sample_ct, raw_genovec);
7784 if (!subsetting_required) {
7785 GenoarrCountFreqsUnsafe(raw_genovec, raw_sample_ct, genocounts);
7786 } else {
7787 GenoarrCountSubsetFreqs(raw_genovec, sample_include_interleaved_vec, raw_sample_ct, sample_ct, genocounts);
7788 }
7789 if (!(vrtype & 0x60)) {
7790 if (is_minimac3_r2 && VrtypeHphase(vrtype)) {
7791 assert(!VrtypeMultiallelicHc(vrtype));
7792 reterr = GetUnphasedBiallelicHetCt(subsetting_required? sample_include : nullptr, raw_genovec, fread_ptr, fread_end, genocounts[1], pgrp, &unphased_het_ct);
7793 if (unlikely(reterr)) {
7794 return reterr;
7795 }
7796 }
7797 goto GetBasicGenotypeCountsAndDosage16s_basic_finish;
7798 }
7799 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
7800 const uint32_t allele_ct = allele_idx_offsets? (allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx]) : 2;
7801 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
7802 uintptr_t* raw_phasepresent = pgrp->workspace_subset;
7803 uint32_t raw_phasepresent_ct = 0;
7804 if (VrtypeHphase(vrtype)) {
7805 uint32_t raw_het_ct = genocounts[1]; // inaccurate if subsetting_required
7806 if (!is_minimac3_r2) {
7807 if (VrtypeMultiallelicHc(vrtype)) {
7808 const uint32_t aux1_first_byte = *fread_ptr++;
7809 const uint32_t aux1a_mode = aux1_first_byte & 15;
7810 const uint32_t aux1b_mode = aux1_first_byte >> 4;
7811 uint32_t raw_10_ct = 0;
7812 if ((!aux1a_mode) || (!aux1b_mode) || subsetting_required) {
7813 GenovecCount12Unsafe(raw_genovec, raw_sample_ct, &raw_het_ct, &raw_10_ct);
7814 }
7815 reterr = SkipAux1a(fread_end, aux1a_mode, raw_sample_ct, allele_ct, raw_het_ct, &fread_ptr);
7816 if (unlikely(reterr)) {
7817 return reterr;
7818 }
7819 reterr = GetAux1bHetIncr(fread_end, aux1b_mode, raw_sample_ct, allele_ct, raw_10_ct, &fread_ptr, &raw_het_ct);
7820 if (unlikely(reterr)) {
7821 return reterr;
7822 }
7823 } else if (subsetting_required) {
7824 raw_het_ct = CountNyp(raw_genovec, kMask5555, raw_sample_ct);
7825 }
7826 reterr = SkipAux2(fread_end, raw_het_ct, &fread_ptr, nullptr);
7827 if (unlikely(reterr)) {
7828 return reterr;
7829 }
7830 } else {
7831 assert(!VrtypeMultiallelicHc(vrtype));
7832 uintptr_t* all_hets = pgrp->workspace_all_hets;
7833 PgrDetectGenoarrHets(raw_genovec, raw_sample_ct, all_hets);
7834 if (subsetting_required) {
7835 raw_het_ct = PopcountWords(all_hets, raw_sample_ctl);
7836 }
7837 const uint32_t first_half_byte_ct = 1 + (raw_het_ct / CHAR_BIT);
7838 const uint32_t explicit_phasepresent = fread_ptr[0] & 1;
7839 if (explicit_phasepresent) {
7840 ExpandBytearr(fread_ptr, all_hets, raw_sample_ctl, raw_het_ct, 1, raw_phasepresent);
7841 raw_phasepresent_ct = PopcountBytes(fread_ptr, first_half_byte_ct) - 1;
7842 const uint32_t second_half_byte_ct = DivUp(raw_phasepresent_ct, CHAR_BIT);
7843 fread_ptr = &(fread_ptr[first_half_byte_ct + second_half_byte_ct]);
7844 } else {
7845 raw_phasepresent_ct = raw_het_ct;
7846 memcpy(raw_phasepresent, all_hets, raw_sample_ctl * sizeof(intptr_t));
7847 fread_ptr = &(fread_ptr[first_half_byte_ct]);
7848 }
7849 }
7850 } else if (VrtypeMultiallelicHc(vrtype)) {
7851 reterr = SkipAux1(fread_end, raw_genovec, raw_sample_ct, allele_ct, &fread_ptr);
7852 if (unlikely(reterr)) {
7853 return reterr;
7854 }
7855 }
7856 if (allele_ct != 2) {
7857 // Maybe make this an invalid function call? If that happens, the
7858 // VrtypeMultiallelicHc() branch above can be removed.
7859 #ifndef PGENLIB_NOPRINT
7860 fputs("multiallelic dosages not yet supported by GetBasicGenotypeCountsAndDosage16s()\n", stderr);
7861 #endif
7862 return kPglRetNotYetSupported;
7863 }
7864
7865 const uint32_t is_unconditional_dosage = ((vrtype & 0x60) == 0x40);
7866 uint64_t alt1_dosage = 0;
7867 uint32_t dosage_ct = 0;
7868 STD_ARRAY_DECL(uint32_t, 4, replaced_genocounts);
7869 if ((!is_minimac3_r2) || (!(vrtype & 0x90))) {
7870 uint64_t alt1_dosage_sq_sum = 0;
7871 if (is_unconditional_dosage) {
7872 // needs to be handled separately from the other cases due to possible
7873 // presence of missing values.
7874 // note that this code will also need to be adjusted when multiallelic
7875 // support is added.
7876 STD_ARRAY_FILL0(replaced_genocounts);
7877 const unsigned char* dosage_main_read = fread_ptr;
7878 if (PtrAddCk(fread_end, raw_sample_ct * sizeof(int16_t), &fread_ptr)) {
7879 return kPglRetMalformedInput;
7880 }
7881 if (subsetting_required) {
7882 uintptr_t sample_uidx_base = 0;
7883 uintptr_t sample_include_bits = sample_include[0];
7884 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
7885 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &sample_include_bits);
7886 const uintptr_t cur_dosage_val = CopyFromUnalignedOffsetU16ZX(dosage_main_read, sample_uidx);
7887 if (cur_dosage_val != 65535) {
7888 alt1_dosage += cur_dosage_val;
7889
7890 // todo: check if this is slow enough to justify removing it from
7891 // the main loop
7892 alt1_dosage_sq_sum += cur_dosage_val * cur_dosage_val;
7893 ++dosage_ct;
7894 }
7895 }
7896 } else {
7897 for (uint32_t sample_uidx = 0; sample_uidx != sample_ct; ++sample_uidx) {
7898 const uintptr_t cur_dosage_val = CopyFromUnalignedOffsetU16ZX(dosage_main_read, sample_uidx);
7899 if (cur_dosage_val != 65535) {
7900 alt1_dosage += cur_dosage_val;
7901 alt1_dosage_sq_sum += cur_dosage_val * cur_dosage_val;
7902 ++dosage_ct;
7903 }
7904 }
7905 }
7906 // update (20 Mar 2019): .pgen specification tightened to remove the need
7907 // to update replaced_genocounts in the main loops above.
7908 STD_ARRAY_COPY(genocounts, 4, replaced_genocounts);
7909 replaced_genocounts[3] = replaced_genocounts[3] + dosage_ct - sample_ct;
7910 } else {
7911 uintptr_t* raw_dosage_present = pgrp->workspace_dosage_present;
7912 uint32_t raw_dosage_ct;
7913 if (!(vrtype & 0x40)) {
7914 // dosage list
7915 if (unlikely(ParseAndSaveDeltalistAsBitarr(fread_end, raw_sample_ct, &fread_ptr, raw_dosage_present, &raw_dosage_ct))) {
7916 return kPglRetMalformedInput;
7917 }
7918 } else {
7919 // dosage bitarray
7920 raw_dosage_present[raw_sample_ctl - 1] = 0;
7921 const uint32_t raw_sample_ctb = DivUp(raw_sample_ct, CHAR_BIT);
7922 memcpy(raw_dosage_present, fread_ptr, raw_sample_ctb);
7923 fread_ptr = &(fread_ptr[raw_sample_ctb]);
7924 raw_dosage_ct = PopcountWords(raw_dosage_present, raw_sample_ctl);
7925 }
7926 const unsigned char* dosage_main_read = fread_ptr;
7927 if (PtrAddCk(fread_end, raw_dosage_ct * sizeof(int16_t), &fread_ptr)) {
7928 return kPglRetMalformedInput;
7929 }
7930 if (subsetting_required) {
7931 uintptr_t sample_widx = 0;
7932 uintptr_t dosage_present_bits = raw_dosage_present[0];
7933 for (uint32_t dosage_idx = 0; dosage_idx != raw_dosage_ct; ++dosage_idx) {
7934 const uintptr_t lowbit = BitIter1y(raw_dosage_present, &sample_widx, &dosage_present_bits);
7935 if (sample_include[sample_widx] & lowbit) {
7936 const uintptr_t cur_dosage_val = CopyFromUnalignedOffsetU16ZX(dosage_main_read, dosage_idx);
7937 alt1_dosage += cur_dosage_val;
7938 alt1_dosage_sq_sum += cur_dosage_val * cur_dosage_val;
7939 ++dosage_ct;
7940 }
7941 }
7942 GenoarrCountSubsetIntersectFreqs(raw_genovec, raw_dosage_present, sample_include, raw_sample_ct, replaced_genocounts);
7943 } else {
7944 if (!imp_r2_ptr) {
7945 for (uint32_t dosage_idx = 0; dosage_idx != raw_dosage_ct; ++dosage_idx) {
7946 uint16_t cur_dosage_u16;
7947 CopyFromUnalignedOffsetU16(&cur_dosage_u16, dosage_main_read, dosage_idx);
7948 alt1_dosage += cur_dosage_u16;
7949 }
7950 } else {
7951 for (uint32_t dosage_idx = 0; dosage_idx != raw_dosage_ct; ++dosage_idx) {
7952 const uintptr_t cur_dosage_val = CopyFromUnalignedOffsetU16ZX(dosage_main_read, dosage_idx);
7953 alt1_dosage += cur_dosage_val;
7954 alt1_dosage_sq_sum += cur_dosage_val * cur_dosage_val;
7955 }
7956 }
7957 dosage_ct = raw_dosage_ct;
7958 GenoarrCountSubsetFreqs2(raw_genovec, raw_dosage_present, raw_sample_ct, raw_dosage_ct, replaced_genocounts);
7959 }
7960 }
7961 const uint32_t replaced_ct = replaced_genocounts[0] + replaced_genocounts[1] + replaced_genocounts[2];
7962 const uint32_t remaining_het_ct = genocounts[1] - replaced_genocounts[1];
7963 const uint32_t remaining_hom_alt_ct = genocounts[2] - replaced_genocounts[2];
7964 const uint32_t alt1_ct = 2 * remaining_hom_alt_ct + remaining_het_ct;
7965 alt1_dosage += alt1_ct * 16384LLU;
7966 all_dosages[1] = alt1_dosage;
7967 const uint32_t nondosage_nm_ct = sample_ct - genocounts[3] - replaced_ct;
7968 const uint32_t new_sample_nm_ct = dosage_ct + nondosage_nm_ct;
7969 all_dosages[0] = new_sample_nm_ct * 32768LLU - alt1_dosage;
7970 if (!imp_r2_ptr) {
7971 return kPglRetSuccess;
7972 }
7973 // possible todo: also move all-hardcall-phase-present, no-dosage
7974 // is_minimac3_r2 case under this branch, since we can just set imp_r2 to
7975 // NaN or 1.
7976 // 16384^2, 32768^2
7977 alt1_dosage_sq_sum += remaining_het_ct * 0x10000000LLU + remaining_hom_alt_ct * 0x40000000LLU;
7978 *imp_r2_ptr = BiallelicDiploidMinimac3R2(alt1_dosage, alt1_dosage_sq_sum, new_sample_nm_ct);
7979 if (!is_minimac3_r2) {
7980 *imp_r2_ptr *= 2;
7981 }
7982 return kPglRetSuccess;
7983 }
7984 // Need to deal with implicitly phased dosages. Best to have raw_genovec,
7985 // raw_phasepresent, dosage_present, and dosage_main all available, then loop
7986 // over everything at once.
7987 // (phaseinfo is irrelevant since only absolute value of (left - right)
7988 // matters.)
7989
7990 // We have the following 2x2x3 cases to deal with:
7991 // - Subsetted vs. un-subsetted. Un-subsetted comes up a lot, so we have an
7992 // optimized code path for it.
7993 // - Unconditional vs. conditional dosage. Unconditional should not come up
7994 // much, so we just mock up raw_dosage_present... er, actually, that
7995 // doesn't work because dosage_main would also need to be collapsed. Sigh.
7996 // Ok, it's still handled separately.
7997 // - Only hardcall-phase, vs. only dosage-phase, vs. both. At least we can
7998 // merge the "only dosage-phase" and "both" cases.
7999 // So we end up with 8 primary code paths.
8000 // This is kind of a nightmare; it would obviously be nicer to move this
8001 // out of pgenlib_internal, and that may eventually happen. But we don't
8002 // want users to be discouraged from running --minimac3-r2-filter when it's
8003 // appropriate just because it's a lot slower than other standard filters;
8004 // and this also serves as a testing ground for efficient phased-dosage
8005 // handling strategies.
8006 if (!VrtypeHphase(vrtype)) {
8007 ZeroWArr(raw_sample_ctl, raw_phasepresent);
8008 }
8009 uintptr_t* raw_dosage_present = nullptr;
8010 const unsigned char* dosage_main_read;
8011 uint32_t raw_dosage_ct = 0;
8012 if (is_unconditional_dosage) {
8013 dosage_main_read = fread_ptr;
8014 if (PtrAddCk(fread_end, raw_sample_ct * sizeof(int16_t), &fread_ptr)) {
8015 return kPglRetMalformedInput;
8016 }
8017 // raw_dosage_ct unused in this case.
8018 } else {
8019 // could move some duplicate code before the big branch
8020 raw_dosage_present = pgrp->workspace_dosage_present;
8021 if (!(vrtype & 0x40)) {
8022 // dosage list
8023 if (unlikely(ParseAndSaveDeltalistAsBitarr(fread_end, raw_sample_ct, &fread_ptr, raw_dosage_present, &raw_dosage_ct))) {
8024 return kPglRetMalformedInput;
8025 }
8026 } else {
8027 // dosage bitarray
8028 raw_dosage_present[raw_sample_ctl - 1] = 0;
8029 const uint32_t raw_sample_ctb = DivUp(raw_sample_ct, CHAR_BIT);
8030 memcpy(raw_dosage_present, fread_ptr, raw_sample_ctb);
8031 fread_ptr = &(fread_ptr[raw_sample_ctb]);
8032 raw_dosage_ct = PopcountWords(raw_dosage_present, raw_sample_ctl);
8033 }
8034 dosage_main_read = fread_ptr;
8035 if (PtrAddCk(fread_end, raw_dosage_ct * sizeof(int16_t), &fread_ptr)) {
8036 return kPglRetMalformedInput;
8037 }
8038 }
8039 const unsigned char* dosage_main_biter = dosage_main_read;
8040 uint64_t hap_ssq_x2 = 0;
8041 uint32_t phased_hc_het_ct = 0;
8042 if (!(vrtype & 0x80)) {
8043 if (is_unconditional_dosage) {
8044 if (!subsetting_required) {
8045 const uint32_t raw_sample_ctl_m1 = raw_sample_ctl - 1;
8046 uint32_t loop_len = kBitsPerWord;
8047 for (uint32_t widx = 0; ; ++widx) {
8048 if (widx >= raw_sample_ctl_m1) {
8049 if (widx > raw_sample_ctl_m1) {
8050 break;
8051 }
8052 loop_len = ModNz(raw_sample_ct, kBitsPerWord);
8053 }
8054 uintptr_t phasepresent_word = raw_phasepresent[widx];
8055 for (uint32_t uii = 0; uii != loop_len; ++uii) {
8056 const uintptr_t cur_dosage_val = CopyFromUnalignedIncrU16ZX(&dosage_main_biter);
8057 if (cur_dosage_val != 65535) {
8058 alt1_dosage += cur_dosage_val;
8059 hap_ssq_x2 += cur_dosage_val * cur_dosage_val;
8060 ++dosage_ct;
8061 if (phasepresent_word & 1) {
8062 // For each dosage, when phasepresent bit is set, implicit
8063 // dphase_delta value is 16384 - |16384 - x|.
8064 const uintptr_t homdist = 16384 - abs_i32(16384 - cur_dosage_val);
8065 hap_ssq_x2 += homdist * homdist;
8066 }
8067 }
8068 phasepresent_word = phasepresent_word >> 1;
8069 }
8070 }
8071 } else {
8072 for (uint32_t widx = 0; widx != raw_sample_ctl; ++widx) {
8073 uintptr_t sample_include_word = sample_include[widx];
8074 if (!sample_include_word) {
8075 continue;
8076 }
8077 const uintptr_t phasepresent_word = raw_phasepresent[widx];
8078 const unsigned char* cur_dosage_main = &(dosage_main_read[widx * kBitsPerWord * sizeof(int16_t)]);
8079 do {
8080 const uint32_t sample_idx_lowbits = ctzw(sample_include_word);
8081 const uintptr_t cur_dosage_val = CopyFromUnalignedOffsetU16ZX(cur_dosage_main, sample_idx_lowbits);
8082 const uintptr_t lowbit = sample_include_word & (-sample_include_word);
8083 if (cur_dosage_val != 65535) {
8084 alt1_dosage += cur_dosage_val;
8085 hap_ssq_x2 += cur_dosage_val * cur_dosage_val;
8086 ++dosage_ct;
8087 if (lowbit & phasepresent_word) {
8088 const uintptr_t homdist = 16384 - abs_i32(16384 - cur_dosage_val);
8089 hap_ssq_x2 += homdist * homdist;
8090 }
8091 }
8092 sample_include_word ^= lowbit;
8093 } while (sample_include_word);
8094 }
8095 }
8096 STD_ARRAY_COPY(genocounts, 4, replaced_genocounts);
8097 replaced_genocounts[3] = replaced_genocounts[3] + dosage_ct - sample_ct;
8098 } else { // !is_unconditional_dosage
8099 if (!subsetting_required) {
8100 // phased_hc_het_ct := popcount(phasepresent & (~dosage_present))
8101 phased_hc_het_ct = raw_phasepresent_ct - PopcountWordsIntersect(raw_phasepresent, raw_dosage_present, raw_sample_ctl);
8102
8103 for (uint32_t widx = 0; widx != raw_sample_ctl; ++widx) {
8104 uintptr_t dosage_present_word = raw_dosage_present[widx];
8105 if (dosage_present_word) {
8106 const uintptr_t phasepresent_word = raw_phasepresent[widx];
8107 do {
8108 const uintptr_t cur_dosage_val = CopyFromUnalignedIncrU16ZX(&dosage_main_biter);
8109 alt1_dosage += cur_dosage_val;
8110 const uintptr_t lowbit = dosage_present_word & (-dosage_present_word);
8111 hap_ssq_x2 += cur_dosage_val * cur_dosage_val;
8112 if (lowbit & phasepresent_word) {
8113 const uintptr_t homdist = 16384 - abs_i32(16384 - cur_dosage_val);
8114 hap_ssq_x2 += homdist * homdist;
8115 }
8116 dosage_present_word ^= lowbit;
8117 } while (dosage_present_word);
8118 }
8119 }
8120 dosage_ct = raw_dosage_ct;
8121 GenoarrCountSubsetFreqs2(raw_genovec, raw_dosage_present, raw_sample_ct, raw_dosage_ct, replaced_genocounts);
8122 } else {
8123 for (uint32_t widx = 0; widx != raw_sample_ctl; ++widx) {
8124 const uintptr_t sample_include_word = sample_include[widx];
8125 uintptr_t dosage_present_word = raw_dosage_present[widx];
8126 if (!sample_include_word) {
8127 dosage_main_biter = &(dosage_main_biter[PopcountWord(dosage_present_word) * sizeof(int16_t)]);
8128 continue;
8129 }
8130 const uintptr_t phasepresent_word = raw_phasepresent[widx];
8131 phased_hc_het_ct += PopcountWord(sample_include_word & phasepresent_word & (~dosage_present_word));
8132 while (dosage_present_word) {
8133 const uintptr_t lowbit = dosage_present_word & (-dosage_present_word);
8134 if (lowbit & sample_include_word) {
8135 const uintptr_t cur_dosage_val = CopyFromUnalignedU16ZX(dosage_main_biter);
8136 alt1_dosage += cur_dosage_val;
8137 hap_ssq_x2 += cur_dosage_val * cur_dosage_val;
8138 ++dosage_ct;
8139 if (lowbit & phasepresent_word) {
8140 const uintptr_t homdist = 16384 - abs_i32(16384 - cur_dosage_val);
8141 hap_ssq_x2 += homdist * homdist;
8142 }
8143 }
8144 dosage_present_word ^= lowbit;
8145 dosage_main_biter += sizeof(int16_t);
8146 }
8147 }
8148 GenoarrCountSubsetIntersectFreqs(raw_genovec, raw_dosage_present, sample_include, raw_sample_ct, replaced_genocounts);
8149 }
8150 }
8151 } else {
8152 if (is_unconditional_dosage) {
8153 if (PtrCheck(fread_end, fread_ptr, raw_sample_ct * sizeof(int16_t))) {
8154 return kPglRetMalformedInput;
8155 }
8156 const unsigned char* dphase_delta_read = fread_ptr;
8157 if (!subsetting_required) {
8158 for (uint32_t sample_uidx = 0; sample_uidx != raw_sample_ct; ++sample_uidx) {
8159 const uintptr_t cur_dosage_val = CopyFromUnalignedOffsetU16ZX(dosage_main_read, sample_uidx);
8160 if (cur_dosage_val != 65535) {
8161 alt1_dosage += cur_dosage_val;
8162 hap_ssq_x2 += cur_dosage_val * cur_dosage_val;
8163 ++dosage_ct;
8164 // .pgen specification now requires this value to never be missing.
8165 const intptr_t dphase_delta_val = CopyFromUnalignedOffsetI16ZX(dphase_delta_read, sample_uidx);
8166 hap_ssq_x2 += dphase_delta_val * dphase_delta_val;
8167 }
8168 }
8169 } else {
8170 for (uint32_t widx = 0; widx != raw_sample_ctl; ++widx) {
8171 uintptr_t sample_include_word = sample_include[widx];
8172 if (!sample_include_word) {
8173 continue;
8174 }
8175 const unsigned char* cur_dosage_main = &(dosage_main_read[widx * kBitsPerWord * sizeof(int16_t)]);
8176 const unsigned char* cur_dphase_delta = &(dphase_delta_read[widx * kBitsPerWord * sizeof(int16_t)]);
8177 do {
8178 const uint32_t sample_idx_lowbits = ctzw(sample_include_word);
8179 const uintptr_t cur_dosage_val = CopyFromUnalignedOffsetU16ZX(cur_dosage_main, sample_idx_lowbits);
8180 if (cur_dosage_val != 65535) {
8181 alt1_dosage += cur_dosage_val;
8182 hap_ssq_x2 += cur_dosage_val * cur_dosage_val;
8183 ++dosage_ct;
8184 const intptr_t dphase_delta_val = CopyFromUnalignedOffsetI16ZX(cur_dphase_delta, sample_idx_lowbits);
8185 hap_ssq_x2 += dphase_delta_val * dphase_delta_val;
8186 }
8187 sample_include_word &= sample_include_word - 1;
8188 } while (sample_include_word);
8189 }
8190 }
8191 STD_ARRAY_COPY(genocounts, 4, replaced_genocounts);
8192 replaced_genocounts[3] = replaced_genocounts[3] + dosage_ct - sample_ct;
8193 } else {
8194 const unsigned char* file_dphase_present = fread_ptr;
8195 const uint32_t raw_dosage_ctb = DivUp(raw_dosage_ct, CHAR_BIT);
8196 if (PtrAddCk(fread_end, raw_dosage_ctb, &fread_ptr)) {
8197 return kPglRetMalformedInput;
8198 }
8199 const uint32_t raw_dphase_ct = PopcountBytes(file_dphase_present, raw_dosage_ctb);
8200 if (PtrCheck(fread_end, fread_ptr, raw_dphase_ct * sizeof(int16_t))) {
8201 return kPglRetMalformedInput;
8202 }
8203 uintptr_t* raw_dphase_present = pgrp->workspace_dphase_present;
8204 ExpandBytearr(file_dphase_present, raw_dosage_present, raw_sample_ctl, raw_dosage_ct, 0, raw_dphase_present);
8205 const unsigned char* dphase_delta_biter = fread_ptr;
8206 if (!subsetting_required) {
8207 phased_hc_het_ct = raw_phasepresent_ct - PopcountWordsIntersect(raw_phasepresent, raw_dosage_present, raw_sample_ctl);
8208
8209 for (uint32_t widx = 0; widx != raw_sample_ctl; ++widx) {
8210 uintptr_t dosage_present_word = raw_dosage_present[widx];
8211 if (dosage_present_word) {
8212 const uintptr_t phasepresent_word = raw_phasepresent[widx];
8213 const uintptr_t dphase_present_word = raw_dphase_present[widx];
8214 do {
8215 const uintptr_t cur_dosage_val = CopyFromUnalignedIncrU16ZX(&dosage_main_biter);
8216 alt1_dosage += cur_dosage_val;
8217 const uintptr_t lowbit = dosage_present_word & (-dosage_present_word);
8218 hap_ssq_x2 += cur_dosage_val * cur_dosage_val;
8219 if (lowbit & dphase_present_word) {
8220 const intptr_t dphase_delta_val = CopyFromUnalignedIncrI16ZX(&dphase_delta_biter);
8221 hap_ssq_x2 += dphase_delta_val * dphase_delta_val;
8222 } else if (lowbit & phasepresent_word) {
8223 const uintptr_t homdist = 16384 - abs_i32(16384 - cur_dosage_val);
8224 hap_ssq_x2 += homdist * homdist;
8225 }
8226 dosage_present_word ^= lowbit;
8227 } while (dosage_present_word);
8228 }
8229 }
8230 dosage_ct = raw_dosage_ct;
8231 GenoarrCountSubsetFreqs2(raw_genovec, raw_dosage_present, raw_sample_ct, raw_dosage_ct, replaced_genocounts);
8232 } else {
8233 for (uint32_t widx = 0; widx != raw_sample_ctl; ++widx) {
8234 const uintptr_t sample_include_word = sample_include[widx];
8235 const uintptr_t dphase_present_word = raw_dphase_present[widx];
8236 uintptr_t dosage_present_word = raw_dosage_present[widx];
8237 if (!sample_include_word) {
8238 dosage_main_biter = &(dosage_main_biter[PopcountWord(dosage_present_word) * sizeof(int16_t)]);
8239 dphase_delta_biter = &(dphase_delta_biter[PopcountWord(dphase_present_word) * sizeof(int16_t)]);
8240 continue;
8241 }
8242 const uintptr_t phasepresent_word = raw_phasepresent[widx];
8243 phased_hc_het_ct += PopcountWord(sample_include_word & phasepresent_word & (~dosage_present_word));
8244 while (dosage_present_word) {
8245 const uintptr_t lowbit = dosage_present_word & (-dosage_present_word);
8246 const uintptr_t dphase_here = lowbit & dphase_present_word;
8247 if (lowbit & sample_include_word) {
8248 const uintptr_t cur_dosage_val = CopyFromUnalignedU16ZX(dosage_main_biter);
8249 alt1_dosage += cur_dosage_val;
8250 hap_ssq_x2 += cur_dosage_val * cur_dosage_val;
8251 ++dosage_ct;
8252 if (dphase_here) {
8253 const intptr_t dphase_delta_val = CopyFromUnalignedI16ZX(dphase_delta_biter);
8254 hap_ssq_x2 += dphase_delta_val * dphase_delta_val;
8255 } else if (lowbit & phasepresent_word) {
8256 const uintptr_t homdist = 16384 - abs_i32(16384 - cur_dosage_val);
8257 hap_ssq_x2 += homdist * homdist;
8258 }
8259 }
8260 dphase_delta_biter += (dphase_here != 0) * sizeof(int16_t);
8261 dosage_present_word ^= lowbit;
8262 dosage_main_biter += sizeof(int16_t);
8263 }
8264 }
8265 GenoarrCountSubsetIntersectFreqs(raw_genovec, raw_dosage_present, sample_include, raw_sample_ct, replaced_genocounts);
8266 }
8267 }
8268 }
8269 const uint32_t replaced_ct = replaced_genocounts[0] + replaced_genocounts[1] + replaced_genocounts[2];
8270 const uint32_t remaining_het_ct = genocounts[1] - replaced_genocounts[1];
8271 const uint32_t remaining_hom_alt_ct = genocounts[2] - replaced_genocounts[2];
8272 const uint32_t alt1_ct = 2 * remaining_hom_alt_ct + remaining_het_ct;
8273 alt1_dosage += alt1_ct * 16384LLU;
8274 all_dosages[1] = alt1_dosage;
8275 const uint32_t nondosage_nm_ct = sample_ct - genocounts[3] - replaced_ct;
8276 const uint32_t new_sample_nm_ct = dosage_ct + nondosage_nm_ct;
8277 all_dosages[0] = new_sample_nm_ct * 32768LLU - alt1_dosage;
8278 hap_ssq_x2 += (remaining_het_ct + phased_hc_het_ct) * 0x10000000LLU + remaining_hom_alt_ct * 0x40000000LLU;
8279 *imp_r2_ptr = BiallelicDiploidMinimac3R2(alt1_dosage, hap_ssq_x2, new_sample_nm_ct);
8280 return kPglRetSuccess;
8281 }
8282
8283 PglErr PgrGetDCounts(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict sample_include_interleaved_vec, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, uint32_t is_minimac3_r2, PgenReader* pgr_ptr, double* imp_r2_ptr, STD_ARRAY_REF(uint32_t, 4) genocounts, uint64_t* __restrict all_dosages) {
8284 if (!sample_ct) {
8285 STD_ARRAY_REF_FILL0(4, genocounts);
8286 all_dosages[0] = 0;
8287 all_dosages[1] = 0;
8288 if (imp_r2_ptr) {
8289 *imp_r2_ptr = 0.0 / 0.0;
8290 }
8291 return kPglRetSuccess;
8292 }
8293 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
8294 assert(vidx < pgrp->fi.raw_variant_ct);
8295 return GetBasicGenotypeCountsAndDosage16s(sample_include, sample_include_interleaved_vec, GetSicp(pssi), sample_ct, vidx, is_minimac3_r2, pgrp, imp_r2_ptr, genocounts, all_dosages);
8296 }
8297
8298 // Does not zero-initialize results[].
8299 void CountAllBytes64(const void* bytearr, uintptr_t byte_ct, uint64_t* __restrict results) {
8300 const unsigned char* bytearr_uc = S_CAST(const unsigned char*, bytearr);
8301 for (uintptr_t ulii = 0; ulii != byte_ct; ++ulii) {
8302 results[bytearr_uc[ulii]] += 1;
8303 }
8304 }
8305
8306 // Does not zero-initialize results[].
8307 void CountAllNybbles64(const void* nybblearr, uintptr_t nybble_ct, uint64_t* __restrict results) {
8308 // possible todo: for sufficiently large nybble_ct, use CountAllBytes and
8309 // then postprocess
8310 const uintptr_t fullbyte_ct = nybble_ct / 2;
8311 const unsigned char* nybblearr_uc = S_CAST(const unsigned char*, nybblearr);
8312 for (uintptr_t ulii = 0; ulii != fullbyte_ct; ++ulii) {
8313 const uint32_t uii = nybblearr_uc[ulii];
8314 results[uii & 15] += 1;
8315 results[uii >> 4] += 1;
8316 }
8317 if (nybble_ct % 2) {
8318 results[nybblearr_uc[fullbyte_ct] & 15] += 1;
8319 }
8320 }
8321
8322 void CountAllAux1aDense(const void* patch_01_fvals, uint32_t allele_ct, uint32_t rare01_ct, uint64_t* __restrict one_cts) {
8323 one_cts[1] -= rare01_ct;
8324 if (allele_ct < 5) {
8325 if (allele_ct == 3) {
8326 // all entries are 0/1 -> 0/2
8327 one_cts[2] = rare01_ct;
8328 return;
8329 }
8330 const uint32_t allele_code_byte_ct = DivUp(rare01_ct, 8);
8331 const uint32_t alt3_ct = PopcountBytes(patch_01_fvals, allele_code_byte_ct);
8332 one_cts[2] = rare01_ct - alt3_ct;
8333 one_cts[3] = alt3_ct;
8334 return;
8335 }
8336 if (allele_ct < 19) {
8337 if (allele_ct < 7) {
8338 STD_ARRAY_DECL(uint32_t, 4, rare0het_counts);
8339 #ifndef NO_UNALIGNED
8340 GenoarrCountFreqs(S_CAST(const uintptr_t*, patch_01_fvals), rare01_ct, rare0het_counts);
8341 #else
8342 GenoarrbCountFreqs(S_CAST(const unsigned char*, patch_01_fvals), rare01_ct, rare0het_counts);
8343 #endif
8344 for (uint32_t allele_idx_p2 = 2; allele_idx_p2 != allele_ct; ++allele_idx_p2) {
8345 one_cts[allele_idx_p2] = rare0het_counts[allele_idx_p2 - 2];
8346 }
8347 return;
8348 }
8349 CountAllNybbles64(patch_01_fvals, rare01_ct, &(one_cts[2]));
8350 return;
8351 }
8352 CountAllBytes64(patch_01_fvals, rare01_ct, &(one_cts[2]));
8353 }
8354
8355 // assumes one_cts[1] initialized to genocounts[1]
8356 // sample_include should be nullptr if we aren't subsetting
8357 PglErr CountAllAux1a(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uintptr_t* __restrict raw_genoarr, uint32_t aux1a_mode, uint32_t raw_sample_ct, uint32_t allele_ct, uint32_t raw_01_ct, const unsigned char** fread_pp, uint64_t* __restrict one_cts, uint32_t* __restrict deltalist_workspace) {
8358 if (aux1a_mode == 15) {
8359 return kPglRetSuccess;
8360 }
8361 if (!sample_include) {
8362 uint32_t rare01_ct;
8363 if (!aux1a_mode) {
8364 const uint32_t fset_byte_ct = DivUp(raw_01_ct, CHAR_BIT);
8365 rare01_ct = PopcountBytes(*fread_pp, fset_byte_ct);
8366 *fread_pp += fset_byte_ct;
8367 } else {
8368 const unsigned char* group_info_iter;
8369 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, nullptr, &group_info_iter, &rare01_ct);
8370 if (unlikely(reterr)) {
8371 return reterr;
8372 }
8373 reterr = SkipDeltalistIds(fread_end, group_info_iter, rare01_ct, raw_sample_ct, 0, fread_pp);
8374 if (unlikely(reterr)) {
8375 return reterr;
8376 }
8377 }
8378 const unsigned char* patch_01_fvals = *fread_pp;
8379 const uint32_t fvals_byte_ct = GetAux1aAlleleEntryByteCt(allele_ct, rare01_ct);
8380 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
8381 return kPglRetMalformedInput;
8382 }
8383 CountAllAux1aDense(patch_01_fvals, allele_ct, rare01_ct, one_cts);
8384 return kPglRetSuccess;
8385 }
8386 const uint32_t allele_code_width = GetAux1aWidth(allele_ct);
8387 const uintptr_t allele_code_mask = (1U << allele_code_width) - 1;
8388 uint64_t* one_cts_offset2 = &(one_cts[2]);
8389 if (!aux1a_mode) {
8390 const uint32_t fset_byte_ct = DivUp(raw_01_ct, CHAR_BIT);
8391 const uint32_t rare01_ct = PopcountBytes(*fread_pp, fset_byte_ct);
8392 const unsigned char* patch_01_fset = *fread_pp;
8393 *fread_pp += fset_byte_ct;
8394 const unsigned char* patch_01_fvals = *fread_pp;
8395 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare01_ct) * allele_code_width, 8);
8396 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
8397 return kPglRetMalformedInput;
8398 }
8399 const Halfword* sample_include_hw = DowncastKWToHW(sample_include);
8400 uintptr_t sample_hwidx = 0;
8401 uintptr_t cur_raw_genoarr_hets = Word01(raw_genoarr[0]);
8402 const uint32_t fset_word_ct_m1 = (fset_byte_ct - 1) / kBytesPerWord;
8403 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
8404 uintptr_t fvals_bits = 0;
8405 uint32_t fvals_widx = 0;
8406 uint32_t subsetted_rare01_ct = 0;
8407 uint32_t loop_len = kBitsPerWord;
8408 uint32_t rare01_lowbits = kBitsPerWord;
8409 for (uint32_t fset_widx = 0; ; ++fset_widx) {
8410 uintptr_t fset_bits;
8411 if (fset_widx >= fset_word_ct_m1) {
8412 if (fset_widx > fset_word_ct_m1) {
8413 break;
8414 }
8415 fset_bits = SubwordLoad(&(patch_01_fset[fset_word_ct_m1 * kBytesPerWord]), ModNz(fset_byte_ct, kBytesPerWord));
8416 loop_len = ModNz(raw_01_ct, kBitsPerWord);
8417 } else {
8418 CopyFromUnalignedOffsetW(&fset_bits, patch_01_fset, fset_widx);
8419 }
8420 if (allele_ct == 3) {
8421 for (uint32_t uii = 0; uii != loop_len; ++uii) {
8422 while (!cur_raw_genoarr_hets) {
8423 cur_raw_genoarr_hets = Word01(raw_genoarr[++sample_hwidx]);
8424 }
8425 if (fset_bits & 1) {
8426 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_hets) / 2;
8427 subsetted_rare01_ct += (sample_include_hw[sample_hwidx] >> sample_uidx_lowbits) & 1;
8428 }
8429 cur_raw_genoarr_hets &= cur_raw_genoarr_hets - 1;
8430 fset_bits = fset_bits >> 1;
8431 }
8432 } else {
8433 for (uint32_t uii = 0; uii != loop_len; ++uii) {
8434 while (!cur_raw_genoarr_hets) {
8435 cur_raw_genoarr_hets = Word01(raw_genoarr[++sample_hwidx]);
8436 }
8437 if (fset_bits & 1) {
8438 if (rare01_lowbits == kBitsPerWord) {
8439 if (fvals_widx == fvals_word_ct_m1) {
8440 fvals_bits = SubwordLoad(&(patch_01_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
8441 } else {
8442 CopyFromUnalignedOffsetW(&fvals_bits, patch_01_fvals, fvals_widx);
8443 }
8444 // unnecessary to apply bzhi here
8445 ++fvals_widx;
8446 rare01_lowbits = 0;
8447 }
8448 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_hets) / 2;
8449 if (sample_include_hw[sample_hwidx] & (1U << sample_uidx_lowbits)) {
8450 ++subsetted_rare01_ct;
8451 one_cts_offset2[(fvals_bits >> rare01_lowbits) & allele_code_mask] += 1;
8452 }
8453 rare01_lowbits += allele_code_width;
8454 }
8455 cur_raw_genoarr_hets &= cur_raw_genoarr_hets - 1;
8456 fset_bits = fset_bits >> 1;
8457 }
8458 }
8459 }
8460 one_cts_offset2[-1] -= subsetted_rare01_ct;
8461 if (allele_ct == 3) {
8462 one_cts_offset2[0] = subsetted_rare01_ct;
8463 }
8464 return kPglRetSuccess;
8465 }
8466 // mode 1: difflist.
8467 if (allele_ct == 3) {
8468 // Use CountDeltalistIntersect shortcut here.
8469 uint32_t subsetted_02_ct;
8470 uint32_t rare01_ct;
8471 PglErr reterr = CountDeltalistIntersect(fread_end, sample_include, raw_sample_ct, fread_pp, &subsetted_02_ct, &rare01_ct);
8472 if (unlikely(reterr)) {
8473 return reterr;
8474 }
8475 one_cts_offset2[-1] -= subsetted_02_ct;
8476 one_cts_offset2[0] = subsetted_02_ct;
8477 return kPglRetSuccess;
8478 }
8479 // Save deltalist elements, iterate.
8480 uint32_t rare01_ct;
8481 PglErr reterr = ParseAndSaveDeltalist(fread_end, raw_sample_ct, fread_pp, deltalist_workspace, &rare01_ct);
8482 if (unlikely(reterr)) {
8483 return reterr;
8484 }
8485 const unsigned char* patch_01_fvals = *fread_pp;
8486 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare01_ct) * allele_code_width, 8);
8487 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
8488 return kPglRetMalformedInput;
8489 }
8490 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
8491 const uint32_t allele_code_logwidth = ctzu32(allele_code_width);
8492 uint32_t subsetted_rare01_ct = 0;
8493 uint32_t loop_len = kBitsPerWord >> allele_code_logwidth;
8494 for (uint32_t fvals_widx = 0; ; ++fvals_widx) {
8495 uintptr_t fvals_bits;
8496 if (fvals_widx >= fvals_word_ct_m1) {
8497 if (fvals_widx > fvals_word_ct_m1) {
8498 break;
8499 }
8500 fvals_bits = SubwordLoad(&(patch_01_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
8501 loop_len = 1 + ((rare01_ct - 1) & (loop_len - 1));
8502 } else {
8503 CopyFromUnalignedOffsetW(&fvals_bits, patch_01_fvals, fvals_widx);
8504 }
8505 const uint32_t* cur_deltalist_base = &(deltalist_workspace[fvals_widx << (kBitsPerWordLog2 - allele_code_logwidth)]);
8506 for (uint32_t uii = 0; uii != loop_len; ++uii) {
8507 const uint32_t sample_uidx = cur_deltalist_base[uii];
8508 if (IsSet(sample_include, sample_uidx)) {
8509 ++subsetted_rare01_ct;
8510 one_cts_offset2[(fvals_bits >> (uii << allele_code_logwidth)) & allele_code_mask] += 1;
8511 }
8512 }
8513 }
8514 one_cts_offset2[-1] -= subsetted_rare01_ct;
8515 return kPglRetSuccess;
8516 }
8517
8518 void CountAllAux1bDense(const void* __restrict patch_10_fvals, uint32_t allele_ct, uint32_t rare10_ct, uint64_t* __restrict one_cts_offset1, uint64_t* __restrict two_cts_offset1) {
8519 // probable todo: faster path if two_cts_offset1 == nullptr
8520 const uint32_t allele_ct_m1 = allele_ct - 1;
8521 two_cts_offset1[0] -= rare10_ct;
8522 if (allele_ct_m1 < 5) {
8523 if (allele_ct_m1 == 2) {
8524 const uint32_t allele_code_byte_ct = DivUp(rare10_ct, 8);
8525 const uint32_t hom22_ct = PopcountBytes(patch_10_fvals, allele_code_byte_ct);
8526 const uint32_t het12_ct = rare10_ct - hom22_ct;
8527 one_cts_offset1[0] += het12_ct;
8528 one_cts_offset1[1] += het12_ct;
8529 two_cts_offset1[1] = hom22_ct;
8530 return;
8531 }
8532 STD_ARRAY_DECL(uint32_t, 4, alt_counts);
8533 #ifndef NO_UNALIGNED
8534 GenoarrCountFreqs(S_CAST(const uintptr_t*, patch_10_fvals), rare10_ct * 2, alt_counts);
8535 #else
8536 GenoarrbCountFreqs(S_CAST(const unsigned char*, patch_10_fvals), rare10_ct * 2, alt_counts);
8537 #endif
8538 one_cts_offset1[0] += alt_counts[0];
8539 for (uint32_t allele_idx_m1 = 1; allele_idx_m1 != allele_ct_m1; ++allele_idx_m1) {
8540 const uint32_t homxx_ct = CountNybble(S_CAST(const unsigned char*, patch_10_fvals), allele_idx_m1 * kMask5555, rare10_ct);
8541 one_cts_offset1[allele_idx_m1] += alt_counts[allele_idx_m1] - 2 * homxx_ct;
8542 two_cts_offset1[allele_idx_m1] = homxx_ct;
8543 }
8544 return;
8545 }
8546 const unsigned char* patch_10_fvals_uc = S_CAST(const unsigned char*, patch_10_fvals);
8547 if (allele_ct_m1 < 17) {
8548 // for larger rare10_ct, this should use a byte counter
8549 for (uint32_t uii = 0; uii != rare10_ct; ++uii) {
8550 const uint32_t cur_byte = patch_10_fvals_uc[uii];
8551 const uint32_t cur_byte_hi = cur_byte >> 4;
8552 const uint32_t cur_byte_lo = cur_byte & 15;
8553 if (cur_byte_hi == cur_byte_lo) {
8554 two_cts_offset1[cur_byte_lo] += 1;
8555 } else {
8556 one_cts_offset1[cur_byte_lo] += 1;
8557 one_cts_offset1[cur_byte_hi] += 1;
8558 }
8559 }
8560 return;
8561 }
8562 for (uint32_t uii = 0; uii != rare10_ct; ++uii) {
8563 const uint32_t cur_byte_lo = patch_10_fvals_uc[2 * uii];
8564 const uint32_t cur_byte_hi = patch_10_fvals_uc[2 * uii + 1];
8565 if (cur_byte_hi == cur_byte_lo) {
8566 two_cts_offset1[cur_byte_lo] += 1;
8567 } else {
8568 one_cts_offset1[cur_byte_lo] += 1;
8569 one_cts_offset1[cur_byte_hi] += 1;
8570 }
8571 }
8572 }
8573
8574 PglErr CountAllAux1b(const unsigned char* fread_end, const uintptr_t* __restrict sample_include, const uintptr_t* __restrict raw_genoarr, uint32_t aux1b_mode, uint32_t raw_sample_ct, uint32_t allele_ct, uint32_t raw_10_ct, const unsigned char** fread_pp, uint64_t* __restrict one_cts, uint64_t* __restrict two_cts, uint32_t* __restrict deltalist_workspace) {
8575 if (aux1b_mode == 15) {
8576 return kPglRetSuccess;
8577 }
8578 uint64_t* one_cts_offset1 = &(one_cts[1]);
8579 uint64_t* two_cts_offset1 = &(two_cts[1]);
8580 if (!sample_include) {
8581 uint32_t rare10_ct;
8582 if (!aux1b_mode) {
8583 const uint32_t fset_byte_ct = DivUp(raw_10_ct, CHAR_BIT);
8584 rare10_ct = PopcountBytes(*fread_pp, fset_byte_ct);
8585 *fread_pp += fset_byte_ct;
8586 } else {
8587 const unsigned char* group_info_iter;
8588 PglErr reterr = ParseDifflistHeader(fread_end, raw_sample_ct, fread_pp, nullptr, &group_info_iter, &rare10_ct);
8589 if (unlikely(reterr)) {
8590 return reterr;
8591 }
8592 reterr = SkipDeltalistIds(fread_end, group_info_iter, rare10_ct, raw_sample_ct, 0, fread_pp);
8593 if (unlikely(reterr)) {
8594 return reterr;
8595 }
8596 }
8597 const unsigned char* patch_10_fvals = *fread_pp;
8598 const uint32_t fvals_byte_ct = GetAux1bAlleleEntryByteCt(allele_ct, rare10_ct);
8599 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
8600 return kPglRetMalformedInput;
8601 }
8602 CountAllAux1bDense(patch_10_fvals, allele_ct, rare10_ct, one_cts_offset1, two_cts_offset1);
8603 return kPglRetSuccess;
8604 }
8605 uintptr_t detect_hom_mask_lo; // unused
8606 const uint32_t allele_code_logwidth = GetAux1bConsts(allele_ct, &detect_hom_mask_lo);
8607 const uint32_t code10_logwidth = allele_code_logwidth + (allele_code_logwidth != 0);
8608 const uint32_t allele_code_width = 1U << allele_code_logwidth;
8609 const uint32_t allele_code_mask = (1U << allele_code_width) - 1;
8610 const uint32_t allele_ct_m1 = allele_ct - 1;
8611 uint32_t rare10_lowbits = kBitsPerWord;
8612 // probable todo: faster paths when two_cts_offset1 == nullptr
8613 if (!aux1b_mode) {
8614 const uint32_t fset_byte_ct = DivUp(raw_10_ct, CHAR_BIT);
8615 const uint32_t rare10_ct = PopcountBytes(*fread_pp, fset_byte_ct);
8616 const unsigned char* patch_10_fset = *fread_pp;
8617 *fread_pp += fset_byte_ct;
8618 const unsigned char* patch_10_fvals = *fread_pp;
8619 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare10_ct) << code10_logwidth, 8);
8620 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
8621 return kPglRetMalformedInput;
8622 }
8623 const Halfword* sample_include_hw = DowncastKWToHW(sample_include);
8624 uintptr_t sample_hwidx = 0;
8625 uintptr_t cur_raw_genoarr_xys = Word10(raw_genoarr[0]);
8626 const uint32_t fset_word_ct_m1 = (fset_byte_ct - 1) / kBytesPerWord;
8627 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
8628 const uint32_t code10_width = 1U << code10_logwidth;
8629 uintptr_t fvals_bits = 0;
8630 uint32_t fvals_widx = 0;
8631 uint32_t subsetted_rare10_ct = 0;
8632 uint32_t loop_len = kBitsPerWord;
8633 for (uint32_t fset_widx = 0; ; ++fset_widx) {
8634 uintptr_t fset_bits;
8635 if (fset_widx >= fset_word_ct_m1) {
8636 if (fset_widx > fset_word_ct_m1) {
8637 break;
8638 }
8639 fset_bits = SubwordLoad(&(patch_10_fset[fset_word_ct_m1 * kBytesPerWord]), ModNz(fset_byte_ct, kBytesPerWord));
8640 loop_len = ModNz(raw_10_ct, kBitsPerWord);
8641 } else {
8642 CopyFromUnalignedOffsetW(&fset_bits, patch_10_fset, fset_widx);
8643 }
8644 if (allele_ct_m1 == 2) {
8645 for (uint32_t uii = 0; uii != loop_len; ++uii) {
8646 while (!cur_raw_genoarr_xys) {
8647 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
8648 }
8649 if (fset_bits & 1) {
8650 if (rare10_lowbits == kBitsPerWord) {
8651 if (fvals_widx == fvals_word_ct_m1) {
8652 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
8653 } else {
8654 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
8655 }
8656 // unnecessary to apply bzhi here
8657 ++fvals_widx;
8658 rare10_lowbits = 0;
8659 }
8660 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_xys) / 2;
8661 if (sample_include_hw[sample_hwidx] & (1U << sample_uidx_lowbits)) {
8662 ++subsetted_rare10_ct;
8663 two_cts_offset1[1] += (fvals_bits >> rare10_lowbits) & 1;
8664 }
8665 ++rare10_lowbits;
8666 }
8667 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
8668 fset_bits = fset_bits >> 1;
8669 }
8670 } else {
8671 for (uint32_t uii = 0; uii != loop_len; ++uii) {
8672 while (!cur_raw_genoarr_xys) {
8673 cur_raw_genoarr_xys = Word10(raw_genoarr[++sample_hwidx]);
8674 }
8675 if (fset_bits & 1) {
8676 if (rare10_lowbits == kBitsPerWord) {
8677 if (fvals_widx == fvals_word_ct_m1) {
8678 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
8679 } else {
8680 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
8681 }
8682 // unnecessary to apply bzhi here
8683 ++fvals_widx;
8684 rare10_lowbits = 0;
8685 }
8686 const uint32_t sample_uidx_lowbits = ctzw(cur_raw_genoarr_xys) / 2;
8687 if (sample_include_hw[sample_hwidx] & (1U << sample_uidx_lowbits)) {
8688 ++subsetted_rare10_ct;
8689 const uintptr_t cur_code_pair = fvals_bits >> rare10_lowbits;
8690 const uint32_t cur_code_hi = (cur_code_pair >> allele_code_width) & allele_code_mask;
8691 const uint32_t cur_code_lo = cur_code_pair & allele_code_mask;
8692 if (cur_code_hi == cur_code_lo) {
8693 two_cts_offset1[cur_code_lo] += 1;
8694 } else {
8695 one_cts_offset1[cur_code_lo] += 1;
8696 one_cts_offset1[cur_code_hi] += 1;
8697 }
8698 }
8699 rare10_lowbits += code10_width;
8700 }
8701 cur_raw_genoarr_xys &= cur_raw_genoarr_xys - 1;
8702 fset_bits = fset_bits >> 1;
8703 }
8704 }
8705 }
8706 two_cts_offset1[0] -= subsetted_rare10_ct;
8707 if (allele_ct == 3) {
8708 const uint32_t subsetted_het12_ct = subsetted_rare10_ct - two_cts_offset1[1];
8709 one_cts_offset1[0] += subsetted_het12_ct;
8710 one_cts_offset1[1] += subsetted_het12_ct;
8711 }
8712 return kPglRetSuccess;
8713 }
8714 // Save deltalist elements, iterate.
8715 uint32_t rare10_ct;
8716 PglErr reterr = ParseAndSaveDeltalist(fread_end, raw_sample_ct, fread_pp, deltalist_workspace, &rare10_ct);
8717 if (unlikely(reterr)) {
8718 return reterr;
8719 }
8720 const unsigned char* patch_10_fvals = *fread_pp;
8721 const uint32_t fvals_byte_ct = DivUpU64(S_CAST(uint64_t, rare10_ct) << code10_logwidth, 8);
8722 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
8723 return kPglRetMalformedInput;
8724 }
8725 const uint32_t fvals_word_ct_m1 = (fvals_byte_ct - 1) / kBytesPerWord;
8726 uint32_t subsetted_rare10_ct = 0;
8727 uint32_t loop_len = kBitsPerWord >> code10_logwidth;
8728 for (uint32_t fvals_widx = 0; ; ++fvals_widx) {
8729 uintptr_t fvals_bits;
8730 if (fvals_widx >= fvals_word_ct_m1) {
8731 if (fvals_widx > fvals_word_ct_m1) {
8732 break;
8733 }
8734 fvals_bits = SubwordLoad(&(patch_10_fvals[fvals_widx * kBytesPerWord]), ModNz(fvals_byte_ct, kBytesPerWord));
8735 loop_len = 1 + ((rare10_ct - 1) & (loop_len - 1));
8736 } else {
8737 CopyFromUnalignedOffsetW(&fvals_bits, patch_10_fvals, fvals_widx);
8738 }
8739 const uint32_t* cur_deltalist_base = &(deltalist_workspace[fvals_widx << (kBitsPerWordLog2 - code10_logwidth)]);
8740 if (allele_ct == 3) {
8741 for (uint32_t uii = 0; uii != loop_len; ++uii) {
8742 const uint32_t sample_uidx = cur_deltalist_base[uii];
8743 if (IsSet(sample_include, sample_uidx)) {
8744 ++subsetted_rare10_ct;
8745 two_cts_offset1[1] += (fvals_bits >> uii) & 1;
8746 }
8747 }
8748 } else {
8749 for (uint32_t uii = 0; uii != loop_len; ++uii) {
8750 const uint32_t sample_uidx = cur_deltalist_base[uii];
8751 if (IsSet(sample_include, sample_uidx)) {
8752 ++subsetted_rare10_ct;
8753 const uintptr_t cur_code_pair = fvals_bits >> (uii << code10_logwidth);
8754 const uint32_t cur_code_hi = (cur_code_pair >> allele_code_width) & allele_code_mask;
8755 const uint32_t cur_code_lo = cur_code_pair & allele_code_mask;
8756 if (cur_code_hi == cur_code_lo) {
8757 two_cts_offset1[cur_code_lo] += 1;
8758 } else {
8759 one_cts_offset1[cur_code_lo] += 1;
8760 one_cts_offset1[cur_code_hi] += 1;
8761 }
8762 }
8763 }
8764 }
8765 }
8766 two_cts_offset1[0] -= subsetted_rare10_ct;
8767 if (allele_ct == 3) {
8768 const uint32_t subsetted_het12_ct = subsetted_rare10_ct - two_cts_offset1[1];
8769 one_cts_offset1[0] += subsetted_het12_ct;
8770 one_cts_offset1[1] += subsetted_het12_ct;
8771 }
8772 return kPglRetSuccess;
8773 }
8774
8775 PglErr GetMultiallelicCountsAndDosage16s(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict sample_include_interleaved_vec, uint32_t sample_ct, uint32_t vidx, uint32_t allele_ct, __maybe_unused uint32_t is_minimac3_r2, PgenReaderMain* pgrp, double* __restrict imp_r2_ptr, uint32_t* __restrict het_ctp, STD_ARRAY_REF(uint32_t, 4) genocounts, uint64_t* all_dosages) {
8776 // only called on multiallelic variants
8777 // no dosages for now
8778 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
8779 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
8780 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
8781 uintptr_t* raw_genovec = pgrp->workspace_vec;
8782 const unsigned char* fread_ptr;
8783 const unsigned char* fread_end;
8784 PglErr reterr = ReadRawGenovec(subsetting_required, vidx, pgrp, &fread_ptr, &fread_end, raw_genovec);
8785 if (unlikely(reterr)) {
8786 return reterr;
8787 }
8788 ZeroTrailingNyps(raw_sample_ct, raw_genovec);
8789 if (!subsetting_required) {
8790 GenoarrCountFreqsUnsafe(raw_genovec, raw_sample_ct, genocounts);
8791 sample_include = nullptr;
8792 } else {
8793 GenoarrCountSubsetFreqs(raw_genovec, sample_include_interleaved_vec, raw_sample_ct, sample_ct, genocounts);
8794 }
8795 uint64_t* one_cts = pgrp->workspace_imp_r2;
8796 uint64_t* two_cts = &(one_cts[allele_ct]);
8797 one_cts[0] = genocounts[1];
8798 one_cts[1] = genocounts[1];
8799 ZeroU64Arr(allele_ct - 2, &(one_cts[2]));
8800 two_cts[0] = genocounts[0];
8801 two_cts[1] = genocounts[2];
8802 ZeroU64Arr(allele_ct - 2, &(two_cts[2]));
8803 // Cases:
8804 // - No hardcall-phase present. Then we don't need to know raw_het_ct.
8805 // - No multiallelic dosages present, not computing minimac3-r2. Then we
8806 // still don't need to know raw_het_ct.
8807 // - Otherwise, we need to know raw_het_ct, either for the minimac3-r2
8808 // computation or to locate the beginning of aux3/aux4.
8809 // If we're computing minimac3-r2, AND
8810 // (i) we're subsetting, or
8811 // (ii) multiallelic dosages are present,
8812 // it's also necessary to compute all_hets, either to compute correct
8813 // subsetted minimac3-r2 or to know how many phased-hardcalls are
8814 // overridden by phased dosages.
8815 const uint32_t raw_het_ct_needed = VrtypeHphase(vrtype) && (is_minimac3_r2 || (vrtype & 0x60));
8816 uintptr_t* all_hets = nullptr;
8817 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
8818 uint32_t raw_het_ct = genocounts[1]; // inaccurate, corrected later if needed
8819 if (VrtypeMultiallelicHc(vrtype)) {
8820 const uint32_t aux1_first_byte = *fread_ptr++;
8821 const uint32_t aux1a_mode = aux1_first_byte & 15;
8822 const uint32_t aux1b_mode = aux1_first_byte >> 4;
8823 uint32_t raw_10_ct = 0;
8824 if ((!aux1a_mode) || (!aux1b_mode) || sample_include) {
8825 GenovecCount12Unsafe(raw_genovec, raw_sample_ct, &raw_het_ct, &raw_10_ct);
8826 }
8827 uint32_t* deltalist_workspace = pgrp->workspace_difflist_sample_ids;
8828 reterr = CountAllAux1a(fread_end, sample_include, raw_genovec, aux1a_mode, raw_sample_ct, allele_ct, raw_het_ct, &fread_ptr, one_cts, deltalist_workspace);
8829 if (unlikely(reterr)) {
8830 return reterr;
8831 }
8832 const unsigned char* aux1b_start = fread_ptr;
8833 reterr = CountAllAux1b(fread_end, sample_include, raw_genovec, aux1b_mode, raw_sample_ct, allele_ct, raw_10_ct, &fread_ptr, one_cts, two_cts, deltalist_workspace);
8834 if (unlikely(reterr)) {
8835 return reterr;
8836 }
8837 if (raw_het_ct_needed) {
8838 if (!sample_include) {
8839 raw_het_ct += genocounts[2];
8840 for (uint32_t aidx = 1; aidx != allele_ct; ++aidx) {
8841 raw_het_ct -= two_cts[aidx];
8842 }
8843 }
8844 if (sample_include || (is_minimac3_r2 && (vrtype & 0x60))) {
8845 all_hets = pgrp->workspace_all_hets;
8846 PgrDetectGenoarrHets(raw_genovec, raw_sample_ct, all_hets);
8847 if (aux1b_mode != 15) {
8848 uintptr_t* aux1b_hets = pgrp->workspace_aux1x_present;
8849 uint32_t aux1b_het_present;
8850 reterr = GetAux1bHets(fread_end, raw_genovec, aux1b_mode, raw_sample_ct, allele_ct, raw_10_ct, &aux1b_start, aux1b_hets, &aux1b_het_present, deltalist_workspace);
8851 if (unlikely(reterr)) {
8852 return reterr;
8853 }
8854 if (aux1b_het_present) {
8855 BitvecOr(aux1b_hets, raw_sample_ctl, all_hets);
8856 }
8857 }
8858 if (sample_include) {
8859 raw_het_ct = PopcountWords(all_hets, raw_sample_ctl);
8860 }
8861 }
8862 }
8863 }
8864 uintptr_t* raw_phasepresent = nullptr;
8865 uint32_t extra_phased_het_ct = 0;
8866 if (raw_het_ct_needed) {
8867 if (!all_hets) {
8868 reterr = SkipAux2(fread_end, raw_het_ct, &fread_ptr, is_minimac3_r2? (&extra_phased_het_ct) : nullptr);
8869 if (unlikely(reterr)) {
8870 return reterr;
8871 }
8872 } else {
8873 raw_phasepresent = pgrp->workspace_subset;
8874 reterr = GetPhasepresentAndSkipPhaseinfo(fread_end, all_hets, raw_sample_ct, raw_het_ct, &fread_ptr, raw_phasepresent, &extra_phased_het_ct);
8875 if (unlikely(reterr)) {
8876 return reterr;
8877 }
8878 if (sample_include) {
8879 extra_phased_het_ct = PopcountWordsIntersect(raw_phasepresent, sample_include, raw_sample_ctl);
8880 }
8881 }
8882 }
8883 if (!(vrtype & 0x60)) {
8884 uint32_t hom_hc_ct = 0;
8885 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
8886 const uint64_t cur_hom_ct = two_cts[allele_idx];
8887 hom_hc_ct += cur_hom_ct;
8888 const uint64_t two_dosage = cur_hom_ct * 0x8000LLU;
8889 const uint64_t dosage_sum = one_cts[allele_idx] * 0x4000LLU + two_dosage;
8890 all_dosages[allele_idx] = dosage_sum;
8891 // Repurpose two_cts[] to store ssqs.
8892 two_cts[allele_idx] = (dosage_sum + two_dosage) * 0x4000LLU;
8893 }
8894 const uint32_t nm_sample_ct = sample_ct - genocounts[3];
8895 *het_ctp = nm_sample_ct - hom_hc_ct;
8896 if (!imp_r2_ptr) {
8897 return kPglRetSuccess;
8898 }
8899 *imp_r2_ptr = MultiallelicDiploidMinimac3R2(all_dosages, two_cts, nm_sample_ct, allele_ct, extra_phased_het_ct);
8900 if (!is_minimac3_r2) {
8901 *imp_r2_ptr *= 2;
8902 }
8903 return kPglRetSuccess;
8904 }
8905 #ifndef PGENLIB_NOPRINT
8906 fputs("dosages not yet supported by GetMultiallelicCountsAndDosage16s()\n", stderr);
8907 #endif
8908 return kPglRetNotYetSupported;
8909 }
8910
8911 PglErr PgrGetMDCounts(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict sample_include_interleaved_vec, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, uint32_t is_minimac3_r2, PgenReader* pgr_ptr, double* __restrict imp_r2_ptr, uint32_t* __restrict het_ctp, STD_ARRAY_REF(uint32_t, 4) genocounts, uint64_t* __restrict all_dosages) {
8912 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
8913 assert(vidx < pgrp->fi.raw_variant_ct);
8914 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
8915 const uint32_t allele_ct = allele_idx_offsets? (allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx]) : 2;
8916 if (!sample_ct) {
8917 STD_ARRAY_REF_FILL0(4, genocounts);
8918 ZeroU64Arr(allele_ct, all_dosages);
8919 if (imp_r2_ptr) {
8920 *imp_r2_ptr = 0.0 / 0.0;
8921 }
8922 return kPglRetSuccess;
8923 }
8924 const uint32_t* sample_include_cumulative_popcounts = GetSicp(pssi);
8925 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
8926 if ((allele_ct == 2) || (!(vrtype & 0x68))) {
8927 PglErr reterr = GetBasicGenotypeCountsAndDosage16s(sample_include, sample_include_interleaved_vec, sample_include_cumulative_popcounts, sample_ct, vidx, is_minimac3_r2, pgrp, imp_r2_ptr, genocounts, all_dosages);
8928 *het_ctp = genocounts[1];
8929 ZeroU64Arr(allele_ct - 2, &(all_dosages[2]));
8930 return reterr;
8931 }
8932 return GetMultiallelicCountsAndDosage16s(sample_include, sample_include_interleaved_vec, sample_ct, vidx, allele_ct, is_minimac3_r2, pgrp, imp_r2_ptr, het_ctp, genocounts, all_dosages);
8933 }
8934
8935 PglErr PgrGetMD(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, PgenVariant* pgvp) {
8936 pgvp->patch_01_ct = 0;
8937 pgvp->patch_10_ct = 0;
8938 pgvp->dosage_ct = 0;
8939 pgvp->multidosage_sample_ct = 0;
8940 if (!sample_ct) {
8941 return kPglRetSuccess;
8942 }
8943 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
8944 const uint32_t* sample_include_cumulative_popcounts = GetSicp(pssi);
8945 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
8946 const uint32_t allele_ct = allele_idx_offsets? (allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx]) : 2;
8947 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
8948 if ((allele_ct == 2) || (!(vrtype & 0x68))) {
8949 return IMPLPgrGetD(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, pgvp->genovec, pgvp->dosage_present, pgvp->dosage_main, &(pgvp->dosage_ct));
8950 }
8951 const unsigned char* fread_ptr;
8952 const unsigned char* fread_end;
8953 uintptr_t* all_hets = VrtypeHphase(vrtype)? pgrp->workspace_all_hets : nullptr;
8954 if (VrtypeMultiallelicHc(vrtype)) {
8955 PglErr reterr = GetMultiallelicCodes(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, all_hets? (&fread_ptr) : nullptr, all_hets? (&fread_end) : nullptr, all_hets, pgvp);
8956 if (!(vrtype & 0x60)) {
8957 return reterr;
8958 }
8959 } else {
8960 // todo: ReadRawGenovec, etc.
8961 }
8962 #ifndef PGENLIB_NOPRINT
8963 fputs("true multiallelic dosages not yet supported by PgrGetMD()\n", stderr);
8964 #endif
8965 return kPglRetNotYetSupported;
8966 }
8967
8968 PglErr IMPLPgrGetDp(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, PgenReaderMain* pgrp, PgenVariant* pgvp) {
8969 assert(vidx < pgrp->fi.raw_variant_ct);
8970 if (!sample_ct) {
8971 pgvp->phasepresent_ct = 0;
8972 pgvp->dosage_ct = 0;
8973 pgvp->dphase_ct = 0;
8974 return kPglRetSuccess;
8975 }
8976 const unsigned char* fread_ptr = nullptr;
8977 const unsigned char* fread_end = nullptr;
8978 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
8979 const uint32_t dosage_is_present = VrtypeDosage(vrtype);
8980 PglErr reterr = ReadGenovecHphaseSubsetUnsafe(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, dosage_is_present? (&fread_ptr) : nullptr, dosage_is_present? (&fread_end) : nullptr, pgvp->genovec, pgvp->phasepresent, pgvp->phaseinfo, &(pgvp->phasepresent_ct));
8981 if (reterr || (!dosage_is_present)) {
8982 pgvp->dosage_ct = 0;
8983 pgvp->dphase_ct = 0;
8984 return reterr;
8985 }
8986 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
8987 const uint32_t allele_ct = allele_idx_offsets? (allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx]) : 2;
8988 return ParseDosage16(fread_ptr, fread_end, sample_include, sample_ct, vidx, allele_ct, pgrp, &(pgvp->dosage_ct), pgvp->dphase_present, pgvp->dphase_delta, &(pgvp->dphase_ct), pgvp->dosage_present, pgvp->dosage_main);
8989 }
8990
8991 PglErr PgrGetInv1Dp(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, AlleleCode allele_idx, PgenReader* pgr_ptr, PgenVariant* pgvp) {
8992 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
8993 const uint32_t* sample_include_cumulative_popcounts = GetSicp(pssi);
8994 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
8995 const uint32_t allele_ct = allele_idx_offsets? (allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx]) : 2;
8996 if ((allele_ct == 2) || (!allele_idx)) {
8997 PglErr reterr = IMPLPgrGetDp(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, pgvp);
8998 if (allele_idx) {
8999 GenovecInvertUnsafe(sample_ct, pgvp->genovec);
9000 if (pgvp->phasepresent_ct) {
9001 BitvecInvert(BitCtToWordCt(sample_ct), pgvp->phaseinfo);
9002 }
9003 if (pgvp->dosage_ct) {
9004 BiallelicDosage16Invert(pgvp->dosage_ct, pgvp->dosage_main);
9005 if (pgvp->dphase_ct) {
9006 BiallelicDphase16Invert(pgvp->dphase_ct, pgvp->dphase_delta);
9007 }
9008 }
9009 }
9010 return reterr;
9011 }
9012 const uint32_t vrtype = pgrp->fi.vrtypes[vidx];
9013 if (!VrtypeDosage(vrtype)) {
9014 pgvp->dosage_ct = 0;
9015 pgvp->dphase_ct = 0;
9016 return IMPLPgrGetInv1P(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx, pgrp, pgvp->genovec, pgvp->phasepresent, pgvp->phaseinfo, &(pgvp->phasepresent_ct));
9017 }
9018 #ifndef PGENLIB_NOPRINT
9019 fputs("multiallelic dosage not yet supported by GetInv1Dp()\n", stderr);
9020 #endif
9021 return kPglRetNotYetSupported;
9022 }
9023
9024 PglErr PgrGetMDp(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, PgenVariant* pgvp) {
9025 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
9026 const uint32_t* sample_include_cumulative_popcounts = GetSicp(pssi);
9027 pgvp->patch_01_ct = 0;
9028 pgvp->patch_10_ct = 0;
9029 pgvp->phasepresent_ct = 0;
9030 pgvp->dosage_ct = 0;
9031 pgvp->multidosage_sample_ct = 0;
9032 pgvp->dphase_ct = 0;
9033 pgvp->multidphase_sample_ct = 0;
9034 if (!sample_ct) {
9035 return kPglRetSuccess;
9036 }
9037 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
9038 const uint32_t allele_ct = allele_idx_offsets? (allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx]) : 2;
9039 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
9040 if ((allele_ct == 2) || (!(vrtype & 0x68))) {
9041 return IMPLPgrGetDp(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, pgvp);
9042 }
9043 const unsigned char* fread_ptr;
9044 const unsigned char* fread_end;
9045 uintptr_t* all_hets = VrtypeHphase(vrtype)? pgrp->workspace_all_hets : nullptr;
9046 if (VrtypeMultiallelicHc(vrtype)) {
9047 PglErr reterr = GetMultiallelicCodes(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, all_hets? (&fread_ptr) : nullptr, all_hets? (&fread_end) : nullptr, all_hets, pgvp);
9048 if (reterr || (!all_hets)) {
9049 pgvp->phasepresent_ct = 0;
9050 return reterr;
9051 }
9052 if (!(vrtype & 0x60)) {
9053 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
9054 return ParseAux2Subset(fread_end, (sample_ct != raw_sample_ct)? sample_include : nullptr, all_hets, nullptr, raw_sample_ct, sample_ct, &fread_ptr, pgvp->phasepresent, pgvp->phaseinfo, &(pgvp->phasepresent_ct), pgrp->workspace_subset);
9055 }
9056 } else {
9057 // todo: ReadRawGenovec, etc.
9058 }
9059 #ifndef PGENLIB_NOPRINT
9060 fputs("true multiallelic dosages not yet supported by PgrGetMDp()\n", stderr);
9061 #endif
9062 return kPglRetNotYetSupported;
9063 }
9064
9065 static_assert(sizeof(AlleleCode) == 1, "CountAux1bHets() must be updated.");
9066 uintptr_t CountAux1bHets(const AlleleCode* patch_10_vals, uintptr_t rare10_ct) {
9067 // Similar to CountByte().
9068 uintptr_t byte_ct = rare10_ct * 2;
9069 #ifdef __LP64__
9070 if (byte_ct < kBytesPerVec) {
9071 #endif
9072 uintptr_t tot = 0;
9073 for (uintptr_t offset = 0; offset < byte_ct; offset += 2) {
9074 tot += (patch_10_vals[offset] != patch_10_vals[offset + 1]);
9075 }
9076 return tot;
9077 #ifdef __LP64__
9078 }
9079 const unsigned char* bytearr_uc_iter = DowncastKToUc(patch_10_vals);
9080 const VecW m0 = vecw_setzero();
9081 const VecW m8 = VCONST_W(kMask00FF);
9082 VecW acc = vecw_setzero();
9083 while (byte_ct > 255 * kBytesPerVec) {
9084 VecUc inner_acc = vecuc_setzero();
9085 for (uint32_t uii = 0; uii != 255; ++uii) {
9086 const VecUc cur_vvec = vecuc_loadu(bytearr_uc_iter);
9087 bytearr_uc_iter = &(bytearr_uc_iter[kBytesPerVec]);
9088 const VecUc shifted_vvec = VecWToUc(vecw_srli(VecUcToW(cur_vvec), 8));
9089 inner_acc = inner_acc - (cur_vvec == shifted_vvec);
9090 }
9091 const VecW partial_sums = VecUcToW(inner_acc) & m8;
9092 acc = acc + vecw_sad(partial_sums, m0);
9093 byte_ct -= 255 * kBytesPerVec;
9094 }
9095 const unsigned char* bytearr_uc_final = &(bytearr_uc_iter[byte_ct - kBytesPerVec]);
9096 VecUc inner_acc = vecuc_setzero();
9097 while (bytearr_uc_iter < bytearr_uc_final) {
9098 const VecUc cur_vvec = vecuc_loadu(bytearr_uc_iter);
9099 bytearr_uc_iter = &(bytearr_uc_iter[kBytesPerVec]);
9100 const VecUc shifted_vvec = VecWToUc(vecw_srli(VecUcToW(cur_vvec), 8));
9101 inner_acc = inner_acc - (cur_vvec == shifted_vvec);
9102 }
9103 VecUc cur_vvec = vecuc_loadu(bytearr_uc_final);
9104 const uintptr_t overlap_byte_ct = bytearr_uc_iter - bytearr_uc_final;
9105 const VecUc shifted_vvec = VecWToUc(vecw_srli(VecUcToW(cur_vvec), 8));
9106 const VecUc mask_vvec = vecuc_loadu(&(kLeadMask[kBytesPerVec - overlap_byte_ct]));
9107 cur_vvec = (cur_vvec == shifted_vvec) & mask_vvec;
9108 inner_acc = inner_acc - cur_vvec;
9109 const VecW partial_sums = VecUcToW(inner_acc) & m8;
9110 acc = acc + vecw_sad(partial_sums, m0);
9111 const uintptr_t tot = HsumW(acc);
9112 return rare10_ct - tot;
9113 #endif
9114 }
9115
9116 PglErr PgrGetRaw(uint32_t vidx, PgenGlobalFlags read_gflags, PgenReader* pgr_ptr, uintptr_t** loadbuf_iter_ptr, unsigned char* loaded_vrtype_ptr) {
9117 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
9118 // currently handles multiallelic hardcalls, hardcall phase, and biallelic
9119 // dosage (both unphased and phased)
9120 // todo: multiallelic dosage
9121 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
9122 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
9123 uintptr_t* genovec = (*loadbuf_iter_ptr);
9124 uintptr_t* loadbuf_iter = &(genovec[NypCtToAlignedWordCt(raw_sample_ct)]);
9125 const uint32_t multiallelic_hc_present = (vrtype / 8) & 1;
9126 const uint32_t save_multiallelic_hc = multiallelic_hc_present && (read_gflags & kfPgenGlobalMultiallelicHardcallFound);
9127 const uint32_t hphase_is_present = (vrtype / 0x10) & 1;
9128 const uint32_t save_hphase = hphase_is_present && (read_gflags & kfPgenGlobalHardcallPhasePresent);
9129 const uint32_t dosage_is_present = (vrtype & 0x60)? 1 : 0;
9130 const uint32_t save_dosage = dosage_is_present && (read_gflags & kfPgenGlobalDosagePresent);
9131
9132 const uint32_t save_dphase = (vrtype & 0x80) && (read_gflags & kfPgenGlobalDosagePhasePresent);
9133 assert(save_dosage || (!save_dphase));
9134
9135 if (loaded_vrtype_ptr) {
9136 *loaded_vrtype_ptr = save_multiallelic_hc * 8 + save_hphase * 0x10 + save_dosage * 0x60 + save_dphase * 0x80;
9137 }
9138 const unsigned char* fread_ptr;
9139 const unsigned char* fread_end;
9140 PglErr reterr = ReadRawGenovec(0, vidx, pgrp, &fread_ptr, &fread_end, genovec);
9141 if ((!(multiallelic_hc_present || save_hphase || save_dosage)) || reterr) {
9142 *loadbuf_iter_ptr = loadbuf_iter;
9143 return reterr;
9144 }
9145
9146 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
9147 ZeroTrailingNyps(raw_sample_ct, genovec);
9148 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
9149 const uint32_t allele_ct = allele_idx_offsets? (allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx]) : 2;
9150 uint32_t het_ct = 0;
9151 if (multiallelic_hc_present) {
9152 if (!save_multiallelic_hc) {
9153 // todo: erase-alt2+ fast path
9154 // mostly mirror PgrGet2P(0, 1), but a bit of extra logic is needed to
9155 // throw out phased-10het entries
9156 return kPglRetNotYetSupported;
9157 }
9158 // assume we always save multiallelic info
9159 // raw format:
9160 // rare01_ct, padded out to a word
9161 // rare10_ct, padded out to a word
9162 // [round up to vector boundary, for patch_01_set]
9163 // aux1a, if not mode 15:
9164 // patch_01_set as bitarray, raw_sample_ctl words
9165 // patch_01_vals, round up to word boundary
9166 // [round up to vector boundary, for patch_10_set]
9167 // aux1b, if not mode 15:
9168 // patch_10_set as bitarray, raw_sample_ctl words
9169 // patch_10_vals, round up to word boundary
9170 // round up to vector boundary at end
9171 const uint32_t aux1_first_byte = *fread_ptr++;
9172 const uint32_t aux1a_mode = aux1_first_byte & 15;
9173 const uint32_t aux1b_mode = aux1_first_byte >> 4;
9174 uint32_t raw_10_ct = 0;
9175 if ((!aux1a_mode) || hphase_is_present) {
9176 if (!aux1b_mode) {
9177 GenovecCount12Unsafe(genovec, raw_sample_ct, &het_ct, &raw_10_ct);
9178 } else {
9179 het_ct = CountNyp(genovec, kMask5555, raw_sample_ct);
9180 }
9181 } else if (!aux1b_mode) {
9182 raw_10_ct = CountNyp(genovec, kMaskAAAA, raw_sample_ct);
9183 }
9184 uintptr_t* multihc_raw = loadbuf_iter;
9185 loadbuf_iter = &(loadbuf_iter[RoundUpPow2(2, kWordsPerVec)]);
9186 uint32_t rare01_ct = 0;
9187 if (aux1a_mode != 15) {
9188 uintptr_t* patch_01_set = loadbuf_iter;
9189 loadbuf_iter = &(loadbuf_iter[raw_sample_ctl]);
9190 // (could decide to vector-align patch_01_vals later)
9191 AlleleCode* patch_01_vals = DowncastWToAC(loadbuf_iter);
9192 reterr = ExportAux1a(fread_end, genovec, aux1a_mode, raw_sample_ct, allele_ct, het_ct, &fread_ptr, patch_01_set, patch_01_vals, &rare01_ct);
9193 if (unlikely(reterr)) {
9194 return reterr;
9195 }
9196 loadbuf_iter = &(loadbuf_iter[DivUp(rare01_ct, kBytesPerWord / sizeof(AlleleCode))]);
9197 AlignWToVec(&loadbuf_iter);
9198 }
9199 uint32_t rare10_ct = 0;
9200 if (aux1b_mode != 15) {
9201 uintptr_t* patch_10_set = loadbuf_iter;
9202 loadbuf_iter = &(loadbuf_iter[raw_sample_ctl]);
9203 AlleleCode* patch_10_vals = DowncastWToAC(loadbuf_iter);
9204 reterr = ExportAux1b(fread_end, genovec, aux1b_mode, raw_sample_ct, allele_ct, raw_10_ct, &fread_ptr, patch_10_set, patch_10_vals, &rare10_ct);
9205 if (unlikely(reterr)) {
9206 return reterr;
9207 }
9208 loadbuf_iter = &(loadbuf_iter[DivUp(rare10_ct, kBytesPerWord / (2 * sizeof(AlleleCode)))]);
9209 AlignWToVec(&loadbuf_iter);
9210 if (hphase_is_present) {
9211 het_ct += CountAux1bHets(patch_10_vals, rare10_ct);
9212 }
9213 }
9214 multihc_raw[0] = rare01_ct;
9215 multihc_raw[1] = rare10_ct;
9216 } else if (hphase_is_present) {
9217 het_ct = CountNyp(genovec, kMask5555, raw_sample_ct);
9218 }
9219
9220 if (hphase_is_present) {
9221 if (unlikely(!het_ct)) {
9222 // there shouldn't be a hphase track at all in this case
9223 return kPglRetMalformedInput;
9224 }
9225 const uint32_t het_ctdl = het_ct / kBitsPerWord;
9226 uintptr_t* phaseraw = loadbuf_iter;
9227 const uint32_t first_half_byte_ct = 1 + (het_ct / CHAR_BIT);
9228 if (save_hphase) {
9229 // this needs to be synced with MakePgenThread()
9230 #ifdef __LP64__
9231 // save het_ct later so we can use PopcountWords() below
9232 phaseraw[0] = 0;
9233 #else
9234 phaseraw[0] = het_ct;
9235 phaseraw[1] = 0;
9236 #endif
9237 loadbuf_iter = &(loadbuf_iter[8 / kBytesPerWord]);
9238 loadbuf_iter[het_ctdl] = 0;
9239 memcpy(loadbuf_iter, fread_ptr, first_half_byte_ct);
9240 loadbuf_iter = &(loadbuf_iter[1 + het_ctdl]);
9241 }
9242 const uint32_t explicit_phasepresent = fread_ptr[0] & 1;
9243 const unsigned char* aux2_start = fread_ptr;
9244 fread_ptr = &(fread_ptr[first_half_byte_ct]);
9245 if (explicit_phasepresent) {
9246 uint32_t raw_phasepresent_ct;
9247 if (save_hphase) {
9248 #ifdef __LP64__
9249 raw_phasepresent_ct = PopcountWords(phaseraw, het_ctdl + 2);
9250 #else
9251 raw_phasepresent_ct = PopcountWords(&(phaseraw[2]), het_ctdl + 1);
9252 #endif
9253 } else {
9254 // bugfix (11 Apr 2018): not copied to phaseraw in this case
9255 raw_phasepresent_ct = PopcountBytes(aux2_start, first_half_byte_ct);
9256 }
9257 --raw_phasepresent_ct;
9258 if (unlikely(!raw_phasepresent_ct)) {
9259 // there shouldn't be a hphase track at all in this case, either
9260 return kPglRetMalformedInput;
9261 }
9262 const uint32_t second_half_byte_ct = DivUp(raw_phasepresent_ct, CHAR_BIT);
9263 if (save_hphase) {
9264 #ifdef __LP64__
9265 phaseraw[0] = het_ct | (S_CAST(uint64_t, raw_phasepresent_ct) << 32);
9266 #else
9267 phaseraw[1] = raw_phasepresent_ct;
9268 #endif
9269 memcpy(loadbuf_iter, fread_ptr, second_half_byte_ct);
9270 loadbuf_iter = &(loadbuf_iter[BitCtToWordCt(raw_phasepresent_ct)]);
9271 }
9272 fread_ptr = &(fread_ptr[second_half_byte_ct]);
9273 }
9274 #ifdef __LP64__
9275 if (save_hphase) {
9276 if (!explicit_phasepresent) {
9277 phaseraw[0] = het_ct;
9278 }
9279 AlignWToVec(&loadbuf_iter);
9280 }
9281 #endif
9282 }
9283 if (!save_dosage) {
9284 *loadbuf_iter_ptr = loadbuf_iter;
9285 return kPglRetSuccess;
9286 }
9287 uintptr_t* dosage_present = loadbuf_iter;
9288 const uint32_t raw_sample_ctaw = BitCtToAlignedWordCt(raw_sample_ct);
9289 loadbuf_iter = &(loadbuf_iter[raw_sample_ctaw]);
9290 uint16_t* dosage_main = DowncastWToU16(loadbuf_iter);
9291 // probable todo: pack this more tightly in the future
9292 const uintptr_t dosage_main_aligned_wordct = kWordsPerVec * DivUp(raw_sample_ct, (kBytesPerVec / sizeof(int16_t)));
9293 loadbuf_iter = &(loadbuf_iter[dosage_main_aligned_wordct]);
9294 uintptr_t* dphase_present = nullptr;
9295 int16_t* dphase_delta = nullptr;
9296 if (save_dphase) {
9297 dphase_present = loadbuf_iter;
9298 loadbuf_iter = &(loadbuf_iter[raw_sample_ctaw]);
9299 dphase_delta = DowncastWToI16(loadbuf_iter);
9300 loadbuf_iter = &(loadbuf_iter[dosage_main_aligned_wordct]);
9301 }
9302 *loadbuf_iter_ptr = loadbuf_iter;
9303 reterr = ParseDosage16(fread_ptr, fread_end, nullptr, raw_sample_ct, vidx, allele_ct, pgrp, nullptr, dphase_present, dphase_delta, nullptr, dosage_present, dosage_main);
9304 return reterr;
9305 }
9306
9307
9308 // Currently assumes no phase or multiallelic hardcalls.
9309 // tried to have more custom code, turned out to not be worth it
9310 PglErr ReadMissingness(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, PgenReaderMain* pgrp, const unsigned char** fread_pp, const unsigned char** fread_endp, uintptr_t* __restrict missingness, uintptr_t* __restrict hets, uintptr_t* __restrict genovec_buf) {
9311 const unsigned char* fread_ptr;
9312 const unsigned char* fread_end;
9313 PglErr reterr = ReadGenovecSubsetUnsafe(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, &fread_ptr, &fread_end, genovec_buf);
9314 ZeroTrailingNyps(sample_ct, genovec_buf);
9315 GenoarrToMissingnessUnsafe(genovec_buf, sample_ct, missingness);
9316 if (hets) {
9317 PgrDetectGenoarrHetsUnsafe(genovec_buf, NypCtToWordCt(sample_ct), hets);
9318 }
9319 if (fread_pp) {
9320 *fread_pp = fread_ptr;
9321 *fread_endp = fread_end;
9322 }
9323 return reterr;
9324 }
9325
9326 PglErr PgrGetMissingness(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, uintptr_t* __restrict missingness, uintptr_t* __restrict genovec_buf) {
9327 if (!sample_ct) {
9328 return kPglRetSuccess;
9329 }
9330 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
9331 // may as well add a hets parameter?
9332 assert(vidx < pgrp->fi.raw_variant_ct);
9333 return ReadMissingness(sample_include, GetSicp(pssi), sample_ct, vidx, pgrp, nullptr, nullptr, missingness, nullptr, genovec_buf);
9334 }
9335
9336 PglErr PgrGetMissingnessD(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, uintptr_t* __restrict missingness_hc, uintptr_t* __restrict missingness_dosage, uintptr_t* __restrict hets, uintptr_t* __restrict genovec_buf) {
9337 if (!sample_ct) {
9338 return kPglRetSuccess;
9339 }
9340 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
9341 // sample_include can't be null
9342 // either missingness_hc or missingness_dosage must be non-null
9343 assert(vidx < pgrp->fi.raw_variant_ct);
9344 const uint32_t* sample_include_cumulative_popcounts = GetSicp(pssi);
9345 const uint32_t vrtype = GetPgfiVrtype(&(pgrp->fi), vidx);
9346 const uint32_t dosage_is_relevant = missingness_dosage && VrtypeDosage(vrtype);
9347 const uint32_t need_to_skip_aux1or2 = dosage_is_relevant && (vrtype & 0x18);
9348 const uint32_t raw_sample_ct = pgrp->fi.raw_sample_ct;
9349 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
9350 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
9351 const unsigned char* fread_ptr = nullptr;
9352 const unsigned char* fread_end = nullptr;
9353 uintptr_t* missingness_base = missingness_hc? missingness_hc : missingness_dosage;
9354 if (!need_to_skip_aux1or2) {
9355 PglErr reterr = ReadMissingness(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, dosage_is_relevant? (&fread_ptr) : nullptr, dosage_is_relevant? (&fread_end) : nullptr, missingness_base, hets, genovec_buf);
9356 if (missingness_dosage && missingness_hc) {
9357 memcpy(missingness_dosage, missingness_hc, BitCtToWordCt(sample_ct) * sizeof(intptr_t));
9358 }
9359 if (reterr || (!dosage_is_relevant)) {
9360 return reterr;
9361 }
9362 } else {
9363 PglErr reterr = ReadRawGenovec(subsetting_required, vidx, pgrp, &fread_ptr, &fread_end, genovec_buf);
9364 if (unlikely(reterr)) {
9365 return reterr;
9366 }
9367 ZeroTrailingNyps(raw_sample_ct, genovec_buf);
9368 uintptr_t* subsetted_genovec = pgrp->workspace_vec;
9369 CopyNyparrNonemptySubset(genovec_buf, sample_include, raw_sample_ct, sample_ct, subsetted_genovec);
9370 GenoarrToMissingnessUnsafe(subsetted_genovec, sample_ct, missingness_base);
9371 if (missingness_hc) {
9372 memcpy(missingness_dosage, missingness_hc, BitCtToWordCt(sample_ct) * sizeof(intptr_t));
9373 }
9374
9375 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
9376 const uint32_t allele_ct = allele_idx_offsets? (allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx]) : 2;
9377 if (VrtypeHphase(vrtype) || hets) {
9378 uintptr_t* all_hets = pgrp->workspace_all_hets;
9379 PgrDetectGenoarrHets(genovec_buf, raw_sample_ct, all_hets);
9380 if (VrtypeMultiallelicHc(vrtype)) {
9381 // see analogous branch in ReadGenovecHphaseSubsetUnsafe()
9382 // probable todo: make this a separate function
9383 const uint32_t aux1_first_byte = *fread_ptr++;
9384 const uint32_t aux1a_mode = aux1_first_byte & 15;
9385 const uint32_t aux1b_mode = aux1_first_byte >> 4;
9386 uint32_t raw_01_ct = 0;
9387 uint32_t raw_10_ct = 0;
9388 if ((!aux1a_mode) || (!aux1b_mode)) {
9389 GenovecCount12Unsafe(genovec_buf, raw_sample_ct, &raw_01_ct, &raw_10_ct);
9390 }
9391 reterr = SkipAux1a(fread_end, aux1a_mode, raw_sample_ct, allele_ct, raw_01_ct, &fread_ptr);
9392 if (unlikely(reterr)) {
9393 return reterr;
9394 }
9395 uintptr_t* aux1b_hets = pgrp->workspace_aux1x_present;
9396 uint32_t* deltalist_workspace = pgrp->workspace_difflist_sample_ids;
9397 uint32_t aux1b_het_present;
9398 reterr = GetAux1bHets(fread_end, genovec_buf, aux1b_mode, raw_sample_ct, allele_ct, raw_10_ct, &fread_ptr, aux1b_hets, &aux1b_het_present, deltalist_workspace);
9399 if (unlikely(reterr)) {
9400 return reterr;
9401 }
9402 if (aux1b_het_present) {
9403 BitvecOr(aux1b_hets, raw_sample_ctl, all_hets);
9404 }
9405 }
9406 if (hets) {
9407 CopyBitarrSubset(all_hets, sample_include, sample_ct, hets);
9408 }
9409 if (VrtypeHphase(vrtype)) {
9410 reterr = SkipAux2(fread_end, PopcountWords(all_hets, raw_sample_ctl), &fread_ptr, nullptr);
9411 if (unlikely(reterr)) {
9412 return reterr;
9413 }
9414 }
9415 } else {
9416 SkipAux1(fread_end, genovec_buf, raw_sample_ct, allele_ct, &fread_ptr);
9417 }
9418 }
9419 // now perform bitwise andnot with dosage_present
9420 if ((vrtype & 0x60) == 0x40) {
9421 // unconditional dosage. spot-check the appropriate entries for equality
9422 // to 65535.
9423 const unsigned char* dosage_main_read = fread_ptr;
9424 // bugfix (18 Feb 2019): sample_include is permitted to be nullptr here
9425 if (!subsetting_required) {
9426 // probable todo: faster iteration over set bits
9427 for (uint32_t widx = 0; widx != raw_sample_ctl; ++widx) {
9428 uintptr_t missing_dosage_bits = missingness_dosage[widx];
9429 if (missing_dosage_bits) {
9430 const unsigned char* cur_dosage_main = &(dosage_main_read[widx * kBitsPerWord * sizeof(int16_t)]);
9431 do {
9432 uint32_t sample_idx_lowbits = ctzw(missing_dosage_bits);
9433 uint16_t cur_dosage_u16;
9434 CopyFromUnalignedOffsetU16(&cur_dosage_u16, cur_dosage_main, sample_idx_lowbits);
9435 if (cur_dosage_u16 != 65535) {
9436 missingness_dosage[widx] ^= missing_dosage_bits & (-missing_dosage_bits);
9437 }
9438 missing_dosage_bits &= missing_dosage_bits - 1;
9439 } while (missing_dosage_bits);
9440 }
9441 }
9442 } else {
9443 uintptr_t sample_uidx_base = 0;
9444 uintptr_t sample_include_bits = sample_include[0];
9445 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
9446 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &sample_include_bits);
9447 if (!IsSet(missingness_dosage, sample_idx)) {
9448 continue;
9449 }
9450 uint16_t cur_dosage_u16;
9451 CopyFromUnalignedOffsetU16(&cur_dosage_u16, dosage_main_read, sample_uidx);
9452 if (cur_dosage_u16 != 65535) {
9453 ClearBit(sample_idx, missingness_dosage);
9454 }
9455 }
9456 }
9457 return kPglRetSuccess;
9458 }
9459 uintptr_t* dosage_present = pgrp->workspace_dosage_present;
9460 if ((vrtype & 0x60) == 0x20) {
9461 // dosage list
9462 uint32_t dummy;
9463 if (unlikely(ParseAndSaveDeltalistAsBitarr(fread_end, raw_sample_ct, &fread_ptr, dosage_present, &dummy))) {
9464 return kPglRetMalformedInput;
9465 }
9466 } else {
9467 // dosage bitarray
9468 dosage_present[raw_sample_ctl - 1] = 0;
9469 const uint32_t raw_sample_ctb = DivUp(raw_sample_ct, CHAR_BIT);
9470 memcpy(dosage_present, fread_ptr, raw_sample_ctb);
9471 }
9472 if (subsetting_required) {
9473 CopyBitarrSubset(dosage_present, sample_include, sample_ct, pgrp->workspace_vec);
9474 dosage_present = pgrp->workspace_vec;
9475 }
9476 BitvecInvmask(dosage_present, BitCtToWordCt(sample_ct), missingness_dosage);
9477 return kPglRetSuccess;
9478 }
9479
9480 static inline BoolErr ValidateVint31(const unsigned char* buf_end, const unsigned char** bufpp, uint32_t* val_ptr) {
9481 if (unlikely(buf_end <= (*bufpp))) {
9482 return 1;
9483 }
9484 uint32_t vint32 = *((*bufpp)++);
9485 if (vint32 <= 127) {
9486 *val_ptr = vint32;
9487 return 0;
9488 }
9489 vint32 &= 127;
9490 for (uint32_t shift = 7; shift != 28; shift += 7) {
9491 if (unlikely(buf_end == (*bufpp))) {
9492 return 1;
9493 }
9494 uint32_t uii = *((*bufpp)++);
9495 vint32 |= (uii & 127) << shift;
9496 if (uii <= 127) {
9497 *val_ptr = vint32;
9498 return 0;
9499 }
9500 }
9501 if (unlikely(buf_end == (*bufpp))) {
9502 return 1;
9503 }
9504 uint32_t uii = *((*bufpp)++);
9505 if (unlikely(uii > 7)) {
9506 return 1;
9507 }
9508 vint32 |= uii << 28;
9509 *val_ptr = vint32;
9510 return 0;
9511 }
9512
9513 BoolErr ValidateDifflistHeader(const unsigned char* fread_end, uint32_t sample_ct, const unsigned char** fread_pp, uintptr_t* raregeno_buf, const unsigned char** difflist_group_info_ptr, uint32_t* difflist_len_ptr) {
9514 // can be used for deltalists: pass raregeno_buf == nullptr.
9515 if (unlikely(ValidateVint31(fread_end, fread_pp, difflist_len_ptr))) {
9516 // todo: ensure fread_pp points to a problematic byte whenever a validate_
9517 // function returns an error, so the error message can provide an accurate
9518 // byte offset.
9519 return 1;
9520 }
9521 const uint32_t difflist_len = *difflist_len_ptr;
9522 *difflist_group_info_ptr = *fread_pp;
9523 if (!difflist_len) {
9524 return 0;
9525 }
9526 if (unlikely(difflist_len > sample_ct / kPglMaxDifflistLenDivisor)) {
9527 return 1;
9528 }
9529 const uint32_t group_ct = DivUp(difflist_len, kPglDifflistGroupSize);
9530 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(sample_ct);
9531 const uint32_t difflist_index_byte_ct = group_ct * (sample_id_byte_ct + 1) - 1;
9532 if (PtrAddCk(fread_end, difflist_index_byte_ct, fread_pp)) {
9533 return 1;
9534 }
9535 if (!raregeno_buf) {
9536 return 0;
9537 }
9538 const uint32_t raregeno_byte_ct = NypCtToByteCt(difflist_len);
9539 const unsigned char* raregeno_start = *fread_pp;
9540 if (PtrAddCk(fread_end, raregeno_byte_ct, fread_pp)) {
9541 return 1;
9542 }
9543 memcpy(raregeno_buf, raregeno_start, raregeno_byte_ct);
9544 const uint32_t difflist_len_mod4 = difflist_len % 4;
9545 if (difflist_len_mod4) {
9546 const uint32_t last_raregeno_byte = (*fread_pp)[-1];
9547 if (unlikely(last_raregeno_byte >> (2 * difflist_len_mod4))) {
9548 return 1;
9549 }
9550 }
9551 return 0;
9552 }
9553
9554 BoolErr ValidateAndApplyDifflist(const unsigned char* fread_end, uint32_t common2_code, const unsigned char** fread_pp, PgenReaderMain* pgrp, uintptr_t* __restrict genoarr) {
9555 // Side effects: uses pgr.workspace_raregeno_tmp_loadbuf.
9556 // Similar to ParseAndApplyDifflist(), but with exhaustive input
9557 // validation.
9558 const uint32_t sample_ct = pgrp->fi.raw_sample_ct;
9559 uintptr_t* cur_raregeno_iter = pgrp->workspace_raregeno_tmp_loadbuf;
9560 const unsigned char* group_info_iter;
9561 uint32_t difflist_len;
9562 if (unlikely(ValidateDifflistHeader(fread_end, sample_ct, fread_pp, cur_raregeno_iter, &group_info_iter, &difflist_len))) {
9563 return 1;
9564 }
9565 if (!difflist_len) {
9566 return 0;
9567 }
9568 const uint32_t subgroup_idx_last = (difflist_len - 1) / kBitsPerWordD2;
9569 if (common2_code) {
9570 // 1-bit format + list of exceptions. In this case,
9571 // (i) the length of the exception list must be < (sample_ct / 16)
9572 // (ii) every raregeno entry must either be one of the two rare genotype
9573 // values, or involve a rare alt allele.
9574 if (unlikely(difflist_len >= (sample_ct / (2 * kPglMaxDifflistLenDivisor)))) {
9575 return 1;
9576 }
9577 const uintptr_t common_code_delta = common2_code & 3;
9578 const uintptr_t inv_common_word1 = (3 - common2_code / 4) * kMask5555;
9579 const uintptr_t inv_common_word2 = inv_common_word1 - (common_code_delta * kMask5555);
9580 for (uint32_t subgroup_idx = 0; ; ++subgroup_idx) {
9581 uintptr_t cur_raregeno_word = cur_raregeno_iter[subgroup_idx];
9582 const uintptr_t match1 = Word11(cur_raregeno_word ^ inv_common_word1);
9583 const uintptr_t match2 = Word11(cur_raregeno_word ^ inv_common_word2);
9584 if (subgroup_idx == subgroup_idx_last) {
9585 // ignore trailing bits
9586 const uint32_t lshift = ((-difflist_len) % kBitsPerWordD2) * 2;
9587 if (unlikely((match1 << lshift) || (match2 << lshift))) {
9588 return 1;
9589 }
9590 break;
9591 }
9592 if (unlikely(match1 || match2)) {
9593 // todo: if (multiallelic_hc_present && (!inv_common_word2)), record
9594 // might be fine; but we need to verify these are actually rare alt
9595 // alleles.
9596 // (er, above comment is obsolete)
9597 return 1;
9598 }
9599 }
9600 }
9601 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(sample_ct);
9602 const unsigned char* group_byte_cts_iter = &(group_info_iter[DivUp(difflist_len, kPglDifflistGroupSize) * sample_id_byte_ct]);
9603 const unsigned char* prev_group_start = *fread_pp;
9604
9605 uintptr_t sample_idx = 0;
9606 for (uint32_t subgroup_idx = 0; ; ++subgroup_idx) {
9607 uint32_t remaining_deltas_in_subgroup = kBitsPerWordD2 - 1;
9608 if (subgroup_idx >= subgroup_idx_last) {
9609 if (subgroup_idx > subgroup_idx_last) {
9610 return 0;
9611 }
9612 remaining_deltas_in_subgroup &= difflist_len - 1;
9613 }
9614 if (!(subgroup_idx % (kPglDifflistGroupSize / kBitsPerWordD2))) {
9615 uintptr_t new_sample_idx_start = SubU32Load(group_info_iter, sample_id_byte_ct);
9616 if (subgroup_idx) {
9617 if (unlikely(sample_idx >= new_sample_idx_start)) {
9618 return 1;
9619 }
9620 const uint32_t group_byte_ct = S_CAST(uint32_t, *group_byte_cts_iter++) + 63;
9621 if (unlikely(S_CAST(uintptr_t, (*fread_pp) - prev_group_start) != group_byte_ct)) {
9622 return 1;
9623 }
9624 prev_group_start = *fread_pp;
9625 }
9626 sample_idx = new_sample_idx_start;
9627 group_info_iter = &(group_info_iter[sample_id_byte_ct]);
9628 } else {
9629 uint32_t sample_idx_incr;
9630 if (unlikely(ValidateVint31(fread_end, fread_pp, &sample_idx_incr) || (!sample_idx_incr))) {
9631 return 1;
9632 }
9633 sample_idx += sample_idx_incr;
9634 }
9635 uintptr_t cur_raregeno_word = *cur_raregeno_iter++;
9636 for (; ; --remaining_deltas_in_subgroup) {
9637 if (unlikely(sample_idx >= sample_ct)) {
9638 return 1;
9639 }
9640 const uintptr_t cur_geno = cur_raregeno_word & 3;
9641 AssignNyparrEntry(sample_idx, cur_geno, genoarr);
9642 if (!remaining_deltas_in_subgroup) {
9643 break;
9644 }
9645 uint32_t sample_idx_incr;
9646 if (unlikely(ValidateVint31(fread_end, fread_pp, &sample_idx_incr) || (!sample_idx_incr))) {
9647 return 1;
9648 }
9649 sample_idx += sample_idx_incr;
9650 cur_raregeno_word >>= 2;
9651 }
9652 }
9653 }
9654
9655 BoolErr ValidateOnebit(const unsigned char* fread_end, const unsigned char** fread_pp, PgenReaderMain* pgrp, uintptr_t* __restrict genoarr) {
9656 // ParseOnebitUnsafe() with exhaustive input validation.
9657 const uint32_t sample_ct = pgrp->fi.raw_sample_ct;
9658 const uint32_t common2_and_bitarray_byte_ct = (sample_ct + 15) / CHAR_BIT;
9659 const unsigned char* onebit_main_iter = *fread_pp;
9660 if (PtrAddCk(fread_end, common2_and_bitarray_byte_ct, fread_pp)) {
9661 return 1;
9662 }
9663 const uintptr_t common2_code = *onebit_main_iter++;
9664 const uintptr_t common_code_delta = common2_code & 3;
9665 uintptr_t word_base = common2_code / 4;
9666 if (unlikely((!common_code_delta) || (word_base + common_code_delta > 3))) {
9667 return 1;
9668 }
9669 word_base *= kMask5555;
9670 const uint32_t genoarr_widx_trail = (sample_ct + 7) / kBitsPerWordD2;
9671 const uint32_t genoarr_widx_end = NypCtToWordCt(sample_ct);
9672 for (uint32_t genoarr_widx = 0; ; ++genoarr_widx) {
9673 uintptr_t ww;
9674 if (genoarr_widx >= genoarr_widx_trail) {
9675 if (genoarr_widx == genoarr_widx_end) {
9676 break;
9677 }
9678 const uint32_t nontrail_byte_ct = ((sample_ct - 1) % kBitsPerWordD2) / CHAR_BIT;
9679 ww = ProperSubwordLoad(&(onebit_main_iter[genoarr_widx_trail * sizeof(Halfword)]), 1 + nontrail_byte_ct);
9680 const uint32_t sample_ct_mod8 = sample_ct % 8;
9681 if (sample_ct_mod8) {
9682 if (unlikely(ww >> (nontrail_byte_ct * 8 + sample_ct_mod8))) {
9683 return 1;
9684 }
9685 }
9686 } else {
9687 Halfword hw;
9688 CopyFromUnalignedOffsetHW(&hw, onebit_main_iter, genoarr_widx);
9689 ww = hw;
9690 }
9691 ww = UnpackHalfwordToWord(ww);
9692 genoarr[genoarr_widx] = word_base + ww * common_code_delta;
9693 }
9694 return ValidateAndApplyDifflist(fread_end, common2_code, fread_pp, pgrp, genoarr);
9695 }
9696
9697 // assumes that we aren't dealing with the trivial fixed-width case.
9698 // saves main genotype array to genovec. does not zero out trailing bits.
9699 BoolErr ValidateGeno(const unsigned char* fread_end, uint32_t vidx, PgenReaderMain* pgrp, const unsigned char** fread_pp, uintptr_t* genovec, char* errstr_buf) {
9700 const uint32_t vrtype = pgrp->fi.vrtypes[vidx];
9701 const uint32_t sample_ct = pgrp->fi.raw_sample_ct;
9702 if (VrtypeLdCompressed(vrtype)) {
9703 CopyNyparr(pgrp->ldbase_genovec, sample_ct, genovec);
9704 if (unlikely(ValidateAndApplyDifflist(fread_end, 0, fread_pp, pgrp, genovec))) {
9705 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid LD difflist for (0-based) variant #%u.\n", vidx);
9706 return 1;
9707 }
9708 if (vrtype & 1) {
9709 GenovecInvertUnsafe(sample_ct, genovec);
9710 }
9711 return 0;
9712 }
9713 const uint32_t is_ldbase = VrtypeLdCompressed(pgrp->fi.vrtypes[vidx + 1]);
9714 if (!(vrtype & 4)) {
9715 if (vrtype & 1) {
9716 if (unlikely(ValidateOnebit(fread_end, fread_pp, pgrp, genovec))) {
9717 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid 1-bit genotype record for (0-based) variant #%u.\n", vidx);
9718 return 1;
9719 }
9720 } else {
9721 const uint32_t genovec_byte_ct = DivUp(sample_ct, 4);
9722 const unsigned char* src_genodata = *fread_pp;
9723 if (PtrAddCk(fread_end, genovec_byte_ct, fread_pp)) {
9724 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid 2-bit genotype record for (0-based) variant #%u\n", vidx);
9725 return 1;
9726 }
9727 memcpy(genovec, src_genodata, genovec_byte_ct);
9728 const uint32_t sample_ct_mod4 = sample_ct % 4;
9729 if (sample_ct_mod4) {
9730 const uint32_t last_geno_byte = (*fread_pp)[-1];
9731 if (unlikely(last_geno_byte >> (2 * sample_ct_mod4))) {
9732 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Last genotype byte for (0-based) variant #%u has nonzero trailing bits.\n", vidx);
9733 return 1;
9734 }
9735 }
9736 }
9737 } else {
9738 const uint32_t vrtype_low2 = vrtype & 3;
9739 if (vrtype_low2 != 1) {
9740 const uint32_t vec_ct = NypCtToVecCt(sample_ct);
9741 vecset(genovec, vrtype_low2 * kMask5555, vec_ct);
9742 if (unlikely(ValidateAndApplyDifflist(fread_end, 0, fread_pp, pgrp, genovec))) {
9743 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid genotype difflist for (0-based) variant #%u.\n", vidx);
9744 return 1;
9745 }
9746 } else {
9747 if (is_ldbase) {
9748 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid LD back-reference from variant #%u to all-hom-ref variant #%u.\n", vidx + 1, vidx);
9749 return 1;
9750 }
9751 ZeroWArr(NypCtToWordCt(sample_ct), genovec);
9752 }
9753 }
9754 if (is_ldbase) {
9755 CopyNyparr(genovec, sample_ct, pgrp->ldbase_genovec);
9756 }
9757 return 0;
9758 }
9759
9760 BoolErr ValidateAndCountDeltalist(const unsigned char* fread_end, uint32_t sample_ct, const unsigned char** fread_pp, uint32_t* __restrict deltalist, uint32_t* deltalist_len_ptr) {
9761 // pass deltalist == nullptr when actual bit positions aren't needed
9762 const unsigned char* group_info_iter;
9763 if (unlikely(ValidateDifflistHeader(fread_end, sample_ct, fread_pp, nullptr, &group_info_iter, deltalist_len_ptr))) {
9764 return 1;
9765 }
9766 const uint32_t deltalist_len = *deltalist_len_ptr;
9767 if (!deltalist_len) {
9768 return 0;
9769 }
9770 const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(sample_ct);
9771 const uint32_t group_idx_last = (deltalist_len - 1) / kPglDifflistGroupSize;
9772 const unsigned char* group_byte_cts_iter = &(group_info_iter[DivUp(deltalist_len, kPglDifflistGroupSize) * sample_id_byte_ct]);
9773 const unsigned char* prev_group_start = *fread_pp;
9774 uint32_t* deltalist_iter = deltalist;
9775 uint32_t group_len_m1 = kPglDifflistGroupSize - 1;
9776 uintptr_t sample_idx = 0;
9777 for (uint32_t group_idx = 0; ; ++group_idx) {
9778 if (group_idx >= group_idx_last) {
9779 if (group_idx > group_idx_last) {
9780 return 0;
9781 }
9782 group_len_m1 &= deltalist_len - 1;
9783 }
9784 uintptr_t new_sample_idx = SubU32Load(group_info_iter, sample_id_byte_ct);
9785 if (group_idx) {
9786 if (unlikely(sample_idx >= new_sample_idx)) {
9787 return 1;
9788 }
9789 const uint32_t group_byte_ct = S_CAST(uint32_t, *group_byte_cts_iter++) + 63;
9790 if (unlikely(S_CAST(uintptr_t, (*fread_pp) - prev_group_start) != group_byte_ct)) {
9791 return 1;
9792 }
9793 prev_group_start = *fread_pp;
9794 }
9795 sample_idx = new_sample_idx;
9796 group_info_iter = &(group_info_iter[sample_id_byte_ct]);
9797 for (uint32_t deltalist_idx_lowbits = 0; ; ++deltalist_idx_lowbits) {
9798 if (unlikely(sample_idx >= sample_ct)) {
9799 return 1;
9800 }
9801 if (deltalist_iter) {
9802 *deltalist_iter++ = sample_idx;
9803 }
9804 if (deltalist_idx_lowbits == group_len_m1) {
9805 break;
9806 }
9807 uint32_t sample_idx_incr;
9808 if (unlikely(ValidateVint31(fread_end, fread_pp, &sample_idx_incr) || (!sample_idx_incr))) {
9809 return 1;
9810 }
9811 sample_idx += sample_idx_incr;
9812 }
9813 }
9814 }
9815
9816 BoolErr ValidateMultiallelicHc(const unsigned char* fread_end, const uintptr_t* __restrict raw_genovec, uint32_t vidx, uint32_t allele_ct, PgenReaderMain* pgrp, const unsigned char** fread_pp, uint32_t* __restrict het_ctp, char* __restrict errstr_buf) {
9817 if (unlikely(allele_ct <= 2)) {
9818 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Multiallelic hardcall track present for (0-based) variant #%u, but it apparently has only %u allele%s.\n", vidx, allele_ct, (allele_ct == 1)? "" : "s");
9819 return 1;
9820 }
9821 const uint32_t sample_ct = pgrp->fi.raw_sample_ct;
9822 const uint32_t aux1_first_byte = **fread_pp;
9823 *fread_pp += 1;
9824 if (unlikely(aux1_first_byte &&
9825 (aux1_first_byte != 1) &&
9826 (aux1_first_byte != 15) &&
9827 (aux1_first_byte != 16) &&
9828 (aux1_first_byte != 17) &&
9829 (aux1_first_byte != 31) &&
9830 (aux1_first_byte != 240) &&
9831 (aux1_first_byte != 241))) {
9832 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic hardcall track mode byte (%u; must be in {0, 1, 15, 16, 17, 31, 240, 241}) in (0-based) variant #%u.\n", aux1_first_byte, vidx);
9833 return 1;
9834 }
9835 const uint32_t aux1a_mode = aux1_first_byte & 15;
9836 const uint32_t aux1b_mode = aux1_first_byte >> 4;
9837 uint32_t raw_01_ct;
9838 uint32_t raw_10_ct;
9839 GenovecCount12Unsafe(raw_genovec, sample_ct, &raw_01_ct, &raw_10_ct);
9840 uint32_t* deltalist_workspace = pgrp->workspace_difflist_sample_ids;
9841 if (aux1a_mode != 15) {
9842 if (unlikely(!raw_01_ct)) {
9843 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Multiallelic het-ref hardcall track present for (0-based) variant #%u, but no het-ref calls exist.\n", vidx);
9844 return 1;
9845 }
9846 uint32_t rare01_ct;
9847 if (!aux1a_mode) {
9848 const uint32_t subset_byte_ct = DivUp(raw_01_ct, CHAR_BIT);
9849 if (PtrCheck(fread_end, *fread_pp, subset_byte_ct)) {
9850 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic het-ref hardcall bitarray-subset for (0-based) variant #%u.\n", vidx);
9851 return 1;
9852 }
9853 rare01_ct = PopcountBytes(*fread_pp, subset_byte_ct);
9854 if (unlikely(!rare01_ct)) {
9855 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Empty multiallelic het-ref hardcall bitarray-subset for (0-based) variant #%u.\n", vidx);
9856 return 1;
9857 }
9858 *fread_pp += subset_byte_ct;
9859 const uint32_t raw_01_ct_mod8 = raw_01_ct % 8;
9860 if (raw_01_ct_mod8) {
9861 if (unlikely((*fread_pp)[-1] >> raw_01_ct_mod8)) {
9862 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Multiallelic het-ref hardcall bitarray-subset for (0-based) variant #%u has nonzero trailing bits.\n", vidx);
9863 return 1;
9864 }
9865 }
9866 } else {
9867 if (unlikely(ValidateAndCountDeltalist(fread_end, sample_ct, fread_pp, deltalist_workspace, &rare01_ct) || (!rare01_ct))) {
9868 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic het-ref hardcall deltalist-subset for (0-based) variant #%u.\n", vidx);
9869 return 1;
9870 }
9871 for (uint32_t uii = 0; uii != rare01_ct; ++uii) {
9872 if (unlikely(GetNyparrEntry(raw_genovec, deltalist_workspace[uii]) != 1)) {
9873 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic het-ref hardcall deltalist-subset for (0-based) variant #%u (an index doesn't correspond to a het-ref call).\n", vidx);
9874 return 1;
9875 }
9876 }
9877 }
9878 if (allele_ct < 5) {
9879 // Nothing to do for allele_ct == 3.
9880 if (allele_ct == 4) {
9881 // 1-bit entries. Contents must be in range, so just validate trailing
9882 // bits.
9883 const uint32_t fvals_byte_ct = DivUp(rare01_ct, 8);
9884 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
9885 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic het-ref hardcall track for (0-based) variant #%u (shorter than expected).\n", vidx);
9886 return 1;
9887 }
9888 const uint32_t rare01_ct_mod8 = rare01_ct % 8;
9889 if (rare01_ct_mod8) {
9890 if (unlikely((*fread_pp)[-1] >> rare01_ct_mod8)) {
9891 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic het-ref hardcall track for (0-based) variant #%u (nonzero trailing bits).\n", vidx);
9892 return 1;
9893 }
9894 }
9895 }
9896 } else {
9897 const unsigned char* fvals = *fread_pp;
9898 if (allele_ct < 19) {
9899 if (allele_ct < 7) {
9900 // 2-bit entries.
9901 const uint32_t fvals_byte_ct = DivUp(rare01_ct, 4);
9902 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
9903 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic het-ref hardcall track for (0-based) variant #%u (shorter than expected).\n", vidx);
9904 return 1;
9905 }
9906 if (allele_ct == 5) {
9907 // Contents may be out-of-range.
9908 const uint32_t fullword_ct = fvals_byte_ct / kBytesPerWord;
9909 uint32_t widx = 0;
9910 if (fullword_ct) {
9911 for (; widx != fullword_ct; ++widx) {
9912 uintptr_t cur_word;
9913 CopyFromUnalignedOffsetW(&cur_word, fvals, widx);
9914 if (unlikely(cur_word & (cur_word >> 1) & kMask5555)) {
9915 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic het-ref hardcall track for (0-based) variant #%u (out-of-range allele code).\n", vidx);
9916 return 1;
9917 }
9918 }
9919 }
9920 for (uint32_t uii = widx * kBytesPerWord; uii != fvals_byte_ct; ++uii) {
9921 const uint32_t cur_byte = fvals[uii];
9922 if (unlikely(cur_byte & (cur_byte >> 1) & 0x55)) {
9923 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic het-ref hardcall track for (0-based) variant #%u (out-of-range allele code).\n", vidx);
9924 return 1;
9925 }
9926 }
9927 }
9928 // Validate trailing bits.
9929 const uint32_t rare01_ct_mod4 = rare01_ct % 4;
9930 if (rare01_ct_mod4) {
9931 if (unlikely((*fread_pp)[-1] >> (2 * rare01_ct_mod4))) {
9932 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic het-ref hardcall track for (0-based) variant #%u (nonzero trailing bits).\n", vidx);
9933 return 1;
9934 }
9935 }
9936 } else {
9937 // 4-bit entries.
9938 const uint32_t fvals_byte_ct = DivUp(rare01_ct, 2);
9939 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
9940 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic het-ref hardcall track for (0-based) variant #%u (shorter than expected).\n", vidx);
9941 return 1;
9942 }
9943 if (allele_ct != 18) {
9944 // Contents may be out-of-range.
9945 // (Can optimize this loop later.)
9946 const uint32_t max_code = allele_ct - 3;
9947 for (uint32_t uii = 0; uii != fvals_byte_ct; ++uii) {
9948 const uint32_t cur_byte = fvals[uii];
9949 if (unlikely(((cur_byte & 15) > max_code) || ((cur_byte >> 4) > max_code))) {
9950 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic het-ref hardcall track for (0-based) variant #%u (out-of-range allele code).\n", vidx);
9951 return 1;
9952 }
9953 }
9954 }
9955 // Validate trailing bits.
9956 const uint32_t rare01_ct_mod2 = rare01_ct % 2;
9957 if (rare01_ct_mod2) {
9958 if (unlikely((*fread_pp)[-1] >> 4)) {
9959 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic het-ref hardcall track for (0-based) variant #%u (nonzero trailing bits).\n", vidx);
9960 return 1;
9961 }
9962 }
9963 }
9964 } else {
9965 // 8-bit entries.
9966 if (PtrAddCk(fread_end, rare01_ct, fread_pp)) {
9967 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic het-ref hardcall track for (0-based) variant #%u (shorter than expected).\n", vidx);
9968 return 1;
9969 }
9970 // Can optimize this loop later.
9971 const uint32_t max_code = allele_ct - 3;
9972 for (uint32_t uii = 0; uii != rare01_ct; ++uii) {
9973 const uint32_t cur_byte = fvals[uii];
9974 if (unlikely(cur_byte > max_code)) {
9975 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic het-ref hardcall track for (0-based) variant #%u (out-of-range allele code).\n", vidx);
9976 return 1;
9977 }
9978 }
9979 }
9980 }
9981 }
9982 if (aux1b_mode != 15) {
9983 if (unlikely(!raw_10_ct)) {
9984 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Multiallelic altxy hardcall track present for (0-based) variant #%u, but no altxy calls exist.\n", vidx);
9985 return 1;
9986 }
9987 uint32_t rare10_ct;
9988 if (!aux1b_mode) {
9989 const uint32_t subset_byte_ct = DivUp(raw_10_ct, CHAR_BIT);
9990 if (PtrCheck(fread_end, *fread_pp, subset_byte_ct)) {
9991 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic altxy hardcall bitarray-subset for (0-based) variant #%u.\n", vidx);
9992 return 1;
9993 }
9994 rare10_ct = PopcountBytes(*fread_pp, subset_byte_ct);
9995 if (unlikely(!rare10_ct)) {
9996 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Empty multiallelic altxy hardcall bitarray-subset for (0-based) variant #%u.\n", vidx);
9997 return 1;
9998 }
9999 *fread_pp += subset_byte_ct;
10000 const uint32_t raw_10_ct_mod8 = raw_10_ct % 8;
10001 if (raw_10_ct_mod8) {
10002 if (unlikely((*fread_pp)[-1] >> raw_10_ct_mod8)) {
10003 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Multiallelic altxy hardcall bitarray-subset for (0-based) variant #%u has nonzero trailing bits.\n", vidx);
10004 return 1;
10005 }
10006 }
10007 } else {
10008 if (unlikely(ValidateAndCountDeltalist(fread_end, sample_ct, fread_pp, deltalist_workspace, &rare10_ct) || (!rare10_ct))) {
10009 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic altxy hardcall deltalist-subset for (0-based) variant #%u.\n", vidx);
10010 return 1;
10011 }
10012 for (uint32_t uii = 0; uii != rare10_ct; ++uii) {
10013 if (unlikely(GetNyparrEntry(raw_genovec, deltalist_workspace[uii]) != 2)) {
10014 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic altxy hardcall deltalist-subset for (0-based) variant #%u (an index doesn't correspond to an altxy call).\n", vidx);
10015 return 1;
10016 }
10017 }
10018 }
10019 const unsigned char* fvals = *fread_pp;
10020 uint32_t het_incr;
10021 if (allele_ct < 6) {
10022 if (allele_ct == 3) {
10023 // 1-bit entries.
10024 const uint32_t fvals_byte_ct = DivUp(rare10_ct, 8);
10025 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
10026 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic altxy hardcall track for (0-based) variant #%u (shorter than expected).\n", vidx);
10027 return 1;
10028 }
10029 const uint32_t rare10_ct_mod8 = rare10_ct % 8;
10030 if (rare10_ct_mod8) {
10031 if (unlikely((*fread_pp)[-1] >> rare10_ct_mod8)) {
10032 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic altxy hardcall track for (0-based) variant #%u (nonzero trailing bits).\n", vidx);
10033 return 1;
10034 }
10035 }
10036 het_incr = rare10_ct - PopcountBytes(fvals, fvals_byte_ct);
10037 } else {
10038 // 2+2 bit entries.
10039 const uint32_t fvals_byte_ct = DivUp(rare10_ct, 2);
10040 if (PtrAddCk(fread_end, fvals_byte_ct, fread_pp)) {
10041 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic altxy hardcall track for (0-based) variant #%u (shorter than expected).\n", vidx);
10042 return 1;
10043 }
10044 // Can optimize this later.
10045 uint64_t nybble_cts[16];
10046 ZeroU64Arr(16, nybble_cts);
10047 CountAllNybbles64(fvals, rare10_ct, nybble_cts);
10048 // 1/1 is invalid here
10049 if (nybble_cts[0]) {
10050 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic altxy hardcall track for (0-based) variant #%u (out-of-range allele code pair).\n", vidx);
10051 return 1;
10052 }
10053 const uint32_t max_code = allele_ct - 2;
10054 for (uint32_t hi_code = 0; hi_code != 4; ++hi_code) {
10055 uint32_t lo_code = hi_code + 1;
10056 if (hi_code > max_code) {
10057 lo_code = 0;
10058 }
10059 const uint64_t* nybble_cts_offset = &(nybble_cts[hi_code * 4]);
10060 for (; lo_code != 4; ++lo_code) {
10061 if (nybble_cts_offset[lo_code]) {
10062 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic altxy hardcall track for (0-based) variant #%u (out-of-range allele code pair).\n", vidx);
10063 return 1;
10064 }
10065 }
10066 }
10067 const uintptr_t rarehom_ct = nybble_cts[5] + nybble_cts[10] + nybble_cts[15];
10068 het_incr = rare10_ct - rarehom_ct;
10069 const uint32_t rare10_ct_mod2 = rare10_ct % 2;
10070 if (rare10_ct_mod2) {
10071 if (unlikely((*fread_pp)[-1] >> 4)) {
10072 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic altxy hardcall track for (0-based) variant #%u (nonzero trailing bits).\n", vidx);
10073 return 1;
10074 }
10075 }
10076 }
10077 } else {
10078 if (allele_ct < 18) {
10079 // 4+4 bit entries.
10080 if (PtrAddCk(fread_end, rare10_ct, fread_pp)) {
10081 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic altxy hardcall track for (0-based) variant #%u (shorter than expected).\n", vidx);
10082 return 1;
10083 }
10084 const uint32_t max_code = allele_ct - 2;
10085 het_incr = 0;
10086 for (uint32_t uii = 0; uii != rare10_ct; ++uii) {
10087 const uint32_t cur_byte = fvals[uii];
10088 const uint32_t lo_code = cur_byte & 15;
10089 const uint32_t hi_code = cur_byte >> 4;
10090 if (unlikely((!hi_code) || (hi_code > max_code) || (lo_code > hi_code))) {
10091 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic altxy hardcall track for (0-based) variant #%u (out-of-range or misordered allele code pair).\n", vidx);
10092 return 1;
10093 }
10094 het_incr += (lo_code != hi_code);
10095 }
10096 } else {
10097 // 8+8 bit entries
10098 if (PtrAddCk(fread_end, 2 * rare10_ct, fread_pp)) {
10099 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic altxy hardcall track for (0-based) variant #%u (shorter than expected).\n", vidx);
10100 return 1;
10101 }
10102 const uint32_t max_code = allele_ct - 2;
10103 het_incr = 0;
10104 for (uint32_t uii = 0; uii != rare10_ct; ++uii) {
10105 const AlleleCode lo_code = fvals[2 * uii];
10106 const AlleleCode hi_code = fvals[2 * uii + 1];
10107 if (unlikely((!hi_code) || (hi_code > max_code) || (lo_code > hi_code))) {
10108 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid multiallelic altxy hardcall track for (0-based) variant #%u (out-of-range or misordered allele code pair).\n", vidx);
10109 return 1;
10110 }
10111 het_incr += (lo_code != hi_code);
10112 }
10113 }
10114 }
10115 *het_ctp += het_incr;
10116 }
10117 return 0;
10118 }
10119
10120 BoolErr ValidateHphase(const unsigned char* fread_end, uint32_t vidx, uint32_t het_ct, const unsigned char** fread_pp, char* errstr_buf) {
10121 if (unlikely(!het_ct)) {
10122 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Hardcall phase track present for (0-based) variant #%u, but there were no heterozygous calls.\n", vidx);
10123 return 1;
10124 }
10125 const uint32_t aux2_first_part_byte_ct = 1 + (het_ct / CHAR_BIT);
10126 const unsigned char* aux2_first_part = *fread_pp;
10127 if (PtrAddCk(fread_end, aux2_first_part_byte_ct, fread_pp)) {
10128 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid hardcall phase track present for (0-based) variant #%u.\n", vidx);
10129 return 1;
10130 }
10131 const uint32_t het_ct_p1_mod8 = (het_ct + 1) % CHAR_BIT;
10132 if (het_ct_p1_mod8) {
10133 // verify trailing bits are zero
10134 if (unlikely((*fread_pp)[-1] >> het_ct_p1_mod8)) {
10135 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Hardcall phase track for (0-based) variant #%u has nonzero trailing bits.\n", vidx);
10136 return 1;
10137 }
10138 }
10139 if (!((*aux2_first_part) & 1)) {
10140 // phase always present, "first part" is only part
10141 return 0;
10142 }
10143 const uint32_t phasepresent_ct = PopcountBytes(aux2_first_part, aux2_first_part_byte_ct) - 1;
10144 if (unlikely(!phasepresent_ct)) {
10145 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Hardcall phase track for (0-based) variant #%u does not have any actual phase information.\n", vidx);
10146 return 1;
10147 }
10148 const uint32_t phaseinfo_byte_ct = DivUp(phasepresent_ct, CHAR_BIT);
10149 if (PtrAddCk(fread_end, phaseinfo_byte_ct, fread_pp)) {
10150 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid hardcall phase track present for (0-based) variant #%u.\n", vidx);
10151 return 1;
10152 }
10153 const uint32_t phasepresent_ct_mod8 = phasepresent_ct % 8;
10154 if (phasepresent_ct_mod8) {
10155 if (unlikely((*fread_pp)[-1] >> phasepresent_ct_mod8)) {
10156 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Hardcall phase track for (0-based) variant #%u has nonzero trailing bits.\n", vidx);
10157 return 1;
10158 }
10159 }
10160 return 0;
10161 }
10162
10163 PglErr ValidateDosage16(const unsigned char* fread_end, uint32_t vidx, PgenReaderMain* pgrp, const unsigned char** fread_pp, char* errstr_buf) {
10164 // similar to ParseDosage16(). doesn't support multiallelic data yet.
10165 const uint32_t vrtype = pgrp->fi.vrtypes[vidx];
10166 const uint32_t sample_ct = pgrp->fi.raw_sample_ct;
10167 if ((vrtype & 0x60) == 0x40) {
10168 // unconditional dosage. handle separately from other two cases since
10169 // 65535 is valid.
10170 const unsigned char* dosage_main_read = *fread_pp;
10171 if (PtrAddCk(fread_end, sample_ct * sizeof(int16_t), fread_pp)) {
10172 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid unconditional dosage track for (0-based) variant #%u.\n", vidx);
10173 return kPglRetMalformedInput;
10174 }
10175 // todo: verify genotype and dosage are consistent
10176 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
10177 uint16_t cur_dosage_val_p1;
10178 CopyFromUnalignedOffsetU16(&cur_dosage_val_p1, dosage_main_read, sample_idx);
10179 cur_dosage_val_p1 += 1; // intentional overflow on 65535
10180 if (unlikely(cur_dosage_val_p1 > 32769)) {
10181 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid unconditional dosage track for (0-based) variant #%u (dosage is greater than 2).\n", vidx);
10182 return kPglRetMalformedInput;
10183 }
10184 }
10185 if (vrtype & 0x80) {
10186 const unsigned char* dphase_delta_read = *fread_pp;
10187 if (PtrAddCk(fread_end, sample_ct * sizeof(int16_t), fread_pp)) {
10188 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid unconditional phased-dosages for (0-based) variant #%u.\n", vidx);
10189 return kPglRetMalformedInput;
10190 }
10191 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
10192 uint16_t dosage_val;
10193 CopyFromUnalignedOffsetU16(&dosage_val, dosage_main_read, sample_idx);
10194 int16_t dphase_delta_val;
10195 CopyFromUnalignedOffsetI16(&dphase_delta_val, dphase_delta_read, sample_idx);
10196 const uint16_t dpiece0_x2 = dosage_val + dphase_delta_val;
10197 const uint16_t dpiece1_x2 = dosage_val - dphase_delta_val;
10198 // Update (11 May 2018): parity condition removed.
10199 if ((dpiece0_x2 > 32768) || (dpiece1_x2 > 32768)) {
10200 if (unlikely((dphase_delta_val != -32768) || (dosage_val != 65535))) {
10201 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid unconditional phased-dosages for (0-based) variant #%u.\n", vidx);
10202 return kPglRetMalformedInput;
10203 }
10204 }
10205 }
10206 }
10207 return kPglRetSuccess;
10208 }
10209 uint32_t dosage_ct;
10210 if ((vrtype & 0x60) == 0x20) {
10211 // dosage list
10212 if (unlikely(ValidateAndCountDeltalist(fread_end, sample_ct, fread_pp, nullptr, &dosage_ct))) {
10213 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid dosage list for (0-based) variant #%u.\n", vidx);
10214 return kPglRetMalformedInput;
10215 }
10216 } else {
10217 const uint32_t sample_ctb = DivUp(sample_ct, CHAR_BIT);
10218 if (PtrCheck(fread_end, *fread_pp, sample_ctb)) {
10219 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid dosage subset for (0-based) variant #%u.\n", vidx);
10220 return kPglRetMalformedInput;
10221 }
10222 dosage_ct = PopcountBytes(*fread_pp, sample_ctb);
10223 *fread_pp += sample_ctb;
10224 const uint32_t sample_ct_mod8 = sample_ct % 8;
10225 if (sample_ct_mod8) {
10226 if (unlikely((*fread_pp)[-1] >> sample_ct_mod8)) {
10227 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Dosage subset bitarray for (0-based) variant #%u has nonzero trailing bits.\n", vidx);
10228 return kPglRetMalformedInput;
10229 }
10230 }
10231 }
10232 const unsigned char* dosage_main_read = *fread_pp;
10233 if (PtrAddCk(fread_end, dosage_ct * sizeof(int16_t), fread_pp)) {
10234 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid dosage track for (0-based) variant #%u.\n", vidx);
10235 return kPglRetMalformedInput;
10236 }
10237 for (uint32_t dosage_idx = 0; dosage_idx != dosage_ct; ++dosage_idx) {
10238 uint16_t cur_dosage_u16;
10239 CopyFromUnalignedOffsetU16(&cur_dosage_u16, dosage_main_read, dosage_idx);
10240 if (unlikely(cur_dosage_u16 > 32768)) {
10241 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid dosage track for (0-based) variant #%u (dosage is greater than 2).\n", vidx);
10242 return kPglRetMalformedInput;
10243 }
10244 }
10245 if (vrtype & 0x80) {
10246 const unsigned char* file_dphase_present = *fread_pp;
10247 const uint32_t dphase_present_byte_ct = DivUp(dosage_ct, CHAR_BIT);
10248 if (PtrAddCk(fread_end, dphase_present_byte_ct, fread_pp)) {
10249 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid phased-dosage track for (0-based) variant #%u.\n", vidx);
10250 return kPglRetMalformedInput;
10251 }
10252 const uint32_t trailing_bit_ct = dosage_ct % CHAR_BIT;
10253 if (unlikely(trailing_bit_ct && ((*fread_pp)[-1] & (255 << trailing_bit_ct)))) {
10254 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid phased-dosage track for (0-based) variant #%u.\n", vidx);
10255 return kPglRetMalformedInput;
10256 }
10257 const unsigned char* dosage_main_read_biter = dosage_main_read;
10258 const unsigned char* dphase_delta_read_biter = *fread_pp;
10259 const uint32_t dphase_widx_last = (dphase_present_byte_ct - 1) / kBytesPerWord;
10260 uint32_t loop_end = kBitsPerWord;
10261 for (uint32_t dphase_widx = 0; ; ++dphase_widx) {
10262 uintptr_t ww;
10263 if (dphase_widx >= dphase_widx_last) {
10264 if (dphase_widx > dphase_widx_last) {
10265 break;
10266 }
10267 loop_end = 1 + ((dosage_ct - 1) % kBitsPerWord);
10268 const uint32_t final_byte_ct = DivUp(loop_end, CHAR_BIT);
10269 ww = SubwordLoad(&(file_dphase_present[dphase_widx * kBytesPerWord]), final_byte_ct);
10270 } else {
10271 CopyFromUnalignedOffsetW(&ww, file_dphase_present, dphase_widx);
10272 }
10273 for (uint32_t dphase_lowbits = 0; dphase_lowbits != loop_end; ++dphase_lowbits, dosage_main_read_biter += sizeof(int16_t)) {
10274 if (!((ww >> dphase_lowbits) & 1)) {
10275 continue;
10276 }
10277 uint16_t dosage_val;
10278 CopyFromUnalignedU16(&dosage_val, dosage_main_read_biter);
10279 int16_t dphase_delta_val;
10280 CopyFromUnalignedIncrI16(&dphase_delta_val, &dphase_delta_read_biter);
10281 const uint16_t dpiece0_x2 = dosage_val + dphase_delta_val;
10282 const uint16_t dpiece1_x2 = dosage_val - dphase_delta_val;
10283 if (unlikely((dpiece0_x2 > 32768) || (dpiece1_x2 > 32768))) {
10284 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid phased-dosage track for (0-based) variant #%u.\n", vidx);
10285 return kPglRetMalformedInput;
10286 }
10287 }
10288 }
10289 if (unlikely(dphase_delta_read_biter == *fread_pp)) {
10290 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid phased-dosage track for (0-based) variant #%u.\n", vidx);
10291 return kPglRetMalformedInput;
10292 }
10293 *fread_pp = dphase_delta_read_biter;
10294 if (PtrCheck(fread_end, *fread_pp, 0)) {
10295 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid phased-dosage track for (0-based) variant #%u.\n", vidx);
10296 return kPglRetMalformedInput;
10297 }
10298 }
10299 return kPglRetSuccess;
10300 }
10301
10302 static_assert(kPglVblockSize == 65536, "PgrValidate() needs to have an error message updated.");
10303 PglErr PgrValidate(PgenReader* pgr_ptr, uintptr_t* genovec_buf, char* errstr_buf) {
10304 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
10305 // Performs all validation which isn't done by pgfi_init_phase{1,2}() and
10306 // PgrInit().
10307 const uintptr_t* allele_idx_offsets = pgrp->fi.allele_idx_offsets;
10308 const uint32_t variant_ct = pgrp->fi.raw_variant_ct;
10309 const uint32_t sample_ct = pgrp->fi.raw_sample_ct;
10310 const uint32_t const_vrtype = pgrp->fi.const_vrtype;
10311 if (const_vrtype != UINT32_MAX) {
10312 if (unlikely(allele_idx_offsets && (allele_idx_offsets[variant_ct] != 2 * variant_ct))) {
10313 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: .pvar file contains multiallelic variant(s), but .%s file does not.\n", (const_vrtype == kPglVrtypePlink1)? "bed" : "pgen");
10314 return kPglRetInconsistentInput;
10315 }
10316 // const uintptr_t const_vrec_width = pgrp->fi.const_vrec_width;
10317 if ((!const_vrtype) || (const_vrtype == kPglVrtypePlink1)) {
10318 // only thing that can go wrong is nonzero trailing bits
10319 const uint32_t dbl_sample_ct_mod4 = 2 * (sample_ct % 4);
10320 if (!dbl_sample_ct_mod4) {
10321 return kPglRetSuccess;
10322 }
10323 for (uint32_t vidx = 0; vidx != variant_ct; ++vidx) {
10324 const unsigned char* fread_ptr;
10325 const unsigned char* fread_end = nullptr;
10326 if (unlikely(InitReadPtrs(vidx, pgrp, &fread_ptr, &fread_end))) {
10327 FillPgenReadErrstrFromErrno(errstr_buf);
10328 return kPglRetReadFail;
10329 }
10330 const uint32_t last_byte_in_record = fread_end[-1];
10331 if (unlikely(last_byte_in_record >> dbl_sample_ct_mod4)) {
10332 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Last byte of (0-based) variant #%u has nonzero trailing bits.\n", vidx);
10333 return kPglRetMalformedInput;
10334 }
10335 }
10336 return kPglRetSuccess;
10337 }
10338 // todo: 16-bit dosage entries can't be in [32769,65534]
10339 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Validation of fixed-width dosage formats is not implemented yet.\n");
10340 return kPglRetNotYetSupported;
10341 }
10342 const unsigned char* vrtypes = pgrp->fi.vrtypes;
10343 for (uint32_t vidx = 0; vidx < variant_ct; vidx += kPglVblockSize) {
10344 if (unlikely(VrtypeLdCompressed(vrtypes[vidx]))) {
10345 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: (0-based) variant #%u is LD-compressed; this is prohibited when the variant index is a multiple of 65536.\n", vidx);
10346 return kPglRetMalformedInput;
10347 }
10348 }
10349 // file size may not be validated yet.
10350 uint64_t fsize;
10351 FILE* ff = pgrp->ff;
10352 if (unlikely(fseeko(ff, 0, SEEK_END))) {
10353 FillPgenReadErrstrFromNzErrno(errstr_buf);
10354 return kPglRetReadFail;
10355 }
10356 fsize = ftello(ff);
10357 pgrp->fp_vidx = 1; // force fseek when loading first variant
10358 // todo: verify equality if no mode-0x11 footer; and if there is a footer,
10359 // validate it
10360 const uint64_t expected_fsize_min = pgrp->fi.var_fpos[variant_ct];
10361 if (unlikely(expected_fsize_min > fsize)) {
10362 char* write_iter = strcpya_k(errstr_buf, "Error: .pgen header indicates that file size should be at least ");
10363 write_iter = i64toa(expected_fsize_min, write_iter);
10364 write_iter = strcpya_k(write_iter, " bytes, but actual file size is ");
10365 write_iter = i64toa(fsize, write_iter);
10366 strcpy_k(write_iter, " bytes.\n");
10367 return kPglRetMalformedInput;
10368 }
10369 const uint32_t vblock_ct = DivUp(variant_ct, kPglVblockSize);
10370 uint32_t header_ctrl = 0;
10371 if (unlikely(fseeko(ff, 11, SEEK_SET))) {
10372 FillPgenReadErrstrFromNzErrno(errstr_buf);
10373 return kPglRetReadFail;
10374 }
10375 header_ctrl = getc_unlocked(ff);
10376 if (unlikely(header_ctrl > 255)) {
10377 FillPgenReadErrstr(ff, errstr_buf);
10378 return kPglRetReadFail;
10379 }
10380 for (uint32_t vblock_idx = 0; vblock_idx != vblock_ct; ++vblock_idx) {
10381 uint64_t vblock_start_fpos;
10382 if (unlikely(!fread_unlocked(&vblock_start_fpos, sizeof(int64_t), 1, ff))) {
10383 FillPgenReadErrstr(ff, errstr_buf);
10384 return kPglRetReadFail;
10385 }
10386 if (unlikely(vblock_start_fpos != pgrp->fi.var_fpos[vblock_idx * kPglVblockSize])) {
10387 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: .pgen header vblock-start index is inconsistent with variant record length index.\n");
10388 return kPglRetMalformedInput;
10389 }
10390 }
10391 const uint32_t vrtype_and_fpos_storage = header_ctrl & 15;
10392 const uint32_t alt_allele_ct_byte_ct = (header_ctrl >> 4) & 3;
10393 const uint32_t nonref_flags_stored = ((header_ctrl >> 6) == 3);
10394
10395 // does not include vrtypes yet
10396 uint64_t vblock_index_byte_ct = kPglVblockSize * (1 + (vrtype_and_fpos_storage & 3) + alt_allele_ct_byte_ct);
10397 if (nonref_flags_stored) {
10398 vblock_index_byte_ct += kPglVblockSize / CHAR_BIT;
10399 }
10400 uint64_t last_vrtype_byte_offset = 0;
10401 uint32_t trailing_shift = 4;
10402 if (vrtype_and_fpos_storage & 8) {
10403 vblock_index_byte_ct += kPglVblockSize >> (10 - vrtype_and_fpos_storage);
10404 if (vrtype_and_fpos_storage == 8) {
10405 const uint32_t variant_ct_mod4 = variant_ct % 4;
10406 if (variant_ct_mod4) {
10407 last_vrtype_byte_offset = 20 + (vblock_ct - 1) * (vblock_index_byte_ct + sizeof(int64_t)) + ((variant_ct % kPglVblockSize) / 4);
10408 trailing_shift = variant_ct_mod4 * 2;
10409 }
10410 } else {
10411 assert(vrtype_and_fpos_storage == 9);
10412 if (variant_ct % 2) {
10413 last_vrtype_byte_offset = 20 + (vblock_ct - 1) * (vblock_index_byte_ct + sizeof(int64_t)) + ((variant_ct % kPglVblockSize) / 2);
10414 }
10415 }
10416 } else if (!(vrtype_and_fpos_storage & 4)) {
10417 vblock_index_byte_ct += kPglVblockSize / 2;
10418 if (variant_ct % 2) {
10419 // bugfix (22 Nov 2017): forgot to add offset in last block
10420 last_vrtype_byte_offset = 20 + (vblock_ct - 1) * (vblock_index_byte_ct + sizeof(int64_t)) + ((variant_ct % kPglVblockSize) / 2);
10421 }
10422 /*
10423 } else {
10424 vblock_index_byte_ct += kPglVblockSize;
10425 */
10426 }
10427 if (last_vrtype_byte_offset) {
10428 uint32_t last_vrtype_byte = 0;
10429 if (unlikely(fseeko(ff, last_vrtype_byte_offset, SEEK_SET))) {
10430 FillPgenReadErrstrFromNzErrno(errstr_buf);
10431 return kPglRetReadFail;
10432 }
10433 last_vrtype_byte = getc_unlocked(ff);
10434 if (unlikely(last_vrtype_byte > 255)) {
10435 FillPgenReadErrstr(ff, errstr_buf);
10436 return kPglRetReadFail;
10437 }
10438 if (unlikely(last_vrtype_byte >> trailing_shift)) {
10439 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Nonzero trailing bits in last vrtype index byte.\n");
10440 return kPglRetMalformedInput;
10441 }
10442 }
10443 const uintptr_t* nonref_flags = pgrp->fi.nonref_flags;
10444 if (nonref_flags) {
10445 const uint32_t variant_ct_modl = variant_ct % kBitsPerWord;
10446 if (variant_ct % CHAR_BIT) {
10447 if (unlikely(nonref_flags[variant_ct / kBitsPerWord] >> variant_ct_modl)) {
10448 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Nonzero trailing bits in last nonref_flags byte.\n");
10449 return kPglRetMalformedInput;
10450 }
10451 }
10452 }
10453
10454 // could move most of this into plink2_common and make it multithreaded, if
10455 // speed is ever an issue.
10456 uint32_t allele_ct = 2;
10457 for (uint32_t vidx = 0; vidx != variant_ct; ++vidx) {
10458 const unsigned char* fread_ptr;
10459 const unsigned char* fread_end;
10460 if (unlikely(InitReadPtrs(vidx, pgrp, &fread_ptr, &fread_end))) {
10461 FillPgenReadErrstrFromErrno(errstr_buf);
10462 return kPglRetReadFail;
10463 }
10464 const unsigned char* fread_ptr_start = fread_ptr;
10465 if (unlikely(ValidateGeno(fread_end, vidx, pgrp, &fread_ptr, genovec_buf, errstr_buf))) {
10466 return kPglRetMalformedInput;
10467 }
10468 ZeroTrailingNyps(sample_ct, genovec_buf);
10469 const uint32_t vrtype = vrtypes[vidx];
10470 uint32_t het_ct = CountNyp(genovec_buf, kMask5555, sample_ct);
10471 if (allele_idx_offsets) {
10472 allele_ct = allele_idx_offsets[vidx + 1] - allele_idx_offsets[vidx];
10473 }
10474 if (VrtypeMultiallelicHc(vrtype)) {
10475 if (unlikely(ValidateMultiallelicHc(fread_end, genovec_buf, vidx, allele_ct, pgrp, &fread_ptr, &het_ct, errstr_buf))) {
10476 return kPglRetMalformedInput;
10477 }
10478 }
10479 // don't need genovec_buf to store main genotypes past this point.
10480 if (VrtypeHphase(vrtype)) {
10481 if (unlikely(ValidateHphase(fread_end, vidx, het_ct, &fread_ptr, errstr_buf))) {
10482 return kPglRetMalformedInput;
10483 }
10484 }
10485 if (vrtype & 0xe0) {
10486 if (unlikely((vrtype & 0xe0) == 0x80)) {
10487 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid record type for (0-based) variant #%u (phased dosage bit set, but main dosage bits unset).\n", vidx);
10488 return kPglRetMalformedInput;
10489 }
10490 PglErr reterr = ValidateDosage16(fread_end, vidx, pgrp, &fread_ptr, errstr_buf);
10491 if (unlikely(reterr)) {
10492 return reterr;
10493 }
10494 }
10495 if (unlikely(fread_ptr != fread_end)) {
10496 // possible todo: tolerate this at the end of a vblock.
10497 char* write_iter = strcpya_k(errstr_buf, "Error: Extra byte(s) in (0-based) variant record #");
10498 write_iter = u32toa(vidx, write_iter);
10499 write_iter = strcpya_k(write_iter, ". (record type = ");
10500 write_iter = u32toa(vrtype, write_iter);
10501 write_iter = strcpya_k(write_iter, "; expected length = ");
10502 write_iter = wtoa(S_CAST(uintptr_t, fread_ptr - fread_ptr_start), write_iter);
10503 write_iter = strcpya_k(write_iter, ", actual = ");
10504 write_iter = wtoa(S_CAST(uintptr_t, fread_end - fread_ptr_start), write_iter);
10505 memcpy_k(write_iter, ")\n\0", 4);
10506 return kPglRetMalformedInput;
10507 }
10508 }
10509 return kPglRetSuccess;
10510 }
10511
10512
10513 BoolErr CleanupPgfi(PgenFileInfo* pgfip, PglErr* reterrp) {
10514 // memory is the responsibility of the caller
10515 if (pgfip->shared_ff) {
10516 BoolErr pgi_fclose_err = 0;
10517 if (pgfip->pgi_ff) {
10518 pgi_fclose_err = fclose_null(&pgfip->pgi_ff);
10519 }
10520 if (unlikely(fclose_null(&pgfip->shared_ff) || pgi_fclose_err)) {
10521 if (*reterrp == kPglRetSuccess) {
10522 *reterrp = kPglRetReadFail;
10523 return 1;
10524 }
10525 }
10526 } else {
10527 assert(!pgfip->pgi_ff);
10528 }
10529 return 0;
10530 }
10531
10532 BoolErr CleanupPgr(PgenReader* pgr_ptr, PglErr* reterrp) {
10533 PgenReaderMain* pgrp = GetPgrp(pgr_ptr);
10534 // assume file is open if pgr.ff is not null
10535 // memory is the responsibility of the caller for now
10536 if (!pgrp->ff) {
10537 return 0;
10538 }
10539 if (fclose_null(&(pgrp->ff))) {
10540 if (*reterrp == kPglRetSuccess) {
10541 *reterrp = kPglRetReadFail;
10542 return 1;
10543 }
10544 }
10545 return 0;
10546 }
10547
10548 #ifdef __cplusplus
10549 } // namespace plink2
10550 #endif