Debian Codegraph @

plink2_common.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 "plink2_common.h"
19 #include "plink2_compress_stream.h"
20
21 #ifdef __cplusplus
22 namespace plink2 {
23 #endif
24
25 const double kSmallDoubles[4] = {0.0, 1.0, 2.0, 3.0};
26
27 void InitPedigreeIdInfo(MiscFlags misc_flags, PedigreeIdInfo* piip) {
28 piip->sii.sample_ids = nullptr;
29 piip->sii.sids = nullptr;
30 piip->sii.max_sample_id_blen = 4;
31 piip->sii.max_sid_blen = 0;
32 piip->sii.flags = kfSampleId0;
33 if (misc_flags & kfMiscNoIdHeader) {
34 piip->sii.flags |= kfSampleIdNoIdHeader;
35 if (misc_flags & kfMiscNoIdHeaderIidOnly) {
36 piip->sii.flags |= kfSampleIdNoIdHeaderIidOnly;
37 }
38 }
39 if (misc_flags & kfMiscStrictSid0) {
40 piip->sii.flags |= kfSampleIdStrictSid0;
41 }
42 piip->parental_id_info.paternal_ids = nullptr;
43 piip->parental_id_info.maternal_ids = nullptr;
44 piip->parental_id_info.max_paternal_id_blen = 2;
45 piip->parental_id_info.max_maternal_id_blen = 2;
46 }
47
48 BoolErr BigstackAllocPgv(uint32_t sample_ct, uint32_t multiallelic_needed, PgenGlobalFlags gflags, PgenVariant* pgvp) {
49 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
50 if (unlikely(bigstack_allocv_w(sample_ctl2, &(pgvp->genovec)))) {
51 return 1;
52 }
53 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
54 if (multiallelic_needed) {
55 if (unlikely(bigstack_allocv_w(sample_ctl, &(pgvp->patch_01_set)) ||
56 bigstack_allocv_ac(sample_ct, &(pgvp->patch_01_vals)) ||
57 bigstack_allocv_w(sample_ctl, &(pgvp->patch_10_set)) ||
58 bigstack_allocv_ac(sample_ct * 2, &(pgvp->patch_10_vals)))) {
59 return 1;
60 }
61 } else {
62 // defensive
63 pgvp->patch_01_set = nullptr;
64 pgvp->patch_01_vals = nullptr;
65 pgvp->patch_10_set = nullptr;
66 pgvp->patch_10_vals = nullptr;
67 }
68 if (gflags & (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePhasePresent)) {
69 if (unlikely(bigstack_allocv_w(sample_ctl, &(pgvp->phasepresent)) ||
70 bigstack_allocv_w(sample_ctl, &(pgvp->phaseinfo)))) {
71 return 1;
72 }
73 } else {
74 pgvp->phasepresent = nullptr;
75 pgvp->phaseinfo = nullptr;
76 }
77 if (gflags & kfPgenGlobalDosagePresent) {
78 if (unlikely(bigstack_allocv_w(sample_ctl, &(pgvp->dosage_present)) ||
79 bigstack_allocv_dosage(sample_ct, &(pgvp->dosage_main)))) {
80 return 1;
81 }
82 if (multiallelic_needed) {
83 // todo
84 }
85 if (gflags & kfPgenGlobalDosagePhasePresent) {
86 if (unlikely(bigstack_allocv_w(sample_ctl, &(pgvp->dphase_present)) ||
87 bigstack_allocv_dphase(sample_ct, &(pgvp->dphase_delta)))) {
88 return 1;
89 }
90 if (multiallelic_needed) {
91 // todo
92 }
93 }
94 } else {
95 pgvp->dosage_present = nullptr;
96 pgvp->dosage_main = nullptr;
97 pgvp->dphase_present = nullptr;
98 pgvp->dphase_delta = nullptr;
99 // todo: multiallelic-dosage buffers
100 }
101 return BigstackBaseSetChecked(g_bigstack_base);
102 }
103
104 static_assert(kDosageMid == 16384, "PrintDosageDecimal() needs to be updated.");
105 char* PrintDosageDecimal(uint32_t remainder, char* start) {
106 // Instead of constant 5-digit precision, we print fewer digits whenever that
107 // doesn't interfere with proper round-tripping. I.e. we search for the
108 // shortest string in
109 // ((n - 0.5)/16384, (n + 0.5)/16384).
110 // E.g. 3277/16384 is 0.20001 when printed with 5-digit precision, but we'd
111 // print that as 0.2 since that's still in (3276.5/16384, 3277.5/16384).
112 *start++ = '.';
113 // (remainder * 2) is in 32768ths
114 // 32768 * 625 = 20480k, smallest common denominator with 10^4
115
116 const uint32_t range_top_20480k = (remainder * 2 + 1) * 625;
117 // this is technically checking a half-open rather than a fully-open
118 // interval, but that's fine since we never hit the boundary points
119 if ((range_top_20480k % 2048) < 1250) {
120 // when this is true, the four-decimal-place approximation is in the range
121 // which round-trips back to our original number.
122 const uint32_t four_decimal_places = range_top_20480k / 2048;
123 return u32toa_trunc4(four_decimal_places, start);
124 }
125
126 // we wish to print (100000 * remainder + 8192) / 16384, left-0-padded. and
127 // may as well banker's round too.
128 //
129 // banker's rounding yields a different result than regular rounding for n/64
130 // when n is congruent to 1 mod 4:
131 // 1/64 = .015625 -> print 0.01562
132 // 3/64 = .046875 -> print 0.04688
133 // 5/64 = .078125 -> print 0.07812
134 const uint32_t five_decimal_places = ((3125 * remainder + 256) / 512) - ((remainder % 1024) == 256);
135 const uint32_t first_decimal_place = five_decimal_places / 10000;
136 *start++ = '0' + first_decimal_place;
137 const uint32_t last_four_digits = five_decimal_places - first_decimal_place * 10000;
138 if (last_four_digits) {
139 return u32toa_trunc4(last_four_digits, start);
140 }
141 return start;
142 }
143
144 static_assert(kDosageMax == 32768, "ddosagetoa() needs to be updated.");
145 char* ddosagetoa(uint64_t dosage, char* start) {
146 // 3 digit precision seems like the best compromise between accuracy and
147 // avoidance of rounding ugliness
148 // (Rounding ugliness is not actually hidden for e.g. 1000 Genomes phase 1,
149 // since there are lots of 0.05 and 0.1 dosages which all get rounded in the
150 // same direction; oh well.)
151
152 // +16 since we need to round .99951 up to 1
153 const uint64_t dosage_p16 = dosage + 16;
154 start = u32toa(dosage_p16 / kDosageMax, start);
155 const uint32_t remainder_p16 = S_CAST(uint32_t, dosage_p16) % kDosageMax;
156 if (remainder_p16 < 33) {
157 return start;
158 }
159 // (1000 * remainder + 16384) / 32768
160 // 1/16 = .0625 -> print 0.062
161 // 3/16 = .1875 -> print 0.188
162 // 5/16 = .3125 -> print 0.312
163 // const uint32_t three_decimal_places = ((125 * remainder + 2048) / 4096) - ((remainder % 8192) == 2048);
164 const uint32_t three_decimal_places = ((125 * remainder_p16 + 48) / 4096) - ((remainder_p16 % 8192) == 4048);
165 // three_decimal_places guaranteed to be nonzero here
166 *start++ = '.';
167 const uint32_t first_decimal_place = three_decimal_places / 100;
168 *start++ = '0' + first_decimal_place;
169 const uint32_t last_two_digits = three_decimal_places - first_decimal_place * 100;
170 if (last_two_digits) {
171 memcpy_k(start, &(kDigitPair[last_two_digits]), 2);
172 return &(start[1 + (start[1] != '0')]);
173 }
174 return start;
175 }
176
177 static_assert(kDosageMax == 32768, "PrintDdosageDecimal() needs to be updated.");
178 char* PrintDdosageDecimal(uint32_t remainder, char* start) {
179 // Instead of constant 5-digit precision, we print fewer digits whenever that
180 // doesn't interfere with proper round-tripping. I.e. we search for the
181 // shortest string in
182 // ((n - 0.5)/32768, (n + 0.5)/32768).
183 // E.g. 6554/32768 is 0.20001 when printed with 5-digit precision, but we'd
184 // print that as 0.2 since that's still in (6553.5/32768, 6554.5/32768).
185 // (This is more precise than necessary for most chromosomes, but it's
186 // necessary for chrX.)
187 *start++ = '.';
188 // (remainder * 2) is in 65536ths
189 // 65536 * 625 = 40960k, smallest common denominator with 10^4
190
191 const uint32_t range_top_40960k = remainder * 1250 + 625;
192 // this is technically checking a half-open rather than a fully-open
193 // interval, but that's fine since we never hit the boundary points
194 if ((range_top_40960k % 4096) < 1250) {
195 // when this is true, the four-decimal-place approximation is in the range
196 // which round-trips back to our original number.
197 const uint32_t four_decimal_places = range_top_40960k / 4096;
198 return u32toa_trunc4(four_decimal_places, start);
199 }
200
201 // we wish to print (100000 * remainder + 16384) / 32768, left-0-padded. and
202 // may as well banker's round too.
203 //
204 // banker's rounding yields a different result than regular rounding for n/64
205 // when n is congruent to 1 mod 4:
206 // 1/64 = .015625 -> print 0.01562
207 // 3/64 = .046875 -> print 0.04688
208 // 5/64 = .078125 -> print 0.07812
209 const uint32_t five_decimal_places = ((3125 * remainder + 512) / 1024) - ((remainder % 2048) == 512);
210 const uint32_t first_decimal_place = five_decimal_places / 10000;
211 *start++ = '0' + first_decimal_place;
212 const uint32_t last_four_digits = five_decimal_places - first_decimal_place * 10000;
213 if (last_four_digits) {
214 return u32toa_trunc4(last_four_digits, start);
215 }
216 return start;
217 }
218
219 static const uint16_t kHcToDosage[1024] = QUAD_TABLE256(0, kDosageMid, kDosageMax, kDosageMissing);
220
221 void PopulateDenseDosage(const uintptr_t* genoarr, const uintptr_t* dosage_present, const Dosage* dosage_main, uint32_t sample_ct, uint32_t dosage_ct, Dosage* dense_dosage) {
222 GenoarrLookup256x2bx4(genoarr, kHcToDosage, sample_ct, dense_dosage);
223 // fill trailing bits with missing values so vector operations work
224 const uint32_t trailing_entry_ct = (-sample_ct) % kDosagePerVec;
225 if (trailing_entry_ct) {
226 Dosage* dense_dosage_end = &(dense_dosage[sample_ct]);
227 for (uint32_t uii = 0; uii != trailing_entry_ct; ++uii) {
228 dense_dosage_end[uii] = kDosageMissing;
229 }
230 }
231 if (dosage_ct) {
232 uintptr_t sample_idx_base = 0;
233 uintptr_t cur_bits = dosage_present[0];
234 for (uint32_t dosage_idx = 0; dosage_idx != dosage_ct; ++dosage_idx) {
235 const uintptr_t sample_idx = BitIter1(dosage_present, &sample_idx_base, &cur_bits);
236 dense_dosage[sample_idx] = dosage_main[dosage_idx];
237 }
238 }
239 }
240
241 // workspace must have at least NypCtToWordCt(sample_ct) words
242 void PopulateDenseDosageNonemptySubset(const uintptr_t* sample_include, const uint32_t* sample_include_cumulative_popcounts, const uintptr_t* genoarr, const uintptr_t* dosage_present, const Dosage* dosage_main, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t dosage_ct, Dosage* dense_dosage, uintptr_t* workspace) {
243 CopyNyparrNonemptySubset(genoarr, sample_include, raw_sample_ct, sample_ct, workspace);
244 GenoarrLookup256x2bx4(workspace, kHcToDosage, sample_ct, dense_dosage);
245 // fill trailing bits with missing values so vector operations work
246 const uint32_t trailing_entry_ct = (-sample_ct) % kDosagePerVec;
247 if (trailing_entry_ct) {
248 Dosage* dense_dosage_end = &(dense_dosage[sample_ct]);
249 for (uint32_t uii = 0; uii != trailing_entry_ct; ++uii) {
250 dense_dosage_end[uii] = kDosageMissing;
251 }
252 }
253 if (dosage_ct) {
254 uintptr_t widx = 0;
255 uintptr_t cur_bits = dosage_present[0];
256 for (uint32_t dosage_idx = 0; dosage_idx != dosage_ct; ++dosage_idx) {
257 const uintptr_t shifted_bit = BitIter1y(dosage_present, &widx, &cur_bits);
258 const uintptr_t sample_include_word = sample_include[widx];
259 if (sample_include_word & shifted_bit) {
260 const uint32_t sample_idx = sample_include_cumulative_popcounts[widx] + PopcountWord(sample_include_word & (shifted_bit - 1));
261 dense_dosage[sample_idx] = dosage_main[dosage_idx];
262 }
263 }
264 }
265 }
266
267 void PopulateRescaledDosage(const uintptr_t* genoarr, const uintptr_t* dosage_present, const Dosage* dosage_main, double slope, double intercept, double missing_val, uint32_t sample_ct, uint32_t dosage_ct, double* expanded_dosages) {
268 double lookup_vals[32] ALIGNV16;
269 lookup_vals[0] = intercept;
270 lookup_vals[2] = intercept + slope;
271 lookup_vals[4] = intercept + 2 * slope;
272 lookup_vals[6] = missing_val;
273 InitLookup16x8bx2(lookup_vals);
274 GenoarrLookup16x8bx2(genoarr, lookup_vals, sample_ct, expanded_dosages);
275 if (!dosage_ct) {
276 return;
277 }
278 slope *= kRecipDosageMid;
279 uintptr_t sample_uidx_base = 0;
280 uintptr_t cur_bits = dosage_present[0];
281 for (uint32_t dosage_idx = 0; dosage_idx != dosage_ct; ++dosage_idx) {
282 const uintptr_t sample_uidx = BitIter1(dosage_present, &sample_uidx_base, &cur_bits);
283 expanded_dosages[sample_uidx] = dosage_main[dosage_idx] * slope + intercept;
284 }
285 }
286
287 void PopulateRescaledDosageF(const uintptr_t* genoarr, const uintptr_t* dosage_present, const Dosage* dosage_main, float slope, float intercept, float missing_val, uint32_t sample_ct, uint32_t dosage_ct, float* expanded_dosages) {
288 float lookup_vals[32] ALIGNV16;
289 lookup_vals[0] = intercept;
290 lookup_vals[2] = intercept + slope;
291 lookup_vals[4] = intercept + 2 * slope;
292 lookup_vals[6] = missing_val;
293 InitLookup16x4bx2(lookup_vals);
294 GenoarrLookup16x4bx2(genoarr, lookup_vals, sample_ct, expanded_dosages);
295 if (!dosage_ct) {
296 return;
297 }
298 slope *= S_CAST(float, kRecipDosageMid);
299 uintptr_t sample_uidx_base = 0;
300 uintptr_t cur_bits = dosage_present[0];
301 for (uint32_t dosage_idx = 0; dosage_idx != dosage_ct; ++dosage_idx) {
302 const uintptr_t sample_uidx = BitIter1(dosage_present, &sample_uidx_base, &cur_bits);
303 expanded_dosages[sample_uidx] = dosage_main[dosage_idx] * slope + intercept;
304 }
305 }
306
307 void DosagePhaseinfoPatch(const uintptr_t* phasepresent, const uintptr_t* phaseinfo, const uintptr_t* dosage_present, const Dosage* dosage_vec, const uintptr_t* dphase_present, uint32_t sample_ct, SDosage* dphase_delta) {
308 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
309 uintptr_t dosage_present_word = 0;
310 for (uint32_t widx = 0; widx != sample_ctl; ++widx) {
311 uintptr_t phasepresent_nodphase_word = phasepresent[widx];
312 if (dphase_present) {
313 phasepresent_nodphase_word &= ~dphase_present[widx];
314 }
315 if (phasepresent_nodphase_word) {
316 const uintptr_t phaseinfo_word = phaseinfo[widx];
317 if (dosage_present) {
318 dosage_present_word = dosage_present[widx];
319 }
320 const uint32_t sample_idx_offset = widx * kBitsPerWord;
321 do {
322 const uint32_t sample_idx_lowbits = ctzw(phasepresent_nodphase_word);
323 const uint32_t sample_idx = sample_idx_offset + sample_idx_lowbits;
324 // should compile to blsi
325 const uintptr_t shifted_bit = phasepresent_nodphase_word & (-phasepresent_nodphase_word);
326 int32_t cur_diff = kDosageMid;
327 if (dosage_present_word & shifted_bit) {
328 cur_diff = DosageHomdist(dosage_vec[sample_idx]);
329 }
330 // todo: verify the compiler optimizes this well
331 if (!(phaseinfo_word & shifted_bit)) {
332 cur_diff = -cur_diff;
333 }
334 dphase_delta[sample_idx] = cur_diff;
335 phasepresent_nodphase_word ^= shifted_bit;
336 } while (phasepresent_nodphase_word);
337 }
338 }
339 }
340
341 void PopulateDenseDphase(const uintptr_t* phasepresent, const uintptr_t* phaseinfo, const uintptr_t* dosage_present, const Dosage* dense_dosage_vec, const uintptr_t* dphase_present, const SDosage* dphase_delta, uint32_t sample_ct, uint32_t phasepresent_ct, uint32_t dosage_ct, uint32_t dphase_ct, SDosage* dense_dphase_delta) {
342 const uint32_t dosagev_ct = DivUp(sample_ct, kDosagePerVec);
343 ZeroDphaseArr(dosagev_ct * kDosagePerVec, dense_dphase_delta);
344 if (dphase_ct) {
345 uintptr_t sample_uidx_base = 0;
346 uintptr_t cur_bits = dphase_present[0];
347 for (uint32_t dphase_idx = 0; dphase_idx != dphase_ct; ++dphase_idx) {
348 const uintptr_t sample_uidx = BitIter1(dphase_present, &sample_uidx_base, &cur_bits);
349 const int32_t dphase_delta_val = dphase_delta[dphase_idx];
350 dense_dphase_delta[sample_uidx] = dphase_delta_val;
351 }
352 } else {
353 dphase_present = nullptr;
354 }
355 if (phasepresent_ct) {
356 DosagePhaseinfoPatch(phasepresent, phaseinfo, dosage_ct? dosage_present : nullptr, dense_dosage_vec, dphase_present, sample_ct, dense_dphase_delta);
357 }
358 }
359
360 static_assert(sizeof(AlleleCode) == 1, "AtLeastOneMultiallelicHet() needs to be updated.");
361 uint32_t AtLeastOneMultiallelicHet(const PgenVariant* pgvp, uint32_t sample_ct) {
362 if (pgvp->patch_01_ct) {
363 return 1;
364 }
365 {
366 const uintptr_t* genoarr = pgvp->genovec;
367 const uint32_t fullvec_ct = sample_ct / kBitsPerWordD2;
368 for (uint32_t uii = 0; uii != fullvec_ct; ++uii) {
369 const uintptr_t geno_word = genoarr[uii];
370 if (Word01(geno_word)) {
371 return 1;
372 }
373 }
374 const uint32_t remainder = sample_ct % kBitsPerWordD2;
375 if (remainder) {
376 if (Word01(bzhi(genoarr[fullvec_ct], 2 * remainder))) {
377 return 1;
378 }
379 }
380 }
381 const uint32_t patch_10_ct = pgvp->patch_10_ct;
382 if (patch_10_ct) {
383 const AlleleCode* patch_10_vals = pgvp->patch_10_vals;
384 #ifdef __LP64__
385 const uint32_t fullvec_ct = patch_10_ct / (kBytesPerVec / 2);
386 const VecU16* patch_10_valias = R_CAST(const VecU16*, patch_10_vals);
387 const VecU16 m8 = vecu16_set1(0xff);
388 for (uint32_t vidx = 0; vidx != fullvec_ct; ++vidx) {
389 const VecU16 vv_orig = vecu16_loadu(&(patch_10_valias[vidx]));
390 const VecU16 vv_hi = vecu16_srli(vv_orig, 8);
391 const VecU16 vv_lo = vv_orig & m8;
392 if (!vecu16s_are_equal(vv_hi, vv_lo)) {
393 return 1;
394 }
395 }
396 uint32_t uii = fullvec_ct * (kBytesPerVec / 2);
397 #else
398 uint32_t uii = 0;
399 #endif
400 for (; uii != patch_10_ct; ++uii) {
401 if (patch_10_vals[2 * uii] != patch_10_vals[2 * uii + 1]) {
402 return 1;
403 }
404 }
405 }
406 return 0;
407 }
408
409 void SetHetMissing(uintptr_t word_ct, uintptr_t* genovec) {
410 // 01 -> 11, nothing else changes
411 #ifdef __LP64__
412 const VecW m1 = VCONST_W(kMask5555);
413 VecW* geno_vvec_iter = R_CAST(VecW*, genovec);
414 const uintptr_t full_vec_ct = word_ct / kWordsPerVec;
415 if (full_vec_ct & 1) {
416 const VecW cur_geno_vword = *geno_vvec_iter;
417 const VecW cur_geno_vword_low_lshifted = vecw_slli(cur_geno_vword & m1, 1);
418 *geno_vvec_iter++ = cur_geno_vword | cur_geno_vword_low_lshifted;
419 }
420 if (full_vec_ct & 2) {
421 VecW cur_geno_vword = *geno_vvec_iter;
422 VecW cur_geno_vword_low_lshifted = vecw_slli(cur_geno_vword & m1, 1);
423 *geno_vvec_iter++ = cur_geno_vword | cur_geno_vword_low_lshifted;
424 cur_geno_vword = *geno_vvec_iter;
425 cur_geno_vword_low_lshifted = vecw_slli(cur_geno_vword & m1, 1);
426 *geno_vvec_iter++ = cur_geno_vword | cur_geno_vword_low_lshifted;
427 }
428 for (uintptr_t ulii = 3; ulii < full_vec_ct; ulii += 4) {
429 VecW cur_geno_vword = *geno_vvec_iter;
430 VecW cur_geno_vword_low_lshifted = vecw_slli(cur_geno_vword & m1, 1);
431 *geno_vvec_iter++ = cur_geno_vword | cur_geno_vword_low_lshifted;
432 cur_geno_vword = *geno_vvec_iter;
433 cur_geno_vword_low_lshifted = vecw_slli(cur_geno_vword & m1, 1);
434 *geno_vvec_iter++ = cur_geno_vword | cur_geno_vword_low_lshifted;
435 cur_geno_vword = *geno_vvec_iter;
436 cur_geno_vword_low_lshifted = vecw_slli(cur_geno_vword & m1, 1);
437 *geno_vvec_iter++ = cur_geno_vword | cur_geno_vword_low_lshifted;
438 cur_geno_vword = *geno_vvec_iter;
439 cur_geno_vword_low_lshifted = vecw_slli(cur_geno_vword & m1, 1);
440 *geno_vvec_iter++ = cur_geno_vword | cur_geno_vword_low_lshifted;
441 }
442 # ifdef USE_AVX2
443 if (word_ct & 2) {
444 const uintptr_t base_idx = full_vec_ct * kWordsPerVec;
445 uintptr_t geno_word = genovec[base_idx];
446 genovec[base_idx] = geno_word | ((geno_word & kMask5555) << 1);
447 geno_word = genovec[base_idx + 1];
448 genovec[base_idx + 1] = geno_word | ((geno_word & kMask5555) << 1);
449 }
450 # endif
451 if (word_ct & 1) {
452 const uintptr_t geno_word = genovec[word_ct - 1];
453 genovec[word_ct - 1] = geno_word | ((geno_word & kMask5555) << 1);
454 }
455 #else
456 for (uintptr_t widx = 0; widx != word_ct; ++widx) {
457 const uintptr_t geno_word = genovec[widx];
458 genovec[widx] = geno_word | ((geno_word & kMask5555) << 1);
459 }
460 #endif
461 }
462
463 void SetHetMissingCleardosage(uintptr_t word_ct, uintptr_t* __restrict genovec, uint32_t* write_dosage_ct_ptr, uintptr_t* __restrict dosagepresent, Dosage* dosage_main) {
464 const uint32_t orig_write_dosage_ct = *write_dosage_ct_ptr;
465 if (orig_write_dosage_ct) {
466 uintptr_t sample_uidx_base = 0;
467 uintptr_t cur_bits = dosagepresent[0];
468 for (uint32_t dosage_read_idx = 0; dosage_read_idx != orig_write_dosage_ct; ++dosage_read_idx) {
469 const uintptr_t sample_uidx = BitIter1(dosagepresent, &sample_uidx_base, &cur_bits);
470 if (GetNyparrEntry(genovec, sample_uidx) == 1) {
471 ClearBit(sample_uidx, dosagepresent);
472 uint32_t dosage_write_idx = dosage_read_idx++;
473 for (; dosage_read_idx == orig_write_dosage_ct; ++dosage_read_idx) {
474 const uintptr_t sample_uidx2 = BitIter1(dosagepresent, &sample_uidx_base, &cur_bits);
475 if (GetNyparrEntry(genovec, sample_uidx2) == 1) {
476 ClearBit(sample_uidx2, dosagepresent);
477 } else {
478 dosage_main[dosage_write_idx++] = dosage_main[dosage_read_idx];
479 }
480 }
481 *write_dosage_ct_ptr = dosage_write_idx;
482 break;
483 }
484 }
485 }
486 SetHetMissing(word_ct, genovec);
487 }
488
489 void SetHetMissingKeepdosage(uintptr_t word_ct, uintptr_t* __restrict genovec, uint32_t* write_dosage_ct_ptr, uintptr_t* __restrict dosagepresent, Dosage* dosage_main) {
490 // count # of 1.00000 dosages we need to insert, and then rewrite dosage_main
491 // from back to front so we don't need temporary buffers.
492
493 const uint32_t orig_dosage_ct = *write_dosage_ct_ptr;
494 // can't assume dosagepresent is initialized in this case
495 if (!orig_dosage_ct) {
496 ZeroWArr(DivUp(word_ct, 2), dosagepresent);
497 }
498 Halfword* dosagepresent_alias = R_CAST(Halfword*, dosagepresent);
499 uint32_t new_dosage_ct = 0;
500 // todo: try vectorizing this loop
501 for (uintptr_t widx = 0; widx != word_ct; ++widx) {
502 const uintptr_t geno_hets = Word01(genovec[widx]);
503 const uintptr_t dosagepresent_word = UnpackHalfwordToWord(dosagepresent_alias[widx]);
504 new_dosage_ct += Popcount01Word(geno_hets & (~dosagepresent_word));
505 }
506 if (!new_dosage_ct) {
507 SetHetMissing(word_ct, genovec);
508 return;
509 }
510 uint32_t dosage_write_idx = orig_dosage_ct + new_dosage_ct;
511 uint32_t dosage_read_idx = orig_dosage_ct;
512 uint32_t widx = word_ct;
513 *write_dosage_ct_ptr = dosage_write_idx;
514 do {
515 --widx;
516 const uintptr_t geno_word = genovec[widx];
517 const uintptr_t dosagepresent_word = UnpackHalfwordToWord(dosagepresent_alias[widx]);
518 const uintptr_t geno_hets = Word01(geno_word);
519 uintptr_t new_dosagepresent_word = dosagepresent_word | geno_hets;
520 if (new_dosagepresent_word) {
521 dosagepresent_alias[widx] = PackWordToHalfword(new_dosagepresent_word);
522 do {
523 const uint32_t top_set_bit = bsrw(new_dosagepresent_word);
524 const uintptr_t cur_bit_word = k1LU << top_set_bit;
525 Dosage cur_dosage = kDosageMid;
526 if (cur_bit_word & dosagepresent_word) {
527 cur_dosage = dosage_main[--dosage_read_idx];
528 }
529 dosage_main[--dosage_write_idx] = cur_dosage;
530 new_dosagepresent_word -= cur_bit_word;
531 } while (new_dosagepresent_word);
532 genovec[widx] = geno_word | (geno_hets << 1);
533 }
534 } while (widx);
535 }
536
537 // These functions may move to pgenlib_misc later.
538 uint32_t CountMissingVec6(const VecW* __restrict geno_vvec, uint32_t vec_ct) {
539 assert(!(vec_ct % 6));
540 const VecW m1 = VCONST_W(kMask5555);
541 const VecW m2 = VCONST_W(kMask3333);
542 const VecW m4 = VCONST_W(kMask0F0F);
543 const VecW* geno_vvec_iter = geno_vvec;
544 VecW acc_bothset = vecw_setzero();
545 uintptr_t cur_incr = 60;
546 for (; ; vec_ct -= cur_incr) {
547 if (vec_ct < 60) {
548 if (!vec_ct) {
549 return HsumW(acc_bothset);
550 }
551 cur_incr = vec_ct;
552 }
553 VecW inner_acc_bothset = vecw_setzero();
554 const VecW* geno_vvec_stop = &(geno_vvec_iter[cur_incr]);
555 do {
556 VecW cur_geno_vword = vecw_loadu(geno_vvec_iter);
557 ++geno_vvec_iter;
558 VecW bothset1 = m1 & cur_geno_vword & vecw_srli(cur_geno_vword, 1);
559
560 cur_geno_vword = vecw_loadu(geno_vvec_iter);
561 ++geno_vvec_iter;
562 bothset1 = bothset1 + (m1 & cur_geno_vword & vecw_srli(cur_geno_vword, 1));
563
564 cur_geno_vword = vecw_loadu(geno_vvec_iter);
565 ++geno_vvec_iter;
566 bothset1 = bothset1 + (m1 & cur_geno_vword & vecw_srli(cur_geno_vword, 1));
567 bothset1 = (bothset1 & m2) + (vecw_srli(bothset1, 2) & m2);
568
569 cur_geno_vword = vecw_loadu(geno_vvec_iter);
570 ++geno_vvec_iter;
571 VecW bothset2 = m1 & cur_geno_vword & vecw_srli(cur_geno_vword, 1);
572
573 cur_geno_vword = vecw_loadu(geno_vvec_iter);
574 ++geno_vvec_iter;
575 bothset2 = bothset2 + (m1 & cur_geno_vword & vecw_srli(cur_geno_vword, 1));
576
577 cur_geno_vword = vecw_loadu(geno_vvec_iter);
578 ++geno_vvec_iter;
579 bothset2 = bothset2 + (m1 & cur_geno_vword & vecw_srli(cur_geno_vword, 1));
580
581 bothset1 = bothset1 + (bothset2 & m2) + (vecw_srli(bothset2, 2) & m2);
582 // these now contain 4-bit values from 0-12
583
584 inner_acc_bothset = inner_acc_bothset + (bothset1 & m4) + (vecw_srli(bothset1, 4) & m4);
585 } while (geno_vvec_iter < geno_vvec_stop);
586 const VecW m0 = vecw_setzero();
587 acc_bothset = acc_bothset + vecw_bytesum(inner_acc_bothset, m0);
588 }
589 }
590
591 uint32_t GenoarrCountMissingUnsafe(const uintptr_t* genoarr, uint32_t sample_ct) {
592 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
593 uint32_t word_idx = sample_ctl2 - (sample_ctl2 % (6 * kWordsPerVec));
594 uint32_t missing_ct = CountMissingVec6(R_CAST(const VecW*, genoarr), word_idx / kWordsPerVec);
595 for (; word_idx != sample_ctl2; ++word_idx) {
596 uintptr_t ww = genoarr[word_idx];
597 // bugfix (19 Oct 2020): forgot to mask out high bits
598 ww = ww & (ww >> 1) & kMask5555;
599 missing_ct += Popcount01Word(ww);
600 }
601 return missing_ct;
602 }
603
604 // geno_vvec allowed to be unaligned.
605 uint32_t CountMissingMaskedVec6(const VecW* __restrict geno_vvec, const VecW* __restrict interleaved_mask_vvec, uint32_t vec_ct) {
606 assert(!(vec_ct % 6));
607 const VecW m1 = VCONST_W(kMask5555);
608 const VecW m2 = VCONST_W(kMask3333);
609 const VecW m4 = VCONST_W(kMask0F0F);
610 const VecW* geno_vvec_iter = geno_vvec;
611 const VecW* interleaved_mask_vvec_iter = interleaved_mask_vvec;
612 VecW acc_bothset = vecw_setzero();
613 uintptr_t cur_incr = 60;
614 for (; ; vec_ct -= cur_incr) {
615 if (vec_ct < 60) {
616 if (!vec_ct) {
617 return HsumW(acc_bothset);
618 }
619 cur_incr = vec_ct;
620 }
621 VecW inner_acc_bothset = vecw_setzero();
622 const VecW* geno_vvec_stop = &(geno_vvec_iter[cur_incr]);
623 do {
624 VecW interleaved_mask_vword = *interleaved_mask_vvec_iter++;
625 VecW cur_geno_vword = vecw_loadu(geno_vvec_iter);
626 ++geno_vvec_iter;
627 VecW cur_mask = interleaved_mask_vword & m1;
628 VecW bothset1 = cur_mask & cur_geno_vword & vecw_srli(cur_geno_vword, 1);
629
630 cur_mask = vecw_srli(interleaved_mask_vword, 1) & m1;
631 cur_geno_vword = vecw_loadu(geno_vvec_iter);
632 ++geno_vvec_iter;
633 bothset1 = bothset1 + (cur_mask & cur_geno_vword & vecw_srli(cur_geno_vword, 1));
634
635 interleaved_mask_vword = *interleaved_mask_vvec_iter++;
636 cur_mask = interleaved_mask_vword & m1;
637 cur_geno_vword = vecw_loadu(geno_vvec_iter);
638 ++geno_vvec_iter;
639 bothset1 = bothset1 + (cur_mask & cur_geno_vword & vecw_srli(cur_geno_vword, 1));
640 bothset1 = (bothset1 & m2) + (vecw_srli(bothset1, 2) & m2);
641
642 cur_mask = vecw_srli(interleaved_mask_vword, 1) & m1;
643 cur_geno_vword = vecw_loadu(geno_vvec_iter);
644 ++geno_vvec_iter;
645 VecW bothset2 = cur_mask & cur_geno_vword & vecw_srli(cur_geno_vword, 1);
646
647 interleaved_mask_vword = *interleaved_mask_vvec_iter++;
648 cur_mask = interleaved_mask_vword & m1;
649 cur_geno_vword = vecw_loadu(geno_vvec_iter);
650 ++geno_vvec_iter;
651 bothset2 = bothset2 + (cur_mask & cur_geno_vword & vecw_srli(cur_geno_vword, 1));
652
653 cur_mask = vecw_srli(interleaved_mask_vword, 1) & m1;
654 cur_geno_vword = vecw_loadu(geno_vvec_iter);
655 ++geno_vvec_iter;
656 bothset2 = bothset2 + (cur_mask & cur_geno_vword & vecw_srli(cur_geno_vword, 1));
657
658 bothset1 = bothset1 + (bothset2 & m2) + (vecw_srli(bothset2, 2) & m2);
659 // these now contain 4-bit values from 0-12
660
661 inner_acc_bothset = inner_acc_bothset + (bothset1 & m4) + (vecw_srli(bothset1, 4) & m4);
662 } while (geno_vvec_iter < geno_vvec_stop);
663 const VecW m0 = vecw_setzero();
664 acc_bothset = acc_bothset + vecw_bytesum(inner_acc_bothset, m0);
665 }
666 }
667
668 uint32_t GenoarrCountMissingSubset(const uintptr_t* genoarr, const uintptr_t* interleaved_vec, uint32_t sample_ct) {
669 // See GenoarrCountSubsetFreqs().
670 const uint32_t sample_ctv2 = NypCtToVecCt(sample_ct);
671 uint32_t missing_ct;
672 #ifdef __LP64__
673 uint32_t vec_idx = sample_ctv2 - (sample_ctv2 % 6);
674 missing_ct = CountMissingMaskedVec6(R_CAST(const VecW*, genoarr), R_CAST(const VecW*, interleaved_vec), vec_idx);
675 const uintptr_t* genoarr_iter = &(genoarr[kWordsPerVec * vec_idx]);
676 const uintptr_t* interleaved_mask_iter = &(interleaved_vec[(kWordsPerVec / 2) * vec_idx]);
677 # ifdef USE_AVX2
678 uintptr_t mask_base1 = 0;
679 uintptr_t mask_base2 = 0;
680 uintptr_t mask_base3 = 0;
681 uintptr_t mask_base4 = 0;
682 for (; vec_idx != sample_ctv2; ++vec_idx) {
683 uintptr_t mask_word1;
684 uintptr_t mask_word2;
685 uintptr_t mask_word3;
686 uintptr_t mask_word4;
687 if (!(vec_idx % 2)) {
688 mask_base1 = *interleaved_mask_iter++;
689 mask_base2 = *interleaved_mask_iter++;
690 mask_base3 = *interleaved_mask_iter++;
691 mask_base4 = *interleaved_mask_iter++;
692 mask_word1 = mask_base1 & kMask5555;
693 mask_word2 = mask_base2 & kMask5555;
694 mask_word3 = mask_base3 & kMask5555;
695 mask_word4 = mask_base4 & kMask5555;
696 } else {
697 mask_word1 = (mask_base1 >> 1) & kMask5555;
698 mask_word2 = (mask_base2 >> 1) & kMask5555;
699 mask_word3 = (mask_base3 >> 1) & kMask5555;
700 mask_word4 = (mask_base4 >> 1) & kMask5555;
701 }
702 for (uint32_t vechalf_idx = 0; ; ++vechalf_idx) {
703 const uintptr_t cur_geno_word1 = *genoarr_iter++;
704 const uintptr_t cur_geno_word2 = *genoarr_iter++;
705 const uintptr_t cur_geno_word1_high_masked = mask_word1 & (cur_geno_word1 >> 1);
706 const uintptr_t cur_geno_word2_high_masked = mask_word2 & (cur_geno_word2 >> 1);
707 missing_ct += PopcountWord(((cur_geno_word1 & cur_geno_word1_high_masked) << 1) | (cur_geno_word2 & cur_geno_word2_high_masked));
708 if (vechalf_idx) {
709 break;
710 }
711 mask_word1 = mask_word3;
712 mask_word2 = mask_word4;
713 }
714 }
715 # else // not USE_AVX2
716 uintptr_t mask_base1 = 0;
717 uintptr_t mask_base2 = 0;
718 for (; vec_idx != sample_ctv2; ++vec_idx) {
719 uintptr_t mask_word1;
720 uintptr_t mask_word2;
721 if (!(vec_idx % 2)) {
722 mask_base1 = *interleaved_mask_iter++;
723 mask_base2 = *interleaved_mask_iter++;
724 mask_word1 = mask_base1 & kMask5555;
725 mask_word2 = mask_base2 & kMask5555;
726 } else {
727 mask_word1 = (mask_base1 >> 1) & kMask5555;
728 mask_word2 = (mask_base2 >> 1) & kMask5555;
729 }
730 const uintptr_t cur_geno_word1 = *genoarr_iter++;
731 const uintptr_t cur_geno_word2 = *genoarr_iter++;
732 const uintptr_t cur_geno_word1_high_masked = mask_word1 & (cur_geno_word1 >> 1);
733 const uintptr_t cur_geno_word2_high_masked = mask_word2 & (cur_geno_word2 >> 1);
734 # ifdef USE_SSE42
735 missing_ct += PopcountWord(((cur_geno_word1 & cur_geno_word1_high_masked) << 1) | (cur_geno_word2 & cur_geno_word2_high_masked));
736 # else
737 missing_ct += NypsumWord((cur_geno_word1 & cur_geno_word1_high_masked) + (cur_geno_word2 & cur_geno_word2_high_masked));
738 # endif
739 }
740 # endif // not USE_AVX2
741 #else // not __LP64__
742 uint32_t word_idx = sample_ctv2 - (sample_ctv2 % 6);
743 missing_ct = CountMissingMaskedVec6(R_CAST(const VecW*, genoarr), R_CAST(const VecW*, interleaved_vec), word_idx);
744 const uintptr_t* interleaved_mask_iter = &(interleaved_vec[word_idx / 2]);
745 uintptr_t mask_base = 0;
746 for (; word_idx != sample_ctv2; ++word_idx) {
747 uintptr_t mask_word;
748 if (!(word_idx % 2)) {
749 mask_base = *interleaved_mask_iter++;
750 mask_word = mask_base & kMask5555;
751 } else {
752 mask_word = (mask_base >> 1) & kMask5555;
753 }
754 const uintptr_t cur_geno_word = genoarr[word_idx];
755 const uintptr_t cur_geno_word_high_masked = mask_word & (cur_geno_word >> 1);
756 missing_ct += Popcount01Word(cur_geno_word & cur_geno_word_high_masked);
757 }
758 #endif
759 return missing_ct;
760 }
761
762 // counts post-dosage missing, for which we don't have an interleaved mask
763 uint32_t GenoarrCountMissingInvsubsetUnsafe(const uintptr_t* genoarr, const uintptr_t* exclude_mask, uint32_t sample_ct) {
764 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
765 const uintptr_t* genoarr_iter = genoarr;
766 const Halfword* exclude_alias_iter = R_CAST(const Halfword*, exclude_mask);
767 uint32_t missing_ct = 0;
768 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
769 uintptr_t ww = *genoarr_iter++;
770 ww = ww & (ww >> 1);
771 const uint32_t include_mask = ~(*exclude_alias_iter++);
772 missing_ct += Popcount01Word(ww & UnpackHalfwordToWord(include_mask));
773 }
774 return missing_ct;
775 }
776
777
778 void CollapsedSampleFmtidInit(const uintptr_t* sample_include, const SampleIdInfo* siip, uint32_t sample_ct, uint32_t include_fid, uint32_t include_sid, uintptr_t max_sample_fmtid_blen, char* collapsed_sample_fmtids_iter) {
779 const char* sample_ids = siip->sample_ids;
780 const char* sids = siip->sids;
781 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
782 uintptr_t max_sid_blen = 0;
783 if (include_sid) {
784 max_sid_blen = sids? siip->max_sid_blen : 2;
785 }
786 uintptr_t sample_uidx_base = 0;
787 uintptr_t cur_bits = sample_include[0];
788 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
789 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
790 const char* cur_sample_id = &(sample_ids[sample_uidx * max_sample_id_blen]);
791 if (!include_fid) {
792 cur_sample_id = AdvPastDelim(cur_sample_id, '\t');
793 }
794 char* write_iter = strcpya(collapsed_sample_fmtids_iter, cur_sample_id);
795 if (include_sid) {
796 *write_iter++ = '\t';
797 if (sids) {
798 strcpy(write_iter, &(sids[sample_uidx * max_sid_blen]));
799 } else {
800 strcpy_k(write_iter, "0");
801 }
802 } else {
803 *write_iter = '\0';
804 }
805 collapsed_sample_fmtids_iter = &(collapsed_sample_fmtids_iter[max_sample_fmtid_blen]);
806 }
807 }
808
809 BoolErr CollapsedSampleFmtidInitAlloc(const uintptr_t* sample_include, const SampleIdInfo* siip, uint32_t sample_ct, uint32_t include_fid, uint32_t include_sid, char** collapsed_sample_fmtids_ptr, uintptr_t* max_sample_fmtid_blen_ptr) {
810 const uintptr_t max_sample_fmtid_blen = GetMaxSampleFmtidBlen(siip, include_fid, include_sid);
811 *max_sample_fmtid_blen_ptr = max_sample_fmtid_blen;
812 // might add sample_fmtid_map later
813 if (unlikely(bigstack_alloc_c(max_sample_fmtid_blen * sample_ct, collapsed_sample_fmtids_ptr))) {
814 return 1;
815 }
816 CollapsedSampleFmtidInit(sample_include, siip, sample_ct, include_fid, include_sid, max_sample_fmtid_blen, *collapsed_sample_fmtids_ptr);
817 return 0;
818 }
819
820 uint32_t OnlyOneFid(const uintptr_t* sample_include, const SampleIdInfo* siip, uint32_t sample_ct) {
821 if (!(siip->flags & kfSampleIdFidPresent)) {
822 return 1;
823 }
824 const char* sample_ids = siip->sample_ids;
825 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
826 uintptr_t sample_uidx_base = 0;
827 uintptr_t cur_bits = sample_include[0];
828 const uintptr_t first_sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
829 const char* fid_start = &(sample_ids[first_sample_uidx * max_sample_id_blen]);
830 const uintptr_t fid_blen = AdvPastDelim(fid_start, '\t') - fid_start;
831 for (uint32_t sample_idx = 1; sample_idx != sample_ct; ++sample_idx) {
832 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
833 const char* cur_fid_start = &(sample_ids[sample_uidx * max_sample_id_blen]);
834 if (!memequal(fid_start, cur_fid_start, fid_blen)) {
835 return 0;
836 }
837 }
838 return 1;
839 }
840
841 uint32_t GetMajIdxMulti(const double* cur_allele_freqs, uint32_t cur_allele_ct) {
842 assert(cur_allele_ct > 2);
843 double max_freq = cur_allele_freqs[1];
844 if (max_freq >= 0.5) {
845 return 1;
846 }
847 double tot_nonlast_freq = cur_allele_freqs[0];
848 uint32_t maj_allele_idx = 1;
849 if (tot_nonlast_freq >= max_freq) {
850 maj_allele_idx = 0;
851 max_freq = tot_nonlast_freq;
852 }
853 tot_nonlast_freq += max_freq;
854 const uint32_t cur_allele_ct_m1 = cur_allele_ct - 1;
855 for (uint32_t allele_idx = 2; allele_idx != cur_allele_ct_m1; ++allele_idx) {
856 const double cur_freq = cur_allele_freqs[allele_idx];
857 if (cur_freq > max_freq) {
858 maj_allele_idx = allele_idx;
859 max_freq = cur_freq;
860 }
861 tot_nonlast_freq += cur_freq;
862 }
863 if (max_freq + tot_nonlast_freq < 1.0 - kSmallEpsilon) {
864 return cur_allele_ct_m1;
865 }
866 return maj_allele_idx;
867 }
868
869 // forced SID '0' if sids == nullptr
870 // ok for sample_augid_map_ptr == nullptr
871 PglErr AugidInitAlloc(const uintptr_t* sample_include, const SampleIdInfo* siip, uint32_t sample_ct, uint32_t alloc_at_end, uint32_t** sample_augid_map_ptr, char** sample_augids_ptr, uintptr_t* max_sample_augid_blen_ptr) {
872 const char* sample_ids = siip->sample_ids;
873 const char* sids = siip->sids;
874 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
875 uintptr_t max_sid_blen = siip->max_sid_blen;
876 if (!sids) {
877 max_sid_blen = 2;
878 }
879 const uintptr_t max_sample_augid_blen = max_sample_id_blen + max_sid_blen;
880 *max_sample_augid_blen_ptr = max_sample_augid_blen;
881 uint32_t* sample_augid_map = nullptr;
882 if (sample_augid_map_ptr) {
883 if (!alloc_at_end) {
884 if (unlikely(bigstack_alloc_u32(sample_ct, sample_augid_map_ptr))) {
885 return kPglRetNomem;
886 }
887 } else {
888 if (unlikely(bigstack_end_alloc_u32(sample_ct, sample_augid_map_ptr))) {
889 return kPglRetNomem;
890 }
891 }
892 sample_augid_map = *sample_augid_map_ptr;
893 }
894 if (!alloc_at_end) {
895 if (unlikely(bigstack_alloc_c(max_sample_augid_blen * sample_ct, sample_augids_ptr))) {
896 return kPglRetNomem;
897 }
898 } else {
899 if (unlikely(bigstack_end_alloc_c(max_sample_augid_blen * sample_ct, sample_augids_ptr))) {
900 return kPglRetNomem;
901 }
902 }
903 char* sample_augids_iter = *sample_augids_ptr;
904 uintptr_t sample_uidx_base = 0;
905 uintptr_t cur_bits = sample_include[0];
906 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
907 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
908 char* write_iter = strcpyax(sample_augids_iter, &(sample_ids[sample_uidx * max_sample_id_blen]), '\t');
909 if (sids) {
910 strcpy(write_iter, &(sids[sample_uidx * max_sid_blen]));
911 } else {
912 strcpy_k(write_iter, "0");
913 }
914 sample_augids_iter = &(sample_augids_iter[max_sample_augid_blen]);
915 if (sample_augid_map) {
916 sample_augid_map[sample_idx] = sample_uidx;
917 }
918 }
919 return kPglRetSuccess;
920 }
921
922 PglErr SortedXidboxInitAlloc(const uintptr_t* sample_include, const SampleIdInfo* siip, uint32_t sample_ct, XidMode xid_mode, uint32_t use_nsort, char** sorted_xidbox_ptr, uint32_t** xid_map_ptr, uintptr_t* max_xid_blen_ptr) {
923 if (!(xid_mode & kfXidModeFlagSid)) {
924 // two fields
925 *max_xid_blen_ptr = siip->max_sample_id_blen;
926 return CopySortStrboxSubset(sample_include, siip->sample_ids, sample_ct, siip->max_sample_id_blen, 0, use_nsort, sorted_xidbox_ptr, xid_map_ptr);
927 }
928 // three fields
929 if (unlikely(AugidInitAlloc(sample_include, siip, sample_ct, 0, xid_map_ptr, sorted_xidbox_ptr, max_xid_blen_ptr))) {
930 return kPglRetNomem;
931 }
932 if (unlikely(SortStrboxIndexed(sample_ct, *max_xid_blen_ptr, use_nsort, *sorted_xidbox_ptr, *xid_map_ptr))) {
933 return kPglRetNomem;
934 }
935 return kPglRetSuccess;
936 }
937
938 PglErr SortedXidboxInitAllocEnd(const uintptr_t* sample_include, const SampleIdInfo* siip, uint32_t sample_ct, XidMode xid_mode, uint32_t use_nsort, char** sorted_xidbox_ptr, uint32_t** xid_map_ptr, uintptr_t* max_xid_blen_ptr) {
939 if (!(xid_mode & kfXidModeFlagSid)) {
940 // two fields
941 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
942 *max_xid_blen_ptr = max_sample_id_blen;
943 if (unlikely(bigstack_end_alloc_u32(sample_ct, xid_map_ptr) ||
944 bigstack_end_alloc_c(sample_ct * max_sample_id_blen, sorted_xidbox_ptr))) {
945 return kPglRetNomem;
946 }
947 return CopySortStrboxSubsetNoalloc(sample_include, siip->sample_ids, sample_ct, max_sample_id_blen, 0, use_nsort, *sorted_xidbox_ptr, *xid_map_ptr);
948 }
949 // three fields
950 if (unlikely(AugidInitAlloc(sample_include, siip, sample_ct, 1, xid_map_ptr, sorted_xidbox_ptr, max_xid_blen_ptr))) {
951 return kPglRetNomem;
952 }
953 if (unlikely(SortStrboxIndexed(sample_ct, *max_xid_blen_ptr, use_nsort, *sorted_xidbox_ptr, *xid_map_ptr))) {
954 return kPglRetNomem;
955 }
956 return kPglRetSuccess;
957 }
958
959 uint32_t XidRead(uintptr_t max_xid_blen, uint32_t comma_delim, XidMode xid_mode, const char** read_pp, char* __restrict idbuf) {
960 // Saves normalized tokens pointed to by *read_pp to idbuf, and advances
961 // *read_pp.
962 //
963 // Input *read_pp must point to beginning of sample ID; this is a change from
964 // plink 1.9.
965 //
966 // *read_pp is now set to point to the end of the last parsed token instead
967 // of the beginning of the next; this is another change from plink 1.9.
968 //
969 // Returns 0 on missing token *or* guaranteed sample ID mismatch (longer than
970 // max_xid_blen); cases can be distinguished by checking whether *read_pp ==
971 // nullptr. Otherwise, returns slen of the parsed ID saved to idbuf. (idbuf
972 // is not null-terminated.)
973 //
974 // Alpha 2 behavior change: If there's no FID column, it's now set to 0
975 // instead of the IID value.
976 const char* first_token_start = *read_pp;
977 uintptr_t slen_fid = 0; // now zero if no FID column
978 uintptr_t blen_sid = 0;
979 const char* sid_ptr = nullptr;
980 const char* token_iter;
981 const char* iid_ptr;
982 uintptr_t slen_iid;
983 if (comma_delim) {
984 token_iter = first_token_start;
985 unsigned char ucc = *token_iter;
986 while (ucc != ',') {
987 if (ucc < 32) {
988 if (unlikely(!(xid_mode & kfXidModeFlagOneCoreTokenOk))) {
989 *read_pp = nullptr;
990 return 0;
991 }
992 goto XidRead_comma_single_core_token;
993 }
994 ucc = *(++token_iter);
995 }
996 if (xid_mode & kfXidModeFlagNeverFid) {
997 XidRead_comma_single_core_token:
998 iid_ptr = first_token_start;
999 slen_iid = token_iter - first_token_start;
1000 } else {
1001 slen_fid = token_iter - first_token_start;
1002 do {
1003 ucc = *(++token_iter);
1004 } while ((ucc == ' ') || (ucc == '\t'));
1005 iid_ptr = token_iter;
1006 while ((ucc >= 32) && (ucc != ',')) {
1007 ucc = *(++token_iter);
1008 }
1009 slen_iid = token_iter - iid_ptr;
1010 }
1011 // token_iter now points to comma/eoln at end of IID
1012 if (xid_mode & (kfXidModeFlagSid | kfXidModeFlagSkipSid)) {
1013 if (*token_iter != ',') {
1014 *read_pp = nullptr;
1015 return 0;
1016 }
1017 do {
1018 ucc = *(++token_iter);
1019 } while ((ucc == ' ') || (ucc == '\t'));
1020 sid_ptr = token_iter;
1021 while ((ucc >= 32) && (ucc != ',')) {
1022 ucc = *(++token_iter);
1023 }
1024 if (xid_mode & kfXidModeFlagSid) {
1025 blen_sid = 1 + S_CAST(uintptr_t, token_iter - sid_ptr);
1026 if (token_iter == sid_ptr) {
1027 // special case: treat missing SID as '0'
1028 blen_sid = 2;
1029 sid_ptr = &(g_one_char_strs[96]);
1030 }
1031 }
1032 }
1033 } else {
1034 assert(!IsEolnKns(*first_token_start));
1035 token_iter = CurTokenEnd(first_token_start);
1036 if (xid_mode & kfXidModeFlagNeverFid) {
1037 XidRead_space_single_core_token:
1038 iid_ptr = first_token_start;
1039 slen_iid = token_iter - first_token_start;
1040 } else {
1041 slen_fid = token_iter - first_token_start;
1042 token_iter = FirstNonTspace(token_iter);
1043 if (IsEolnKns(*token_iter)) {
1044 if (unlikely(!(xid_mode & kfXidModeFlagOneCoreTokenOk))) {
1045 *read_pp = nullptr;
1046 return 0;
1047 }
1048 // need to backtrack
1049 token_iter = &(first_token_start[slen_fid]);
1050 // bugfix (26 Feb 2018): forgot to zero this
1051 slen_fid = 0;
1052 goto XidRead_space_single_core_token;
1053 }
1054 iid_ptr = token_iter;
1055 token_iter = CurTokenEnd(token_iter);
1056 slen_iid = token_iter - iid_ptr;
1057 }
1058 // token_iter now points to space/eoln at end of IID
1059 if (xid_mode & (kfXidModeFlagSid | kfXidModeFlagSkipSid)) {
1060 token_iter = FirstNonTspace(token_iter);
1061 if (unlikely(IsEolnKns(*token_iter))) {
1062 *read_pp = nullptr;
1063 return 0;
1064 }
1065 sid_ptr = token_iter;
1066 token_iter = CurTokenEnd(token_iter);
1067 if (xid_mode & kfXidModeFlagSid) {
1068 blen_sid = 1 + S_CAST(uintptr_t, token_iter - sid_ptr);
1069 }
1070 }
1071 }
1072 *read_pp = token_iter;
1073 const uintptr_t slen_final = slen_fid + (slen_fid == 0) + slen_iid + blen_sid + 1;
1074 if (slen_final >= max_xid_blen) {
1075 // avoid buffer overflow
1076 return 0;
1077 }
1078 char* idbuf_iter = idbuf;
1079 if (slen_fid) {
1080 idbuf_iter = memcpya(idbuf, first_token_start, slen_fid);
1081 } else {
1082 *idbuf_iter++ = '0';
1083 }
1084 *idbuf_iter++ = '\t';
1085 idbuf_iter = memcpya(idbuf_iter, iid_ptr, slen_iid);
1086 if (blen_sid) {
1087 *idbuf_iter++ = '\t';
1088 memcpy(idbuf_iter, sid_ptr, blen_sid - 1);
1089 }
1090 return slen_final;
1091 }
1092
1093 BoolErr SortedXidboxReadMultifind(const char* __restrict sorted_xidbox, uintptr_t max_xid_blen, uintptr_t xid_ct, uint32_t comma_delim, XidMode xid_mode, const char** read_pp, uint32_t* __restrict xid_idx_start_ptr, uint32_t* __restrict xid_idx_end_ptr, char* __restrict idbuf) {
1094 // sorted_xidbox = packed, sorted list of ID strings to search over.
1095 const uint32_t slen_final = XidRead(max_xid_blen, comma_delim, xid_mode, read_pp, idbuf);
1096 if (!slen_final) {
1097 return 1;
1098 }
1099 const uint32_t lb_idx = bsearch_strbox_lb(idbuf, sorted_xidbox, slen_final, max_xid_blen, xid_ct);
1100 idbuf[slen_final] = ' ';
1101 const uint32_t ub_idx = ExpsearchStrLb(idbuf, sorted_xidbox, slen_final + 1, max_xid_blen, xid_ct, lb_idx);
1102 if (lb_idx == ub_idx) {
1103 return 1;
1104 }
1105 *xid_idx_start_ptr = lb_idx;
1106 *xid_idx_end_ptr = ub_idx;
1107 return 0;
1108 }
1109
1110 PglErr LoadXidHeader(const char* flag_name, XidHeaderFlags xid_header_flags, uintptr_t* line_idx_ptr, TextStream* txsp, XidMode* xid_mode_ptr, char** line_startp) {
1111 // possible todo: support comma delimiter
1112 uintptr_t line_idx = *line_idx_ptr;
1113 char* line_iter;
1114 uint32_t is_header_line;
1115 do {
1116 ++line_idx;
1117 line_iter = TextGet(txsp);
1118 // eof may be ok
1119 if (!line_iter) {
1120 return TextStreamRawErrcode(txsp);
1121 }
1122 is_header_line = (line_iter[0] == '#');
1123 } while (is_header_line && (!tokequal_k(&(line_iter[1]), "FID")) && (!tokequal_k(&(line_iter[1]), "IID")));
1124 if (line_startp) {
1125 *line_startp = line_iter;
1126 }
1127 XidMode xid_mode = kfXidMode0;
1128 if (is_header_line) {
1129 // The following header leading columns are supported:
1130 // #FID IID
1131 // #FID IID SID (SID ignored if kfXidHeaderIgnoreSid set)
1132 // #IID
1133 // #IID SID
1134 char* linebuf_iter = &(line_iter[4]);
1135 if (line_iter[1] == 'I') {
1136 xid_mode = kfXidModeFlagNeverFid;
1137 } else {
1138 linebuf_iter = FirstNonTspace(linebuf_iter);
1139 if (unlikely(!tokequal_k(linebuf_iter, "IID"))) {
1140 logerrprintf("Error: No IID column on line %" PRIuPTR " of --%s file.\n", line_idx, flag_name);
1141 return kPglRetMalformedInput;
1142 }
1143 linebuf_iter = &(linebuf_iter[3]);
1144 }
1145 linebuf_iter = FirstNonTspace(linebuf_iter);
1146 if (tokequal_k(linebuf_iter, "SID")) {
1147 if (!(xid_header_flags & kfXidHeaderIgnoreSid)) {
1148 xid_mode |= kfXidModeFlagSid;
1149 } else {
1150 xid_mode |= kfXidModeFlagSkipSid;
1151 }
1152 linebuf_iter = FirstNonTspace(&(linebuf_iter[3]));
1153 }
1154 if ((xid_mode & kfXidModeCoreMask) == kfXidModeFlagNeverFid) {
1155 xid_mode |= kfXidModeFlagOneCoreTokenOk;
1156 }
1157 line_iter = linebuf_iter;
1158 } else {
1159 xid_mode = (xid_header_flags & kfXidHeaderFixedWidth)? kfXidModeFidIid : kfXidModeFidIidOrIid;
1160 }
1161 *line_idx_ptr = line_idx;
1162 *xid_mode_ptr = xid_mode;
1163 return kPglRetSuccess;
1164 }
1165
1166 PglErr OpenAndLoadXidHeader(const char* fname, const char* flag_name, XidHeaderFlags xid_header_flags, uint32_t max_line_blen, TextStream* txsp, XidMode* xid_mode_ptr, uintptr_t* line_idx_ptr, char** line_startp) {
1167 PglErr reterr = InitTextStream(fname, max_line_blen, 1, txsp);
1168 // remove unlikely() if any caller treats eof as ok
1169 if (unlikely(reterr)) {
1170 return reterr;
1171 }
1172 *line_idx_ptr = 0;
1173 return LoadXidHeader(flag_name, xid_header_flags, line_idx_ptr, txsp, xid_mode_ptr, line_startp);
1174 }
1175
1176 PglErr LoadXidHeaderPair(const char* flag_name, uint32_t sid_over_fid, uintptr_t* line_idx_ptr, TextStream* txsp, XidMode* xid_mode_ptr, char** line_startp, char** line_iterp) {
1177 uintptr_t line_idx = *line_idx_ptr;
1178 char* line_iter;
1179 uint32_t is_header_line;
1180 do {
1181 ++line_idx;
1182 line_iter = TextGet(txsp);
1183 // eof may be ok
1184 if (!line_iter) {
1185 return TextStreamRawErrcode(txsp);
1186 }
1187 is_header_line = (line_iter[0] == '#');
1188 } while (is_header_line && (!tokequal_k(&(line_iter[1]), "FID1")) && (!tokequal_k(&(line_iter[1]), "ID1")) && (!tokequal_k(&(line_iter[1]), "IID1")));
1189 if (line_startp) {
1190 *line_startp = line_iter;
1191 }
1192 XidMode xid_mode = kfXidMode0;
1193 if (is_header_line) {
1194 // The following header leading columns are supported:
1195 // #FID1 {I}ID1 FID2 {I}ID2
1196 // #FID1 {I}ID1 SID1 FID2 {I}ID2 SID2
1197 // #{I}ID1 {I}ID2
1198 // #{I}ID1 SID1 {I}ID2 SID2
1199 char* linebuf_iter = &(line_iter[4]);
1200 if (line_iter[1] == 'I') {
1201 xid_mode = kfXidModeFlagNeverFid;
1202 } else {
1203 linebuf_iter = FirstNonTspace(linebuf_iter);
1204 if (tokequal_k(linebuf_iter, "ID1")) {
1205 linebuf_iter = &(linebuf_iter[3]);
1206 } else if (likely(tokequal_k(linebuf_iter, "IID1"))) {
1207 linebuf_iter = &(linebuf_iter[4]);
1208 } else {
1209 logerrprintf("Error: No [I]ID1 column on line %" PRIuPTR " of --%s file.\n", line_idx, flag_name);
1210 return kPglRetMalformedInput;
1211 }
1212 }
1213 linebuf_iter = FirstNonTspace(linebuf_iter);
1214 if (tokequal_k(linebuf_iter, "SID1")) {
1215 xid_mode |= kfXidModeFlagSid;
1216 linebuf_iter = FirstNonTspace(&(linebuf_iter[4]));
1217 }
1218 // Now verify the expected ID2 token sequence follows.
1219 if (!(xid_mode & kfXidModeFlagNeverFid)) {
1220 if (unlikely(!tokequal_k(linebuf_iter, "FID2"))) {
1221 logerrprintf("Error: No FID2 column on line %" PRIuPTR " of --%s file.\n", line_idx, flag_name);
1222 return kPglRetMalformedInput;
1223 }
1224 linebuf_iter = FirstNonTspace(&(linebuf_iter[4]));
1225 }
1226 if (tokequal_k(linebuf_iter, "ID2")) {
1227 linebuf_iter = &(linebuf_iter[3]);
1228 } else if (likely(tokequal_k(linebuf_iter, "IID2"))) {
1229 linebuf_iter = &(linebuf_iter[4]);
1230 } else {
1231 logerrprintf("Error: No [I]ID2 column on line %" PRIuPTR " of --%s file.\n", line_idx, flag_name);
1232 return kPglRetMalformedInput;
1233 }
1234 if (xid_mode & kfXidModeFlagSid) {
1235 linebuf_iter = FirstNonTspace(linebuf_iter);
1236 if (unlikely(!tokequal_k(linebuf_iter, "SID2"))) {
1237 logerrprintf("Error: No SID2 column on line %" PRIuPTR " of --%s file.\n", line_idx, flag_name);
1238 return kPglRetMalformedInput;
1239 }
1240 linebuf_iter = &(linebuf_iter[4]);
1241 }
1242 line_iter = linebuf_iter;
1243 } else {
1244 // Assume the file contains nothing but ID pairs.
1245 const uint32_t token_ct = CountTokens(line_iter);
1246 if (token_ct == 2) {
1247 xid_mode = kfXidModeIid;
1248 } else if (token_ct == 4) {
1249 xid_mode = sid_over_fid? kfXidModeIidSid : kfXidModeFidIid;
1250 } else if (likely(token_ct == 6)) {
1251 xid_mode = kfXidModeFidIidSid;
1252 } else {
1253 logerrprintf("Error: Unexpected token count on line %" PRIuPTR " of --%s file.\n", line_idx, flag_name);
1254 return kPglRetMalformedInput;
1255 }
1256 }
1257 if (line_iter) {
1258 *line_iterp = line_iter;
1259 }
1260 *line_idx_ptr = line_idx;
1261 *xid_mode_ptr = xid_mode;
1262 return kPglRetSuccess;
1263 }
1264
1265 // Assumes no duplicates.
1266 void InitXidHtable(const SampleIdInfo* siip, uint32_t sample_ct, uint32_t xid_htable_size, uint32_t* xid_htable, char* idbuf) {
1267 SetAllU32Arr(xid_htable_size, xid_htable);
1268 const char* sample_ids_iter = siip->sample_ids;
1269 const char* sids_iter = siip->sids;
1270 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
1271 const uintptr_t max_sid_blen = siip->max_sid_blen;
1272 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1273 uint32_t slen = strlen(sample_ids_iter);
1274 const char* cur_sample_id;
1275 if (!sids_iter) {
1276 cur_sample_id = sample_ids_iter;
1277 } else {
1278 char* id_iter = memcpyax(idbuf, sample_ids_iter, slen, '\t');
1279 const uint32_t sid_blen = 1 + strlen(sids_iter);
1280 memcpy(id_iter, sids_iter, sid_blen);
1281 slen += sid_blen;
1282 sids_iter = &(sids_iter[max_sid_blen]);
1283 cur_sample_id = idbuf;
1284 }
1285 HtableAddNondup(cur_sample_id, slen, xid_htable_size, sample_idx, xid_htable);
1286 sample_ids_iter = &(sample_ids_iter[max_sample_id_blen]);
1287 }
1288 }
1289
1290 BoolErr LookupXidHtable(const char* line_start, const SampleIdInfo* siip, const uint32_t* xid_htable, uint32_t xid_htable_size, uint32_t fid_present, uint32_t sid_present, uint32_t* sample_idxp, char* idbuf) {
1291 const char* read_iid_start = line_start;
1292 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
1293 char* write_id_iter = idbuf;
1294 if (fid_present) {
1295 const char* fid_end = CurTokenEnd(line_start);
1296 const uint32_t fid_slen = fid_end - line_start;
1297 // check this before copying, to prevent idbuf overflow
1298 if (fid_slen + 2 >= max_sample_id_blen) {
1299 *sample_idxp = UINT32_MAX;
1300 return 0;
1301 }
1302 write_id_iter = memcpya(write_id_iter, line_start, fid_slen);
1303 read_iid_start = FirstNonTspace(fid_end);
1304 if (unlikely(IsEolnKns(*read_iid_start))) {
1305 return 1;
1306 }
1307 } else {
1308 *write_id_iter++ = '0';
1309 }
1310 *write_id_iter++ = '\t';
1311 const char* read_iid_end = CurTokenEnd(read_iid_start);
1312 const uint32_t iid_slen = read_iid_end - read_iid_start;
1313 const uint32_t fid_iid_slen = iid_slen + S_CAST(uintptr_t, write_id_iter - idbuf);
1314 if (fid_iid_slen >= max_sample_id_blen) {
1315 *sample_idxp = UINT32_MAX;
1316 return 0;
1317 }
1318 write_id_iter = memcpya(write_id_iter, read_iid_start, iid_slen);
1319
1320 const char* sample_ids = siip->sample_ids;
1321 const char* sids = siip->sids;
1322 if (!sids) {
1323 *write_id_iter = '\0';
1324 *sample_idxp = StrboxHtableFind(idbuf, sample_ids, xid_htable, max_sample_id_blen, fid_iid_slen, xid_htable_size);
1325 return 0;
1326 }
1327
1328 *write_id_iter++ = '\t';
1329 char* write_sid_start = write_id_iter;
1330 uint32_t sid_slen = 1;
1331 const uintptr_t max_sid_blen = siip->max_sid_blen;
1332 if (sid_present) {
1333 const char* read_sid_start = FirstNonTspace(read_iid_end);
1334 if (unlikely(IsEolnKns(*read_sid_start))) {
1335 return 1;
1336 }
1337 const char* read_sid_end = CurTokenEnd(read_sid_start);
1338 sid_slen = read_sid_end - read_sid_start;
1339 if (sid_slen >= max_sid_blen) {
1340 *sample_idxp = UINT32_MAX;
1341 return 0;
1342 }
1343 write_id_iter = memcpya(write_id_iter, read_sid_start, sid_slen);
1344 } else {
1345 *write_id_iter++ = '0';
1346 }
1347 *write_id_iter = '\0';
1348 const uint32_t fid_iid_blen = fid_iid_slen + 1;
1349 const uint32_t sid_blen = sid_slen + 1;
1350 uint32_t hashval = Hashceil(idbuf, fid_iid_slen + sid_blen, xid_htable_size);
1351 write_sid_start[-1] = '\0';
1352 while (1) {
1353 const uint32_t sample_idx = xid_htable[hashval];
1354 if ((sample_idx == UINT32_MAX) ||
1355 (memequal(idbuf, &(sample_ids[sample_idx * max_sample_id_blen]), fid_iid_blen) &&
1356 memequal(write_sid_start, &(sids[sample_idx * max_sid_blen]), sid_blen))) {
1357 *sample_idxp = sample_idx;
1358 return 0;
1359 }
1360 if (++hashval == xid_htable_size) {
1361 hashval = 0;
1362 }
1363 }
1364 }
1365
1366 PglErr CheckXidUniqueness(const uintptr_t* sample_include, const SampleIdInfo* siip, const char* err_suffix_str, uint32_t sample_ct) {
1367 // PopulateStrboxHtable() isn't sufficient for this when SIDs are present.
1368 unsigned char* bigstack_mark = g_bigstack_base;
1369 PglErr reterr = kPglRetSuccess;
1370 {
1371 const uint32_t xid_htable_size = GetHtableFastSize(sample_ct);
1372 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
1373 const uintptr_t max_sid_blen = siip->max_sid_blen;
1374 uint32_t* xid_htable;
1375 char* idbuf;
1376 if (unlikely(bigstack_alloc_u32(xid_htable_size, &xid_htable) ||
1377 bigstack_alloc_c(max_sample_id_blen + max_sid_blen, &idbuf))) {
1378 goto CheckXidUniqueness_ret_NOMEM;
1379 }
1380 // Lots of overlap with InitXidHtable().
1381 SetAllU32Arr(xid_htable_size, xid_htable);
1382 const char* sample_ids = siip->sample_ids;
1383 const char* sids = siip->sids;
1384 uintptr_t sample_uidx_base = 0;
1385 uintptr_t cur_bits = sample_include[0];
1386 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1387 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
1388 const char* cur_sample_id = &(sample_ids[sample_uidx * max_sample_id_blen]);
1389 const uint32_t sample_id_slen = strlen(cur_sample_id);
1390 uint32_t xid_slen = sample_id_slen;
1391 const char* cur_xid;
1392 if (!sids) {
1393 cur_xid = cur_sample_id;
1394 } else {
1395 char* id_iter = memcpyax(idbuf, cur_sample_id, sample_id_slen, '\t');
1396 const char* cur_sid = &(sids[sample_uidx * max_sample_id_blen]);
1397 const uint32_t sid_blen = 1 + strlen(cur_sid);
1398 memcpy(id_iter, cur_sid, sid_blen);
1399 xid_slen += sid_blen;
1400 cur_xid = idbuf;
1401 }
1402 for (uint32_t hashval = Hashceil(cur_xid, xid_slen, xid_htable_size); ; ) {
1403 const uint32_t cur_htable_entry = xid_htable[hashval];
1404 if (cur_htable_entry == UINT32_MAX) {
1405 xid_htable[hashval] = sample_uidx;
1406 break;
1407 }
1408 if (memequal(cur_sample_id, &(sample_ids[cur_htable_entry * max_sample_id_blen]), sample_id_slen + 1)) {
1409 if ((!sids) || memequal(&(cur_xid[sample_id_slen + 1]), &(sids[cur_htable_entry * max_sid_blen]), xid_slen - sample_id_slen)) {
1410 char* write_iter = strcpya_k(g_logbuf, "Error: Duplicate sample ID \"");
1411 const char* fid_end = AdvToDelim(cur_sample_id, '\t');
1412 const char* iid_start = &(fid_end[1]);
1413 write_iter = memcpyax(write_iter, cur_sample_id, fid_end - cur_sample_id, ' ');
1414 write_iter = strcpya(write_iter, iid_start);
1415 if (sids) {
1416 *write_iter++ = ' ';
1417 write_iter = memcpya(write_iter, &(cur_xid[sample_id_slen + 1]), xid_slen - sample_id_slen - 1);
1418 }
1419 *write_iter++ = '"';
1420 if (err_suffix_str) {
1421 write_iter = strcpya(write_iter, err_suffix_str);
1422 }
1423 strcpy_k(write_iter, ".\n");
1424 WordWrapB(0);
1425 logerrputsb();
1426 goto CheckXidUniqueness_ret_MALFORMED_INPUT;
1427 }
1428 }
1429 if (++hashval == xid_htable_size) {
1430 hashval = 0;
1431 }
1432 }
1433 }
1434 }
1435 while (0) {
1436 CheckXidUniqueness_ret_NOMEM:
1437 reterr = kPglRetNomem;
1438 break;
1439 CheckXidUniqueness_ret_MALFORMED_INPUT:
1440 reterr = kPglRetMalformedInput;
1441 break;
1442 }
1443 BigstackReset(bigstack_mark);
1444 return reterr;
1445 }
1446
1447 PglErr LoadSampleIds(const char* fnames, const uintptr_t* sample_include, const SampleIdInfo* siip, const char* flag_name, uint32_t raw_sample_ct, uint32_t sample_ct, LoadSampleIdsFlags flags, uintptr_t** loaded_bitarrp, uint32_t* duplicate_ctp) {
1448 unsigned char* bigstack_mark = g_bigstack_base;
1449 PglErr reterr = kPglRetSuccess;
1450 const char* fname_iter = fnames;
1451 const char* fname_txs = nullptr;
1452 TextStream txs;
1453 PreinitTextStream(&txs);
1454 uintptr_t line_idx;
1455 {
1456 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
1457 uintptr_t* loaded_bitarr;
1458 if (unlikely(bigstack_calloc_w(raw_sample_ctl, &loaded_bitarr))) {
1459 goto LoadSampleIds_ret_NOMEM;
1460 }
1461 unsigned char* bigstack_mark2 = g_bigstack_base;
1462
1463 const uint32_t families_only = flags & kfLoadSampleIdsFamOnly;
1464 const char* sample_ids = siip->sample_ids;
1465 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
1466 char* idbuf = nullptr;
1467 uint32_t* xid_map = nullptr;
1468 char* sorted_xidbox = nullptr;
1469 uintptr_t max_xid_blen = max_sample_id_blen - 1;
1470 if (families_only) {
1471 // only need to do this once
1472 if (unlikely(bigstack_alloc_u32(sample_ct, &xid_map) ||
1473 bigstack_alloc_c(sample_ct * max_xid_blen, &sorted_xidbox))) {
1474 goto LoadSampleIds_ret_NOMEM;
1475 }
1476 uintptr_t sample_uidx_base = 0;
1477 uintptr_t cur_bits = sample_include[0];
1478 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1479 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
1480 const char* fidt_ptr = &(sample_ids[sample_uidx * max_sample_id_blen]);
1481 const char* fidt_end = AdvPastDelim(fidt_ptr, '\t');
1482 const uint32_t cur_fidt_slen = fidt_end - fidt_ptr;
1483 // include trailing tab, to simplify bsearch_strbox_lb() usage
1484 memcpyx(&(sorted_xidbox[sample_idx * max_xid_blen]), fidt_ptr, cur_fidt_slen, '\0');
1485 xid_map[sample_idx] = sample_uidx;
1486 }
1487 if (unlikely(SortStrboxIndexed(sample_ct, max_xid_blen, 0, sorted_xidbox, xid_map))) {
1488 goto LoadSampleIds_ret_NOMEM;
1489 }
1490 }
1491
1492 unsigned char* bigstack_mark3 = nullptr;
1493 const char* fnames_iter = fnames;
1494 uintptr_t duplicate_ct = 0;
1495 do {
1496 if (!bigstack_mark3) {
1497 fname_txs = fnames_iter;
1498 reterr = SizeAndInitTextStream(fnames_iter, bigstack_left() - (bigstack_left() / 4), 1, &txs);
1499 if (unlikely(reterr)) {
1500 goto LoadSampleIds_ret_TSTREAM_FAIL;
1501 }
1502 bigstack_mark3 = g_bigstack_base;
1503 } else {
1504 reterr = TextRetarget(fnames_iter, &txs);
1505 if (unlikely(reterr)) {
1506 goto LoadSampleIds_ret_TSTREAM_FAIL;
1507 }
1508 fname_txs = fnames_iter;
1509 }
1510 char* line_start;
1511 XidMode xid_mode;
1512 line_idx = 0;
1513 uint32_t skip_header = 0;
1514 if (families_only) {
1515 skip_header = 1;
1516 } else {
1517 reterr = LoadXidHeader(flag_name, (siip->sids || (siip->flags & kfSampleIdStrictSid0))? kfXidHeader0 : kfXidHeaderIgnoreSid, &line_idx, &txs, &xid_mode, &line_start);
1518 if (reterr) {
1519 if (likely(reterr == kPglRetEof)) {
1520 reterr = kPglRetSuccess;
1521 goto LoadSampleIds_empty_file;
1522 }
1523 goto LoadSampleIds_ret_TSTREAM_XID_FAIL;
1524 }
1525 reterr = SortedXidboxInitAlloc(sample_include, siip, sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen);
1526 if (unlikely(reterr)) {
1527 goto LoadSampleIds_ret_1;
1528 }
1529 if (unlikely(bigstack_alloc_c(max_xid_blen, &idbuf))) {
1530 goto LoadSampleIds_ret_NOMEM;
1531 }
1532 if (*line_start == '#') {
1533 skip_header = 1;
1534 }
1535 }
1536 if (skip_header) {
1537 ++line_idx;
1538 line_start = TextGet(&txs);
1539 }
1540 for (; line_start; ++line_idx, line_start = TextGet(&txs)) {
1541 if (!families_only) {
1542 const char* linebuf_iter = line_start;
1543 uint32_t xid_idx_start;
1544 uint32_t xid_idx_end;
1545 if (!SortedXidboxReadMultifind(sorted_xidbox, max_xid_blen, sample_ct, 0, xid_mode, &linebuf_iter, &xid_idx_start, &xid_idx_end, idbuf)) {
1546 uint32_t sample_uidx = xid_map[xid_idx_start];
1547 if (IsSet(loaded_bitarr, sample_uidx)) {
1548 ++duplicate_ct;
1549 } else {
1550 for (uint32_t xid_idx = xid_idx_start; ; ) {
1551 SetBit(sample_uidx, loaded_bitarr);
1552 if (++xid_idx == xid_idx_end) {
1553 break;
1554 }
1555 sample_uidx = xid_map[xid_idx];
1556 }
1557 }
1558 } else if (unlikely(!linebuf_iter)) {
1559 goto LoadSampleIds_ret_MISSING_TOKENS;
1560 }
1561 } else {
1562 char* token_end = CurTokenEnd(line_start);
1563 // bugfix (28 Oct 2018): \n was being clobbered and not replaced
1564 // const char orig_token_end_char = *token_end;
1565 *token_end = '\t';
1566 const uint32_t slen = 1 + S_CAST(uintptr_t, token_end - line_start);
1567 uint32_t lb_idx = bsearch_strbox_lb(line_start, sorted_xidbox, slen, max_xid_blen, sample_ct);
1568 *token_end = ' ';
1569 const uint32_t ub_idx = bsearch_strbox_lb(line_start, sorted_xidbox, slen, max_xid_blen, sample_ct);
1570 if (ub_idx != lb_idx) {
1571 uint32_t sample_uidx = xid_map[lb_idx];
1572 if (IsSet(loaded_bitarr, sample_uidx)) {
1573 ++duplicate_ct;
1574 } else {
1575 for (uint32_t xid_map_idx = lb_idx; ; ) {
1576 SetBit(sample_uidx, loaded_bitarr);
1577 if (++xid_map_idx == ub_idx) {
1578 break;
1579 }
1580 sample_uidx = xid_map[xid_map_idx];
1581 }
1582 }
1583 }
1584 // *token_end = orig_token_end_char;
1585 }
1586 }
1587 if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
1588 goto LoadSampleIds_ret_TSTREAM_FAIL;
1589 }
1590 LoadSampleIds_empty_file:
1591 if (!(flags & kfLoadSampleIdsMultifile)) {
1592 break;
1593 }
1594 BigstackReset(bigstack_mark3);
1595 fnames_iter = strnul(fnames_iter);
1596 ++fnames_iter;
1597 } while (*fnames_iter);
1598 reterr = kPglRetSuccess;
1599 *loaded_bitarrp = loaded_bitarr;
1600 if (duplicate_ctp) {
1601 *duplicate_ctp = duplicate_ct;
1602 }
1603 bigstack_mark = bigstack_mark2;
1604 }
1605 while (0) {
1606 LoadSampleIds_ret_NOMEM:
1607 reterr = kPglRetNomem;
1608 break;
1609 LoadSampleIds_ret_TSTREAM_XID_FAIL:
1610 if (!TextStreamErrcode(&txs)) {
1611 break;
1612 }
1613 LoadSampleIds_ret_TSTREAM_FAIL:
1614 TextStreamErrPrint(fname_txs, &txs);
1615 break;
1616 LoadSampleIds_ret_MISSING_TOKENS:
1617 logerrprintf("Error: --%s: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", flag_name, line_idx, fname_iter);
1618 reterr = kPglRetMalformedInput;
1619 break;
1620 }
1621 LoadSampleIds_ret_1:
1622 if (fname_txs) {
1623 CleanupTextStream2(fname_txs, &txs, &reterr);
1624 }
1625 BigstackReset(bigstack_mark);
1626 return reterr;
1627 }
1628
1629 char* AppendSpacedXid(const char* sample_ids, const char* sids, uint32_t write_fid, uint32_t write_sid, uintptr_t max_sample_id_blen, uintptr_t max_sid_blen, uintptr_t sample_uidx, char* write_iter) {
1630 const char* fid = &(sample_ids[max_sample_id_blen * sample_uidx]);
1631 const char* fid_end = AdvToDelim(fid, '\t');
1632 if (write_fid) {
1633 write_iter = memcpyax(write_iter, fid, fid_end - fid, ' ');
1634 }
1635 const char* iid = &(fid_end[1]);
1636 write_iter = strcpya(write_iter, iid);
1637 if (write_sid) {
1638 *write_iter++ = ' ';
1639 if (sids) {
1640 write_iter = strcpya(write_iter, &(sids[max_sid_blen * sample_uidx]));
1641 } else {
1642 *write_iter++ = '0';
1643 }
1644 }
1645 return write_iter;
1646 }
1647
1648 // accept 'M'/'F'/'m'/'f' since that's more readable without being any less
1649 // efficient
1650 const unsigned char g_char_to_sex[256] =
1651 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1652 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1653 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1654 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1655 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0,
1656 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1657 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0,
1658 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1659 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1660 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1661 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1662 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1663 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1664 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1665 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1666 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1667
1668 const char g_xymt_log_names[kChrOffsetCt][5] = {"chrX", "chrY", "XY", "chrM", "PAR1", "PAR2"};
1669
1670 static_assert(!(kChrRawEnd % kBytesPerVec), "kChrRawEnd must be a multiple of kBytesPerVec.");
1671 PglErr InitChrInfo(ChrInfo* cip) {
1672 // "constructor". initializes with maximum capacity. doesn't use bigstack.
1673 // chr_mask, haploid_mask: bits
1674 // chr_file_order, chr_idx_to_foidx: uint32s
1675 // chr_fo_vidx_start: uint32s, with an extra trailing element
1676 // nonstd_names: intptr_ts
1677 // nonstd_id_htable: kChrHtableSize uint32s
1678
1679 // this assumes kChrRawEnd is divisible by kBytesPerVec
1680 const uintptr_t vecs_required = 2 * BitCtToVecCt(kChrRawEnd) + 3 * (kChrRawEnd / kInt32PerVec) + 1 + (kChrRawEnd / kWordsPerVec) + Int32CtToVecCt(kChrHtableSize);
1681
1682 // needed for proper cleanup
1683 cip->name_ct = 0;
1684 cip->incl_excl_name_stack = nullptr;
1685 if (unlikely(vecaligned_malloc(vecs_required * kBytesPerVec, &(cip->chr_mask)))) {
1686 return kPglRetNomem;
1687 }
1688 uintptr_t* alloc_iter = &(cip->chr_mask[BitCtToVecCt(kChrRawEnd) * kWordsPerVec]);
1689 cip->haploid_mask = alloc_iter;
1690 alloc_iter = &(alloc_iter[BitCtToVecCt(kChrRawEnd) * kWordsPerVec]);
1691 cip->chr_file_order = R_CAST(uint32_t*, alloc_iter);
1692 alloc_iter = &(alloc_iter[(kChrRawEnd / kInt32PerVec) * kWordsPerVec]);
1693 cip->chr_fo_vidx_start = R_CAST(uint32_t*, alloc_iter);
1694 alloc_iter = &(alloc_iter[((kChrRawEnd / kInt32PerVec) + 1) * kWordsPerVec]);
1695 cip->chr_idx_to_foidx = R_CAST(uint32_t*, alloc_iter);
1696 alloc_iter = &(alloc_iter[(kChrRawEnd / kInt32PerVec) * kWordsPerVec]);
1697 cip->nonstd_names = R_CAST(const char**, alloc_iter);
1698 alloc_iter = &(alloc_iter[kChrRawEnd]);
1699 cip->nonstd_id_htable = R_CAST(uint32_t*, alloc_iter);
1700 // alloc_iter = &(alloc_iter[((kChrHtableSize + (kInt32PerVec - 1)) / kInt32PerVec) * kWordsPerVec]);
1701 // SetAllU32Arr(kChrHtableSize, cip->nonstd_id_htable);
1702
1703 ZeroWArr(kChrMaskWords, cip->chr_mask);
1704 ZeroWArr(kChrExcludeWords, cip->chr_exclude);
1705
1706 // This is a change from plink 1.x. MT > M since the former matches Ensembl,
1707 // while the latter doesn't match any major resource. no "chr" to reduce
1708 // file sizes and reduce the impact of this change.
1709 cip->output_encoding = kfChrOutputMT;
1710
1711 cip->zero_extra_chrs = 0;
1712 cip->is_include_stack = 0;
1713 cip->chrset_source = kChrsetSourceDefault;
1714 cip->autosome_ct = 22;
1715 for (uint32_t xymt_idx = 0; xymt_idx != kChrOffsetCt; ++xymt_idx) {
1716 cip->xymt_codes[xymt_idx] = 23 + xymt_idx;
1717 }
1718 // Now includes MT again, as of alpha 2.
1719 cip->haploid_mask[0] = 0x5800000;
1720 ZeroWArr(kChrMaskWords - 1, &(cip->haploid_mask[1]));
1721 return kPglRetSuccess;
1722 }
1723
1724 // explicit plink 1.07 species (now initialized by command line parser):
1725 // human: 22, X, Y, XY, MT, PAR1, PAR2 (PAR1/PAR2 added, XY deprecated in plink
1726 // 2.0)
1727 // cow: 29, X, Y, MT
1728 // dog: 38, X, Y, XY, MT, PAR1, PAR2 (updated 11 Aug 2023)
1729 // horse: 31, X, Y
1730 // mouse: 19, X, Y
1731 // rice: 12
1732 // sheep: 26, X, Y
1733
1734 // must be safe to call this twice.
1735 void FinalizeChrset(MiscFlags misc_flags, ChrInfo* cip) {
1736 uint32_t autosome_ct = cip->autosome_ct;
1737 uint32_t max_code = autosome_ct;
1738 for (uint32_t xymt_idx_p1 = kChrOffsetCt; xymt_idx_p1; --xymt_idx_p1) {
1739 if (!IsI32Neg(cip->xymt_codes[xymt_idx_p1 - 1])) {
1740 max_code = autosome_ct + xymt_idx_p1;
1741 break;
1742 }
1743 }
1744
1745 // could initialize haploid_mask bits (after the first) here, instead of
1746 // earlier...
1747
1748 cip->max_numeric_code = MINV(max_code, autosome_ct + 4);
1749 cip->max_code = max_code;
1750 uintptr_t* chr_mask = cip->chr_mask;
1751 uintptr_t last_chr_mask_word = chr_mask[kChrMaskWords - 1];
1752 STD_ARRAY_REF(uint32_t, kChrOffsetCt) xymt_codes = cip->xymt_codes;
1753 if (last_chr_mask_word) {
1754 // avoids repeating some work if this is called twice
1755 chr_mask[kChrMaskWords - 1] = 0;
1756
1757 uint32_t xymt_include = last_chr_mask_word >> (kBitsPerWord - kChrOffsetCt);
1758 do {
1759 const uint32_t xymt_idx = ctzu32(xymt_include);
1760 const uint32_t cur_chr_code = xymt_codes[xymt_idx];
1761 if (!IsI32Neg(cur_chr_code)) {
1762 SetBit(cur_chr_code, chr_mask);
1763 }
1764 xymt_include &= xymt_include - 1;
1765 } while (xymt_include);
1766 } else if (AllWordsAreZero(chr_mask, kChrExcludeWords) && (!cip->is_include_stack)) {
1767 // init_default_chr_mask()
1768 SetAllBits(cip->autosome_ct + 1, chr_mask);
1769 for (uint32_t xymt_idx = 0; xymt_idx != kChrOffsetCt; ++xymt_idx) {
1770 const uint32_t cur_chr_code = cip->xymt_codes[xymt_idx];
1771 if (!IsI32Neg(cur_chr_code)) {
1772 SetBit(cur_chr_code, chr_mask);
1773 }
1774 }
1775 } else if (misc_flags & (kfMiscAutosomePar | kfMiscAutosomeOnly)) {
1776 FillBitsNz(1, cip->autosome_ct + 1, chr_mask);
1777 ClearBitsNz(cip->autosome_ct + 1, kChrExcludeWords * kBitsPerWord, chr_mask);
1778 if (misc_flags & kfMiscAutosomePar) {
1779 uint32_t par_chr_code = cip->xymt_codes[kChrOffsetXY];
1780 if (!IsI32Neg(par_chr_code)) {
1781 SetBit(par_chr_code, chr_mask);
1782 }
1783 par_chr_code = cip->xymt_codes[kChrOffsetPAR1];
1784 if (!IsI32Neg(par_chr_code)) {
1785 SetBit(par_chr_code, chr_mask);
1786 }
1787 par_chr_code = cip->xymt_codes[kChrOffsetPAR2];
1788 if (!IsI32Neg(par_chr_code)) {
1789 SetBit(par_chr_code, chr_mask);
1790 }
1791 }
1792 }
1793
1794 uintptr_t* chr_exclude = cip->chr_exclude;
1795 uintptr_t last_chr_exclude_word = chr_exclude[kChrExcludeWords - 1];
1796 uint32_t xymt_exclude = last_chr_exclude_word >> (kBitsPerWord - kChrOffsetCt);
1797 last_chr_exclude_word = bzhi(last_chr_exclude_word, kBitsPerWord - kChrOffsetCt);
1798 for (uint32_t widx = 0; widx != kChrExcludeWords - 1; ++widx) {
1799 chr_mask[widx] &= ~chr_exclude[widx];
1800 }
1801 chr_mask[kChrExcludeWords - 1] &= ~last_chr_exclude_word;
1802 if (xymt_exclude) {
1803 do {
1804 const uint32_t xymt_idx = ctzu32(xymt_exclude);
1805 const uint32_t cur_chr_code = xymt_codes[xymt_idx];
1806 if (!IsI32Neg(cur_chr_code)) {
1807 ClearBit(cur_chr_code, chr_mask);
1808 }
1809 xymt_exclude &= xymt_exclude - 1;
1810 } while (xymt_exclude);
1811 }
1812 SetAllU32Arr(max_code + 1, cip->chr_idx_to_foidx);
1813 }
1814
1815 void ForgetExtraChrNames(uint32_t reinitialize, ChrInfo* cip) {
1816 const uint32_t name_ct = cip->name_ct;
1817 if (name_ct) {
1818 const char** nonstd_names = cip->nonstd_names;
1819 const uint32_t chr_idx_end = cip->max_code + 1 + name_ct;
1820 for (uint32_t chr_idx = cip->max_code + 1; chr_idx != chr_idx_end; ++chr_idx) {
1821 free_const(nonstd_names[chr_idx]);
1822 nonstd_names[chr_idx] = nullptr;
1823 }
1824 if (reinitialize) {
1825 // SetAllU32Arr(kChrHtableSize, cip->nonstd_id_htable);
1826 cip->name_ct = 0;
1827 }
1828 }
1829 }
1830
1831 // not currently called. might want to do so in the future.
1832 PglErr FinalizeChrInfo(ChrInfo* cip) {
1833 const uint32_t chr_ct = cip->chr_ct;
1834 const uint32_t name_ct = cip->name_ct;
1835 const uint32_t chr_code_end = cip->max_code + 1 + name_ct;
1836 const uint32_t chr_code_bitvec_ct = BitCtToVecCt(chr_code_end);
1837 const uint32_t chr_ct_int32vec_ct = Int32CtToVecCt(chr_ct);
1838 const uint32_t chr_ct_p1_int32vec_ct = 1 + (chr_ct / kInt32PerVec);
1839 const uint32_t chr_code_end_int32vec_ct = Int32CtToVecCt(chr_code_end);
1840 const uint32_t chr_code_end_wordvec_ct = WordCtToVecCt(chr_code_end);
1841 uint32_t final_vecs_required = 2 * chr_code_bitvec_ct + chr_ct_int32vec_ct + chr_ct_p1_int32vec_ct + chr_code_end_int32vec_ct;
1842 if (name_ct) {
1843 final_vecs_required += chr_code_end_wordvec_ct + Int32CtToVecCt(kChrHtableSize);
1844 }
1845 uintptr_t* new_alloc;
1846 if (unlikely(vecaligned_malloc(final_vecs_required * kBytesPerVec, &new_alloc))) {
1847 return kPglRetNomem;
1848 }
1849 uintptr_t* old_alloc = cip->chr_mask;
1850 uintptr_t* new_alloc_iter = new_alloc;
1851
1852 memcpy(new_alloc_iter, cip->chr_mask, chr_code_bitvec_ct * kBytesPerVec);
1853 cip->chr_mask = new_alloc_iter;
1854 new_alloc_iter = &(new_alloc_iter[chr_code_bitvec_ct * kWordsPerVec]);
1855
1856 memcpy(new_alloc_iter, cip->haploid_mask, chr_code_bitvec_ct * kBytesPerVec);
1857 cip->haploid_mask = new_alloc_iter;
1858 new_alloc_iter = &(new_alloc_iter[chr_code_bitvec_ct * kWordsPerVec]);
1859
1860 memcpy(new_alloc_iter, cip->chr_file_order, chr_ct_int32vec_ct * kBytesPerVec);
1861 cip->chr_file_order = R_CAST(uint32_t*, new_alloc_iter);
1862 new_alloc_iter = &(new_alloc_iter[chr_ct_int32vec_ct * kWordsPerVec]);
1863
1864 memcpy(new_alloc_iter, cip->chr_fo_vidx_start, chr_ct_p1_int32vec_ct * kBytesPerVec);
1865 cip->chr_fo_vidx_start = R_CAST(uint32_t*, new_alloc_iter);
1866 new_alloc_iter = &(new_alloc_iter[chr_ct_p1_int32vec_ct * kWordsPerVec]);
1867
1868 memcpy(new_alloc_iter, cip->chr_idx_to_foidx, chr_code_end_int32vec_ct * kBytesPerVec);
1869 cip->chr_idx_to_foidx = R_CAST(uint32_t*, new_alloc_iter);
1870
1871 if (!name_ct) {
1872 cip->nonstd_names = nullptr;
1873 cip->nonstd_id_htable = nullptr;
1874 } else {
1875 new_alloc_iter = &(new_alloc_iter[chr_code_end_int32vec_ct * kWordsPerVec]);
1876
1877 memcpy(new_alloc_iter, cip->nonstd_names, chr_code_end_wordvec_ct * kBytesPerVec);
1878 cip->nonstd_names = R_CAST(const char**, new_alloc_iter);
1879 new_alloc_iter = &(new_alloc_iter[chr_code_end_wordvec_ct * kWordsPerVec]);
1880
1881 memcpy(new_alloc_iter, cip->nonstd_id_htable, kChrHtableSize * sizeof(int32_t));
1882 cip->nonstd_id_htable = R_CAST(uint32_t*, new_alloc_iter);
1883 }
1884 vecaligned_free(old_alloc);
1885 return kPglRetSuccess;
1886 }
1887
1888 void CleanupChrInfo(ChrInfo* cip) {
1889 if (cip->chr_mask) {
1890 ForgetExtraChrNames(0, cip);
1891 vecaligned_free(cip->chr_mask);
1892 cip->chr_mask = nullptr;
1893 }
1894 LlStr* llstr_ptr = cip->incl_excl_name_stack;
1895 while (llstr_ptr) {
1896 LlStr* next_ptr = llstr_ptr->next;
1897 free(llstr_ptr);
1898 llstr_ptr = next_ptr;
1899 }
1900 cip->incl_excl_name_stack = nullptr;
1901 }
1902
1903 char* ChrNameStd(const ChrInfo* cip, uint32_t chr_idx, char* buf) {
1904 const uint32_t output_encoding = cip->output_encoding;
1905 if (chr_idx > cip->max_numeric_code) {
1906 // This is usually encoding-independent; no real numeric representation of
1907 // PAR1/PAR2 is defined. However, since there'd otherwise be no way to
1908 // include the pseudoautosomal regions in e.g. ADMIXTURE, we render them
1909 // them as 25 (in the human case) when "--output-chr 26" is specified.
1910 if (output_encoding) {
1911 const uint32_t parx = 'P' + ('A' << 8) + ('R' << 16) + ('0' << 24) + ((chr_idx - cip->max_numeric_code) << 24);
1912 return memcpya(buf, &parx, 4);
1913 }
1914 return u32toa(cip->autosome_ct + (kChrOffsetXY + 1), buf);
1915 }
1916 if (output_encoding & (kfChrOutputPrefix | kfChrOutput0M)) {
1917 if (output_encoding == kfChrOutput0M) {
1918 // force two chars
1919 if (chr_idx <= cip->autosome_ct) {
1920 buf = memcpya_k(buf, &(kDigitPair[chr_idx]), 2);
1921 } else if (chr_idx == cip->xymt_codes[kChrOffsetY]) {
1922 buf = strcpya_k(buf, "XY");
1923 } else {
1924 *buf++ = '0';
1925 if (chr_idx == cip->xymt_codes[kChrOffsetX]) {
1926 *buf++ = 'X';
1927 } else {
1928 // assumes only X/Y/XY/MT defined
1929 *buf++ = (chr_idx == cip->xymt_codes[kChrOffsetY])? 'Y' : 'M';
1930 }
1931 }
1932 return buf;
1933 }
1934 buf = strcpya_k(buf, "chr");
1935 }
1936 if ((!(output_encoding & (kfChrOutputM | kfChrOutputMT))) || (chr_idx <= cip->autosome_ct)) {
1937 return u32toa(chr_idx, buf);
1938 }
1939 if (chr_idx == cip->xymt_codes[kChrOffsetX]) {
1940 *buf++ = 'X';
1941 } else if (chr_idx == cip->xymt_codes[kChrOffsetY]) {
1942 *buf++ = 'Y';
1943 } else if (chr_idx == cip->xymt_codes[kChrOffsetXY]) {
1944 buf = strcpya_k(buf, "XY");
1945 } else {
1946 *buf++ = 'M';
1947 if (output_encoding & kfChrOutputMT) {
1948 *buf++ = 'T';
1949 }
1950 }
1951 return buf;
1952 }
1953
1954 char* chrtoa(const ChrInfo* cip, uint32_t chr_idx, char* buf) {
1955 // assumes chr_idx is valid
1956 if (!chr_idx) {
1957 // Note that this never has a 'chr' prefix. Which is probably fine, it
1958 // isn't a real chromosome.
1959 *buf++ = '0';
1960 return buf;
1961 }
1962 if (chr_idx <= cip->max_code) {
1963 return ChrNameStd(cip, chr_idx, buf);
1964 }
1965 if (cip->zero_extra_chrs) {
1966 *buf++ = '0';
1967 return buf;
1968 }
1969 return strcpya(buf, cip->nonstd_names[chr_idx]);
1970 }
1971
1972 uint32_t GetMaxChrSlen(const ChrInfo* cip) {
1973 // does not include trailing null
1974 // can be overestimate
1975 // if more functions start calling this, it should just be built into
1976 // LoadPvar() instead
1977 if (cip->zero_extra_chrs) {
1978 return 3 + kMaxChrTextnum;
1979 }
1980 const uint32_t chr_ct = cip->chr_ct;
1981 const uint32_t max_code = cip->max_code;
1982 uint32_t max_chr_slen = 3 + kMaxChrTextnum;
1983 for (uint32_t chr_fo_idx = 0; chr_fo_idx != chr_ct; ++chr_fo_idx) {
1984 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
1985 if (!IsSet(cip->chr_mask, chr_idx)) {
1986 continue;
1987 }
1988 if (chr_idx > max_code) {
1989 const uint32_t name_slen = strlen(cip->nonstd_names[chr_idx]);
1990 if (name_slen > max_chr_slen) {
1991 max_chr_slen = name_slen;
1992 }
1993 }
1994 }
1995 return max_chr_slen;
1996 }
1997
1998 uint32_t IsHaploidChrPresent(const ChrInfo* cip) {
1999 const uintptr_t* chr_mask = cip->chr_mask;
2000 const uintptr_t* haploid_mask = cip->haploid_mask;
2001 // since we don't load haploid vs. diploid info from ##contig header lines,
2002 // this is sufficient
2003 for (uint32_t widx = 0; widx != kChrExcludeWords; ++widx) {
2004 if (chr_mask[widx] & haploid_mask[widx]) {
2005 return 1;
2006 }
2007 }
2008 return 0;
2009 }
2010
2011 uint32_t IsAutosomalDiploidChrPresent(const ChrInfo* cip) {
2012 const uintptr_t* haploid_mask = cip->haploid_mask;
2013 if (haploid_mask[0] & 1) {
2014 return 0;
2015 }
2016 const uint32_t max_code_p1 = cip->max_code + 1;
2017 const uint32_t name_ct = cip->name_ct;
2018 const uint32_t chr_code_end = max_code_p1 + name_ct;
2019 const uint32_t word_ct = BitCtToWordCt(chr_code_end);
2020 const uintptr_t* chr_mask = cip->chr_mask;
2021 for (uint32_t widx = 0; widx != word_ct; ++widx) {
2022 if (chr_mask[widx] & (~haploid_mask[widx])) {
2023 return 1;
2024 }
2025 }
2026 return 0;
2027 }
2028
2029 static inline uint32_t SingleCapLetterChrCode(uint32_t cap_letter) {
2030 if (cap_letter == 'X') {
2031 return kChrRawX;
2032 }
2033 if (cap_letter == 'Y') {
2034 return kChrRawY;
2035 }
2036 if (cap_letter == 'M') {
2037 return kChrRawMT;
2038 }
2039 return UINT32_MAX;
2040 }
2041
2042 #ifndef HIGH_AUTOSOME_NUM_BUILD
2043 static_assert(kMaxChrTextnumSlen == 2, "GetChrCodeRaw() must be updated.");
2044 #else
2045 static_assert(kMaxChrTextnumSlen == 3, "GetChrCodeRaw() must be updated.");
2046 #endif
2047 uint32_t GetChrCodeRaw(const char* str_iter) {
2048 // any character <= ' ' is considered a terminator
2049 // note that char arithmetic tends to be compiled to uint32 operations, so we
2050 // mostly work with ints here
2051 uint32_t first_char_code = ctou32(str_iter[0]);
2052 uint32_t first_char_toui;
2053 if (first_char_code < 58) {
2054 GetChrCodeRaw_digits:
2055 first_char_toui = first_char_code - '0';
2056 if (first_char_toui < 10) {
2057 const uint32_t second_char_code = ctou32(str_iter[1]);
2058 if (second_char_code <= ' ') {
2059 return first_char_toui;
2060 }
2061 const uint32_t third_char_code = ctou32(str_iter[2]);
2062 #ifndef HIGH_AUTOSOME_NUM_BUILD
2063 if (third_char_code <= ' ') {
2064 const uint32_t second_char_toui = second_char_code - '0';
2065 if (second_char_toui < 10) {
2066 return first_char_toui * 10 + second_char_toui;
2067 }
2068 if (!first_char_toui) {
2069 // accept '0X', '0Y', '0M' emitted by Oxford software
2070 return SingleCapLetterChrCode(second_char_code & 0xdf);
2071 }
2072 }
2073 #else
2074 const uint32_t second_char_toui = second_char_code - '0';
2075 if (second_char_toui < 10) {
2076 if (third_char_code <= ' ') {
2077 return first_char_toui * 10 + second_char_toui;
2078 }
2079 if (ctou32(str_iter[3]) <= ' ') {
2080 const uint32_t third_char_toui = third_char_code - '0';
2081 if (third_char_toui < 10) {
2082 return first_char_toui * 100 + second_char_toui * 10 + third_char_toui;
2083 }
2084 }
2085 } else {
2086 // accept '0X', '0Y', '0M' emitted by Oxford software
2087 if ((!first_char_toui) && (third_char_code <= ' ')) {
2088 return SingleCapLetterChrCode(second_char_code & 0xdf);
2089 }
2090 }
2091 #endif
2092 }
2093 return UINT32_MAX;
2094 }
2095 first_char_code &= 0xdf;
2096 uint32_t second_char_code = ctou32(str_iter[1]);
2097 if (first_char_code == 'P') {
2098 // chrPAR1 *not* supported; has to be PAR1 by itself.
2099 // can't do uint16_t compare of multiple characters, since we could be
2100 // dealing with a length-1 null-terminated string; that IS faster when it's
2101 // safe, though
2102 if (((second_char_code & 0xdf) == 'A') && ((ctou32(str_iter[2]) & 0xdf) == 'R')) {
2103 const uint32_t par_idx_m1 = ctou32(str_iter[3]) - '1';
2104 if ((par_idx_m1 < 2) && (ctou32(str_iter[4]) <= ' ')) {
2105 return kChrRawPAR1 + par_idx_m1;
2106 }
2107 }
2108 return UINT32_MAX;
2109 }
2110 if (first_char_code == 'C') {
2111 if (((second_char_code & 0xdf) != 'H') || ((ctou32(str_iter[2]) & 0xdf) != 'R')) {
2112 return UINT32_MAX;
2113 }
2114 str_iter = &(str_iter[3]);
2115 first_char_code = ctou32(str_iter[0]);
2116 if (first_char_code < 58) {
2117 goto GetChrCodeRaw_digits;
2118 }
2119 first_char_code &= 0xdf;
2120 second_char_code = ctou32(str_iter[1]);
2121 }
2122 if (second_char_code <= ' ') {
2123 return SingleCapLetterChrCode(first_char_code);
2124 }
2125 if (ctou32(str_iter[2]) <= ' ') {
2126 second_char_code &= 0xdf;
2127 if ((first_char_code == 'X') && (second_char_code == 'Y')) {
2128 return kChrRawXY;
2129 } else if ((first_char_code == 'M') && (second_char_code == 'T')) {
2130 return kChrRawMT;
2131 }
2132 }
2133 return UINT32_MAX;
2134 }
2135
2136 uint32_t GetChrCode(const char* chr_name, const ChrInfo* cip, uint32_t name_slen) {
2137 // requires chr_name to be null-terminated
2138 // in practice, name_slen will usually already be known, may as well avoid
2139 // redundant strlen() calls even though this uglifies the interface
2140 // does not perform exhaustive error-checking
2141 // UINT32_MAX = --allow-extra-chr ok, UINT32_MAXM1 = total fail
2142 uint32_t chr_code_raw = GetChrCodeRaw(chr_name);
2143 if (chr_code_raw <= cip->max_numeric_code) {
2144 return chr_code_raw;
2145 }
2146 if (chr_code_raw != UINT32_MAX) {
2147 if (chr_code_raw >= kMaxContigs) {
2148 return cip->xymt_codes[chr_code_raw - kMaxContigs];
2149 }
2150 return UINT32_MAXM1;
2151 }
2152 if (!cip->name_ct) {
2153 return UINT32_MAX;
2154 }
2155 // note that IdHtableFind returns UINT32_MAX if name not found
2156 // can't overread, nonstd_names not in main workspace
2157 return IdHtableFind(chr_name, cip->nonstd_names, cip->nonstd_id_htable, name_slen, kChrHtableSize);
2158 }
2159
2160 uint32_t GetChrCodeCounted(const ChrInfo* cip, uint32_t name_slen, char* chr_name) {
2161 // When the chromosome name isn't null-terminated.
2162 // Yeah, probably want to revise this so that chr_name doesn't need to be
2163 // mutable here. However, that currently requires new substitutes for both
2164 // GetChrCodeRaw AND IdHtableFind (IdHtableFindNnt doesn't work due to
2165 // overread); when either of those are needed for some other reason, that's a
2166 // good time to revise this function.
2167 char* s_end = &(chr_name[name_slen]);
2168 const char tmpc = *s_end;
2169 *s_end = '\0';
2170 const uint32_t chr_code = GetChrCode(chr_name, cip, name_slen);
2171 *s_end = tmpc;
2172 return chr_code;
2173 }
2174
2175 void ChrError(const char* chr_name, const char* file_descrip, const ChrInfo* cip, uintptr_t line_idx, uint32_t error_code) {
2176 // assumes chr_name is null-terminated
2177 const uint32_t raw_code = GetChrCodeRaw(chr_name);
2178 logputs("\n");
2179 if (line_idx) {
2180 logerrprintfww("Error: Invalid chromosome code '%s' on line %" PRIuPTR " of %s.\n", chr_name, line_idx, file_descrip);
2181 } else {
2182 logerrprintfww("Error: Invalid chromosome code '%s' in %s.\n", chr_name, file_descrip);
2183 }
2184 if ((S_CAST(int32_t, raw_code) > S_CAST(int32_t, cip->max_numeric_code)) && ((raw_code <= kMaxChrTextnum + kChrOffsetCt) || (raw_code >= kMaxContigs))) {
2185 // numeric code or X/Y/MT/PAR
2186 if (cip->chrset_source == kChrsetSourceDefault) {
2187 logerrputs("(This is disallowed for humans. Check if the problem is with your data, or if\nyou forgot to define a different chromosome set with e.g. --chr-set.).\n");
2188 } else if (cip->chrset_source == kChrsetSourceCmdline) {
2189 logerrputs("(This is disallowed by your command-line flags.)\n");
2190 } else {
2191 // kChrsetSourceFile
2192 logerrputs("(This is disallowed by the file's own ##chrSet header line.)\n");
2193 }
2194 // maybe want to print message(s) depending on whether chromosome set was
2195 // defined on the command line or by the input file?
2196 } else if (error_code == UINT32_MAX) {
2197 logerrputs("(Use --allow-extra-chr to force it to be accepted.)\n");
2198 }
2199 }
2200
2201 PglErr TryToAddChrName(const char* chr_name, const char* file_descrip, uintptr_t line_idx, uint32_t name_slen, uint32_t prohibit_extra_chrs, uint32_t* chr_idx_ptr, ChrInfo* cip) {
2202 // assumes chr_name is either nonstandard (i.e. not "2", "chr2", "chrX",
2203 // etc.), or a rejected xymt.
2204 // requires chr_name to be null-terminated
2205 // assumes chr_idx currently has the return value of GetChrCode()
2206 if (unlikely(prohibit_extra_chrs || ((*chr_idx_ptr) == UINT32_MAXM1))) {
2207 ChrError(chr_name, file_descrip, cip, line_idx, *chr_idx_ptr);
2208 return kPglRetMalformedInput;
2209 }
2210 // When --allow-extra-chr was specified, we save all nonstandard but valid
2211 // chromosome names, even if they're all filtered out by the chromosome mask.
2212
2213 // quasi-bugfix: remove redundant hash table check
2214
2215 if (unlikely(chr_name[0] == '#')) {
2216 // redundant with some of the comment-skipping loaders, but this isn't
2217 // performance-critical
2218 logputs("\n");
2219 logerrputs("Error: Chromosome/contig names may not begin with '#'.\n");
2220 return kPglRetMalformedInput;
2221 }
2222 if (unlikely(name_slen > kMaxIdSlen)) {
2223 logputs("\n");
2224 if (line_idx) {
2225 logerrprintfww("Error: Line %" PRIuPTR " of %s has an excessively long chromosome/contig name. (The " PROG_NAME_STR " limit is " MAX_ID_SLEN_STR " characters.)\n", line_idx, file_descrip);
2226 } else {
2227 logerrprintfww("Error: Excessively long chromosome/contig name in %s. (The " PROG_NAME_STR " limit is " MAX_ID_SLEN_STR " characters.)\n", file_descrip);
2228 }
2229 return kPglRetMalformedInput;
2230 }
2231 const uint32_t max_code_p1 = cip->max_code + 1;
2232 const uint32_t name_ct = cip->name_ct;
2233 const uint32_t chr_code_end = max_code_p1 + name_ct;
2234 if (unlikely(chr_code_end == kMaxContigs)) {
2235 logputs("\n");
2236 #ifdef HIGH_CONTIG_BUILD
2237 logerrputs("Error: Too many distinct nonstandard chromosome/contig names.\n");
2238 #else
2239 logerrputs("Error: Too many distinct nonstandard chromosome/contig names.\nThe usual limit is about 65k. You can raise this to ~980k by uncommenting\n\"#define HIGH_CONTIG_BUILD\" at the top of plink2_common.h and recompiling. If\nthat still isn't enough, we should be able to help you if you make a post in\nthe plink2-users Google group.\n");
2240 #endif
2241 return kPglRetMalformedInput;
2242 }
2243 if (!name_ct) {
2244 // lazy initialization
2245 SetAllU32Arr(kChrHtableSize, cip->nonstd_id_htable);
2246 }
2247 char* new_nonstd_name;
2248 if (unlikely(pgl_malloc(name_slen + 1, &new_nonstd_name))) {
2249 return kPglRetNomem;
2250 }
2251 LlStr* name_stack_ptr = cip->incl_excl_name_stack;
2252 uint32_t in_name_stack = 0;
2253 while (name_stack_ptr) {
2254 // there shouldn't be many of these, so sorting is unimportant
2255 if (!strcmp(chr_name, name_stack_ptr->str)) {
2256 in_name_stack = 1;
2257 break;
2258 }
2259 name_stack_ptr = name_stack_ptr->next;
2260 }
2261 if ((in_name_stack && cip->is_include_stack) || ((!in_name_stack) && (!cip->is_include_stack))) {
2262 SetBit(chr_code_end, cip->chr_mask);
2263 if (cip->haploid_mask[0] & 1) {
2264 SetBit(chr_code_end, cip->haploid_mask);
2265 }
2266 }
2267 memcpy(new_nonstd_name, chr_name, name_slen + 1);
2268 cip->nonstd_names[chr_code_end] = new_nonstd_name;
2269 *chr_idx_ptr = chr_code_end;
2270 cip->name_ct = name_ct + 1;
2271 uint32_t* id_htable = cip->nonstd_id_htable;
2272 HtableAddNondup(chr_name, name_slen, kChrHtableSize, chr_code_end, id_htable);
2273 return kPglRetSuccess;
2274 }
2275
2276
2277 /*
2278 uintptr_t count_11_vecs(const VecW* geno_vvec, uintptr_t vec_ct) {
2279 // Counts number of aligned 11s in vptr[0..(vec_ct-1)]. Assumes vec_ct is a
2280 // multiple of 6 (0 ok).
2281 assert(!(vec_ct % 6));
2282 const VecW m1 = VCONST_W(kMask5555);
2283 const VecW m2 = VCONST_W(kMask3333);
2284 const VecW m4 = VCONST_W(kMask0F0F);
2285 const VecW m8 = VCONST_W(kMask00FF);
2286 const VecW* geno_vvec_iter = geno_vvec;
2287 const VecW* geno_vvec_end = &(geno_vvec[vec_ct]);
2288 uintptr_t tot = 0;
2289
2290 while (1) {
2291 const VecW* geno_vvec_stop = &(geno_vvec_iter[60]);
2292
2293 UniVec acc;
2294 acc.vw = vecw_setzero();
2295
2296 if (geno_vvec_stop > geno_vvec_end) {
2297 if (geno_vvec_iter == geno_vvec_end) {
2298 return tot;
2299 }
2300 geno_vvec_stop = geno_vvec_end;
2301 }
2302 do {
2303 VecW cur_geno_vword = *geno_vvec_iter++;
2304 VecW count1 = cur_geno_vword & m1;
2305 count1 = count1 & vecw_srli(cur_geno_vword, 1);
2306
2307 cur_geno_vword = *geno_vvec_iter++;
2308 VecW cur_11 = cur_geno_vword & m1;
2309 cur_11 = cur_11 & vecw_srli(cur_geno_vword, 1);
2310 count1 = count1 + cur_11;
2311
2312 cur_geno_vword = *geno_vvec_iter++;
2313 cur_11 = cur_geno_vword & m1;
2314 cur_11 = cur_11 & vecw_srli(cur_geno_vword, 1);
2315 count1 = count1 + cur_11;
2316 count1 = (count1 & m2) + (vecw_srli(count1, 2) & m2);
2317
2318 cur_geno_vword = *geno_vvec_iter++;
2319 VecW count2 = cur_geno_vword & m1;
2320 count2 = count2 & vecw_srli(cur_geno_vword, 1);
2321
2322 cur_geno_vword = *geno_vvec_iter++;
2323 VecW cur_11 = cur_geno_vword & m1;
2324 cur_11 = cur_11 & vecw_srli(cur_geno_vword, 1);
2325 count2 = count2 + cur_11;
2326
2327 cur_geno_vword = *geno_vvec_iter++;
2328 cur_11 = cur_geno_vword & m1;
2329 cur_11 = cur_11 & vecw_srli(cur_geno_vword, 1);
2330 count2 = count2 + cur_11;
2331 count1 = count1 + (count2 & m2) + (vecw_srli(count2, 2) & m2);
2332
2333 acc.vw = acc.vw + (count1 & m4) + (vecw_srli(count1, 4) & m4);
2334 } while (geno_vvec_iter < geno_vvec_stop);
2335 acc.vw = (acc.vw & m8) + (vecw_srli(acc.vw, 8) & m8);
2336 tot += UniVecHsum16(acc);
2337 }
2338 }
2339
2340 uintptr_t count_11_longs(const uintptr_t* genovec, uintptr_t word_ct) {
2341 uintptr_t tot = 0;
2342 if (word_ct >= (6 * kWordsPerVec)) {
2343 assert(IsVecAligned(genovec));
2344 const uintptr_t remainder = word_ct % (6 * kWordsPerVec);
2345 const uintptr_t main_block_word_ct = word_ct - remainder;
2346 tot = count_11_vecs((const VecW*)genovec, main_block_word_ct / kWordsPerVec);
2347 word_ct = remainder;
2348 genovec = &(genovec[main_block_word_ct]);
2349 }
2350 for (uintptr_t trailing_word_idx = 0; trailing_word_idx != word_ct; ++trailing_word_idx) {
2351 const uintptr_t cur_geno_word = genovec[trailing_word_idx];
2352 tot += Popcount01Word(Word11(cur_geno_word));
2353 }
2354 }
2355 */
2356
2357 uint32_t AllGenoEqual(const uintptr_t* genoarr, uint32_t sample_ct) {
2358 const uint32_t word_ct_m1 = (sample_ct - 1) / kBitsPerWordD2;
2359 const uintptr_t match_word = (genoarr[0] & 3) * kMask5555;
2360 for (uint32_t widx = 0; widx != word_ct_m1; ++widx) {
2361 if (genoarr[widx] != match_word) {
2362 return 0;
2363 }
2364 }
2365 const uint32_t remainder = ModNz(sample_ct, kBitsPerWordD2);
2366 return !bzhi_max(genoarr[word_ct_m1] ^ match_word, 2 * remainder);
2367 }
2368
2369 void InterleavedMaskZero(const uintptr_t* __restrict interleaved_mask, uintptr_t geno_vec_ct, uintptr_t* __restrict genovec) {
2370 const uintptr_t twovec_ct = geno_vec_ct / 2;
2371 #ifdef __LP64__
2372 const VecW m1 = VCONST_W(kMask5555);
2373 const VecW* interleaved_mask_iter = R_CAST(const VecW*, interleaved_mask);
2374 VecW* genovvec_iter = R_CAST(VecW*, genovec);
2375 for (uintptr_t twovec_idx = 0; twovec_idx != twovec_ct; ++twovec_idx) {
2376 const VecW mask_vvec = *interleaved_mask_iter++;
2377 VecW mask_first = mask_vvec & m1;
2378 mask_first = mask_first | vecw_slli(mask_first, 1);
2379 VecW mask_second = vecw_and_notfirst(m1, mask_vvec);
2380 mask_second = mask_second | vecw_srli(mask_second, 1);
2381 *genovvec_iter = (*genovvec_iter) & mask_first;
2382 ++genovvec_iter;
2383 *genovvec_iter = (*genovvec_iter) & mask_second;
2384 ++genovvec_iter;
2385 }
2386 if (geno_vec_ct & 1) {
2387 VecW mask_first = *interleaved_mask_iter;
2388 mask_first = mask_first | vecw_slli(mask_first, 1);
2389 *genovvec_iter = (*genovvec_iter) & mask_first;
2390 }
2391 #else
2392 const uintptr_t* interleaved_mask_iter = interleaved_mask;
2393 uintptr_t* genovec_iter = genovec;
2394 for (uintptr_t twovec_idx = 0; twovec_idx != twovec_ct; ++twovec_idx) {
2395 const uintptr_t mask_word = *interleaved_mask_iter++;
2396 *genovec_iter &= (mask_word & kMask5555) * 3;
2397 ++genovec_iter;
2398 *genovec_iter &= ((mask_word >> 1) & kMask5555) * 3;
2399 ++genovec_iter;
2400 }
2401 if (geno_vec_ct & 1) {
2402 const uintptr_t mask_word = *interleaved_mask_iter;
2403 *genovec_iter &= mask_word * 3;
2404 }
2405 #endif
2406 }
2407
2408 void InterleavedMaskMissing(const uintptr_t* __restrict interleaved_mask, uintptr_t geno_vec_ct, uintptr_t* __restrict genovec) {
2409 const uintptr_t twovec_ct = geno_vec_ct / 2;
2410 #ifdef __LP64__
2411 const VecW m1 = VCONST_W(kMask5555);
2412 const VecW inv_m1 = VCONST_W(kMaskAAAA);
2413 const VecW* interleaved_mask_iter = R_CAST(const VecW*, interleaved_mask);
2414 VecW* genovvec_iter = R_CAST(VecW*, genovec);
2415 for (uintptr_t twovec_idx = 0; twovec_idx != twovec_ct; ++twovec_idx) {
2416 const VecW mask_vvec = *interleaved_mask_iter++;
2417 VecW set_first = vecw_and_notfirst(mask_vvec, m1);
2418 set_first = set_first | vecw_slli(set_first, 1);
2419 VecW set_second = vecw_and_notfirst(mask_vvec, inv_m1);
2420 set_second = set_second | vecw_srli(set_second, 1);
2421 *genovvec_iter = (*genovvec_iter) | set_first;
2422 ++genovvec_iter;
2423 *genovvec_iter = (*genovvec_iter) | set_second;
2424 ++genovvec_iter;
2425 }
2426 if (geno_vec_ct & 1) {
2427 VecW set_first = vecw_and_notfirst(*interleaved_mask_iter, m1);
2428 set_first = set_first | vecw_slli(set_first, 1);
2429 *genovvec_iter = (*genovvec_iter) | set_first;
2430 }
2431 #else
2432 const uintptr_t* interleaved_mask_iter = interleaved_mask;
2433 uintptr_t* genovec_iter = genovec;
2434 for (uintptr_t twovec_idx = 0; twovec_idx != twovec_ct; ++twovec_idx) {
2435 const uintptr_t set_invword = *interleaved_mask_iter++;
2436 *genovec_iter |= ((~set_invword) & kMask5555) * 3;
2437 ++genovec_iter;
2438 *genovec_iter |= (((~set_invword) >> 1) & kMask5555) * 3;
2439 ++genovec_iter;
2440 }
2441 if (geno_vec_ct & 1) {
2442 const uintptr_t set_invword = *interleaved_mask_iter;
2443 *genovec_iter |= ((~set_invword) & kMask5555) * 3;
2444 }
2445 #endif
2446 }
2447
2448 void InterleavedSetMissing(const uintptr_t* __restrict interleaved_set, uintptr_t geno_vec_ct, uintptr_t* __restrict genovec) {
2449 const uintptr_t twovec_ct = geno_vec_ct / 2;
2450 #ifdef __LP64__
2451 const VecW m1 = VCONST_W(kMask5555);
2452 const VecW* interleaved_set_iter = R_CAST(const VecW*, interleaved_set);
2453 VecW* genovvec_iter = R_CAST(VecW*, genovec);
2454 for (uintptr_t twovec_idx = 0; twovec_idx != twovec_ct; ++twovec_idx) {
2455 const VecW set_vvec = *interleaved_set_iter++;
2456 VecW set_first = set_vvec & m1;
2457 set_first = set_first | vecw_slli(set_first, 1);
2458 VecW set_second = vecw_and_notfirst(m1, set_vvec);
2459 set_second = set_second | vecw_srli(set_second, 1);
2460 *genovvec_iter = (*genovvec_iter) | set_first;
2461 ++genovvec_iter;
2462 *genovvec_iter = (*genovvec_iter) | set_second;
2463 ++genovvec_iter;
2464 }
2465 if (geno_vec_ct & 1) {
2466 VecW set_first = *interleaved_set_iter;
2467 set_first = set_first | vecw_slli(set_first, 1);
2468 *genovvec_iter = (*genovvec_iter) | set_first;
2469 }
2470 #else
2471 const uintptr_t* interleaved_set_iter = interleaved_set;
2472 uintptr_t* genovec_iter = genovec;
2473 for (uintptr_t twovec_idx = 0; twovec_idx != twovec_ct; ++twovec_idx) {
2474 const uintptr_t set_word = *interleaved_set_iter++;
2475 *genovec_iter |= (set_word & kMask5555) * 3;
2476 ++genovec_iter;
2477 *genovec_iter |= ((set_word >> 1) & kMask5555) * 3;
2478 ++genovec_iter;
2479 }
2480 if (geno_vec_ct & 1) {
2481 const uintptr_t set_word = *interleaved_set_iter;
2482 *genovec_iter |= set_word * 3;
2483 }
2484 #endif
2485 }
2486
2487 void InterleavedSetMissingCleardosage(const uintptr_t* __restrict orig_set, const uintptr_t* __restrict interleaved_set, uintptr_t geno_vec_ct, uintptr_t* __restrict genovec, uint32_t* __restrict write_dosage_ct_ptr, uintptr_t* __restrict dosagepresent, Dosage* dosage_main) {
2488 const uint32_t orig_write_dosage_ct = *write_dosage_ct_ptr;
2489 if (orig_write_dosage_ct) {
2490 uintptr_t sample_widx = 0;
2491 uintptr_t cur_bits = dosagepresent[0];
2492 for (uint32_t dosage_read_idx = 0; dosage_read_idx != orig_write_dosage_ct; ++dosage_read_idx) {
2493 const uintptr_t lowbit = BitIter1y(dosagepresent, &sample_widx, &cur_bits);
2494 if (orig_set[sample_widx] & lowbit) {
2495 dosagepresent[sample_widx] ^= lowbit;
2496 uint32_t dosage_write_idx = dosage_read_idx++;
2497 for (; dosage_read_idx == orig_write_dosage_ct; ++dosage_read_idx) {
2498 const uintptr_t lowbit2 = BitIter1y(dosagepresent, &sample_widx, &cur_bits);
2499 if (orig_set[sample_widx] & lowbit2) {
2500 dosagepresent[sample_widx] ^= lowbit2;
2501 } else {
2502 dosage_main[dosage_write_idx++] = dosage_main[dosage_read_idx];
2503 }
2504 }
2505 *write_dosage_ct_ptr = dosage_write_idx;
2506 break;
2507 }
2508 }
2509 }
2510 InterleavedSetMissing(interleaved_set, geno_vec_ct, genovec);
2511 }
2512
2513 void SetMaleHetMissing(const uintptr_t* __restrict sex_male_interleaved, uint32_t geno_vec_ct, uintptr_t* __restrict genovec) {
2514 const uint32_t twovec_ct = geno_vec_ct / 2;
2515 #ifdef __LP64__
2516 const VecW m1 = VCONST_W(kMask5555);
2517 const VecW* sex_male_interleaved_iter = R_CAST(const VecW*, sex_male_interleaved);
2518 VecW* genovvec_iter = R_CAST(VecW*, genovec);
2519 for (uint32_t twovec_idx = 0; twovec_idx != twovec_ct; ++twovec_idx) {
2520 const VecW sex_male_vvec = *sex_male_interleaved_iter++;
2521 // we wish to bitwise-or with (sex_male_nypvec_01 & genovec) << 1
2522 const VecW sex_male_first = sex_male_vvec & m1;
2523 const VecW sex_male_second_shifted = vecw_and_notfirst(m1, sex_male_vvec);
2524 VecW cur_geno_vword = *genovvec_iter;
2525
2526 const VecW missing_male_vword = sex_male_first & cur_geno_vword;
2527
2528 *genovvec_iter++ = cur_geno_vword | vecw_slli(missing_male_vword, 1);
2529 cur_geno_vword = *genovvec_iter;
2530 *genovvec_iter++ = cur_geno_vword | (sex_male_second_shifted & vecw_slli(cur_geno_vword, 1));
2531 }
2532 if (geno_vec_ct & 1) {
2533 const VecW sex_male_first = (*sex_male_interleaved_iter) & m1;
2534 const VecW cur_geno_vword = *genovvec_iter;
2535 const VecW missing_male_vword = sex_male_first & cur_geno_vword;
2536 *genovvec_iter = cur_geno_vword | vecw_slli(missing_male_vword, 1);
2537 }
2538 #else
2539 const uintptr_t* sex_male_interleaved_iter = sex_male_interleaved;
2540 uintptr_t* genovec_iter = genovec;
2541 for (uint32_t twovec_idx = 0; twovec_idx != twovec_ct; ++twovec_idx) {
2542 const uintptr_t sex_male_word = *sex_male_interleaved_iter++;
2543 uintptr_t cur_geno_word = *genovec_iter;
2544 *genovec_iter++ = cur_geno_word | ((sex_male_word & kMask5555 & cur_geno_word) << 1);
2545 cur_geno_word = *genovec_iter;
2546 *genovec_iter++ = cur_geno_word | (sex_male_word & kMaskAAAA & (cur_geno_word << 1));
2547 }
2548 if (geno_vec_ct & 1) {
2549 const uintptr_t sex_male_word = *sex_male_interleaved_iter;
2550 uintptr_t cur_geno_word = *genovec_iter;
2551 *genovec_iter = cur_geno_word | ((sex_male_word & kMask5555 & cur_geno_word) << 1);
2552 }
2553 #endif
2554 }
2555
2556 void EraseMaleHetDosages(const uintptr_t* __restrict sex_male, const uintptr_t* __restrict genoarr, uint32_t* __restrict write_dosage_ct_ptr, uintptr_t* __restrict dosagepresent, Dosage* dosage_main) {
2557 const uint32_t orig_write_dosage_ct = *write_dosage_ct_ptr;
2558 if (!orig_write_dosage_ct) {
2559 return;
2560 }
2561 uintptr_t sample_uidx_base = 0;
2562 uintptr_t cur_bits = dosagepresent[0];
2563 for (uint32_t dosage_read_idx = 0; dosage_read_idx != orig_write_dosage_ct; ++dosage_read_idx) {
2564 const uintptr_t sample_uidx = BitIter1(dosagepresent, &sample_uidx_base, &cur_bits);
2565 if (IsSet(sex_male, sample_uidx) && (GetNyparrEntry(genoarr, sample_uidx) == 1)) {
2566 ClearBit(sample_uidx, dosagepresent);
2567 uint32_t dosage_write_idx = dosage_read_idx++;
2568 for (; dosage_read_idx != orig_write_dosage_ct; ++dosage_read_idx) {
2569 const uintptr_t sample_uidx2 = BitIter1(dosagepresent, &sample_uidx_base, &cur_bits);
2570 if (IsSet(sex_male, sample_uidx2) && (GetNyparrEntry(genoarr, sample_uidx2) == 1)) {
2571 ClearBit(sample_uidx2, dosagepresent);
2572 } else {
2573 dosage_main[dosage_write_idx++] = dosage_main[dosage_read_idx];
2574 }
2575 }
2576 *write_dosage_ct_ptr = dosage_write_idx;
2577 return;
2578 }
2579 }
2580 }
2581
2582 void EraseMaleDphases(const uintptr_t* __restrict sex_male, uint32_t* __restrict write_dphase_ct_ptr, uintptr_t* __restrict dphasepresent, SDosage* dphase_delta) {
2583 const uint32_t orig_write_dphase_ct = *write_dphase_ct_ptr;
2584 if (!orig_write_dphase_ct) {
2585 return;
2586 }
2587 uintptr_t sample_widx = 0;
2588 uintptr_t cur_bits = dphasepresent[0];
2589 for (uint32_t dphase_read_idx = 0; dphase_read_idx != orig_write_dphase_ct; ++dphase_read_idx) {
2590 const uintptr_t lowbit = BitIter1y(dphasepresent, &sample_widx, &cur_bits);
2591 if (sex_male[sample_widx] & lowbit) {
2592 dphasepresent[sample_widx] ^= lowbit;
2593 uint32_t dphase_write_idx = dphase_read_idx++;
2594 for (; dphase_read_idx == orig_write_dphase_ct; ++dphase_read_idx) {
2595 const uintptr_t lowbit2 = BitIter1y(dphasepresent, &sample_widx, &cur_bits);
2596 if (sex_male[sample_widx] & lowbit2) {
2597 dphasepresent[sample_widx] ^= lowbit2;
2598 } else {
2599 dphase_delta[dphase_write_idx++] = dphase_delta[dphase_read_idx];
2600 }
2601 }
2602 *write_dphase_ct_ptr = dphase_write_idx;
2603 return;
2604 }
2605 }
2606 }
2607
2608 void SetMaleHetMissingCleardosage(const uintptr_t* __restrict sex_male, const uintptr_t* __restrict sex_male_interleaved, uint32_t geno_vec_ct, uintptr_t* __restrict genovec, uint32_t* __restrict write_dosage_ct_ptr, uintptr_t* __restrict dosagepresent, Dosage* dosage_main) {
2609 if (*write_dosage_ct_ptr) {
2610 EraseMaleHetDosages(sex_male, genovec, write_dosage_ct_ptr, dosagepresent, dosage_main);
2611 }
2612 SetMaleHetMissing(sex_male_interleaved, geno_vec_ct, genovec);
2613 }
2614
2615 void SetMaleHetMissingKeepdosage(const uintptr_t* __restrict sex_male, const uintptr_t* __restrict sex_male_interleaved, uint32_t geno_word_ct, uintptr_t* __restrict genovec, uint32_t* __restrict write_dosage_ct_ptr, uintptr_t* __restrict dosagepresent, Dosage* dosage_main) {
2616 // count # of 1.00000 dosages we need to insert, and then rewrite dosage_main
2617 // from back to front so we don't need temporary buffers.
2618 const uint32_t orig_dosage_ct = *write_dosage_ct_ptr;
2619 if (!orig_dosage_ct) {
2620 // can't assume dosagepresent is initialized in this case
2621 ZeroWArr(DivUp(geno_word_ct, 2), dosagepresent);
2622 }
2623 const Halfword* sex_male_alias = R_CAST(const Halfword*, sex_male);
2624 Halfword* dosagepresent_alias = R_CAST(Halfword*, dosagepresent);
2625 uint32_t new_dosage_ct = 0;
2626 // todo: try vectorizing this loop
2627 for (uintptr_t widx = 0; widx != geno_word_ct; ++widx) {
2628 const uintptr_t geno_hets = Word01(genovec[widx]);
2629 const uintptr_t male_nodosage_word = UnpackHalfwordToWord(sex_male_alias[widx] & (~dosagepresent_alias[widx]));
2630 new_dosage_ct += Popcount01Word(geno_hets & male_nodosage_word);
2631 }
2632 if (!new_dosage_ct) {
2633 SetMaleHetMissing(sex_male_interleaved, WordCtToVecCt(geno_word_ct), genovec);
2634 return;
2635 }
2636 uint32_t dosage_write_idx = orig_dosage_ct + new_dosage_ct;
2637 uint32_t dosage_read_idx = orig_dosage_ct;
2638 uint32_t widx = geno_word_ct;
2639 *write_dosage_ct_ptr = dosage_write_idx;
2640 do {
2641 --widx;
2642 const uintptr_t geno_word = genovec[widx];
2643 const uintptr_t male_geno_hets = geno_word & (~(geno_word >> 1)) & UnpackHalfwordToWord(sex_male_alias[widx]);
2644 const uintptr_t dosagepresent_word = UnpackHalfwordToWord(dosagepresent_alias[widx]);
2645 uintptr_t new_dosagepresent_word = dosagepresent_word | male_geno_hets;
2646 if (new_dosagepresent_word) {
2647 dosagepresent_alias[widx] = PackWordToHalfword(new_dosagepresent_word);
2648 do {
2649 const uint32_t top_set_bit = bsrw(new_dosagepresent_word);
2650 const uintptr_t cur_bit_word = k1LU << top_set_bit;
2651 Dosage cur_dosage = kDosageMid;
2652 if (cur_bit_word & dosagepresent_word) {
2653 cur_dosage = dosage_main[--dosage_read_idx];
2654 }
2655 dosage_main[--dosage_write_idx] = cur_dosage;
2656 new_dosagepresent_word -= cur_bit_word;
2657 } while (new_dosagepresent_word);
2658 genovec[widx] = geno_word | (male_geno_hets << 1);
2659 }
2660 } while (widx);
2661 }
2662
2663 // Clears each bit in bitarr which doesn't correspond to a genovec het.
2664 // Assumes that either trailing bits of bitarr are already zero, or trailing
2665 // bits of genovec are zero.
2666 //
2667 // Similar to PgrDetectGenoarrHetsUnsafe().
2668 void MaskGenoarrHetsMultiallelicUnsafe(const uintptr_t* __restrict genoarr, const uintptr_t* __restrict patch_10_set, const AlleleCode* __restrict patch_10_vals, uint32_t raw_sample_ctl2, uintptr_t* __restrict bitarr) {
2669 // Related to PgrDetectGenoarrHetsMultiallelic().
2670 const Halfword* patch_10_set_alias = R_CAST(const Halfword*, patch_10_set);
2671 const AlleleCode* patch_10_vals_iter = patch_10_vals;
2672 Halfword* bitarr_alias = R_CAST(Halfword*, bitarr);
2673 for (uint32_t widx = 0; widx != raw_sample_ctl2; ++widx) {
2674 const uintptr_t cur_word = genoarr[widx];
2675 uint32_t patch_10_hw = patch_10_set_alias[widx];
2676 uint32_t cur_hets = Pack01ToHalfword(cur_word);
2677 while (patch_10_hw) {
2678 const AlleleCode code1 = *patch_10_vals_iter++;
2679 const AlleleCode code2 = *patch_10_vals_iter++;
2680 if (code1 != code2) {
2681 cur_hets |= ctzu32(patch_10_hw);
2682 }
2683 patch_10_hw &= patch_10_hw - 1;
2684 }
2685 bitarr_alias[widx] &= cur_hets;
2686 }
2687 }
2688
2689 /*
2690 uint32_t chr_window_max(const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bp, uint32_t chr_fo_idx, uint32_t ct_max, uint32_t bp_max, uint32_t cur_window_max) {
2691 if (cur_window_max >= ct_max) {
2692 return ct_max;
2693 }
2694 const uint32_t chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
2695 uint32_t variant_uidx = AdvBoundedTo1Bit(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], chr_end);
2696 const uint32_t variant_ct = PopcountBitRange(variant_include, variant_uidx, chr_end);
2697 if (variant_ct <= cur_window_max) {
2698 return cur_window_max;
2699 }
2700 uint32_t window_idx_first = 0;
2701 uint32_t window_uidx_first = variant_uidx;
2702 uint32_t window_bp_first = variant_bp[variant_uidx];
2703 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_uidx, ++variant_idx) {
2704 MovU32To1Bit(variant_include, &variant_uidx);
2705 uint32_t variant_bp_thresh = variant_bp[variant_uidx];
2706 if (variant_bp_thresh < bp_max) {
2707 variant_bp_thresh = 0;
2708 } else {
2709 variant_bp_thresh -= bp_max;
2710 }
2711 if (variant_bp_thresh > window_bp_first) {
2712 do {
2713 ++window_uidx_first;
2714 MovU32To1Bit(variant_include, &window_uidx_first);
2715 window_bp_first = variant_bp[window_uidx_first];
2716 ++window_idx_first;
2717 } while (variant_bp_thresh > window_bp_first);
2718 } else if (variant_idx - window_idx_first == cur_window_max) {
2719 if (++cur_window_max == ct_max) {
2720 return cur_window_max;
2721 }
2722 }
2723 }
2724 return cur_window_max;
2725 }
2726 */
2727
2728 uint32_t NotOnlyXymt(const uintptr_t* variant_include, const ChrInfo* cip, uint32_t raw_variant_ct, uint32_t xymt_offset) {
2729 const uint32_t xymt_code = cip->xymt_codes[xymt_offset];
2730 assert(!IsI32Neg(xymt_code));
2731 const uint32_t cur_chr_fo_idx = cip->chr_idx_to_foidx[xymt_code];
2732 const uint32_t chr_start = cip->chr_fo_vidx_start[cur_chr_fo_idx];
2733 if (chr_start) {
2734 const uint32_t first_uidx = AdvTo1Bit(variant_include, 0);
2735 if (first_uidx < chr_start) {
2736 return 1;
2737 }
2738 }
2739 const uint32_t chr_end = cip->chr_fo_vidx_start[cur_chr_fo_idx + 1];
2740 return (chr_end < raw_variant_ct) && (!AllBitsAreZero(variant_include, chr_end, raw_variant_ct));
2741 }
2742
2743 uint32_t CountNonAutosomalVariants(const uintptr_t* variant_include, const ChrInfo* cip, uint32_t count_x, uint32_t count_mt) {
2744 // for backward compatibility, unplaced markers are considered to be
2745 // autosomal here
2746 uint32_t ct = 0;
2747 if (count_x) {
2748 uint32_t x_code;
2749 if (XymtExists(cip, kChrOffsetX, &x_code)) {
2750 ct += CountChrVariantsUnsafe(variant_include, cip, x_code);
2751 }
2752 }
2753 uint32_t y_code;
2754 if (XymtExists(cip, kChrOffsetY, &y_code)) {
2755 ct += CountChrVariantsUnsafe(variant_include, cip, y_code);
2756 }
2757 if (count_mt) {
2758 uint32_t mt_code;
2759 if (XymtExists(cip, kChrOffsetMT, &mt_code)) {
2760 ct += CountChrVariantsUnsafe(variant_include, cip, mt_code);
2761 }
2762 }
2763 return ct;
2764 }
2765
2766 void ExcludeNonAutosomalVariants(const ChrInfo* cip, uintptr_t* variant_include) {
2767 uint32_t x_code;
2768 if (XymtExists(cip, kChrOffsetX, &x_code)) {
2769 const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[x_code];
2770 ClearBitsNz(cip->chr_fo_vidx_start[chr_fo_idx], cip->chr_fo_vidx_start[chr_fo_idx + 1], variant_include);
2771 }
2772 uint32_t y_code;
2773 if (XymtExists(cip, kChrOffsetY, &y_code)) {
2774 const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[y_code];
2775 ClearBitsNz(cip->chr_fo_vidx_start[chr_fo_idx], cip->chr_fo_vidx_start[chr_fo_idx + 1], variant_include);
2776 }
2777 uint32_t mt_code;
2778 if (XymtExists(cip, kChrOffsetMT, &mt_code)) {
2779 const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[mt_code];
2780 ClearBitsNz(cip->chr_fo_vidx_start[chr_fo_idx], cip->chr_fo_vidx_start[chr_fo_idx + 1], variant_include);
2781 }
2782 }
2783
2784 PglErr ConditionalAllocateNonAutosomalVariants(const ChrInfo* cip, const char* calc_descrip, uint32_t raw_variant_ct, const uintptr_t** variant_include_ptr, uint32_t* variant_ct_ptr) {
2785 const uint32_t non_autosomal_variant_ct = CountNonAutosomalVariants(*variant_include_ptr, cip, 1, 1);
2786 if (!non_autosomal_variant_ct) {
2787 return kPglRetSuccess;
2788 }
2789 *variant_ct_ptr -= non_autosomal_variant_ct;
2790 if (calc_descrip) {
2791 logprintf("Excluding %u variant%s on non-autosomes from %s.\n", non_autosomal_variant_ct, (non_autosomal_variant_ct == 1)? "" : "s", calc_descrip);
2792 if (unlikely(!(*variant_ct_ptr))) {
2793 logerrprintf("Error: No variants remaining for %s.\n", calc_descrip);
2794 return kPglRetDegenerateData;
2795 }
2796 }
2797 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
2798 uintptr_t* working_variant_include;
2799 if (unlikely(bigstack_alloc_w(raw_variant_ctl, &working_variant_include))) {
2800 return kPglRetNomem;
2801 }
2802 memcpy(working_variant_include, *variant_include_ptr, raw_variant_ctl * sizeof(intptr_t));
2803 ExcludeNonAutosomalVariants(cip, working_variant_include);
2804 *variant_include_ptr = working_variant_include;
2805 return kPglRetSuccess;
2806 }
2807
2808 void FillSubsetChrFoVidxStart(const uintptr_t* variant_include, const ChrInfo* cip, uint32_t* subset_chr_fo_vidx_start) {
2809 const uint32_t chr_ct = cip->chr_ct;
2810 subset_chr_fo_vidx_start[0] = 0;
2811 uint32_t variant_uidx = 0;
2812 uint32_t variant_idx = 0;
2813 for (uint32_t chr_fo_idx = 1; chr_fo_idx <= chr_ct; ++chr_fo_idx) {
2814 const uint32_t chr_end_variant_uidx = cip->chr_fo_vidx_start[chr_fo_idx];
2815 variant_idx += PopcountBitRange(variant_include, variant_uidx, chr_end_variant_uidx);
2816 subset_chr_fo_vidx_start[chr_fo_idx] = variant_idx;
2817 variant_uidx = chr_end_variant_uidx;
2818 }
2819 }
2820
2821 /*
2822 BoolErr allele_set(const char* newval, uint32_t allele_slen, char** allele_ptr) {
2823 char* newptr;
2824 if (allele_slen == 1) {
2825 // const_cast
2826 newptr = (char*)((uintptr_t)(&(g_one_char_strs[((unsigned char)(*newval)) * 2])));
2827 } else {
2828 char* new_alloc;
2829 if (pgl_malloc(allele_slen + 1, &new_alloc)) {
2830 return 1;
2831 }
2832 memcpyx(new_alloc, newval, allele_slen, '\0');
2833 newptr = new_alloc;
2834 }
2835 *allele_ptr = newptr;
2836 return 0;
2837 }
2838
2839 BoolErr allele_reset(const char* newval, uint32_t allele_slen, char** allele_ptr) {
2840 char* newptr;
2841 if (allele_slen == 1) {
2842 // const_cast
2843 newptr = (char*)((uintptr_t)(&(g_one_char_strs[((unsigned char)(*newval)) * 2])));
2844 } else {
2845 char* new_alloc;
2846 if (pgl_malloc(allele_slen + 1, &new_alloc)) {
2847 return 1;
2848 }
2849 memcpyx(new_alloc, newval, allele_slen, '\0');
2850 newptr = new_alloc;
2851 }
2852 const uintptr_t bigstack_end_addr = (uintptr_t)g_bigstack_end;
2853 const uintptr_t maxdiff = ((uintptr_t)(&(g_one_char_strs[512]))) - bigstack_end_addr;
2854 // take advantage of unsigned wraparound
2855 if ((((uintptr_t)(*allele_ptr)) - bigstack_end_addr) >= maxdiff) {
2856 free(*allele_ptr);
2857 }
2858 *allele_ptr = newptr;
2859 return 0;
2860 }
2861
2862 void cleanup_allele_storage(uint32_t max_allele_slen, uintptr_t allele_storage_entry_ct, const char** allele_storage) {
2863 // Now doesn't improperly free bigstack allocations (as long as they aren't
2864 // past g_bigstack_end), and doesn't need to be called at all most of the
2865 // time.
2866
2867 // An alternative representation: have a separate bitarray which indicates
2868 // whether the allele_storage[] element should be interpreted as a heap
2869 // pointer or an in-place zero-terminated string (i.e. string length can be
2870 // up to 7 on 64-bit systems). I expect that to be more efficient for new
2871 // datasets, but let's get the simple (and 1.9-codebase-compatible)
2872 // implementation working first, and then benchmark the fancier code later.
2873 if (allele_storage && (max_allele_slen > 1)) {
2874 const uintptr_t bigstack_end_addr = (uintptr_t)g_bigstack_end;
2875 const uintptr_t maxdiff = ((uintptr_t)(&(g_one_char_strs[512]))) - bigstack_end_addr;
2876 for (uintptr_t idx = 0; idx != allele_storage_entry_ct; ++idx) {
2877 const char* cur_entry = allele_storage[idx];
2878 assert(cur_entry);
2879 // take advantage of unsigned wraparound
2880 if ((((uintptr_t)cur_entry) - bigstack_end_addr) >= maxdiff) {
2881 free_const(cur_entry);
2882 }
2883 }
2884 }
2885 }
2886 */
2887
2888 uint32_t IsCategoricalPhenostr(const char* phenostr_iter) {
2889 uint32_t first_char_code = ctou32(*phenostr_iter++);
2890 // allow leading +/-
2891 if ((first_char_code == 43) || (first_char_code == 45)) {
2892 first_char_code = ctou32(*phenostr_iter++);
2893 }
2894 if (((first_char_code - 48) < 10) || (first_char_code == 44) || (first_char_code < 32)) {
2895 // the last two conditions are for detecting CSV empty strings
2896 return 0;
2897 }
2898 if (first_char_code == 46) {
2899 // decimal point. classify based on whether next character is a digit.
2900 const uint32_t second_char_code = ctou32(phenostr_iter[0]);
2901 return ((second_char_code - 48) >= 10);
2902 }
2903 // allow any capitalization of "NA"/"nan", but not "inf"
2904 if ((first_char_code & 0xdf) != 78) {
2905 return 1;
2906 }
2907 const uint32_t second_char_code = ctou32(phenostr_iter[0]);
2908 if ((second_char_code & 0xdf) != 65) {
2909 return 1;
2910 }
2911 const uint32_t third_char_code = ctou32(phenostr_iter[1]);
2912 if ((third_char_code & 0xdf) == 78) {
2913 return (ctou32(phenostr_iter[2]) > ' ');
2914 }
2915 return (third_char_code > 32);
2916 }
2917
2918 uint32_t IsCategoricalPhenostrNocsv(const char* phenostr_iter) {
2919 uint32_t first_char_code = ctou32(*phenostr_iter++);
2920 // allow leading +/-
2921 if ((first_char_code == 43) || (first_char_code == 45)) {
2922 first_char_code = ctou32(*phenostr_iter++);
2923 }
2924 if ((first_char_code - 48) < 10) {
2925 return 0;
2926 }
2927 if (first_char_code == 46) {
2928 // decimal point. classify based on whether next character is a digit.
2929 const uint32_t second_char_code = ctou32(phenostr_iter[0]);
2930 return ((second_char_code - 48) >= 10);
2931 }
2932 // allow any capitalization of "NA"/"nan", but not "inf"
2933 if ((first_char_code & 0xdf) != 78) {
2934 return 1;
2935 }
2936 const uint32_t second_char_code = ctou32(phenostr_iter[0]);
2937 if ((second_char_code & 0xdf) != 65) {
2938 return 1;
2939 }
2940 const uint32_t third_char_code = ctou32(phenostr_iter[1]);
2941 if ((third_char_code & 0xdf) == 78) {
2942 return (ctou32(phenostr_iter[2]) > ' ');
2943 }
2944 return (third_char_code > 32);
2945 }
2946
2947 uint32_t FirstCcOrQtPhenoIdx(const PhenoCol* pheno_cols, uint32_t pheno_ct) {
2948 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
2949 if (pheno_cols[pheno_idx].type_code < kPhenoDtypeCat) {
2950 return pheno_idx;
2951 }
2952 }
2953 return UINT32_MAX;
2954 }
2955
2956 uint32_t IsConstCovar(const PhenoCol* covar_col, const uintptr_t* sample_include, uint32_t raw_sample_ct) {
2957 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
2958 const uintptr_t* nonmiss = covar_col->nonmiss;
2959 if (covar_col->type_code == kPhenoDtypeQt) {
2960 const double* covar_vals = covar_col->data.qt;
2961 for (uint32_t widx = 0; widx != raw_sample_ctl; ++widx) {
2962 uintptr_t cur_bits = sample_include[widx] & nonmiss[widx];
2963 if (cur_bits) {
2964 const double first_covar_val = covar_vals[widx * kBitsPerWord + ctzw(cur_bits)];
2965 cur_bits &= cur_bits - 1;
2966 while (1) {
2967 if (cur_bits) {
2968 const double* cur_covar_vals = &(covar_vals[widx * kBitsPerWord]);
2969 do {
2970 const uint32_t bit_idx = ctzw(cur_bits);
2971 if (cur_covar_vals[bit_idx] != first_covar_val) {
2972 return 0;
2973 }
2974 cur_bits &= cur_bits - 1;
2975 } while (cur_bits);
2976 }
2977 ++widx;
2978 if (widx == raw_sample_ctl) {
2979 return 1;
2980 }
2981 cur_bits = sample_include[widx] & nonmiss[widx];
2982 }
2983 }
2984 }
2985 return 1;
2986 }
2987 assert(covar_col->type_code == kPhenoDtypeCat);
2988 const uint32_t* covar_cats = covar_col->data.cat;
2989 for (uint32_t widx = 0; widx != raw_sample_ctl; ++widx) {
2990 uintptr_t cur_bits = sample_include[widx] & nonmiss[widx];
2991 if (cur_bits) {
2992 const uint32_t first_covar_cat = covar_cats[widx * kBitsPerWord + ctzw(cur_bits)];
2993 cur_bits &= cur_bits - 1;
2994 while (1) {
2995 if (cur_bits) {
2996 const uint32_t* cur_covar_cats = &(covar_cats[widx * kBitsPerWord]);
2997 do {
2998 const uint32_t bit_idx = ctzw(cur_bits);
2999 if (cur_covar_cats[bit_idx] != first_covar_cat) {
3000 return 0;
3001 }
3002 cur_bits &= cur_bits - 1;
3003 } while (cur_bits);
3004 }
3005 ++widx;
3006 if (widx == raw_sample_ctl) {
3007 return 1;
3008 }
3009 cur_bits = sample_include[widx] & nonmiss[widx];
3010 }
3011 }
3012 }
3013 return 1;
3014 }
3015
3016 uint32_t IdentifyRemainingCats(const uintptr_t* sample_include, const PhenoCol* covar_col, uint32_t sample_ct, uintptr_t* observed_cat_bitarr) {
3017 // assumes covar_col->type_code == kPhenoTypeCat
3018 const uint32_t nonnull_cat_ct = covar_col->nonnull_category_ct;
3019 const uint32_t* covar_cats = covar_col->data.cat;
3020 const uint32_t word_ct = 1 + (nonnull_cat_ct / kBitsPerWord);
3021 ZeroWArr(word_ct, observed_cat_bitarr);
3022 uintptr_t sample_uidx_base = 0;
3023 uintptr_t cur_bits = sample_include[0];
3024 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
3025 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
3026 SetBit(covar_cats[sample_uidx], observed_cat_bitarr);
3027 }
3028 return PopcountWords(observed_cat_bitarr, word_ct);
3029 }
3030
3031 // returns index of most common category
3032 uint32_t IdentifyRemainingCatsAndMostCommon(const uintptr_t* sample_include, const PhenoCol* covar_col, uint32_t sample_ct, uintptr_t* observed_cat_bitarr, uint32_t* cat_obs_buf) {
3033 // assumes covar_col->type_code == kPhenoTypeCat
3034 const uint32_t nonnull_cat_ct = covar_col->nonnull_category_ct;
3035 const uint32_t* covar_cats = covar_col->data.cat;
3036 const uint32_t word_ct = 1 + (nonnull_cat_ct / kBitsPerWord);
3037 ZeroWArr(word_ct, observed_cat_bitarr);
3038 ZeroU32Arr(nonnull_cat_ct + 1, cat_obs_buf);
3039 uintptr_t sample_uidx_base = 0;
3040 uintptr_t cur_bits = sample_include[0];
3041 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
3042 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
3043 cat_obs_buf[covar_cats[sample_uidx]] += 1;
3044 SetBit(covar_cats[sample_uidx], observed_cat_bitarr);
3045 }
3046 if (cat_obs_buf[0]) {
3047 // don't actually need this for now since we're only calling this with the
3048 // missing category excluded, but let's be consistent.
3049 SetBit(0, observed_cat_bitarr);
3050 }
3051 uint32_t best_cat_idx = 0;
3052 uint32_t best_cat_obs_ct = 0;
3053 for (uint32_t cat_idx = 1; cat_idx <= nonnull_cat_ct; ++cat_idx) {
3054 const uint32_t cat_obs_ct = cat_obs_buf[cat_idx];
3055 if (cat_obs_ct) {
3056 SetBit(cat_idx, observed_cat_bitarr);
3057 if (cat_obs_ct > best_cat_obs_ct) {
3058 best_cat_idx = cat_idx;
3059 best_cat_obs_ct = cat_obs_ct;
3060 }
3061 }
3062 }
3063 return best_cat_idx;
3064 }
3065
3066 uint32_t GetCatSamples(const uintptr_t* sample_include_base, const PhenoCol* cat_pheno_col, uint32_t raw_sample_ctl, uint32_t sample_ct, uint32_t cat_uidx, uintptr_t* cur_cat_samples) {
3067 ZeroWArr(raw_sample_ctl, cur_cat_samples);
3068 const uint32_t* cat_vals = cat_pheno_col->data.cat;
3069 uintptr_t sample_uidx_base = 0;
3070 uintptr_t cur_bits = sample_include_base[0];
3071 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
3072 const uintptr_t sample_uidx = BitIter1(sample_include_base, &sample_uidx_base, &cur_bits);
3073 if (cat_vals[sample_uidx] == cat_uidx) {
3074 SetBit(sample_uidx, cur_cat_samples);
3075 }
3076 }
3077 return PopcountWords(cur_cat_samples, raw_sample_ctl);
3078 }
3079
3080 uint32_t RemoveExcludedCats(const uint32_t* data_cat, const uintptr_t* cat_keep_bitarr, uint32_t raw_sample_ct, uint32_t in_sample_ct, uintptr_t* sample_include) {
3081 uintptr_t sample_include_base = 0;
3082 uintptr_t sample_include_bits = sample_include[0];
3083 for (uint32_t sample_idx = 0; sample_idx != in_sample_ct; ++sample_idx) {
3084 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_include_base, &sample_include_bits);
3085 if (!IsSet(cat_keep_bitarr, data_cat[sample_uidx])) {
3086 ClearBit(sample_uidx, sample_include);
3087 }
3088 }
3089 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
3090 return PopcountWords(sample_include, raw_sample_ctl);
3091 }
3092
3093 void CleanupPhenoCols(uint32_t pheno_ct, PhenoCol* pheno_cols) {
3094 if (pheno_cols) {
3095 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
3096 vecaligned_free_cond(pheno_cols[pheno_idx].nonmiss);
3097 }
3098 free(pheno_cols);
3099 }
3100 }
3101
3102 PglErr ParseChrRanges(const char* const* argvk, const char* flagname_p, const char* errstr_append, uint32_t param_ct, uint32_t prohibit_extra_chrs, uint32_t xymt_subtract, char range_delim, ChrInfo* cip, uintptr_t* chr_mask) {
3103 PglErr reterr = kPglRetSuccess;
3104 {
3105 const char* cur_arg_ptr = argvk[1];
3106 char* token_buf = g_textbuf;
3107 const char* range_end = nullptr;
3108 uint32_t cur_param_idx = 1;
3109 uint32_t rs_len = 0;
3110 uint32_t re_len = 0;
3111 while (1) {
3112 const char* range_start;
3113 if (unlikely(ParseNextRange(argvk, param_ct, range_delim, &cur_param_idx, &cur_arg_ptr, &range_start, &rs_len, &range_end, &re_len))) {
3114 snprintf(g_logbuf, kLogbufSize, "Error: Invalid --%s parameter '%s'.\n", flagname_p, argvk[cur_param_idx]);
3115 goto ParseChrRanges_ret_INVALID_CMDLINE_WWA;
3116 }
3117 if (!range_start) {
3118 break;
3119 }
3120 // Could avoid this copy, but only at the cost of mutating argv. Which
3121 // isn't actually problematic--it's not like we have multiple threads
3122 // parsing the command line--but it's not like this is a performance
3123 // bottleneck either.
3124 // ParseNextRange() prevents buffer overflow.
3125 memcpyx(token_buf, range_start, rs_len, '\0');
3126 uint32_t chr_code_start = GetChrCodeRaw(token_buf);
3127 if (IsI32Neg(chr_code_start)) {
3128 if (unlikely(prohibit_extra_chrs)) {
3129 snprintf(g_logbuf, kLogbufSize, "Error: Invalid --%s chromosome code '%s'.\n", flagname_p, token_buf);
3130 goto ParseChrRanges_ret_INVALID_CMDLINE_WWA;
3131 }
3132 if (unlikely(range_end)) {
3133 goto ParseChrRanges_ret_INVALID_CMDLINE_NONSTD;
3134 }
3135 if (unlikely(PushLlStr(token_buf, &(cip->incl_excl_name_stack)))) {
3136 goto ParseChrRanges_ret_NOMEM;
3137 }
3138 } else {
3139 if (chr_code_start >= kMaxContigs) {
3140 chr_code_start -= xymt_subtract;
3141 }
3142 if (range_end) {
3143 memcpyx(token_buf, range_end, re_len, '\0');
3144 uint32_t chr_code_end = GetChrCodeRaw(token_buf);
3145 if (unlikely(IsI32Neg(chr_code_end))) {
3146 if (prohibit_extra_chrs) {
3147 snprintf(g_logbuf, kLogbufSize, "Error: Invalid --%s chromosome code '%s'.\n", flagname_p, range_end);
3148 goto ParseChrRanges_ret_INVALID_CMDLINE_WWA;
3149 }
3150 goto ParseChrRanges_ret_INVALID_CMDLINE_NONSTD;
3151 }
3152 if (unlikely(chr_code_end >= kMaxContigs)) {
3153 // prohibit stuff like "--chr par1-par2", "--chr x-y", "--chr x-26"
3154 snprintf(g_logbuf, kLogbufSize, "Error: --%s chromosome code '%s' cannot be the end of a range.\n", flagname_p, range_end);
3155 goto ParseChrRanges_ret_INVALID_CMDLINE_WWA;
3156 }
3157 if (unlikely(chr_code_end <= chr_code_start)) {
3158 snprintf(g_logbuf, kLogbufSize, "Error: --%s chromosome code '%s' is not greater than '%s'.\n", flagname_p, range_end, range_start);
3159 goto ParseChrRanges_ret_INVALID_CMDLINE_WWA;
3160 }
3161 FillBitsNz(chr_code_start, chr_code_end + 1, chr_mask);
3162 } else {
3163 SetBit(chr_code_start, chr_mask);
3164 }
3165 }
3166 }
3167 // no compelling reason to prohibit "--not-chr ,"
3168 }
3169 while (0) {
3170 ParseChrRanges_ret_NOMEM:
3171 reterr = kPglRetNomem;
3172 break;
3173 ParseChrRanges_ret_INVALID_CMDLINE_NONSTD:
3174 logerrputs("Error: Chromosome ranges cannot include nonstandard names.\n");
3175 reterr = kPglRetInvalidCmdline;
3176 break;
3177 ParseChrRanges_ret_INVALID_CMDLINE_WWA:
3178 WordWrapB(0);
3179 logerrputsb();
3180 logerrputs(errstr_append);
3181 reterr = kPglRetInvalidCmdline;
3182 break;
3183 }
3184 return reterr;
3185 }
3186
3187 uint32_t MultiallelicVariantPresent(const uintptr_t* variant_include, const uintptr_t* allele_idx_offsets, uint32_t variant_ct) {
3188 if (!allele_idx_offsets) {
3189 return 0;
3190 }
3191 uintptr_t variant_uidx_base = 0;
3192 uintptr_t cur_bits = variant_include[0];
3193 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
3194 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
3195 if (allele_idx_offsets[variant_uidx + 1] != allele_idx_offsets[variant_uidx] + 2) {
3196 return 1;
3197 }
3198 }
3199 return 0;
3200 }
3201
3202 uint32_t CountBiallelicVariants(const uintptr_t* variant_include, const uintptr_t* allele_idx_offsets, uint32_t variant_ct) {
3203 if (!allele_idx_offsets) {
3204 return variant_ct;
3205 }
3206 uint32_t biallelic_variant_ct = 0;
3207 uintptr_t variant_uidx_base = 0;
3208 uintptr_t cur_bits = variant_include[0];
3209 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
3210 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
3211 biallelic_variant_ct += (allele_idx_offsets[variant_uidx + 1] == allele_idx_offsets[variant_uidx] + 2);
3212 }
3213 return biallelic_variant_ct;
3214 }
3215
3216 uintptr_t CountAlleles(const uintptr_t* variant_include, const uintptr_t* allele_idx_offsets, uint32_t raw_variant_ct, uint32_t variant_ct) {
3217 if (!allele_idx_offsets) {
3218 return variant_ct * 2;
3219 }
3220 if (raw_variant_ct == variant_ct) {
3221 return allele_idx_offsets[raw_variant_ct];
3222 }
3223 uintptr_t allele_ct = 0;
3224 uint32_t variant_uidx = 0;
3225 while (variant_ct) {
3226 const uint32_t variant_uidx_start = AdvTo1Bit(variant_include, variant_uidx);
3227 variant_uidx = AdvBoundedTo0Bit(variant_include, variant_uidx_start + 1, raw_variant_ct);
3228 allele_ct += allele_idx_offsets[variant_uidx] - allele_idx_offsets[variant_uidx_start];
3229 variant_ct -= variant_uidx - variant_uidx_start;
3230 }
3231 return allele_ct;
3232 }
3233
3234 /*
3235 uintptr_t GetMaxAlleleBlockSize(const uintptr_t* __restrict variant_include, const uintptr_t* __restrict allele_idx_offsets, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t read_block_size) {
3236 uintptr_t max_allele_block_size = 2 * read_block_size;
3237 if (!allele_idx_offsets) {
3238 return max_allele_block_size;
3239 }
3240 uint32_t variant_idx = 0;
3241 uint32_t variant_uidx_end = 0;
3242 while (1) {
3243 uint32_t variant_uidx = variant_uidx_end;
3244 variant_uidx_end += read_block_size;
3245 if (variant_uidx_end > raw_variant_ct) {
3246 variant_uidx_end = raw_variant_ct;
3247 read_block_size = raw_variant_ct - variant_uidx;
3248 }
3249 uint32_t cur_variant_ct = PopcountBitRange(variant_include, variant_uidx, variant_uidx_end);
3250 if (cur_variant_ct) {
3251 const uint32_t omitted_variant_ct = read_block_size - cur_variant_ct;
3252 const uintptr_t block_size_ubound = allele_idx_offsets[variant_uidx_end] - allele_idx_offsets[variant_uidx] - (2 * omitted_variant_ct);
3253 variant_idx += cur_variant_ct;
3254 if (block_size_ubound > max_allele_block_size) {
3255 // subtract at beginning of each variant_include bitblock, add at end.
3256 uintptr_t cur_allele_block_size = 0;
3257 do {
3258 const uint32_t cur_bitblock_start = AdvTo1Bit(variant_include, variant_uidx);
3259 // deliberate underflow
3260 cur_allele_block_size -= allele_idx_offsets[cur_bitblock_start];
3261 if (variant_uidx_end - cur_bitblock_start == cur_variant_ct) {
3262 cur_allele_block_size += allele_idx_offsets[variant_uidx_end];
3263 break;
3264 }
3265 variant_uidx = AdvTo0Bit(variant_include, cur_bitblock_start);
3266 cur_allele_block_size += allele_idx_offsets[variant_uidx];
3267 cur_variant_ct -= variant_uidx - cur_bitblock_start;
3268 } while (cur_variant_ct);
3269 if (cur_allele_block_size > max_allele_block_size) {
3270 max_allele_block_size = cur_allele_block_size;
3271 }
3272 }
3273 if (variant_idx == variant_ct) {
3274 return max_allele_block_size;
3275 }
3276 }
3277 }
3278 }
3279 */
3280
3281 uintptr_t GetMaxAltAlleleBlockSize(const uintptr_t* __restrict variant_include, const uintptr_t* __restrict allele_idx_offsets, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t read_block_size) {
3282 uintptr_t max_alt_allele_block_size = read_block_size;
3283 if (!allele_idx_offsets) {
3284 return max_alt_allele_block_size;
3285 }
3286 uint32_t variant_idx = 0;
3287 for (uint32_t variant_uidx_end = 0; ; ) {
3288 uint32_t variant_uidx = variant_uidx_end;
3289 variant_uidx_end += read_block_size;
3290 if (variant_uidx_end > raw_variant_ct) {
3291 variant_uidx_end = raw_variant_ct;
3292 read_block_size = raw_variant_ct - variant_uidx;
3293 }
3294 uint32_t cur_variant_ct = PopcountBitRange(variant_include, variant_uidx, variant_uidx_end);
3295 if (cur_variant_ct) {
3296 const uint32_t omitted_variant_ct = read_block_size - cur_variant_ct;
3297 const uintptr_t cur_ubound = allele_idx_offsets[variant_uidx_end] - allele_idx_offsets[variant_uidx] - omitted_variant_ct - read_block_size;
3298 variant_idx += cur_variant_ct;
3299 if (cur_ubound > max_alt_allele_block_size) {
3300 // subtract at beginning of each variant_include bitblock, add at end.
3301 // deliberate underflow
3302 uintptr_t cur_alt_allele_block_size = -S_CAST(uintptr_t, cur_variant_ct);
3303 do {
3304 const uint32_t cur_bitblock_start = AdvTo1Bit(variant_include, variant_uidx);
3305 // deliberate underflow
3306 cur_alt_allele_block_size -= allele_idx_offsets[cur_bitblock_start];
3307 if (variant_uidx_end - cur_bitblock_start == cur_variant_ct) {
3308 cur_alt_allele_block_size += allele_idx_offsets[variant_uidx_end];
3309 break;
3310 }
3311 variant_uidx = AdvTo0Bit(variant_include, cur_bitblock_start);
3312 cur_alt_allele_block_size += allele_idx_offsets[variant_uidx];
3313 cur_variant_ct -= variant_uidx - cur_bitblock_start;
3314 } while (cur_variant_ct);
3315 if (cur_alt_allele_block_size > max_alt_allele_block_size) {
3316 max_alt_allele_block_size = cur_alt_allele_block_size;
3317 }
3318 }
3319 if (variant_idx == variant_ct) {
3320 return max_alt_allele_block_size;
3321 }
3322 }
3323 }
3324 }
3325
3326 uintptr_t GetMhcWordCt(uintptr_t sample_ct) {
3327 const uintptr_t sample_ctl = BitCtToWordCt(sample_ct);
3328 const uintptr_t patch_01_max_word_ct = sample_ctl + DivUp(sizeof(AlleleCode) * sample_ct, kBytesPerWord);
3329 const uintptr_t patch_10_max_word_ct = sample_ctl + DivUp(2 * sizeof(AlleleCode) * sample_ct, kBytesPerWord);
3330 return RoundUpPow2(patch_01_max_word_ct, kWordsPerVec) + RoundUpPow2(patch_10_max_word_ct, kWordsPerVec);
3331 }
3332
3333 PglErr PgenMtLoadInit(const uintptr_t* variant_include, uint32_t sample_ct, uint32_t variant_ct, uintptr_t bytes_avail, uintptr_t pgr_alloc_cacheline_ct, uintptr_t thread_xalloc_cacheline_ct, uintptr_t per_variant_xalloc_byte_ct, uintptr_t per_alt_allele_xalloc_byte_ct, PgenFileInfo* pgfip, uint32_t* calc_thread_ct_ptr, uintptr_t*** genovecs_ptr, uintptr_t*** mhc_ptr, uintptr_t*** phasepresent_ptr, uintptr_t*** phaseinfo_ptr, uintptr_t*** dosage_present_ptr, Dosage*** dosage_mains_ptr, uintptr_t*** dphase_present_ptr, SDosage*** dphase_delta_ptr, uint32_t* read_block_size_ptr, uintptr_t* max_alt_allele_block_size_ptr, STD_ARRAY_REF(unsigned char*, 2) main_loadbufs, PgenReader*** pgr_pps, uint32_t** read_variant_uidx_starts_ptr) {
3334 uintptr_t cachelines_avail = bytes_avail / kCacheline;
3335 uint32_t read_block_size = kPglVblockSize;
3336 uint64_t multiread_cacheline_ct;
3337 for (; ; read_block_size /= 2) {
3338 multiread_cacheline_ct = PgfiMultireadGetCachelineReq(variant_include, pgfip, variant_ct, read_block_size);
3339 // limit each raw load buffer to 1/4 of remaining workspace
3340 // if there's an additional per-variant allocation, put it in the same bin
3341 // as the load buffers
3342 if ((multiread_cacheline_ct + (S_CAST(uint64_t, per_variant_xalloc_byte_ct) * read_block_size) / kCacheline) * 4 <= cachelines_avail) {
3343 break;
3344 }
3345 // lots of callers require read_block_size to be either raw_variant_ct or a
3346 // multiple of kBitsPerVec
3347 #ifdef __LP64__
3348 if (read_block_size <= kBitsPerVec) {
3349 return kPglRetNomem;
3350 }
3351 #else
3352 if (read_block_size <= kCacheline) {
3353 return kPglRetNomem;
3354 }
3355 #endif
3356 }
3357 #ifndef __LP64__
3358 if (multiread_cacheline_ct > (kMaxBytesPerIO / kCacheline)) {
3359 return kPglRetNomem;
3360 }
3361 #endif
3362 main_loadbufs[0] = S_CAST(unsigned char*, bigstack_alloc_raw(multiread_cacheline_ct * kCacheline));
3363 main_loadbufs[1] = S_CAST(unsigned char*, bigstack_alloc_raw(multiread_cacheline_ct * kCacheline));
3364 pgfip->block_base = main_loadbufs[0];
3365 *read_block_size_ptr = read_block_size;
3366 cachelines_avail -= 2 * (multiread_cacheline_ct + (S_CAST(uint64_t, per_variant_xalloc_byte_ct) * read_block_size) / kCacheline);
3367 if (per_alt_allele_xalloc_byte_ct) {
3368 const uintptr_t max_alt_allele_block_size = GetMaxAltAlleleBlockSize(variant_include, pgfip->allele_idx_offsets, pgfip->raw_variant_ct, variant_ct, read_block_size);
3369
3370 cachelines_avail -= DivUpU64(S_CAST(uint64_t, per_alt_allele_xalloc_byte_ct) * read_block_size, kCacheline);
3371 // we assume it's unnecessary to return this if
3372 // per_alt_allele_xalloc_byte_ct is zero
3373 *max_alt_allele_block_size_ptr = max_alt_allele_block_size;
3374 }
3375 // reduce calc_thread_ct if necessary
3376 uint32_t calc_thread_ct = *calc_thread_ct_ptr;
3377 if (calc_thread_ct > read_block_size) {
3378 calc_thread_ct = read_block_size;
3379 *calc_thread_ct_ptr = calc_thread_ct;
3380 }
3381
3382 // pgr_pps, read_variant_uidx_starts_ptr, (*pgr_pps)[tidx], pgr_alloc;
3383 // deliberately a slight overestimate
3384 const uintptr_t pgr_struct_alloc = RoundUpPow2(sizeof(PgenReader), kCacheline);
3385 uintptr_t thread_alloc_cacheline_ct = 1 + 1 + (pgr_struct_alloc / kCacheline) + pgr_alloc_cacheline_ct + thread_xalloc_cacheline_ct;
3386
3387 const uint32_t sample_ctcl2 = NypCtToCachelineCt(sample_ct);
3388 const uint32_t sample_ctcl = BitCtToCachelineCt(sample_ct);
3389
3390 // todo: multiallelic dosage
3391 const uintptr_t dosage_main_cl = DivUp(sample_ct, (kCacheline / sizeof(Dosage)));
3392 uintptr_t mhc_cl = 0;
3393 if (genovecs_ptr) {
3394 thread_alloc_cacheline_ct += 1 + sample_ctcl2;
3395 if (mhc_ptr) {
3396 mhc_cl = DivUp(GetMhcWordCt(sample_ct), kWordsPerCacheline);
3397 thread_alloc_cacheline_ct += 1 + mhc_cl;
3398 }
3399 if (phasepresent_ptr) {
3400 assert(phaseinfo_ptr);
3401 thread_alloc_cacheline_ct += 2 + sample_ctcl;
3402 }
3403 if (dosage_present_ptr) {
3404 assert(dosage_mains_ptr);
3405 thread_alloc_cacheline_ct += 2 + sample_ctcl + dosage_main_cl;
3406 if (dphase_present_ptr) {
3407 assert(dphase_delta_ptr);
3408 thread_alloc_cacheline_ct += 2 + sample_ctcl + dosage_main_cl;
3409 }
3410 }
3411 }
3412 if (thread_alloc_cacheline_ct * calc_thread_ct > cachelines_avail) {
3413 if (thread_alloc_cacheline_ct > cachelines_avail) {
3414 return kPglRetNomem;
3415 }
3416 calc_thread_ct = cachelines_avail / thread_alloc_cacheline_ct;
3417 *calc_thread_ct_ptr = calc_thread_ct;
3418 }
3419
3420 const uint32_t array_of_ptrs_alloc = RoundUpPow2(calc_thread_ct * sizeof(intptr_t), kCacheline);
3421 *pgr_pps = S_CAST(PgenReader**, bigstack_alloc_raw(array_of_ptrs_alloc));
3422 *read_variant_uidx_starts_ptr = S_CAST(uint32_t*, bigstack_alloc_raw_rd(calc_thread_ct * sizeof(int32_t)));
3423 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
3424 (*pgr_pps)[tidx] = S_CAST(PgenReader*, bigstack_alloc_raw(pgr_struct_alloc));
3425 // PreinitPgr(g_pgr_ptrs[tidx]);
3426 unsigned char* pgr_alloc = S_CAST(unsigned char*, bigstack_alloc_raw(pgr_alloc_cacheline_ct * kCacheline));
3427
3428 // shouldn't be possible for this to fail
3429 PgrInit(nullptr, 0, pgfip, (*pgr_pps)[tidx], pgr_alloc);
3430 }
3431 if (genovecs_ptr) {
3432 *genovecs_ptr = S_CAST(uintptr_t**, bigstack_alloc_raw(array_of_ptrs_alloc));
3433 if (mhc_ptr) {
3434 *mhc_ptr = S_CAST(uintptr_t**, bigstack_alloc_raw(array_of_ptrs_alloc));
3435 }
3436 if (phasepresent_ptr) {
3437 *phasepresent_ptr = S_CAST(uintptr_t**, bigstack_alloc_raw(array_of_ptrs_alloc));
3438 *phaseinfo_ptr = S_CAST(uintptr_t**, bigstack_alloc_raw(array_of_ptrs_alloc));
3439 }
3440 if (dosage_present_ptr) {
3441 *dosage_present_ptr = S_CAST(uintptr_t**, bigstack_alloc_raw(array_of_ptrs_alloc));
3442 *dosage_mains_ptr = S_CAST(Dosage**, bigstack_alloc_raw(array_of_ptrs_alloc));
3443 if (dphase_present_ptr) {
3444 *dphase_present_ptr = S_CAST(uintptr_t**, bigstack_alloc_raw(array_of_ptrs_alloc));
3445 *dphase_delta_ptr = S_CAST(SDosage**, bigstack_alloc_raw(array_of_ptrs_alloc));
3446 }
3447 }
3448 const uintptr_t genovec_alloc = sample_ctcl2 * kCacheline;
3449 const uintptr_t bitarray_alloc = sample_ctcl * kCacheline;
3450 const uintptr_t dosage_main_alloc = dosage_main_cl * kCacheline;
3451 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
3452 (*genovecs_ptr)[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(genovec_alloc));
3453 if (mhc_ptr) {
3454 (*mhc_ptr)[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(mhc_cl * kCacheline));
3455 }
3456 if (phasepresent_ptr) {
3457 (*phasepresent_ptr)[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(bitarray_alloc));
3458 (*phaseinfo_ptr)[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(bitarray_alloc));
3459 }
3460 if (dosage_present_ptr) {
3461 (*dosage_present_ptr)[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(bitarray_alloc));
3462 (*dosage_mains_ptr)[tidx] = S_CAST(Dosage*, bigstack_alloc_raw(dosage_main_alloc));
3463 if (dphase_present_ptr) {
3464 (*dphase_present_ptr)[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(bitarray_alloc));
3465 (*dphase_delta_ptr)[tidx] = S_CAST(SDosage*, bigstack_alloc_raw(dosage_main_alloc));
3466 }
3467 }
3468 }
3469 }
3470 return kPglRetSuccess;
3471 }
3472
3473 uint32_t MultireadNonempty(const uintptr_t* variant_include, const ThreadGroup* tgp, uint32_t raw_variant_ct, uint32_t read_block_size, PgenFileInfo* pgfip, uint32_t* read_block_idxp, PglErr* reterrp) {
3474 if (IsLastBlock(tgp)) {
3475 return 0;
3476 }
3477 // This condition ensures the PopcountWords() calls are valid. If it's
3478 // ever inconvenient, PopcountBitRange() can be used instead.
3479 assert((!(read_block_size % kBitsPerVec)) || (raw_variant_ct <= read_block_size));
3480
3481 const uint32_t read_block_sizel = read_block_size / kBitsPerWord;
3482 uint32_t read_block_idx = *read_block_idxp;
3483 uint32_t offset = read_block_idx * read_block_size;
3484 uint32_t cur_read_block_size = read_block_size;
3485 uint32_t cur_block_write_ct;
3486 for (; ; ++read_block_idx, offset += read_block_size) {
3487 if (offset + read_block_size >= raw_variant_ct) {
3488 cur_read_block_size = raw_variant_ct - offset;
3489 // trailing bits of variant_include must not be set, otherwise this
3490 // miscounts
3491 cur_block_write_ct = PopcountWords(&(variant_include[read_block_idx * read_block_sizel]), BitCtToWordCt(cur_read_block_size));
3492 assert(cur_block_write_ct); // otherwise, IsLastBlock should be set
3493 break;
3494 }
3495 cur_block_write_ct = PopcountWords(&(variant_include[read_block_idx * read_block_sizel]), read_block_sizel);
3496 if (cur_block_write_ct) {
3497 break;
3498 }
3499 }
3500 *read_block_idxp = read_block_idx;
3501 *reterrp = PgfiMultiread(variant_include, offset, offset + cur_read_block_size, cur_block_write_ct, pgfip);
3502 return cur_block_write_ct;
3503 }
3504
3505 void ExpandMhc(uint32_t sample_ct, uintptr_t* mhc, uintptr_t** patch_01_set_ptr, AlleleCode** patch_01_vals_ptr, uintptr_t** patch_10_set_ptr, AlleleCode** patch_10_vals_ptr) {
3506 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
3507 *patch_01_set_ptr = mhc;
3508 AlleleCode* patch_01_vals = R_CAST(AlleleCode*, &(mhc[sample_ctl]));
3509 *patch_01_vals_ptr = patch_01_vals;
3510 AlleleCode* patch_01_vals_end = &(patch_01_vals[sample_ct]);
3511 AlignACToVec(&patch_01_vals_end);
3512 uintptr_t* patch_10_set = R_CAST(uintptr_t*, patch_01_vals_end);
3513 *patch_10_set_ptr = patch_10_set;
3514 *patch_10_vals_ptr = R_CAST(AlleleCode*, &(patch_10_set[sample_ctl]));
3515 }
3516
3517 // Returns 2 if resize needed (str_ct == strset_table_size / 2), 1 if OOM
3518 uint32_t StrsetAdd(unsigned char* arena_top, const char* src, uint32_t slen, uint32_t strset_table_size, char** strset, uint32_t* str_ctp, unsigned char** arena_bottom_ptr) {
3519 for (uint32_t hashval = Hashceil(src, slen, strset_table_size); ; ) {
3520 char* strset_entry = strset[hashval];
3521 if (!strset_entry) {
3522 const uint32_t str_ct = 1 + (*str_ctp);
3523 if (unlikely(str_ct * 2 > strset_table_size)) {
3524 return 2;
3525 }
3526 *str_ctp = str_ct;
3527 return S_CAST(uint32_t, StoreStringAtBase(arena_top, src, slen, arena_bottom_ptr, &(strset[hashval])));
3528 }
3529 if (strequal_unsafe(strset_entry, src, slen)) {
3530 return 0;
3531 }
3532 if (++hashval == strset_table_size) {
3533 hashval = 0;
3534 }
3535 }
3536 }
3537
3538 uint32_t StrsetAddEnd(unsigned char* arena_bottom, const char* src, uint32_t slen, uint32_t strset_table_size, char** strset, uint32_t* str_ctp, unsigned char** arena_top_ptr) {
3539 for (uint32_t hashval = Hashceil(src, slen, strset_table_size); ; ) {
3540 char* strset_entry = strset[hashval];
3541 if (!strset_entry) {
3542 const uint32_t str_ct = 1 + (*str_ctp);
3543 if (unlikely(str_ct * 2 > strset_table_size)) {
3544 return 2;
3545 }
3546 *str_ctp = str_ct;
3547 return S_CAST(uint32_t, StoreStringAtEnd(arena_bottom, src, slen, arena_top_ptr, &(strset[hashval])));
3548 }
3549 if (strequal_unsafe(strset_entry, src, slen)) {
3550 return 0;
3551 }
3552 if (++hashval == strset_table_size) {
3553 hashval = 0;
3554 }
3555 }
3556 }
3557
3558 void RepopulateStrset(char* str_iter, uint32_t str_ct, uint32_t strset_size, char** strset) {
3559 ZeroPtrArr(strset_size, strset);
3560 for (uint32_t str_idx = 0; str_idx != str_ct; ++str_idx) {
3561 char* str_end = strnul(str_iter);
3562 const uint32_t slen = str_end - str_iter;
3563 for (uint32_t hashval = Hashceil(str_iter, slen, strset_size); ; ) {
3564 char* strset_entry = strset[hashval];
3565 if (!strset_entry) {
3566 strset[hashval] = str_iter;
3567 break;
3568 }
3569 if (++hashval == strset_size) {
3570 hashval = 0;
3571 }
3572 }
3573 str_iter = &(str_end[1]);
3574 }
3575 }
3576
3577 BoolErr StrsetAddResize(unsigned char* arena_top, const char* src, uint32_t slen, uint32_t strset_table_size_max, char** strset, uint32_t* strset_table_sizep, uint32_t* str_ctp, unsigned char** arena_bottom_ptr) {
3578 uint32_t strset_table_size = *strset_table_sizep;
3579 uint32_t retval = StrsetAdd(arena_top, src, slen, strset_table_size, strset, str_ctp, arena_bottom_ptr);
3580 if (!retval) {
3581 return 0;
3582 }
3583 if (unlikely((retval == 1) || (strset_table_size == strset_table_size_max))) {
3584 return 1;
3585 }
3586 const uint32_t new_table_size = MINV(strset_table_size * 2LLU, strset_table_size_max);
3587 const uint64_t bytes_needed = sizeof(intptr_t) * (new_table_size - strset_table_size);
3588 if (S_CAST(uintptr_t, arena_top - (*arena_bottom_ptr)) < bytes_needed) {
3589 return 1;
3590 }
3591 unsigned char* old_str_base = R_CAST(unsigned char*, &(strset[strset_table_size]));
3592 unsigned char* new_str_base = R_CAST(unsigned char*, &(strset[new_table_size]));
3593 memmove(new_str_base, old_str_base, (*arena_bottom_ptr) - old_str_base);
3594 *arena_bottom_ptr += bytes_needed;
3595 RepopulateStrset(R_CAST(char*, new_str_base), *str_ctp, new_table_size, strset);
3596 *strset_table_sizep = new_table_size;
3597 return (StrsetAdd(arena_top, src, slen, new_table_size, strset, str_ctp, arena_bottom_ptr) != 0);
3598 }
3599
3600 BoolErr StrsetAddEndResize(unsigned char* arena_bottom, const char* src, uint32_t slen, uint32_t strset_table_size_max, char*** strsetp, uint32_t* strset_table_sizep, uint32_t* str_ctp, unsigned char** arena_top_ptr) {
3601 char** strset = *strsetp;
3602 uint32_t strset_table_size = *strset_table_sizep;
3603 uint32_t retval = StrsetAddEnd(arena_bottom, src, slen, strset_table_size, strset, str_ctp, arena_top_ptr);
3604 if (!retval) {
3605 return 0;
3606 }
3607 if (unlikely((retval == 1) || (strset_table_size == strset_table_size_max))) {
3608 return 1;
3609 }
3610 const uint32_t new_table_size = MINV(strset_table_size * 2LLU, strset_table_size_max);
3611 const uint64_t bytes_needed = sizeof(intptr_t) * (new_table_size - strset_table_size);
3612 unsigned char* old_str_base = *arena_top_ptr;
3613 if (unlikely(S_CAST(uintptr_t, old_str_base - arena_bottom) < bytes_needed)) {
3614 return 1;
3615 }
3616 unsigned char* new_str_base = old_str_base - bytes_needed;
3617 memmove(new_str_base, old_str_base, R_CAST(unsigned char*, strset) - old_str_base);
3618 *arena_top_ptr = new_str_base;
3619 strset -= new_table_size - strset_table_size;
3620 *strsetp = strset;
3621 RepopulateStrset(R_CAST(char*, new_str_base), *str_ctp, new_table_size, strset);
3622 *strset_table_sizep = new_table_size;
3623 return (StrsetAddEnd(arena_bottom, src, slen, new_table_size, strset, str_ctp, arena_top_ptr) != 0);
3624 }
3625
3626 PglErr WriteSampleIdsOverride(const uintptr_t* sample_include, const SampleIdInfo* siip, const char* outname, uint32_t sample_ct, SampleIdFlags override_flags) {
3627 FILE* outfile = nullptr;
3628 PglErr reterr = kPglRetSuccess;
3629 {
3630 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
3631 goto WriteSampleIdsOverride_ret_OPEN_FAIL;
3632 }
3633 const char* sample_ids = siip->sample_ids;
3634 const char* sids = siip->sids;
3635 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
3636 const uintptr_t max_sid_blen = siip->max_sid_blen;
3637 char* write_iter = g_textbuf;
3638 char* textbuf_flush = &(write_iter[kMaxMediumLine]);
3639 if (!(override_flags & kfSampleIdNoIdHeader)) {
3640 *write_iter++ = '#';
3641 if (override_flags & kfSampleIdFidPresent) {
3642 write_iter = strcpya_k(write_iter, "FID\t");
3643 } else {
3644 // every single row starts with "0\t", so this causes only IIDs to be
3645 // reported
3646 sample_ids = &(sample_ids[2]);
3647 }
3648 write_iter = strcpya_k(write_iter, "IID");
3649 if (sids) {
3650 write_iter = strcpya_k(write_iter, "\tSID");
3651 }
3652 AppendBinaryEoln(&write_iter);
3653 } else {
3654 if (override_flags & kfSampleIdNoIdHeaderIidOnly) {
3655 // We've previously verified that all FIDs are in fact '0'.
3656 sample_ids = &(sample_ids[2]);
3657 }
3658 sids = nullptr;
3659 }
3660 uintptr_t sample_uidx_base = 0;
3661 uintptr_t cur_bits = sample_include[0];
3662 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
3663 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
3664 write_iter = strcpya(write_iter, &(sample_ids[sample_uidx * max_sample_id_blen]));
3665 if (sids) {
3666 *write_iter++ = '\t';
3667 write_iter = strcpya(write_iter, &(sids[sample_uidx * max_sid_blen]));
3668 }
3669 AppendBinaryEoln(&write_iter);
3670 if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
3671 goto WriteSampleIdsOverride_ret_WRITE_FAIL;
3672 }
3673 }
3674 if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) {
3675 goto WriteSampleIdsOverride_ret_WRITE_FAIL;
3676 }
3677 }
3678 while (0) {
3679 WriteSampleIdsOverride_ret_OPEN_FAIL:
3680 reterr = kPglRetOpenFail;
3681 break;
3682 WriteSampleIdsOverride_ret_WRITE_FAIL:
3683 reterr = kPglRetWriteFail;
3684 break;
3685 }
3686 fclose_cond(outfile);
3687 return reterr;
3688 }
3689
3690 uint32_t RealpathIdentical(const char* outname, const char* read_realpath, char* write_realpath_buf) {
3691 #ifdef _WIN32
3692 const uint32_t fname_slen = GetFullPathName(outname, kPglFnamesize, write_realpath_buf, nullptr);
3693 return (fname_slen && (fname_slen <= kPglFnamesize) && memequal(read_realpath, write_realpath_buf, fname_slen + 1));
3694 #else
3695 return (realpath(outname, write_realpath_buf) && strequal_overread(read_realpath, write_realpath_buf));
3696 #endif
3697 }
3698
3699 char* PrintMultiallelicHcAsDs(uint32_t hc1, uint32_t hc2, uint32_t allele_ct, char* start) {
3700 if (hc1 == kMissingAlleleCode) {
3701 *start++ = '.';
3702 return start;
3703 }
3704 for (uint32_t uii = 1; uii < hc1; ++uii) {
3705 start = strcpya_k(start, "0,");
3706 }
3707 if (hc1 == hc2) {
3708 if (hc1) {
3709 start = strcpya_k(start, "2,");
3710 }
3711 for (uint32_t uii = hc1 + 1; uii != allele_ct; ++uii) {
3712 start = strcpya_k(start, "0,");
3713 }
3714 return &(start[-1]);
3715 }
3716 if (hc1) {
3717 start = strcpya_k(start, "1,");
3718 }
3719 for (uint32_t uii = hc1 + 1; uii != hc2; ++uii) {
3720 start = strcpya_k(start, "0,");
3721 }
3722 start = strcpya_k(start, "1,");
3723 for (uint32_t uii = hc2 + 1; uii != allele_ct; ++uii) {
3724 start = strcpya_k(start, "0,");
3725 }
3726 return &(start[-1]);
3727 }
3728
3729 char* PrintMultiallelicHcAsHaploidDs(uint32_t hc1, uint32_t hc2, uint32_t allele_ct, char* start) {
3730 if (hc1 == kMissingAlleleCode) {
3731 *start++ = '.';
3732 return start;
3733 }
3734 for (uint32_t uii = 1; uii < hc1; ++uii) {
3735 start = strcpya_k(start, "0,");
3736 }
3737 if (hc1 == hc2) {
3738 if (hc1) {
3739 start = strcpya_k(start, "1,");
3740 }
3741 for (uint32_t uii = hc1 + 1; uii != allele_ct; ++uii) {
3742 start = strcpya_k(start, "0,");
3743 }
3744 return &(start[-1]);
3745 }
3746 if (hc1) {
3747 start = strcpya_k(start, "0.5,");
3748 }
3749 for (uint32_t uii = hc1 + 1; uii != hc2; ++uii) {
3750 start = strcpya_k(start, "0,");
3751 }
3752 start = strcpya_k(start, "0.5,");
3753 for (uint32_t uii = hc2 + 1; uii != allele_ct; ++uii) {
3754 start = strcpya_k(start, "0,");
3755 }
3756 return &(start[-1]);
3757 }
3758
3759 const char g_vft_names[3][18] = {"extract", "extract-intersect", "exclude"};
3760
3761 void PgenErrPrintEx(const char* file_descrip, uint32_t prepend_lf, PglErr reterr, uint32_t variant_uidx) {
3762 if (reterr == kPglRetReadFail) {
3763 if (prepend_lf) {
3764 logputs("\n");
3765 }
3766 logerrprintfww(kErrprintfFread, file_descrip, rstrerror(errno));
3767 } else if (reterr == kPglRetMalformedInput) {
3768 if (prepend_lf) {
3769 logputs("\n");
3770 }
3771 if (variant_uidx == UINT32_MAX) {
3772 logerrprintfww("Error: Failed to unpack variant in %s.\n", file_descrip);
3773 } else {
3774 logerrprintfww("Error: Failed to unpack (0-based) variant #%u in %s.\n", variant_uidx, file_descrip);
3775 }
3776 logerrputs("You can use --validate to check whether it is malformed.\n* If it is malformed, you probably need to either re-download the file, or\n address an error in the command that generated the input .pgen.\n* If it appears to be valid, you have probably encountered a plink2 bug. If\n you report the error on GitHub or the plink2-users Google group (make sure to\n include the full .log file in your report), we'll try to address it.\n");
3777 }
3778 }
3779
3780 void PgenWriteFinishErrPrint(PglErr reterr, char* outname, char* outname_end) {
3781 // This mirrors include/pgenlib_write.cc PwcFinish().
3782 if (reterr == kPglRetOpenFail) {
3783 // Only way this can happen is if .pgen.tmp reopen fails.
3784 logputs("\n");
3785 snprintf(outname_end, kMaxOutfnameExtBlen, ".pgen.tmp");
3786 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
3787 } else if (reterr == kPglRetRewindFail) {
3788 logputs("\n");
3789 snprintf(outname_end, kMaxOutfnameExtBlen, ".pgen.tmp");
3790 logerrprintfww("Error: %s is malformed.\n", outname);
3791 }
3792 }
3793
3794 // Given <outname>.tmp.pgen and <outname>.tmp.pgen.pgi, this generates
3795 // <outname>.pgen and then deletes the two temporary files.
3796 // TODO: add a third pgenlib_write mode which takes care of this automatically.
3797 // At the minimal cost of one extra malloc/free (for the base filename string),
3798 // we avoid the need to create a temporary index file.
3799 PglErr EmbedPgenIndex(char* outname, char* outname_end) {
3800 FILE* infile = nullptr;
3801 FILE* outfile = nullptr;
3802 PglErr reterr = kPglRetSuccess;
3803 {
3804 strcpy_k(outname_end, ".pgen");
3805 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
3806 goto EmbedPgenIndex_ret_OPEN_FAIL;
3807 }
3808 strcpy_k(outname_end, ".tmp.pgen.pgi");
3809 if (unlikely(fopen_checked(outname, FOPEN_RB, &infile))) {
3810 goto EmbedPgenIndex_ret_OPEN_FAIL;
3811 }
3812 if (unlikely(fseeko(infile, 0, SEEK_END))) {
3813 goto EmbedPgenIndex_ret_READ_PGI_FAIL;
3814 }
3815 const uint64_t pgi_fsize = ftello(infile);
3816 if (unlikely(pgi_fsize < 20)) {
3817 goto EmbedPgenIndex_ret_INVALID_INDEX;
3818 }
3819 rewind(infile);
3820 uint32_t variant_ct;
3821 {
3822 char startbuf[12];
3823 if (unlikely(!fread(startbuf, 12, 1, infile))) {
3824 goto EmbedPgenIndex_ret_READ_PGI_FAIL;
3825 }
3826 if (unlikely(!memequal_sk(startbuf, "l\x1b\x30"))) {
3827 goto EmbedPgenIndex_ret_INVALID_INDEX;
3828 }
3829 memcpy(&variant_ct, &(startbuf[3]), 4);
3830 // May allow variant_ct == 0 later.
3831 if (unlikely((!variant_ct) || (variant_ct > kPglMaxVariantCt))) {
3832 goto EmbedPgenIndex_ret_INVALID_INDEX;
3833 }
3834 startbuf[2] = 0x10;
3835 if (unlikely(!fwrite_unlocked(startbuf, 12, 1, outfile))) {
3836 goto EmbedPgenIndex_ret_WRITE_FAIL;
3837 }
3838 }
3839 {
3840 const uint32_t vblock_ct = DivUp(variant_ct, kPglVblockSize);
3841 // The next (vblock_ct * 8) bytes of the .pgen.pgi file are a
3842 // random-access index, reporting the byte positions that variants 0,
3843 // 65536, 131072, etc. start at in the .pgen.
3844 // We must increment these positions by (pgi_fsize - 3), since the .pgen
3845 // without an embedded index has only 3 header bytes.
3846 if (unlikely(pgi_fsize < 12 + vblock_ct * 8)) {
3847 goto EmbedPgenIndex_ret_INVALID_INDEX;
3848 }
3849 const uint32_t kPglFwriteBlockSizeD8 = kPglFwriteBlockSize / 8;
3850 const uint64_t offset_incr = pgi_fsize - 3;
3851 uint32_t remaining_vblock_ct = vblock_ct;
3852 uint64_t offset_buf[kPglFwriteBlockSizeD8];
3853 while (remaining_vblock_ct > kPglFwriteBlockSizeD8) {
3854 if (unlikely(!fread(offset_buf, kPglFwriteBlockSize, 1, infile))) {
3855 goto EmbedPgenIndex_ret_READ_PGI_FAIL;
3856 }
3857 for (uint32_t uii = 0; uii != kPglFwriteBlockSizeD8; ++uii) {
3858 offset_buf[uii] += offset_incr;
3859 }
3860 if (unlikely(!fwrite_unlocked(offset_buf, kPglFwriteBlockSize, 1, outfile))) {
3861 goto EmbedPgenIndex_ret_WRITE_FAIL;
3862 }
3863 remaining_vblock_ct -= kPglFwriteBlockSizeD8;
3864 }
3865 if (unlikely(!fread(offset_buf, remaining_vblock_ct * 8, 1, infile))) {
3866 goto EmbedPgenIndex_ret_READ_PGI_FAIL;
3867 }
3868 for (uint32_t uii = 0; uii != remaining_vblock_ct; ++uii) {
3869 offset_buf[uii] += offset_incr;
3870 }
3871 if (unlikely(!fwrite_unlocked(offset_buf, remaining_vblock_ct * 8, 1, outfile))) {
3872 goto EmbedPgenIndex_ret_WRITE_FAIL;
3873 }
3874 }
3875 while (1) {
3876 unsigned char copybuf[kPglFwriteBlockSize];
3877 uintptr_t nbyte = fread(copybuf, 1, kPglFwriteBlockSize, infile);
3878 if (!nbyte) {
3879 break;
3880 }
3881 if (unlikely(!fwrite_unlocked(copybuf, nbyte, 1, outfile))) {
3882 goto EmbedPgenIndex_ret_WRITE_FAIL;
3883 }
3884 }
3885 if (unlikely(fclose_null(&infile))) {
3886 goto EmbedPgenIndex_ret_READ_PGI_FAIL;
3887 }
3888 strcpy_k(outname_end, ".tmp.pgen");
3889 if (unlikely(fopen_checked(outname, FOPEN_RB, &infile))) {
3890 goto EmbedPgenIndex_ret_OPEN_FAIL;
3891 }
3892 unsigned char copybuf[kPglFwriteBlockSize + 3];
3893 uintptr_t nbyte = fread(copybuf, 1, kPglFwriteBlockSize + 3, infile);
3894 if (unlikely((nbyte <= 3) || (!memequal_sk(copybuf, "l\x1b\x20")))) {
3895 logerrprintfww("Error: %s does not appear to be a .pgen with an external index file.\n", outname);
3896 goto EmbedPgenIndex_ret_MALFORMED_INPUT;
3897 }
3898 nbyte -= 3;
3899 if (unlikely(!fwrite_unlocked(&(copybuf[3]), nbyte, 1, outfile))) {
3900 goto EmbedPgenIndex_ret_WRITE_FAIL;
3901 }
3902 while (1) {
3903 nbyte = fread(copybuf, 1, kPglFwriteBlockSize, infile);
3904 if (!nbyte) {
3905 break;
3906 }
3907 if (unlikely(!fwrite_unlocked(copybuf, nbyte, 1, outfile))) {
3908 goto EmbedPgenIndex_ret_WRITE_FAIL;
3909 }
3910 }
3911 if (unlikely(fclose_null(&infile))) {
3912 goto EmbedPgenIndex_ret_READ_PGEN_FAIL;
3913 }
3914 if (unlikely(fclose_null(&outfile))) {
3915 goto EmbedPgenIndex_ret_WRITE_FAIL;
3916 }
3917 if (unlikely(unlink(outname))) {
3918 logerrprintfww("Error: Failed to delete %s .\n", outname);
3919 goto EmbedPgenIndex_ret_WRITE_FAIL;
3920 }
3921 strcpy_k(outname_end, ".tmp.pgen.pgi");
3922 if (unlikely(unlink(outname))) {
3923 logerrprintfww("Error: Failed to delete %s .\n", outname);
3924 goto EmbedPgenIndex_ret_WRITE_FAIL;
3925 }
3926 }
3927 while (0) {
3928 EmbedPgenIndex_ret_OPEN_FAIL:
3929 reterr = kPglRetOpenFail;
3930 break;
3931 EmbedPgenIndex_ret_READ_PGI_FAIL:
3932 // strcpy_k(outname_end, ".tmp.pgen.pgi");
3933 logerrprintfww(kErrprintfFread, outname, rstrerror(errno));
3934 reterr = kPglRetReadFail;
3935 break;
3936 EmbedPgenIndex_ret_READ_PGEN_FAIL:
3937 // strcpy_k(outname_end, ".tmp.pgen");
3938 logerrprintfww(kErrprintfFread, outname, rstrerror(errno));
3939 reterr = kPglRetReadFail;
3940 break;
3941 EmbedPgenIndex_ret_WRITE_FAIL:
3942 reterr = kPglRetWriteFail;
3943 break;
3944 EmbedPgenIndex_ret_INVALID_INDEX:
3945 // strcpy_k(outname_end, ".tmp.pgen.pgi");
3946 logerrprintfww("Error: %s does not appear to be a .pgen index file.\n", outname);
3947 EmbedPgenIndex_ret_MALFORMED_INPUT:
3948 reterr = kPglRetMalformedInput;
3949 break;
3950 }
3951 fclose_cond(outfile);
3952 fclose_cond(infile);
3953 return reterr;
3954 }
3955
3956 CXXCONST_CP HkvlineValEnd(const char* val_start) {
3957 if (val_start[0] != '"') {
3958 const char* val_end = strchrnul2_n(val_start, ',', '>');
3959 if (unlikely(*val_end == '\n')) {
3960 return nullptr;
3961 }
3962 return S_CAST(CXXCONST_CP, val_end);
3963 }
3964 const char* val_iter = &(val_start[1]);
3965 while (1) {
3966 val_iter = strchrnul2_n(val_iter, '\\', '"');
3967 if (*val_iter == '"') {
3968 break;
3969 }
3970 if (unlikely((*val_iter != '\\') || (val_iter[1] < 32))) {
3971 return nullptr;
3972 }
3973 val_iter = &(val_iter[2]);
3974 }
3975 const char* val_end = &(val_iter[1]);
3976 if (likely((*val_end == ',') || (*val_end == '>'))) {
3977 return S_CAST(CXXCONST_CP, val_end);
3978 }
3979 return nullptr;
3980 }
3981
3982 IntErr HkvlineFind2K(const char* dict_iter, const char* key, uint32_t key_slen, const char** val_ptr, uint32_t* val_slenp) {
3983 while (1) {
3984 if (dict_iter[-1] == '>') {
3985 return 1;
3986 }
3987 const char* val_prestart = strchrnul_n(dict_iter, '=');
3988 if (unlikely(*val_prestart == '\n')) {
3989 return 2;
3990 }
3991 const char* val_start = &(val_prestart[1]);
3992 const char* val_end = HkvlineValEnd(val_start);
3993 if (unlikely(val_end == nullptr)) {
3994 return 2;
3995 }
3996 if ((S_CAST(uintptr_t, val_prestart - dict_iter) == key_slen) && memequal(dict_iter, key, key_slen)) {
3997 *val_ptr = val_start;
3998 *val_slenp = val_end - val_start;
3999 return 0;
4000 }
4001 dict_iter = &(val_end[1]);
4002 }
4003 }
4004
4005 BoolErr HkvlineNumTypeK(const char* dict_iter, const char** numstr_ptr, uint32_t* num_slenp, const char** typestr_ptr, uint32_t* type_slenp) {
4006 uint32_t need_numstr = 1;
4007 uint32_t need_typestr = 1;
4008 while (1) {
4009 // Note that this is true on the first iteration when ID is the only key.
4010 if (unlikely(dict_iter[-1] == '>')) {
4011 return 1;
4012 }
4013 const char* val_prestart = strchrnul_n(dict_iter, '=');
4014 if (unlikely(*val_prestart == '\n')) {
4015 return 1;
4016 }
4017 const char* val_start = &(val_prestart[1]);
4018 const char* val_end = HkvlineValEnd(val_start);
4019 if (unlikely(val_end == nullptr)) {
4020 return 1;
4021 }
4022 const uint32_t key_slen = val_prestart - dict_iter;
4023 if (need_numstr && strequal_k(dict_iter, "Number", key_slen)) {
4024 *numstr_ptr = val_start;
4025 *num_slenp = val_end - val_start;
4026 if (!need_typestr) {
4027 return 0;
4028 }
4029 need_numstr = 0;
4030 } else if (need_typestr && strequal_k(dict_iter, "Type", key_slen)) {
4031 *typestr_ptr = val_start;
4032 *type_slenp = val_end - val_start;
4033 if (!need_numstr) {
4034 return 0;
4035 }
4036 need_typestr = 0;
4037 }
4038 ++dict_iter;
4039 }
4040 }
4041
4042 PglErr HkvlineForceIdFirst(uintptr_t workspace_size, char* hline_kv_start, void* workspace) {
4043 if (memequal_sk(hline_kv_start, "ID=")) {
4044 return kPglRetSuccess;
4045 }
4046 char* idval;
4047 uint32_t id_slen;
4048 if (unlikely(HkvlineFind(hline_kv_start, "ID", &idval, &id_slen))) {
4049 return kPglRetMalformedInput;
4050 }
4051 const uintptr_t tmp_nbyte = id_slen + (3 * k1LU);
4052 if (tmp_nbyte > workspace_size) {
4053 return kPglRetNomem;
4054 }
4055 char* idkey_start = &(idval[-3]);
4056 char* workspace_c = S_CAST(char*, workspace);
4057 memcpy(workspace_c, idkey_start, tmp_nbyte);
4058 memmove(&(hline_kv_start[tmp_nbyte + 1]), hline_kv_start, &(idkey_start[-1]) - hline_kv_start);
4059 memcpy(hline_kv_start, workspace_c, tmp_nbyte);
4060 hline_kv_start[tmp_nbyte] = ',';
4061 return kPglRetSuccess;
4062 }
4063
4064 PglErr NsortDedupAndWrite(const char* outname, uintptr_t str_ct, uint32_t max_slen, uint32_t output_zst, uint32_t max_thread_ct, const char** strptr_arr, uintptr_t* nwrite_ptr) {
4065 unsigned char* bigstack_mark = g_bigstack_base;
4066 char* cswritep = nullptr;
4067 CompressStreamState css;
4068 PglErr reterr = kPglRetSuccess;
4069 PreinitCstream(&css);
4070 {
4071 StrptrArrNsort(str_ct, strptr_arr);
4072 const uintptr_t overflow_buf_size = kCompressStreamBlock + strlen(EOLN_STR) + max_slen;
4073 reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, overflow_buf_size, &css, &cswritep);
4074 if (unlikely(reterr)) {
4075 goto NsortDedupAndWrite_ret_1;
4076 }
4077 const char* prev_id = nullptr;
4078 uintptr_t dup_ct = 0;
4079 uint32_t prev_slen = 0;
4080 for (uintptr_t ulii = 0; ulii != str_ct; ++ulii) {
4081 const char* cur_id = strptr_arr[ulii];
4082 const uint32_t cur_slen = strlen(cur_id);
4083 if ((cur_slen == prev_slen) && memequal(prev_id, cur_id, prev_slen)) {
4084 ++dup_ct;
4085 continue;
4086 }
4087 cswritep = memcpya(cswritep, cur_id, cur_slen);
4088 AppendBinaryEoln(&cswritep);
4089 if (unlikely(Cswrite(&css, &cswritep))) {
4090 goto NsortDedupAndWrite_ret_WRITE_FAIL;
4091 }
4092 prev_id = cur_id;
4093 prev_slen = cur_slen;
4094 }
4095 if (unlikely(CswriteCloseNull(&css, cswritep))) {
4096 goto NsortDedupAndWrite_ret_WRITE_FAIL;
4097 }
4098 *nwrite_ptr = str_ct - dup_ct;
4099 }
4100 while (0) {
4101 NsortDedupAndWrite_ret_WRITE_FAIL:
4102 reterr = kPglRetWriteFail;
4103 break;
4104 }
4105 NsortDedupAndWrite_ret_1:
4106 CswriteCloseCond(&css, cswritep);
4107 BigstackReset(bigstack_mark);
4108 return reterr;
4109 }
4110
4111 typedef struct VariantLastAlidxMakerStruct {
4112 const uintptr_t* allele_idx_offsets;
4113 uint32_t raw_variant_ct;
4114
4115 // Bit k is set iff it's equal to (allele_idx_offsets[x] - 1) for some x.
4116 // This has the property that PopcountBitRange(0, allele_idx) = variant_uidx.
4117 uintptr_t* variant_last_alidxs;
4118 uint32_t* variant_last_alidxs_cumulative_popcounts;
4119 } VariantLastAlidxMaker;
4120
4121 void VariantLastAlidxMakerMain(uint32_t tidx, uint32_t thread_ct, VariantLastAlidxMaker* ctx) {
4122 const uintptr_t* allele_idx_ends = &(ctx->allele_idx_offsets[1]);
4123 const uint32_t raw_variant_ct = ctx->raw_variant_ct;
4124 const uintptr_t raw_allele_ct = ctx->allele_idx_offsets[raw_variant_ct];
4125 const uintptr_t raw_allele_ctl = BitCtToWordCt(raw_allele_ct);
4126 const uintptr_t cacheline_ct = DivUp(raw_allele_ctl, kWordsPerCacheline);
4127
4128 const uintptr_t widx_start = kWordsPerCacheline * ((cacheline_ct * S_CAST(uint64_t, tidx)) / thread_ct);
4129 const uintptr_t widx_stop = (tidx + 1 == thread_ct)? (raw_allele_ctl - 1) : (kWordsPerCacheline * ((cacheline_ct * (S_CAST(uint64_t, tidx) + 1)) / thread_ct));
4130 uintptr_t* alidxs = ctx->variant_last_alidxs;
4131 uint32_t* alidxs_cumulative_popcounts = ctx->variant_last_alidxs_cumulative_popcounts;
4132
4133 uint32_t cur_vidx = 0;
4134 if (tidx) {
4135 // How many variants end before or at allele_idx == widx_start *
4136 // kBitsPerWord?
4137 cur_vidx = UpperBoundNonemptyW(allele_idx_ends, raw_variant_ct, widx_start * kBitsPerWord);
4138 }
4139 // This is >= widx_start * kBitsPerWord.
4140 uintptr_t cur_allele_idx = allele_idx_ends[cur_vidx] - 1;
4141
4142 uintptr_t cur_allele_widx = cur_allele_idx / kBitsPerWord;
4143 for (uintptr_t widx = widx_start; widx != widx_stop; ++widx) {
4144 alidxs_cumulative_popcounts[widx] = cur_vidx;
4145 uintptr_t cur_word = 0;
4146 if (cur_allele_widx == widx) {
4147 uint32_t shift_ct = cur_allele_idx % kBitsPerWord;
4148 // fast path when multiallelic variants are rare.
4149 const uint32_t speculate_ct = (kBitsPerWord + 1 - shift_ct) / 2;
4150 const uint32_t speculative_vidx = cur_vidx + speculate_ct;
4151 if ((speculative_vidx < raw_variant_ct) && (allele_idx_ends[speculative_vidx] == cur_allele_idx + 1 + speculate_ct * 2)) {
4152 // next speculate_ct variants must all be biallelic
4153 cur_word = kMask5555 << shift_ct;
4154 cur_vidx = speculative_vidx;
4155 cur_allele_idx += speculate_ct * 2;
4156 ++cur_allele_widx;
4157 } else {
4158 while (1) {
4159 cur_word |= k1LU << shift_ct;
4160 ++cur_vidx;
4161 cur_allele_idx = allele_idx_ends[cur_vidx] - 1;
4162 cur_allele_widx = cur_allele_idx / kBitsPerWord;
4163 if (cur_allele_widx != widx) {
4164 break;
4165 }
4166 shift_ct = cur_allele_idx % kBitsPerWord;
4167 }
4168 }
4169 }
4170 alidxs[widx] = cur_word;
4171 }
4172 if (tidx + 1 == thread_ct) {
4173 alidxs_cumulative_popcounts[widx_stop] = cur_vidx;
4174 uintptr_t cur_word = 0;
4175 while (1) {
4176 cur_word |= k1LU << (cur_allele_idx % kBitsPerWord);
4177 ++cur_vidx;
4178 if (cur_vidx == raw_variant_ct) {
4179 break;
4180 }
4181 cur_allele_idx = allele_idx_ends[cur_vidx] - 1;
4182 }
4183 alidxs[widx_stop] = cur_word;
4184 }
4185 }
4186
4187 THREAD_FUNC_DECL VariantLastAlidxMakerThread(void* raw_arg) {
4188 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
4189 const uint32_t tidx = arg->tidx;
4190 VariantLastAlidxMaker* ctx = S_CAST(VariantLastAlidxMaker*, arg->sharedp->context);
4191
4192 const uint32_t thread_ct = GetThreadCt(arg->sharedp) + 1;
4193 VariantLastAlidxMakerMain(tidx, thread_ct, ctx);
4194 THREAD_RETURN;
4195 }
4196
4197 PglErr AllocAndFillVariantLastAlidxs(const uintptr_t* allele_idx_offsets, uint32_t raw_variant_ct, uint32_t max_thread_ct, const uintptr_t** variant_last_alidxsp, const uint32_t** variant_last_alidxs_cumulative_popcountsp) {
4198 if (!allele_idx_offsets) {
4199 *variant_last_alidxsp = nullptr;
4200 *variant_last_alidxs_cumulative_popcountsp = nullptr;
4201 return kPglRetSuccess;
4202 }
4203 PglErr reterr = kPglRetSuccess;
4204 ThreadGroup tg;
4205 PreinitThreads(&tg);
4206 VariantLastAlidxMaker ctx;
4207 {
4208 const uintptr_t raw_allele_ct = allele_idx_offsets[raw_variant_ct];
4209 const uintptr_t raw_allele_ctl = BitCtToWordCt(raw_allele_ct);
4210 if (unlikely(bigstack_alloc_w(raw_allele_ctl, &ctx.variant_last_alidxs) ||
4211 bigstack_alloc_u32(raw_allele_ctl, &ctx.variant_last_alidxs_cumulative_popcounts))) {
4212 goto AllocAndFillVariantLastAlidxs_ret_NOMEM;
4213 }
4214 ctx.allele_idx_offsets = allele_idx_offsets;
4215 ctx.raw_variant_ct = raw_variant_ct;
4216 uint32_t thread_ct = raw_variant_ct / 65536;
4217 if (!thread_ct) {
4218 thread_ct = 1;
4219 } else if (thread_ct > max_thread_ct) {
4220 thread_ct = max_thread_ct;
4221 }
4222 if (unlikely(SetThreadCt0(thread_ct - 1, &tg))) {
4223 goto AllocAndFillVariantLastAlidxs_ret_NOMEM;
4224 }
4225 if (thread_ct > 1) {
4226 SetThreadFuncAndData(VariantLastAlidxMakerThread, &ctx, &tg);
4227 DeclareLastThreadBlock(&tg);
4228 if (unlikely(SpawnThreads(&tg))) {
4229 goto AllocAndFillVariantLastAlidxs_ret_THREAD_CREATE_FAIL;
4230 }
4231 }
4232 VariantLastAlidxMakerMain(thread_ct - 1, thread_ct, &ctx);
4233 JoinThreads0(&tg);
4234 *variant_last_alidxsp = ctx.variant_last_alidxs;
4235 *variant_last_alidxs_cumulative_popcountsp = ctx.variant_last_alidxs_cumulative_popcounts;
4236 }
4237 while (0) {
4238 AllocAndFillVariantLastAlidxs_ret_NOMEM:
4239 reterr = kPglRetNomem;
4240 break;
4241 AllocAndFillVariantLastAlidxs_ret_THREAD_CREATE_FAIL:
4242 reterr = kPglRetThreadCreateFail;
4243 break;
4244 }
4245 CleanupThreads(&tg);
4246 return reterr;
4247 }
4248
4249 void GetBpWindow(const uintptr_t* variant_include, const uint32_t* variant_bps, uint32_t variant_uidx, uint32_t bp_radius, uint32_t* start_vidxp, uint32_t* end_vidxp) {
4250 assert(IsSet(variant_include, variant_uidx));
4251 const uint32_t center_bp = variant_bps[variant_uidx];
4252 {
4253 const uint32_t search_start_vidx = *start_vidxp;
4254 if (variant_uidx > search_start_vidx) {
4255 uint32_t first_bp = 0;
4256 if (center_bp > bp_radius) {
4257 first_bp = center_bp - bp_radius;
4258 }
4259 const uint32_t start_vidx = LowerBoundConstrainedNonemptyU32(variant_bps, search_start_vidx, variant_uidx, first_bp);
4260 *start_vidxp = AdvTo1Bit(variant_include, start_vidx);
4261 }
4262 }
4263 const uint32_t search_start_vidx = variant_uidx + 1;
4264 const uint32_t search_end_vidx = *end_vidxp;
4265 if (search_start_vidx < search_end_vidx) {
4266 const uint32_t end_vidx = LowerBoundConstrainedNonemptyU32(variant_bps, search_start_vidx, search_end_vidx, center_bp + bp_radius + 1);
4267 *end_vidxp = 1 + FindLast1BitBefore(variant_include, end_vidx);
4268 }
4269 }
4270
4271 PgenGlobalFlags GflagsVfilter(const uintptr_t* variant_include, const unsigned char* vrtypes, uint32_t raw_variant_ct, PgenGlobalFlags input_gflags) {
4272 PgenGlobalFlags read_gflags = kfPgenGlobal0;
4273 if (!vrtypes) {
4274 return input_gflags;
4275 }
4276 const uintptr_t* vrtypes_alias = R_CAST(const uintptr_t*, vrtypes);
4277 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
4278 uint32_t mask_multiply = ((input_gflags & kfPgenGlobalHardcallPhasePresent)? 0x10 : 0) + ((input_gflags & kfPgenGlobalDosagePresent)? 0x60 : 0) + ((input_gflags & kfPgenGlobalDosagePhasePresent)? 0x80 : 0);
4279 uintptr_t vrtypes_or = 0;
4280 // todo: try changing loop to be vec-based, use movemask to extract
4281 // information from vrtypes in 64-bit cases
4282 for (uint32_t widx = 0; widx != raw_variant_ctl; ++widx) {
4283 uintptr_t cur_variant_include_word = variant_include[widx];
4284 if (cur_variant_include_word) {
4285 // bugfix (20 Aug 2018): this needs to advance on every variant_include
4286 // word, not just the nonzero ones
4287 const uintptr_t* cur_vrtypes = &(vrtypes_alias[8 * widx]);
4288 #ifdef __LP64__
4289 for (uint32_t vi_byte_idx = 0; vi_byte_idx != 8; ++vi_byte_idx) {
4290 # ifdef USE_AVX2
4291 // this doesn't seem to be much faster than non-AVX2 code on my Mac...
4292 // inverse-movemask shouldn't be better than regular movemask here
4293 const uintptr_t cur_mask = _pdep_u64(cur_variant_include_word, kMask0101);
4294 # else
4295 // this operation maps binary hgfedcba to h0000000g0000000f...
4296 // ^ ^ ^
4297 // | | |
4298 // 56 48 40
4299 // 1. (cur_variant_include_word & 0xfe) gives us hgfedcb0;
4300 // necessary to avoid carryover.
4301 // 2. multiply by the number with bits 7, 14, 21, ..., 49 set, to
4302 // get hgfedcbhgfedcbhgf...
4303 // ^ ^ ^
4304 // | | |
4305 // 56 48 40
4306 // 3. mask out all but bits 8, 16, 24, ..., 56
4307 // todo: test if this actually beats the per-character loop...
4308 const uintptr_t cur_mask = (((cur_variant_include_word & 0xfe) * 0x2040810204080LLU) & kMask0101) | (cur_variant_include_word & 1);
4309 # endif
4310 vrtypes_or |= cur_vrtypes[vi_byte_idx] & (cur_mask * mask_multiply);
4311 cur_variant_include_word >>= 8;
4312 }
4313 #else
4314 for (uint32_t vi_hexa_idx = 0; vi_hexa_idx != 8; ++vi_hexa_idx) {
4315 // dcba -> d0000000c0000000b0000000a
4316 const uintptr_t cur_mask = ((cur_variant_include_word & 0xf) * 0x204081) & kMask0101;
4317 vrtypes_or |= cur_vrtypes[vi_hexa_idx] & (cur_mask * mask_multiply);
4318 cur_variant_include_word >>= 4;
4319 }
4320 #endif
4321 if (vrtypes_or) {
4322 // bugfix (8 Oct 2017): forgot to multiply by kMask0101
4323 if (vrtypes_or & (0x10 * kMask0101)) {
4324 read_gflags |= kfPgenGlobalHardcallPhasePresent;
4325 mask_multiply -= 0x10;
4326 }
4327 if (vrtypes_or & (0x60 * kMask0101)) {
4328 read_gflags |= kfPgenGlobalDosagePresent;
4329 mask_multiply -= 0x60;
4330 }
4331 if (vrtypes_or & (0x80 * kMask0101)) {
4332 read_gflags |= kfPgenGlobalDosagePhasePresent;
4333 mask_multiply -= 0x80;
4334 }
4335 if (!mask_multiply) {
4336 return read_gflags;
4337 }
4338 }
4339 }
4340 }
4341 return read_gflags;
4342 }
4343
4344 uint32_t TriangleDivide(int64_t cur_prod_x2, int32_t modif) {
4345 // return smallest integer vv for which (vv * (vv + modif)) is no smaller
4346 // than cur_prod_x2, and neither term in the product is negative.
4347 int64_t vv;
4348 if (cur_prod_x2 == 0) {
4349 if (modif < 0) {
4350 return -modif;
4351 }
4352 return 0;
4353 }
4354 vv = S_CAST(int64_t, sqrt(S_CAST(double, cur_prod_x2)));
4355 while ((vv - 1) * (vv + modif - 1) >= cur_prod_x2) {
4356 vv--;
4357 }
4358 while (vv * (vv + modif) < cur_prod_x2) {
4359 vv++;
4360 }
4361 return vv;
4362 }
4363
4364 void ParallelBounds(uint32_t ct, int32_t start, uint32_t parallel_idx, uint32_t parallel_tot, int32_t* __restrict bound_start_ptr, int32_t* __restrict bound_end_ptr) {
4365 int32_t modif = 1 - start * 2;
4366 int64_t ct_tot = S_CAST(int64_t, ct) * (ct + modif);
4367 *bound_start_ptr = TriangleDivide((ct_tot * parallel_idx) / parallel_tot, modif);
4368 *bound_end_ptr = TriangleDivide((ct_tot * (parallel_idx + 1)) / parallel_tot, modif);
4369 }
4370
4371 void AppendZerotabsUnsafe(uint32_t zerotab_ct, char** cswritep_ptr) {
4372 // (roughly same performance as creating a zero-tab constant buffer in
4373 // advance)
4374 const uint32_t word_ct = DivUp(zerotab_ct, kBytesPerWord / 2);
4375 const uintptr_t zerotab_word = 0x930 * kMask0001;
4376 char* cswritep = *cswritep_ptr;
4377 for (uint32_t widx = 0; widx != word_ct; ++widx) {
4378 CAppendW(zerotab_word, &cswritep);
4379 }
4380 *cswritep_ptr = &((*cswritep_ptr)[2 * zerotab_ct]);
4381 }
4382
4383 typedef struct InitAllelePermuteCtxStruct {
4384 const uintptr_t* allele_idx_offsets;
4385 uint32_t raw_variant_ct;
4386
4387 AlleleCode* allele_permute;
4388 } InitAllelePermuteCtx;
4389
4390 void InitAllelePermuteMain(uintptr_t tidx, uintptr_t thread_ct, InitAllelePermuteCtx* ctx) {
4391 const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
4392 const uintptr_t* allele_idx_offset_ends = &(allele_idx_offsets[1]);
4393 const uint32_t raw_variant_ct = ctx->raw_variant_ct;
4394 const uint32_t variant_uidx_start = (raw_variant_ct * S_CAST(uint64_t, tidx)) / thread_ct;
4395 const uint32_t variant_uidx_end = (raw_variant_ct * (S_CAST(uint64_t, tidx) + 1)) / thread_ct;
4396 uintptr_t allele_idx_offset_start = allele_idx_offsets[variant_uidx_start];
4397 AlleleCode* allele_permute_iter = &(ctx->allele_permute[allele_idx_offset_start]);
4398 // could fill with zeroes first?
4399 for (uint32_t vidx = variant_uidx_start; vidx != variant_uidx_end; ++vidx) {
4400 const uintptr_t allele_idx_offset_end = allele_idx_offset_ends[vidx];
4401 const uint32_t allele_ct = allele_idx_offset_end - allele_idx_offset_start;
4402 for (uint32_t aidx = 0; aidx != allele_ct; ++aidx) {
4403 *allele_permute_iter++ = aidx;
4404 }
4405 allele_idx_offset_start = allele_idx_offset_end;
4406 }
4407 }
4408
4409 THREAD_FUNC_DECL InitAllelePermuteThread(void* raw_arg) {
4410 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
4411 const uint32_t tidx = arg->tidx;
4412 InitAllelePermuteCtx* ctx = S_CAST(InitAllelePermuteCtx*, arg->sharedp->context);
4413
4414 const uint32_t thread_ct = GetThreadCt(arg->sharedp) + 1;
4415 InitAllelePermuteMain(tidx, thread_ct, ctx);
4416 THREAD_RETURN;
4417 }
4418
4419 PglErr InitAllelePermuteUnsafe(const uintptr_t* allele_idx_offsets, uint32_t raw_variant_ct, uint32_t max_thread_ct, AlleleCode* allele_permute) {
4420 if (!allele_idx_offsets) {
4421 uintptr_t* allele_permute_ul = R_CAST(uintptr_t*, allele_permute);
4422 const uintptr_t allele_code_range_size = k1LU << (8 * sizeof(AlleleCode));
4423 const uintptr_t fill_word = ((~k0LU) / ((allele_code_range_size - 1) * (allele_code_range_size + 1))) * allele_code_range_size;
4424 const uintptr_t word_ct = DivUp(raw_variant_ct, sizeof(intptr_t) / (sizeof(AlleleCode) * 2));
4425 for (uintptr_t widx = 0; widx != word_ct; ++widx) {
4426 allele_permute_ul[widx] = fill_word;
4427 }
4428 return kPglRetSuccess;
4429 }
4430 assert(allele_idx_offsets[raw_variant_ct] > raw_variant_ct * 2);
4431 PglErr reterr = kPglRetSuccess;
4432 ThreadGroup tg;
4433 PreinitThreads(&tg);
4434 InitAllelePermuteCtx ctx;
4435 {
4436 ctx.allele_idx_offsets = allele_idx_offsets;
4437 ctx.raw_variant_ct = raw_variant_ct;
4438 ctx.allele_permute = allele_permute;
4439 uint32_t thread_ct = raw_variant_ct / 65536;
4440 if (!thread_ct) {
4441 thread_ct = 1;
4442 } else if (thread_ct > max_thread_ct) {
4443 thread_ct = max_thread_ct;
4444 }
4445 if (unlikely(SetThreadCt0(thread_ct - 1, &tg))) {
4446 goto InitAllelePermuteUnsafe_ret_NOMEM;
4447 }
4448 if (thread_ct > 1) {
4449 SetThreadFuncAndData(InitAllelePermuteThread, &ctx, &tg);
4450 DeclareLastThreadBlock(&tg);
4451 if (unlikely(SpawnThreads(&tg))) {
4452 goto InitAllelePermuteUnsafe_ret_THREAD_CREATE_FAIL;
4453 }
4454 }
4455 InitAllelePermuteMain(thread_ct - 1, thread_ct, &ctx);
4456 JoinThreads0(&tg);
4457 }
4458 while (0) {
4459 InitAllelePermuteUnsafe_ret_NOMEM:
4460 reterr = kPglRetNomem;
4461 break;
4462 InitAllelePermuteUnsafe_ret_THREAD_CREATE_FAIL:
4463 reterr = kPglRetThreadCreateFail;
4464 break;
4465 }
4466 CleanupThreads(&tg);
4467 return reterr;
4468 }
4469
4470 #ifdef __cplusplus
4471 } // namespace plink2
4472 #endif