Debian Codegraph @

plink2_data.cc

raw
1 // This file is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
2 // Christopher Chang.
3 //
4 // This program is free software: you can redistribute it and/or modify it
5 // under the terms of the GNU General Public License as published by the Free
6 // Software Foundation, either version 3 of the License, or (at your option)
7 // any later version.
8 //
9 // This program 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 General Public License for
12 // more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17
18 #include "include/pgenlib_write.h"
19 #include "plink2_compress_stream.h"
20 #include "plink2_data.h"
21 #include "plink2_pvar.h"
22
23 #include <time.h> // time()
24 #include <unistd.h> // unlink()
25
26 #ifdef __cplusplus
27 namespace plink2 {
28 #endif
29
30 PglErr WriteMapOrBim(const char* outname, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* allele_presents, const AlleleCode* allele_permute, const double* variant_cms, uint32_t variant_ct, uint32_t max_allele_slen, char delim, char output_missing_geno_char, uint32_t output_zst, uint32_t thread_ct) {
31 // - Normally generates a .bim file. Set max_allele_slen to zero to generate
32 // a .map.
33 // - allele_presents must be nullptr unless we're trimming alt alleles.
34 // - Errors out when writing .bim if any remaining variant is multiallelic
35 // and allele_permute is nullptr.
36 // - Multiallelic-split case is handled by WriteBimSplit().
37 unsigned char* bigstack_mark = g_bigstack_base;
38 char* cswritep = nullptr;
39 CompressStreamState css;
40 PglErr reterr = kPglRetSuccess;
41 PreinitCstream(&css);
42 {
43 const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
44 // includes trailing tab
45 char* chr_buf;
46 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
47 goto WriteMapOrBim_ret_NOMEM;
48 }
49 const uintptr_t overflow_buf_size = kCompressStreamBlock + kMaxIdSlen + 512 + 2 * max_allele_slen;
50 reterr = InitCstreamAlloc(outname, 0, output_zst, thread_ct, overflow_buf_size, &css, &cswritep);
51 if (unlikely(reterr)) {
52 goto WriteMapOrBim_ret_1;
53 }
54
55 uintptr_t variant_uidx_base = 0;
56 uintptr_t cur_bits = variant_include[0];
57 uint32_t chr_fo_idx = UINT32_MAX;
58 uint32_t chr_end = 0;
59 uint32_t chr_buf_blen = 0;
60 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
61 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
62 if (variant_uidx >= chr_end) {
63 do {
64 ++chr_fo_idx;
65 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
66 } while (variant_uidx >= chr_end);
67 char* chr_name_end = chrtoa(cip, cip->chr_file_order[chr_fo_idx], chr_buf);
68 *chr_name_end = delim;
69 chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
70 }
71 cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
72 cswritep = strcpyax(cswritep, variant_ids[variant_uidx], delim);
73 if (!variant_cms) {
74 *cswritep++ = '0';
75 } else {
76 cswritep = dtoa_g_p8(variant_cms[variant_uidx], cswritep);
77 }
78 *cswritep++ = delim;
79 cswritep = u32toa(variant_bps[variant_uidx], cswritep);
80 if (max_allele_slen) {
81 *cswritep++ = delim;
82 uintptr_t allele_idx_offset_base = variant_uidx * 2;
83 if (allele_idx_offsets) {
84 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
85 if (!allele_permute) {
86 const uintptr_t allele_idx_offset_end = allele_idx_offsets[variant_uidx + 1];
87 if (allele_idx_offset_end != allele_idx_offset_base + 2) {
88 // not actually unlikely at this point, but simplest to stay
89 // consistent
90 // see e.g. https://www.biostars.org/p/9531649/ for a reason NOT
91 // to mention --max-alleles in the error message
92 if (unlikely((!allele_presents) || (!AllBitsAreZero(allele_presents, 2 + allele_idx_offset_base, allele_idx_offset_end)))) {
93 logputs("\n");
94 logerrprintfww("Error: %s cannot contain multiallelic variants.\n", outname);
95 goto WriteMapOrBim_ret_INCONSISTENT_INPUT;
96 }
97 }
98 }
99 }
100 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
101 // note that VCF ref allele corresponds to A2, not A1
102 if (!allele_permute) {
103 if ((!allele_presents) || IsSet(allele_presents, 1 + allele_idx_offset_base)) {
104 cswritep = strcpya(cswritep, cur_alleles[1]);
105 } else {
106 *cswritep++ = output_missing_geno_char;
107 }
108 *cswritep++ = delim;
109 cswritep = strcpya(cswritep, cur_alleles[0]);
110 } else {
111 const AlleleCode* cur_allele_permute = &(allele_permute[allele_idx_offset_base]);
112 if ((!allele_presents) || IsSet(allele_presents, cur_allele_permute[1] + allele_idx_offset_base)) {
113 cswritep = strcpya(cswritep, cur_alleles[cur_allele_permute[1]]);
114 } else {
115 *cswritep++ = output_missing_geno_char;
116 }
117 *cswritep++ = delim;
118 cswritep = strcpya(cswritep, cur_alleles[cur_allele_permute[0]]);
119 }
120 }
121 AppendBinaryEoln(&cswritep);
122 if (unlikely(Cswrite(&css, &cswritep))) {
123 goto WriteMapOrBim_ret_WRITE_FAIL;
124 }
125 }
126 if (unlikely(CswriteCloseNull(&css, cswritep))) {
127 goto WriteMapOrBim_ret_WRITE_FAIL;
128 }
129 }
130 while (0) {
131 WriteMapOrBim_ret_NOMEM:
132 reterr = kPglRetNomem;
133 break;
134 WriteMapOrBim_ret_WRITE_FAIL:
135 reterr = kPglRetWriteFail;
136 break;
137 WriteMapOrBim_ret_INCONSISTENT_INPUT:
138 reterr = kPglRetInconsistentInput;
139 break;
140 }
141 WriteMapOrBim_ret_1:
142 CswriteCloseCond(&css, cswritep);
143 BigstackReset(bigstack_mark);
144 return reterr;
145 }
146
147 PglErr PvarInfoReloadHeader(TextStream* pvar_reload_txsp, char** line_iterp, uint32_t* info_col_idx_ptr) {
148 char* line_iter;
149 do {
150 PglErr reterr = TextNextLineLstrip(pvar_reload_txsp, &line_iter);
151 if (unlikely(reterr)) {
152 return reterr;
153 }
154 } while (!StrStartsWithUnsafe(line_iter, "#CHROM"));
155 uint32_t info_col_idx = 0;
156 do {
157 line_iter = NextToken(line_iter);
158 ++info_col_idx;
159 } while (!tokequal_k(line_iter, "INFO"));
160 *line_iterp = line_iter;
161 *info_col_idx_ptr = info_col_idx;
162 return kPglRetSuccess;
163 }
164
165 // May use all remaining workspace memory.
166 PglErr PvarInfoOpenAndReloadHeader(const char* pvar_info_reload, uint32_t calc_thread_ct, TextStream* pvar_reload_txsp, char** line_iterp, uint32_t* info_col_idx_ptr) {
167 PglErr reterr = SizeAndInitTextStream(pvar_info_reload, bigstack_left(), calc_thread_ct, pvar_reload_txsp);
168 if (unlikely(reterr)) {
169 return reterr;
170 }
171 return PvarInfoReloadHeader(pvar_reload_txsp, line_iterp, info_col_idx_ptr);
172 }
173
174 void PvarInfoWrite(uint32_t info_pr_flag_present, uint32_t is_pr, char* info_token, char** write_iter_ptr) {
175 char* info_token_end = CurTokenEnd(info_token);
176 uint32_t info_token_slen = info_token_end - info_token;
177 char* info_token_pr = nullptr;
178 if (info_pr_flag_present) {
179 info_token_pr = InfoPrStart(info_token_slen, info_token);
180 }
181 char* write_iter = *write_iter_ptr;
182 if (is_pr || (!info_token_pr)) {
183 write_iter = memcpya(write_iter, info_token, info_token_slen);
184 if (is_pr && (!info_token_pr)) {
185 if ((info_token_slen == 1) && (info_token[0] == '.')) {
186 write_iter[-1] = 'P';
187 *write_iter++ = 'R';
188 } else {
189 write_iter = strcpya_k(write_iter, ";PR");
190 }
191 }
192 } else {
193 // possible with --real-ref-alleles/--ref-from-fa
194 if (info_token_pr == info_token) {
195 if (info_token_slen == 2) {
196 *write_iter++ = '.';
197 } else {
198 write_iter = memcpya(write_iter, &(info_token[3]), info_token_slen - 3);
199 }
200 } else {
201 write_iter = memcpya(write_iter, info_token, S_CAST(uintptr_t, info_token_pr - info_token) - 1);
202 const char* pr_end = &(info_token_pr[2]);
203 write_iter = memcpya(write_iter, pr_end, info_token_end - pr_end);
204 }
205 }
206 *write_iter_ptr = write_iter;
207 }
208
209 PglErr PvarInfoReload(uint32_t info_col_idx, uint32_t variant_uidx, TextStream* pvar_reload_txsp, char** line_iterp, uint32_t* trs_variant_uidx_ptr) {
210 uint32_t trs_variant_uidx = *trs_variant_uidx_ptr;
211 char* line_iter = AdvPastDelim(*line_iterp, '\n');
212 if (trs_variant_uidx < variant_uidx) {
213 TextSetPos(line_iter, pvar_reload_txsp);
214 PglErr reterr = TextSkipNz(variant_uidx - trs_variant_uidx, pvar_reload_txsp);
215 if (unlikely(reterr)) {
216 return reterr;
217 }
218 line_iter = TextLineEnd(pvar_reload_txsp);
219 trs_variant_uidx = variant_uidx;
220 }
221 PglErr reterr = TextNextLineLstripUnsafe(pvar_reload_txsp, &line_iter);
222 if (unlikely(reterr)) {
223 return reterr;
224 }
225 *line_iterp = NextTokenMultFar(line_iter, info_col_idx);
226
227 // index *after* just-loaded line.
228 *trs_variant_uidx_ptr = trs_variant_uidx + 1;
229 return kPglRetSuccess;
230 }
231
232 PglErr PvarInfoReloadAndWrite(uint32_t info_pr_flag_present, uint32_t info_col_idx, uint32_t variant_uidx, uint32_t is_pr, TextStream* pvar_reload_txsp, char** line_iterp, char** write_iter_ptr, uint32_t* trs_variant_uidx_ptr) {
233 PglErr reterr = PvarInfoReload(info_col_idx, variant_uidx, pvar_reload_txsp, line_iterp, trs_variant_uidx_ptr);
234 if (unlikely(reterr)) {
235 return reterr;
236 }
237 PvarInfoWrite(info_pr_flag_present, is_pr, *line_iterp, write_iter_ptr);
238 return kPglRetSuccess;
239 }
240
241 PglErr PvarInfoPermuteWrite(const AlleleCode* cur_allele_permute, const char* const* info_keys, const uint32_t* info_keys_htable, const char* variant_id, const char* info_subtoken_iter, uint32_t info_keys_htable_size, uint32_t allele_ct, uint32_t is_pr, char** write_iter_ptr, const char** info_allele_val_starts, uint32_t* info_allele_val_slens) {
242 const char* info_token_end = CurTokenEnd(info_subtoken_iter);
243 const uint32_t info_token_slen = info_token_end - info_subtoken_iter;
244 char* write_iter = *write_iter_ptr;
245 if ((info_token_slen == 1) && (info_subtoken_iter[0] == '.')) {
246 if (is_pr) {
247 write_iter = strcpya_k(write_iter, "PR");
248 } else {
249 *write_iter++ = '.';
250 }
251 *write_iter_ptr = write_iter;
252 return kPglRetSuccess;
253 }
254 // Some logic shared with WritePvar{Split,Join}() and merge.
255 while (1) {
256 const char* info_subtoken_end = AdvToDelimOrEnd(info_subtoken_iter, info_token_end, ';');
257 const char* key_end = AdvToDelimOrEnd(info_subtoken_iter, info_subtoken_end, '=');
258 const uint32_t key_slen = key_end - info_subtoken_iter;
259 const uint32_t kidx = IdHtableFindNnt(info_subtoken_iter, info_keys, info_keys_htable, key_slen, info_keys_htable_size);
260 if (unlikely(kidx == UINT32_MAX)) {
261 logputs("\n");
262 if (key_slen <= 77) {
263 char* err_write_iter = strcpya_k(g_logbuf, "Error: INFO key '");
264 err_write_iter = memcpya(err_write_iter, info_subtoken_iter, key_slen);
265 err_write_iter = strcpya_k(err_write_iter, "' for variant ID '");
266 err_write_iter = strcpya(err_write_iter, variant_id);
267 strcpy_k(err_write_iter, "' missing from header.\n");
268 } else {
269 // key_slen could overflow buffer, so don't unconditionally print it.
270 // (Threshold could be a lot higher, but .log readability goes down
271 // past 77.)
272 snprintf(g_logbuf, kLogbufSize, "Error: INFO key for variant ID '%s' missing from header.\n", variant_id);
273 }
274 WordWrapB(0);
275 logerrputsb();
276 return kPglRetMalformedInput;
277 }
278 const int32_t knum = const_container_of(info_keys[kidx], InfoVtype, key)->num;
279 if (knum != kInfoVtypeSkip) {
280 if (key_end == info_subtoken_end) {
281 if (unlikely(knum)) {
282 logputs("\n");
283 logerrprintfww("Error: INFO key '%s' for variant ID '%s' does not have an accompanying value.\n", info_keys[kidx], variant_id);
284 return kPglRetMalformedInput;
285 }
286 write_iter = memcpyax(write_iter, info_subtoken_iter, key_slen, ';');
287 } else {
288 if (unlikely(!knum)) {
289 logputs("\n");
290 logerrprintfww("Error: INFO key '%s' for variant ID '%s' has an accompanying value, despite being of type Flag.\n", info_keys[kidx], variant_id);
291 return kPglRetMalformedInput;
292 }
293 if ((!IsInfoVtypeARSkip(knum)) || strequal_k(key_end, "=.", info_subtoken_end - key_end)) {
294 // No reordering.
295 // Considered expanding =. to =.,.,. here since the VCF specification
296 // does not make it obvious that the former is allowed for Number=A
297 // and Number=R, but decided against it because it would be
298 // inconsistent with how INFO for non-permuted variants is left
299 // unchanged.
300 write_iter = memcpyax(write_iter, info_subtoken_iter, info_subtoken_end - info_subtoken_iter, ';');
301 } else {
302 // Number=A or Number=R.
303 // For Number=A, we associate a missing value with the original REF
304 // allele.
305 write_iter = memcpyax(write_iter, info_subtoken_iter, key_slen, '=');
306 info_subtoken_iter = &(key_end[1]);
307 const uint32_t aidx_start = knum - kInfoVtypeR;
308 if (knum == kInfoVtypeA) {
309 info_allele_val_starts[0] = &(g_one_char_strs[92]); // '.'
310 info_allele_val_slens[0] = 1;
311 }
312 for (uint32_t read_aidx = aidx_start; ; ) {
313 const char* val_end = AdvToDelimOrEnd(info_subtoken_iter, info_subtoken_end, ',');
314 info_allele_val_starts[read_aidx] = info_subtoken_iter;
315 info_allele_val_slens[read_aidx] = val_end - info_subtoken_iter;
316 ++read_aidx;
317 if (val_end == info_subtoken_end) {
318 if (unlikely(read_aidx != allele_ct)) {
319 logputs("\n");
320 logerrprintfww("Error: Too few values for INFO key '%s', variant ID '%s'.\n", info_keys[kidx], variant_id);
321 return kPglRetMalformedInput;
322 }
323 break;
324 }
325 if (unlikely(read_aidx == allele_ct)) {
326 logputs("\n");
327 logerrprintfww("Error: Too many values for INFO key '%s', variant ID '%s'.\n", info_keys[kidx], variant_id);
328 return kPglRetMalformedInput;
329 }
330 info_subtoken_iter = &(val_end[1]);
331 }
332 for (uint32_t write_aidx = aidx_start; write_aidx != allele_ct; ++write_aidx) {
333 const uint32_t read_aidx = cur_allele_permute[write_aidx];
334 write_iter = memcpyax(write_iter, info_allele_val_starts[read_aidx], info_allele_val_slens[read_aidx], ',');
335 }
336 write_iter[-1] = ';';
337 }
338 }
339 }
340 if (info_subtoken_end == info_token_end) {
341 break;
342 }
343 info_subtoken_iter = &(info_subtoken_end[1]);
344 }
345 if (is_pr) {
346 write_iter = strcpya_k(write_iter, "PR");
347 } else {
348 --write_iter;
349 }
350 *write_iter_ptr = write_iter;
351 return kPglRetSuccess;
352 }
353
354 PglErr PvarInfoPermuteReloadAndWrite(const AlleleCode* cur_allele_permute, const char* const* info_keys, const uint32_t* info_keys_htable, const char* variant_id, uint32_t info_col_idx, uint32_t info_keys_htable_size, uint32_t variant_uidx, uint32_t allele_ct, uint32_t is_pr, TextStream* pvar_reload_txsp, char** line_iterp, char** write_iter_ptr, uint32_t* trs_variant_uidx_ptr, const char** info_allele_val_starts, uint32_t* info_allele_val_slens) {
355 PglErr reterr = PvarInfoReload(info_col_idx, variant_uidx, pvar_reload_txsp, line_iterp, trs_variant_uidx_ptr);
356 if (unlikely(reterr)) {
357 return reterr;
358 }
359 return PvarInfoPermuteWrite(cur_allele_permute, info_keys, info_keys_htable, variant_id, *line_iterp, info_keys_htable_size, allele_ct, is_pr, write_iter_ptr, info_allele_val_starts, info_allele_val_slens);
360 }
361
362 void AppendChrsetLine(const ChrInfo* cip, char** write_iter_ptr) {
363 char* write_iter = strcpya_k(*write_iter_ptr, "##chrSet=<ID=1,");
364 if (!(cip->haploid_mask[0] & 1)) {
365 write_iter = strcpya_k(write_iter, "autosomePairCt=");
366 write_iter = u32toa(cip->autosome_ct, write_iter);
367 if (!IsI32Neg(cip->xymt_codes[kChrOffsetX])) {
368 write_iter = strcpya_k(write_iter, ",X");
369 }
370 if (!IsI32Neg(cip->xymt_codes[kChrOffsetY])) {
371 write_iter = strcpya_k(write_iter, ",Y");
372 }
373 if (!IsI32Neg(cip->xymt_codes[kChrOffsetXY])) {
374 write_iter = strcpya_k(write_iter, ",XY");
375 }
376 if (!IsI32Neg(cip->xymt_codes[kChrOffsetMT])) {
377 write_iter = strcpya_k(write_iter, ",M");
378 }
379 if (!IsI32Neg(cip->xymt_codes[kChrOffsetPAR1])) {
380 write_iter = strcpya_k(write_iter, ",PAR1");
381 }
382 if (!IsI32Neg(cip->xymt_codes[kChrOffsetPAR2])) {
383 write_iter = strcpya_k(write_iter, ",PAR2");
384 }
385 } else {
386 write_iter = strcpya_k(write_iter, "haploidAutosomeCt=");
387 write_iter = u32toa(cip->autosome_ct, write_iter);
388 }
389 *write_iter++ = '>';
390 *write_iter_ptr = write_iter;
391 AppendBinaryEoln(write_iter_ptr);
392 }
393
394 // fileformat, fileDate, source
395 void AppendVcfHeaderStart(uint32_t v43, char** cswritepp) {
396 char* cswritep = *cswritepp;
397 cswritep = strcpya_k(cswritep, "##fileformat=VCFv4.");
398 *cswritep++ = v43 + '2';
399 cswritep = strcpya_k(cswritep, EOLN_STR "##fileDate=");
400 time_t rawtime;
401 time(&rawtime);
402 const struct tm* loctime = localtime(&rawtime);
403 cswritep += strftime(cswritep, kMaxMediumLine, "%Y%m%d", loctime);
404 cswritep = strcpya_k(cswritep, EOLN_STR "##source=PLINKv2.0" EOLN_STR);
405 *cswritepp = cswritep;
406 return;
407 }
408
409 /*
410 // Note that the order-of-operations page lists this as happening right after
411 // the filtering performed by LoadPvar(). Which is effectively true, since we
412 // ignore variant_include (this is safe since LoadPvar() always initializes
413 // all variant_bps[] and allele_storage[] entries appropriately).
414 // possible todo: ChrInfo can have a length field, which is initialized by the
415 // ##contig header line when possible, but when that doesn't exist LoadPvar()
416 // can conditionally detect INFO/END and take that into account. (Or a reason
417 // to keep the entire info_end array in memory may emerge.)
418 //
419 // Update (10 Apr 2022): Discontinuing lower-bound length= entries in exported
420 // VCF/BCF headers, since --fa can now be used whenever length values are
421 // needed.
422 uint32_t ChrLenLbound(const ChrInfo* cip, const uint32_t* variant_bps, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uint32_t* new_variant_idx_to_old, uint32_t chr_fo_idx, uint32_t max_allele_slen, UnsortedVar vpos_sortstatus) {
423 const uint32_t vidx_start = cip->chr_fo_vidx_start[chr_fo_idx];
424 const uint32_t vidx_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
425 assert(vidx_start != vidx_end);
426 if (!(vpos_sortstatus & kfUnsortedVarBp)) {
427 if (!new_variant_idx_to_old) {
428 if (max_allele_slen == 1) {
429 return variant_bps[vidx_end - 1];
430 }
431 uint32_t bp_end = 0;
432 for (uint32_t vidx = vidx_end; vidx != vidx_start; ) {
433 --vidx;
434 const uint32_t cur_bp = variant_bps[vidx];
435 if (cur_bp + max_allele_slen <= bp_end) {
436 break;
437 }
438 uintptr_t allele_idx_offset_base = vidx * 2;
439 if (allele_idx_offsets) {
440 allele_idx_offset_base = allele_idx_offsets[vidx];
441 }
442 // We only care about reference-allele length.
443 const uint32_t cur_bp_end = cur_bp + strlen(allele_storage[allele_idx_offset_base]) - 1;
444 if (cur_bp_end > bp_end) {
445 bp_end = cur_bp_end;
446 }
447 }
448 return bp_end;
449 }
450 if (max_allele_slen == 1) {
451 return variant_bps[new_variant_idx_to_old[vidx_end - 1]];
452 }
453 uint32_t bp_end = 0;
454 for (uint32_t new_vidx = vidx_end; new_vidx != vidx_start; ) {
455 --new_vidx;
456 const uint32_t old_vidx = new_variant_idx_to_old[new_vidx];
457 const uint32_t cur_bp = variant_bps[old_vidx];
458 if (cur_bp + max_allele_slen <= bp_end) {
459 break;
460 }
461 uintptr_t allele_idx_offset_base = old_vidx * 2;
462 if (allele_idx_offsets) {
463 allele_idx_offset_base = allele_idx_offsets[old_vidx];
464 }
465 const uint32_t cur_bp_end = cur_bp + strlen(allele_storage[allele_idx_offset_base]) - 1;
466 if (cur_bp_end > bp_end) {
467 bp_end = cur_bp_end;
468 }
469 }
470 return bp_end;
471 }
472 uint32_t bp_end = U32ArrMax(&(variant_bps[vidx_start]), vidx_end - vidx_start);
473 if (max_allele_slen == 1) {
474 return bp_end;
475 }
476 uint32_t min_check_bp = 0;
477 if (bp_end >= max_allele_slen) {
478 min_check_bp = bp_end + 1 - max_allele_slen;
479 }
480 for (uint32_t vidx = vidx_start; vidx != vidx_end; ++vidx) {
481 const uint32_t cur_bp = variant_bps[vidx];
482 if (cur_bp < min_check_bp) {
483 continue;
484 }
485 uintptr_t allele_idx_offset_base = vidx * 2;
486 if (allele_idx_offsets) {
487 allele_idx_offset_base = allele_idx_offsets[vidx];
488 }
489 const uint32_t cur_bp_end = cur_bp + strlen(allele_storage[allele_idx_offset_base]) - 1;
490 if (cur_bp_end > bp_end) {
491 bp_end = cur_bp_end;
492 }
493 }
494 return bp_end;
495 }
496 */
497
498 uint64_t FindContigHeaderLineLengthStr(const char* contig_line_end) {
499 // Similar to BcfHeaderLineIdxCheck() in plink2_import.cc.
500 // It would be simpler to insist on a null-terminated input string and then
501 // just use strstr() to search for ",length="; that would almost always do
502 // the right thing. But the VCF specification allows that substring to also
503 // appear in e.g. the middle of a Description value.
504 const char* line_iter = contig_line_end;
505 uint64_t retval = 0;
506 while (1) {
507 const char* tag_start = &(line_iter[1]);
508 if (memequal_sk(tag_start, "length=")) {
509 if (unlikely(retval)) {
510 logerrputs("Error: Malformed ##contig line in .pvar file (multiple length= fields).\n");
511 return UINT64_MAX;
512 }
513 line_iter = &(tag_start[7]);
514 if (unlikely(*line_iter == '"')) {
515 logerrputs("Error: Malformed ##contig line in .pvar file (length= field has string instead\nof integer value).\n");
516 return UINT64_MAX;
517 }
518 retval = line_iter - contig_line_end;
519 line_iter = strchrnul2_n(line_iter, ',', '>');
520 retval |= S_CAST(uint64_t, line_iter - contig_line_end) << 32;
521 if (*line_iter == ',') {
522 continue;
523 }
524 if (unlikely(*line_iter == '\n')) {
525 logerrputs("Error: Malformed ##contig line in .pvar file (no '>' terminator).\n");
526 return UINT64_MAX;
527 }
528 return retval;
529 }
530 line_iter = AdvPastDelim(tag_start, '=');
531 if (*line_iter != '"') {
532 line_iter = strchrnul_n(line_iter, ',');
533 if (*line_iter == ',') {
534 continue;
535 }
536 // Could also verify that there's a '>'-terminator?
537 return retval;
538 }
539 // Need to worry about backslash-escaped characters.
540 ++line_iter;
541 while (1) {
542 line_iter = strchrnul2_n(line_iter, '\\', '"');
543 const char cc = *line_iter;
544 if (cc == '"') {
545 break;
546 }
547 if (unlikely((cc == '\n') || (line_iter[1] == '\n'))) {
548 logerrputs("Error: Malformed ##contig line in .pvar file (no '>' terminator).\n");
549 return UINT64_MAX;
550 }
551 line_iter = &(line_iter[2]);
552 }
553 ++line_iter;
554 const char cc = *line_iter;
555 if (cc == ',') {
556 continue;
557 }
558 if (likely(cc == '>')) {
559 return retval;
560 }
561 logerrputs("Error: Malformed ##contig line in .pvar file (string value doesn't end with\ncomma or '>').\n");
562 return UINT64_MAX;
563 }
564 }
565
566 char* WriteRestOfHeaderLine(const char* hkvline_iter, const char* idval, const char* closing_gt, uint32_t id_slen, char* write_iter) {
567 if (idval > hkvline_iter) {
568 // Copy entries before ",ID=".
569 const char* idkey_prestart = &(idval[-4]);
570 *write_iter++ = ',';
571 write_iter = memcpya(write_iter, hkvline_iter, idkey_prestart - hkvline_iter);
572 }
573 const char* idval_end = &(idval[id_slen]);
574 return memcpya(write_iter, idval_end, closing_gt - idval_end);
575 }
576
577 // Read: assumes hkvline_iter, idval, and id_slen are return values from
578 // HkvlineId(), and closing_gt points to the closing '>'.
579 // Write: assumes ID key=value has been written, but NOT trailing comma, and
580 // finishes in an analogous state.
581 BoolErr FixAndWriteContigHeaderLine(const char* hkvline_iter, const char* idval, const char* closing_gt, uint32_t id_slen, uint32_t contig_len, char** writep_ptr) {
582 if (hkvline_iter > closing_gt) {
583 // Only ID field present in input.
584 char* writep = strcpya_k(*writep_ptr, ",length=");
585 *writep_ptr = u32toa(contig_len, writep);
586 return 0;
587 }
588 const char* idval_end = &(idval[id_slen]);
589 const char* lenvalstr_start;
590 uint32_t lenval_slen;
591 IntErr interr = HkvlineFindK(hkvline_iter, "length", &lenvalstr_start, &lenval_slen);
592 if (interr) {
593 if (unlikely(S_CAST(int32_t, interr) == 2)) {
594 return 1;
595 }
596 // Existing header line doesn't contain a length. Place the length
597 // immediately after the ID, and then append the rest of the existing line.
598 char* writep = strcpya_k(*writep_ptr, ",length=");
599 writep = u32toa_x(contig_len, ',', writep);
600 if (idval < hkvline_iter) {
601 writep = memcpya(writep, hkvline_iter, closing_gt - hkvline_iter);
602 } else {
603 const char* idkey_start = &(idval[-3]);
604 writep = memcpya(writep, hkvline_iter, idkey_start - hkvline_iter);
605 writep = memcpya(writep, idval_end, closing_gt - idval_end);
606 }
607 *writep_ptr = writep;
608 return 0;
609 }
610 char* writep = *writep_ptr;
611 const char* lenvalstr_end = &(lenvalstr_start[lenval_slen]);
612 *writep++ = ',';
613 if (idval < lenvalstr_start) {
614 // Usual case: ID was before length in input.
615 if (idval < hkvline_iter) {
616 writep = memcpya(writep, hkvline_iter, lenvalstr_start - hkvline_iter);
617 } else {
618 const char* idkey_start = &(idval[-3]);
619 writep = memcpya(writep, hkvline_iter, idkey_start - hkvline_iter);
620 writep = memcpya(writep, idval_end, lenvalstr_start - idval_end);
621 }
622 writep = u32toa(contig_len, writep);
623 writep = memcpya(writep, lenvalstr_end, closing_gt - lenvalstr_end);
624 } else {
625 // ID is later.
626 writep = memcpya(writep, hkvline_iter, lenvalstr_start - hkvline_iter);
627 writep = u32toa(contig_len, writep);
628 const char* idkey_prestart = &(idval[-4]);
629 writep = memcpya(writep, lenvalstr_end, idkey_prestart - lenvalstr_end);
630 writep = memcpya(writep, idval_end, closing_gt - idval_end);
631 }
632 *writep_ptr = writep;
633 return 0;
634 }
635
636 BoolErr CsWriteRestOfHeaderLine(const char* hkvline_iter, const char* idval, const char* line_end, uint32_t id_slen, CompressStreamState* css_ptr, char** writep_ptr) {
637 if (idval > hkvline_iter) {
638 // Copy entries before ",ID=".
639 const char* idkey_prestart = &(idval[-4]);
640 char* cswritep = *writep_ptr;
641 *cswritep++ = ',';
642 *writep_ptr = cswritep;
643 if (unlikely(CsputsStd(hkvline_iter, idkey_prestart - hkvline_iter, css_ptr, writep_ptr))) {
644 return 1;
645 }
646 }
647 const char* idval_end = &(idval[id_slen]);
648 return CsputsStd(idval_end, line_end - idval_end, css_ptr, writep_ptr);
649 }
650
651 PglErr CsFixAndWriteContigHeaderLine(const char* hkvline_iter, const char* idval, const char* line_end, uint32_t id_slen, uint32_t contig_len, CompressStreamState* css_ptr, char** writep_ptr) {
652 if (hkvline_iter[-1] == '>') {
653 // Only ID field present in input.
654 char* cswritep = strcpya_k(*writep_ptr, ",length=");
655 *writep_ptr = u32toa_x(contig_len, '>', cswritep);
656 AppendBinaryEoln(writep_ptr);
657 return Cswrite(css_ptr, writep_ptr)? kPglRetWriteFail : kPglRetSuccess;
658 }
659 const char* idval_end = &(idval[id_slen]);
660 const char* lenvalstr_start;
661 uint32_t lenval_slen;
662 IntErr interr = HkvlineFindK(hkvline_iter, "length", &lenvalstr_start, &lenval_slen);
663 if (interr) {
664 if (unlikely(S_CAST(int32_t, interr) == 2)) {
665 logerrputs("Error: Malformed ##contig line in .pvar file.\n");
666 return kPglRetMalformedInput;
667 }
668 // Existing header line doesn't contain a length. Place the length
669 // immediately after the ID, and then append the rest of the existing line.
670 char* cswritep = strcpya_k(*writep_ptr, ",length=");
671 *writep_ptr = u32toa_x(contig_len, ',', cswritep);
672 if (idval < hkvline_iter) {
673 return CsputsStd(hkvline_iter, line_end - hkvline_iter, css_ptr, writep_ptr)? kPglRetWriteFail : kPglRetSuccess;
674 }
675 const char* idkey_start = &(idval[-3]);
676 if (unlikely(CsputsStd(hkvline_iter, idkey_start - hkvline_iter, css_ptr, writep_ptr) ||
677 CsputsStd(idval_end, line_end - idval_end, css_ptr, writep_ptr))) {
678 return kPglRetWriteFail;
679 }
680 return kPglRetSuccess;
681 }
682 char* cswritep = *writep_ptr;
683 const char* lenvalstr_end = &(lenvalstr_start[lenval_slen]);
684 *cswritep++ = ',';
685 if (idval < lenvalstr_start) {
686 // Usual case: ID was before length in input.
687 if (idval < hkvline_iter) {
688 if (unlikely(CsputsStd(hkvline_iter, lenvalstr_start - hkvline_iter, css_ptr, &cswritep))) {
689 return kPglRetWriteFail;
690 }
691 } else {
692 const char* idkey_start = &(idval[-3]);
693 if (unlikely(CsputsStd(hkvline_iter, idkey_start - hkvline_iter, css_ptr, &cswritep) ||
694 CsputsStd(idval_end, lenvalstr_start - idval_end, css_ptr, &cswritep))) {
695 return kPglRetWriteFail;
696 }
697 }
698 *writep_ptr = u32toa(contig_len, cswritep);
699 return CsputsStd(lenvalstr_end, line_end - lenvalstr_end, css_ptr, writep_ptr)? kPglRetWriteFail : kPglRetSuccess;
700 }
701 // ID is later.
702 if (unlikely(CsputsStd(hkvline_iter, lenvalstr_start - hkvline_iter, css_ptr, &cswritep))) {
703 return kPglRetWriteFail;
704 }
705 *writep_ptr = u32toa(contig_len, cswritep);
706 const char* idkey_prestart = &(idval[-4]);
707 if (unlikely(CsputsStd(lenvalstr_end, idkey_prestart - lenvalstr_end, css_ptr, writep_ptr) ||
708 CsputsStd(idval_end, line_end - idval_end, css_ptr, writep_ptr))) {
709 return kPglRetWriteFail;
710 }
711 return kPglRetSuccess;
712 }
713
714 PglErr PvarXheaderWrite(const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* contig_lens, uintptr_t xheader_blen, uint32_t vcfheader, uint32_t write_filter, uint32_t write_info, uint32_t append_info_pr_header_line, char* xheader, CompressStreamState* css_ptr, char** cswritepp) {
715 unsigned char* bigstack_mark = g_bigstack_base;
716 PglErr reterr = kPglRetSuccess;
717 {
718 if ((!vcfheader) && (!contig_lens)) {
719 if (write_filter && write_info) {
720 if (unlikely(CsputsStd(xheader, xheader_blen, css_ptr, cswritepp))) {
721 goto PvarXheaderWrite_ret_WRITE_FAIL;
722 }
723 } else {
724 // Filter out FILTER/INFO definitions iff the corresponding column has
725 // been removed.
726 const char* copy_start = xheader;
727 const char* xheader_end = &(xheader[xheader_blen]);
728 for (const char* xheader_iter = xheader; xheader_iter != xheader_end; ) {
729 const char* next_line_start = AdvPastDelim(xheader_iter, '\n');
730 if (((!write_filter) && StrStartsWithUnsafe(xheader_iter, "##FILTER=<")) ||
731 ((!write_info) && StrStartsWithUnsafe(xheader_iter, "##INFO=<"))) {
732 if (copy_start != xheader_iter) {
733 if (unlikely(CsputsStd(copy_start, xheader_iter - copy_start, css_ptr, cswritepp))) {
734 goto PvarXheaderWrite_ret_WRITE_FAIL;
735 }
736 }
737 copy_start = next_line_start;
738 }
739 xheader_iter = next_line_start;
740 }
741 if (copy_start != xheader_end) {
742 if (unlikely(CsputsStd(copy_start, xheader_end - copy_start, css_ptr, cswritepp))) {
743 goto PvarXheaderWrite_ret_WRITE_FAIL;
744 }
745 }
746 }
747 } else {
748 // See the start of ExportVcf().
749 if (vcfheader) {
750 AppendVcfHeaderStart(1, cswritepp);
751 }
752 const uint32_t chr_ctl = BitCtToWordCt(cip->chr_ct);
753 uintptr_t* written_contig_header_lines;
754 if (unlikely(bigstack_calloc_w(chr_ctl, &written_contig_header_lines))) {
755 goto PvarXheaderWrite_ret_NOMEM;
756 }
757 uint32_t contig_zero_written = 0;
758 char* cswritep = *cswritepp;
759 // ExportVcf() has to perform a customized --merge-par operation, so it
760 // has special handling of chrX/PAR1/PAR2 ##contig header lines. We omit
761 // that here.
762 char* xheader_end = &(xheader[xheader_blen]);
763 for (char* line_end = xheader; line_end != xheader_end; ) {
764 char* line_start = line_end;
765 line_end = AdvPastDelim(line_start, '\n');
766 if (StrStartsWithUnsafe(line_start, "##contig=<")) {
767 char* hkvline_iter = &(line_start[strlen("##contig=<")]);
768 char* idval;
769 uint32_t id_slen;
770 if (unlikely(HkvlineId(&hkvline_iter, &idval, &id_slen))) {
771 logerrputs("Error: Malformed ##contig line in .pvar file.\n");
772 goto PvarXheaderWrite_ret_MALFORMED_INPUT;
773 }
774 if (hkvline_iter[-1] == '>') {
775 // regenerate instead of keeping
776 continue;
777 }
778 const uint32_t chr_idx = GetChrCodeCounted(cip, id_slen, idval);
779 if (IsI32Neg(chr_idx) || (!IsSet(cip->chr_mask, chr_idx))) {
780 continue;
781 }
782 const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[chr_idx];
783 if (unlikely(IsSet(written_contig_header_lines, chr_fo_idx))) {
784 logerrputs("Error: Duplicate ##contig line in .pvar file.\n");
785 goto PvarXheaderWrite_ret_MALFORMED_INPUT;
786 }
787 SetBit(chr_fo_idx, written_contig_header_lines);
788 // if --output-chr was used at some point, we need to sync the
789 // ##contig chromosome code with the code in the .pvar body.
790 char* chr_name_write_start = strcpya_k(cswritep, "##contig=<ID=");
791 char* chr_name_write_end = chrtoa(cip, chr_idx, chr_name_write_start);
792 if ((*chr_name_write_start == '0') && (chr_name_write_end == &(chr_name_write_start[1]))) {
793 // --allow-extra-chr 0 special case
794 // note that cswritep has *not* been advanced
795 contig_zero_written = 1; // technically we write this a bit later
796 continue;
797 }
798 cswritep = chr_name_write_end;
799 if (contig_lens && contig_lens[chr_idx]) {
800 reterr = CsFixAndWriteContigHeaderLine(hkvline_iter, idval, line_end, id_slen, contig_lens[chr_idx], css_ptr, &cswritep);
801 if (unlikely(reterr)) {
802 goto PvarXheaderWrite_ret_1;
803 }
804 } else {
805 if (unlikely(CsWriteRestOfHeaderLine(hkvline_iter, idval, line_end, id_slen, css_ptr, &cswritep))) {
806 goto PvarXheaderWrite_ret_WRITE_FAIL;
807 }
808 }
809 } else {
810 if (((!write_filter) && StrStartsWithUnsafe(line_start, "##FILTER=<")) ||
811 ((!write_info) && StrStartsWithUnsafe(line_start, "##INFO=<"))) {
812 continue;
813 }
814 if (unlikely(CsputsStd(line_start, line_end - line_start, css_ptr, &cswritep))) {
815 goto PvarXheaderWrite_ret_WRITE_FAIL;
816 }
817 }
818 }
819 // fill in the missing ##contig lines
820 if (contig_zero_written) {
821 cswritep = strcpya_k(cswritep, "##contig=<ID=0,length=2147483645>" EOLN_STR);
822 }
823 for (uint32_t chr_fo_idx = 0; chr_fo_idx != cip->chr_ct; ++chr_fo_idx) {
824 if (IsSet(written_contig_header_lines, chr_fo_idx)) {
825 continue;
826 }
827 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
828 // AllBitsAreZero() doesn't do what we want in the --sort-vars case,
829 // but fortunately we don't need it there.
830 if ((!IsSet(cip->chr_mask, chr_idx)) || (variant_include && AllBitsAreZero(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], cip->chr_fo_vidx_start[chr_fo_idx + 1]))) {
831 continue;
832 }
833 char* chr_name_write_start = strcpya_k(cswritep, "##contig=<ID=");
834 char* chr_name_write_end = chrtoa(cip, chr_idx, chr_name_write_start);
835 if ((*chr_name_write_start == '0') && (chr_name_write_end == &(chr_name_write_start[1]))) {
836 // --allow-extra-chr 0 special case
837 if (contig_zero_written) {
838 continue;
839 }
840 contig_zero_written = 1;
841 cswritep = strcpya_k(chr_name_write_end, ",length=2147483645");
842 } else if (contig_lens && contig_lens[chr_idx]) {
843 cswritep = strcpya_k(chr_name_write_end, ",length=");
844 cswritep = u32toa(contig_lens[chr_idx], cswritep);
845 } else {
846 cswritep = chr_name_write_end;
847 }
848 *cswritep++ = '>';
849 AppendBinaryEoln(&cswritep);
850 if (unlikely(Cswrite(css_ptr, &cswritep))) {
851 goto PvarXheaderWrite_ret_WRITE_FAIL;
852 }
853 }
854 *cswritepp = cswritep;
855 }
856 if (append_info_pr_header_line) {
857 *cswritepp = strcpya_k(*cswritepp, "##INFO=<ID=PR,Number=0,Type=Flag,Description=\"Provisional reference allele, may not be based on real reference genome\">" EOLN_STR);
858 }
859 }
860 while (0) {
861 PvarXheaderWrite_ret_NOMEM:
862 reterr = kPglRetNomem;
863 break;
864 PvarXheaderWrite_ret_WRITE_FAIL:
865 reterr = kPglRetWriteFail;
866 break;
867 PvarXheaderWrite_ret_MALFORMED_INPUT:
868 reterr = kPglRetMalformedInput;
869 break;
870 }
871 PvarXheaderWrite_ret_1:
872 BigstackReset(bigstack_mark);
873 return reterr;
874 }
875
876 BoolErr PvarInfoWriteStatus(const uintptr_t* variant_include, const uintptr_t* nonref_flags, uint32_t raw_variant_ct, InfoFlags info_flags, uint32_t nonref_flags_storage, PvarPsamFlags pvar_psam_flags, const char** pvar_info_reload_ptr, uint32_t* write_info_ptr, uint32_t* write_info_pr_ptr) {
877 const uint32_t all_nonref = (nonref_flags_storage == 2);
878 uint32_t write_info_pr = all_nonref;
879 if ((*pvar_info_reload_ptr) && (!(pvar_psam_flags & kfPvarColXinfo))) {
880 // bugfix (6 Feb 2021): don't write INFO column when INFO column
881 // explicitly excluded here, but pvar_info_reload is needed for some
882 // other reason (e.g. VCF/BCF export, --rm-dup)
883 *pvar_info_reload_ptr = nullptr;
884 }
885 const uint32_t write_info = (pvar_psam_flags & kfPvarColInfo) || (*pvar_info_reload_ptr);
886 if (write_info && nonref_flags) {
887 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
888 write_info_pr = !IntersectionIsEmpty(variant_include, nonref_flags, raw_variant_ctl);
889 }
890 *write_info_ptr = write_info;
891 *write_info_pr_ptr = write_info_pr && write_info;
892 return ((*write_info_pr_ptr) && (info_flags & kfInfoPrNonflagPresent));
893 }
894
895 PglErr WritePvar(const char* outname, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* allele_presents, const AlleleCode* allele_permute, const uintptr_t* qual_present, const float* quals, const uintptr_t* filter_present, const uintptr_t* filter_npass, const char* const* filter_storage, const uintptr_t* nonref_flags, const char* pvar_info_reload, const double* variant_cms, const uint32_t* contig_lens, const char* const* info_keys, const uint32_t* info_keys_htable, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct, uint32_t max_allele_slen, uintptr_t xheader_blen, InfoFlags info_flags, uint32_t nonref_flags_storage, uint32_t max_filter_slen, uint32_t info_reload_slen, uint32_t info_keys_htable_size, PvarPsamFlags pvar_psam_flags, char output_missing_geno_char, uint32_t write_info, uint32_t write_info_pr, uint32_t thread_ct, char* xheader) {
896 // allele_presents must be nullptr unless we're trimming alt alleles
897 // split/join cases handled by WritePvarSplit() and WritePvarJoin()
898 unsigned char* bigstack_mark = g_bigstack_base;
899 char* cswritep = nullptr;
900 PglErr reterr = kPglRetSuccess;
901 CompressStreamState css;
902 TextStream pvar_reload_txs;
903 PreinitCstream(&css);
904 PreinitTextStream(&pvar_reload_txs);
905 {
906 const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
907 // includes trailing tab
908 char* chr_buf;
909
910 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
911 goto WritePvar_ret_NOMEM;
912 }
913 const char** info_allele_val_starts = nullptr;
914 uint32_t* info_allele_val_slens = nullptr;
915 if (allele_permute && write_info) {
916 if (unlikely(bigstack_alloc_kcp(max_allele_ct, &info_allele_val_starts) ||
917 bigstack_alloc_u32(max_allele_ct, &info_allele_val_slens))) {
918 goto WritePvar_ret_NOMEM;
919 }
920 }
921 uintptr_t overflow_buf_size = kCompressStreamBlock + kMaxIdSlen + 512 + 2 * max_allele_slen + max_filter_slen + info_reload_slen;
922 if (overflow_buf_size < 2 * kCompressStreamBlock) {
923 overflow_buf_size = 2 * kCompressStreamBlock;
924 }
925 const uint32_t output_zst = (pvar_psam_flags / kfPvarZs) & 1;
926 reterr = InitCstreamAlloc(outname, 0, output_zst, thread_ct, overflow_buf_size, &css, &cswritep);
927 if (unlikely(reterr)) {
928 goto WritePvar_ret_1;
929 }
930 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
931 const uint32_t all_nonref = (nonref_flags_storage == 2);
932
933 uint32_t write_filter = 0;
934 if (pvar_psam_flags & kfPvarColFilter) {
935 write_filter = 1;
936 } else if ((pvar_psam_flags & kfPvarColMaybefilter) && filter_present) {
937 write_filter = !IntersectionIsEmpty(variant_include, filter_present, raw_variant_ctl);
938 }
939 char* pvar_info_line_iter = nullptr;
940 uint32_t info_col_idx = 0; // could save this during first load instead
941 const uint32_t info_pr_flag_present = (info_flags / kfInfoPrFlagPresent) & 1;
942 if (pvar_psam_flags & (kfPvarColXheader | kfPvarColVcfheader)) {
943 reterr = PvarXheaderWrite(variant_include, cip, contig_lens, xheader_blen, (pvar_psam_flags / kfPvarColVcfheader) & 1, write_filter, write_info, write_info_pr && (!info_pr_flag_present), xheader, &css, &cswritep);
944 if (unlikely(reterr)) {
945 goto WritePvar_ret_1;
946 }
947 }
948 // bugfix (30 Jul 2017): may be necessary to reload INFO when no ## lines
949 // are in the header... er, should we still allow this?
950 if (pvar_info_reload) {
951 reterr = PvarInfoOpenAndReloadHeader(pvar_info_reload, 1 + (thread_ct > 1), &pvar_reload_txs, &pvar_info_line_iter, &info_col_idx);
952 if (unlikely(reterr)) {
953 goto WritePvar_ret_TSTREAM_FAIL;
954 }
955 }
956 if (cip->chrset_source) {
957 AppendChrsetLine(cip, &cswritep);
958 }
959 cswritep = strcpya_k(cswritep, "#CHROM\tPOS\tID\tREF\tALT");
960
961 uint32_t write_qual = 0;
962 if (pvar_psam_flags & kfPvarColQual) {
963 write_qual = 1;
964 } else if ((pvar_psam_flags & kfPvarColMaybequal) && qual_present) {
965 write_qual = !IntersectionIsEmpty(variant_include, qual_present, raw_variant_ctl);
966 }
967 if (write_qual) {
968 cswritep = strcpya_k(cswritep, "\tQUAL");
969 }
970
971 if (write_filter) {
972 cswritep = strcpya_k(cswritep, "\tFILTER");
973 }
974
975 if (write_info) {
976 cswritep = strcpya_k(cswritep, "\tINFO");
977 }
978
979 uint32_t write_cm = 0;
980 if (pvar_psam_flags & kfPvarColCm) {
981 write_cm = 1;
982 } else if ((pvar_psam_flags & kfPvarColMaybecm) && variant_cms) {
983 if (raw_variant_ct == variant_ct) {
984 // nonzero_cm_present check was performed
985 write_cm = 1;
986 } else {
987 uintptr_t variant_uidx_base = 0;
988 uintptr_t cur_bits = variant_include[0];
989 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
990 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
991 if (variant_cms[variant_uidx] != 0.0) {
992 write_cm = 1;
993 break;
994 }
995 }
996 }
997 }
998 if (write_cm) {
999 cswritep = strcpya_k(cswritep, "\tCM");
1000 }
1001 AppendBinaryEoln(&cswritep);
1002
1003 const AlleleCode* cur_allele_permute = nullptr;
1004 uint32_t trs_variant_uidx = 0;
1005 uintptr_t variant_uidx_base = 0;
1006 uintptr_t cur_bits = variant_include[0];
1007 uint32_t chr_fo_idx = UINT32_MAX;
1008 uint32_t chr_end = 0;
1009 uint32_t chr_buf_blen = 0;
1010 uint32_t ref_allele_idx = 0;
1011 uint32_t alt1_allele_idx = 1;
1012 uint32_t cur_allele_ct = 2;
1013 uint32_t alleles_permuted = 0;
1014 uint32_t pct = 0;
1015 uint32_t next_print_variant_idx = variant_ct / 100;
1016 fputs("0%", stdout);
1017 fflush(stdout);
1018 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
1019 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
1020 if (variant_uidx >= chr_end) {
1021 do {
1022 ++chr_fo_idx;
1023 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
1024 } while (variant_uidx >= chr_end);
1025 char* chr_name_end = chrtoa(cip, cip->chr_file_order[chr_fo_idx], chr_buf);
1026 *chr_name_end = '\t';
1027 chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
1028 }
1029 cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
1030 cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep);
1031 const char* variant_id = variant_ids[variant_uidx];
1032 cswritep = strcpyax(cswritep, variant_id, '\t');
1033 uintptr_t allele_idx_offset_base;
1034 if (!allele_idx_offsets) {
1035 allele_idx_offset_base = variant_uidx * 2;
1036 } else {
1037 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
1038 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
1039 }
1040 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
1041 if (allele_permute) {
1042 cur_allele_permute = &(allele_permute[allele_idx_offset_base]);
1043 ref_allele_idx = cur_allele_permute[0];
1044 alt1_allele_idx = cur_allele_permute[1];
1045 }
1046 // bugfix (2 Jan 2021): forgot to apply --output-missing-genotype setting
1047 // here.
1048 // This check is only need for REF and ALT1; later ALTs are not permitted
1049 // to be missing.
1050 if (!strequal_k_unsafe(cur_alleles[ref_allele_idx], ".")) {
1051 cswritep = strcpya(cswritep, cur_alleles[ref_allele_idx]);
1052 } else {
1053 *cswritep++ = output_missing_geno_char;
1054 }
1055 *cswritep++ = '\t';
1056 uint32_t alt_allele_written = 0;
1057 if ((!allele_presents) || IsSet(allele_presents, allele_idx_offset_base + alt1_allele_idx)) {
1058 if (!strequal_k_unsafe(cur_alleles[alt1_allele_idx], ".")) {
1059 cswritep = strcpya(cswritep, cur_alleles[alt1_allele_idx]);
1060 } else {
1061 *cswritep++ = output_missing_geno_char;
1062 }
1063 alt_allele_written = 1;
1064 }
1065 if (unlikely(Cswrite(&css, &cswritep))) {
1066 goto WritePvar_ret_WRITE_FAIL;
1067 }
1068 for (uint32_t aidx = 2; aidx != cur_allele_ct; ++aidx) {
1069 const uint32_t write_aidx = cur_allele_permute? cur_allele_permute[aidx] : aidx;
1070 if (allele_presents && (!IsSet(allele_presents, allele_idx_offset_base + write_aidx))) {
1071 continue;
1072 }
1073 if (alt_allele_written) {
1074 *cswritep++ = ',';
1075 }
1076 alt_allele_written = 1;
1077 cswritep = strcpya(cswritep, cur_alleles[write_aidx]);
1078 if (unlikely(Cswrite(&css, &cswritep))) {
1079 goto WritePvar_ret_WRITE_FAIL;
1080 }
1081 }
1082 if (!alt_allele_written) {
1083 *cswritep++ = output_missing_geno_char;
1084 }
1085
1086 if (write_qual) {
1087 *cswritep++ = '\t';
1088 if ((!qual_present) || (!IsSet(qual_present, variant_uidx))) {
1089 *cswritep++ = '.';
1090 } else {
1091 cswritep = ftoa_g(quals[variant_uidx], cswritep);
1092 }
1093 }
1094
1095 if (write_filter) {
1096 *cswritep++ = '\t';
1097 if ((!filter_present) || (!IsSet(filter_present, variant_uidx))) {
1098 *cswritep++ = '.';
1099 } else if (!IsSet(filter_npass, variant_uidx)) {
1100 cswritep = strcpya_k(cswritep, "PASS");
1101 } else {
1102 cswritep = strcpya(cswritep, filter_storage[variant_uidx]);
1103 }
1104 }
1105
1106 if (write_info) {
1107 *cswritep++ = '\t';
1108 const uint32_t is_pr = all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx));
1109 if (pvar_info_line_iter) {
1110 if (cur_allele_permute) {
1111 alleles_permuted = 0;
1112 for (uint32_t aidx = 0; aidx != cur_allele_ct; ++aidx) {
1113 if (cur_allele_permute[aidx] != aidx) {
1114 alleles_permuted = 1;
1115 break;
1116 }
1117 }
1118 }
1119 if (!alleles_permuted) {
1120 reterr = PvarInfoReloadAndWrite(info_pr_flag_present, info_col_idx, variant_uidx, is_pr, &pvar_reload_txs, &pvar_info_line_iter, &cswritep, &trs_variant_uidx);
1121 if (unlikely(reterr)) {
1122 goto WritePvar_ret_TSTREAM_FAIL;
1123 }
1124 } else {
1125 reterr = PvarInfoPermuteReloadAndWrite(cur_allele_permute, info_keys, info_keys_htable, variant_id, info_col_idx, info_keys_htable_size, variant_uidx, cur_allele_ct, is_pr, &pvar_reload_txs, &pvar_info_line_iter, &cswritep, &trs_variant_uidx, info_allele_val_starts, info_allele_val_slens);
1126 if (unlikely(reterr)) {
1127 if (reterr == kPglRetMalformedInput) {
1128 goto WritePvar_ret_1;
1129 }
1130 goto WritePvar_ret_TSTREAM_FAIL;
1131 }
1132 }
1133 } else {
1134 if (is_pr) {
1135 cswritep = strcpya_k(cswritep, "PR");
1136 } else {
1137 *cswritep++ = '.';
1138 }
1139 }
1140 }
1141
1142 if (write_cm) {
1143 *cswritep++ = '\t';
1144 if (!variant_cms) {
1145 *cswritep++ = '0';
1146 } else {
1147 cswritep = dtoa_g_p8(variant_cms[variant_uidx], cswritep);
1148 }
1149 }
1150 AppendBinaryEoln(&cswritep);
1151 if (variant_idx >= next_print_variant_idx) {
1152 if (pct > 10) {
1153 putc_unlocked('\b', stdout);
1154 }
1155 pct = (variant_idx * 100LLU) / variant_ct;
1156 printf("\b\b%u%%", pct++);
1157 fflush(stdout);
1158 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
1159 }
1160 }
1161 if (unlikely(CswriteCloseNull(&css, cswritep))) {
1162 goto WritePvar_ret_WRITE_FAIL;
1163 }
1164 if (pct > 10) {
1165 putc_unlocked('\b', stdout);
1166 }
1167 fputs("\b\b", stdout);
1168 }
1169 while (0) {
1170 WritePvar_ret_NOMEM:
1171 reterr = kPglRetNomem;
1172 break;
1173 WritePvar_ret_TSTREAM_FAIL:
1174 TextStreamErrPrint(pvar_info_reload, &pvar_reload_txs);
1175 break;
1176 WritePvar_ret_WRITE_FAIL:
1177 reterr = kPglRetWriteFail;
1178 break;
1179 }
1180 WritePvar_ret_1:
1181 CswriteCloseCond(&css, cswritep);
1182 CleanupTextStream2(pvar_info_reload, &pvar_reload_txs, &reterr);
1183 BigstackReset(bigstack_mark);
1184 return reterr;
1185 }
1186
1187 PglErr WriteFam(const char* outname, const uintptr_t* sample_include, const PedigreeIdInfo* piip, const uintptr_t* sex_nm, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const uint32_t* new_sample_idx_to_old, const char* legacy_output_missing_pheno, uint32_t sample_ct, uint32_t pheno_ct, char delim) {
1188 FILE* outfile = nullptr;
1189 PglErr reterr = kPglRetSuccess;
1190 {
1191 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
1192 goto WriteFam_ret_OPEN_FAIL;
1193 }
1194 uintptr_t* pheno_nm = nullptr;
1195 uintptr_t* pheno_cc = nullptr;
1196 double* pheno_qt = nullptr;
1197 // .fam files don't support categorical phenotypes
1198 const uint32_t pheno_idx = FirstCcOrQtPhenoIdx(pheno_cols, pheno_ct);
1199 if (pheno_idx != UINT32_MAX) {
1200 const PhenoDtype type_code = pheno_cols[pheno_idx].type_code;
1201 pheno_nm = pheno_cols[pheno_idx].nonmiss;
1202 if (type_code == kPhenoDtypeCc) {
1203 pheno_cc = pheno_cols[pheno_idx].data.cc;
1204 } else {
1205 pheno_qt = pheno_cols[pheno_idx].data.qt;
1206 }
1207 }
1208 const uint32_t lomp_slen = strlen(legacy_output_missing_pheno);
1209
1210 // possible todo: warning if two sample IDs only differ in SID? (check for
1211 // this if any file is being exported that can't have a SID column)
1212 const char* sample_ids = piip->sii.sample_ids;
1213 const char* paternal_ids = piip->parental_id_info.paternal_ids;
1214 const char* maternal_ids = piip->parental_id_info.maternal_ids;
1215 const uintptr_t max_sample_id_blen = piip->sii.max_sample_id_blen;
1216 const uintptr_t max_paternal_id_blen = piip->parental_id_info.max_paternal_id_blen;
1217 const uintptr_t max_maternal_id_blen = piip->parental_id_info.max_maternal_id_blen;
1218 uintptr_t sample_uidx_base = 0;
1219 uintptr_t cur_bits = sample_include[0];
1220 uint32_t sample_uidx2 = 0;
1221 char* write_iter = g_textbuf;
1222 char* textbuf_flush = &(write_iter[kMaxMediumLine]);
1223 // not really necessary to make sample_uidx increment dependent on
1224 // new_sample_idx_to_old == nullptr
1225 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1226 uintptr_t sample_uidx;
1227 if (!new_sample_idx_to_old) {
1228 sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
1229 } else {
1230 do {
1231 sample_uidx = new_sample_idx_to_old[sample_uidx2++];
1232 } while (!IsSet(sample_include, sample_uidx));
1233 }
1234 const char* cur_sample_id = &(sample_ids[max_sample_id_blen * sample_uidx]);
1235 if (delim == '\t') {
1236 write_iter = strcpya(write_iter, cur_sample_id);
1237 } else {
1238 const char* fid_end = AdvToDelim(cur_sample_id, '\t');
1239 write_iter = memcpyax(write_iter, cur_sample_id, fid_end - cur_sample_id, delim);
1240 write_iter = strcpya(write_iter, &(fid_end[1]));
1241 }
1242 *write_iter++ = delim;
1243 write_iter = strcpyax(write_iter, &(paternal_ids[max_paternal_id_blen * sample_uidx]), delim);
1244 write_iter = strcpyax(write_iter, &(maternal_ids[max_maternal_id_blen * sample_uidx]), delim);
1245 *write_iter++ = Sexchar(sex_nm, sex_male, sample_uidx);
1246 *write_iter++ = delim;
1247 if ((!pheno_nm) || (!IsSet(pheno_nm, sample_uidx))) {
1248 write_iter = memcpya(write_iter, legacy_output_missing_pheno, lomp_slen);
1249 } else if (pheno_cc) {
1250 // do we want to allow user to force 0/1 output?
1251 *write_iter++ = '1' + IsSet(pheno_cc, sample_uidx);
1252 } else {
1253 write_iter = dtoa_g(pheno_qt[sample_uidx], write_iter);
1254 }
1255 AppendBinaryEoln(&write_iter);
1256 if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
1257 goto WriteFam_ret_WRITE_FAIL;
1258 }
1259 }
1260 if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) {
1261 goto WriteFam_ret_WRITE_FAIL;
1262 }
1263 }
1264 while (0) {
1265 WriteFam_ret_OPEN_FAIL:
1266 reterr = kPglRetOpenFail;
1267 break;
1268 WriteFam_ret_WRITE_FAIL:
1269 reterr = kPglRetWriteFail;
1270 break;
1271 }
1272 fclose_cond(outfile);
1273 return reterr;
1274 }
1275
1276 uint32_t DataFidColIsRequired(const uintptr_t* sample_include, const SampleIdInfo* siip, uint32_t sample_ct, uint32_t maybe_modifier) {
1277 if (maybe_modifier & 2) {
1278 return 1;
1279 }
1280 if ((!(maybe_modifier & 1)) || (!(siip->flags & kfSampleIdFidPresent))) {
1281 return 0;
1282 }
1283 const char* sample_ids = siip->sample_ids;
1284 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
1285 uintptr_t sample_uidx_base = 0;
1286 uintptr_t cur_bits = sample_include[0];
1287 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1288 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
1289 if (!memequal_sk(&(sample_ids[sample_uidx * max_sample_id_blen]), "0\t")) {
1290 return 1;
1291 }
1292 }
1293 return 0;
1294 }
1295
1296 uint32_t DataSidColIsRequired(const uintptr_t* sample_include, const char* sids, uint32_t sample_ct, uint32_t max_sid_blen, uint32_t maybe_modifier) {
1297 // note that MAYBESID and SID can both be set
1298 if (maybe_modifier & 2) {
1299 return 1;
1300 }
1301 if (sids && (maybe_modifier & 1)) {
1302 uintptr_t sample_uidx_base = 0;
1303 uintptr_t cur_bits = sample_include[0];
1304 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1305 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
1306 if (!strequal_k_unsafe(&(sids[sample_uidx * max_sid_blen]), "0")) {
1307 return 1;
1308 }
1309 }
1310 }
1311 return 0;
1312 }
1313
1314 uint32_t DataParentalColsAreRequired(const uintptr_t* sample_include, const SampleIdInfo* siip, const ParentalIdInfo* parental_id_infop, uint32_t sample_ct, uint32_t maybe_modifier) {
1315 if (maybe_modifier & 2) {
1316 return 1;
1317 }
1318 if ((!(maybe_modifier & 1)) || (!(siip->flags & kfSampleIdParentsPresent))) {
1319 return 0;
1320 }
1321 const char* paternal_ids = parental_id_infop->paternal_ids;
1322 const char* maternal_ids = parental_id_infop->maternal_ids;
1323 const uintptr_t max_paternal_id_blen = parental_id_infop->max_paternal_id_blen;
1324 const uintptr_t max_maternal_id_blen = parental_id_infop->max_maternal_id_blen;
1325 uintptr_t sample_uidx_base = 0;
1326 uintptr_t cur_bits = sample_include[0];
1327 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1328 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
1329 if ((!strequal_k_unsafe(&(paternal_ids[sample_uidx * max_paternal_id_blen]), "0")) || (!strequal_k_unsafe(&(maternal_ids[sample_uidx * max_maternal_id_blen]), "0"))) {
1330 return 1;
1331 }
1332 }
1333 return 0;
1334 }
1335
1336 char* AppendPhenoStr(const PhenoCol* pheno_col, const char* output_missing_pheno, uint32_t omp_slen, uint32_t sample_uidx, char* write_iter) {
1337 const PhenoDtype type_code = pheno_col->type_code;
1338 if (type_code <= kPhenoDtypeQt) {
1339 if (!IsSet(pheno_col->nonmiss, sample_uidx)) {
1340 write_iter = memcpya(write_iter, output_missing_pheno, omp_slen);
1341 } else if (type_code == kPhenoDtypeCc) {
1342 *write_iter++ = '1' + IsSet(pheno_col->data.cc, sample_uidx);
1343 } else {
1344 write_iter = dtoa_g(pheno_col->data.qt[sample_uidx], write_iter);
1345 }
1346 } else {
1347 write_iter = strcpya(write_iter, pheno_col->category_names[pheno_col->data.cat[sample_uidx]]);
1348 }
1349 return write_iter;
1350 }
1351
1352 char* AppendPhenoStrEx(const PhenoCol* pheno_col, const char* output_missing_pheno, uint32_t omp_slen, uint32_t sample_uidx, char ctrl_char, char* write_iter) {
1353 const PhenoDtype type_code = pheno_col->type_code;
1354 if (type_code <= kPhenoDtypeQt) {
1355 if (!IsSet(pheno_col->nonmiss, sample_uidx)) {
1356 write_iter = memcpya(write_iter, output_missing_pheno, omp_slen);
1357 } else if (type_code == kPhenoDtypeCc) {
1358 *write_iter++ = ctrl_char + IsSet(pheno_col->data.cc, sample_uidx);
1359 } else {
1360 write_iter = dtoa_g(pheno_col->data.qt[sample_uidx], write_iter);
1361 }
1362 } else {
1363 write_iter = strcpya(write_iter, pheno_col->category_names[pheno_col->data.cat[sample_uidx]]);
1364 }
1365 return write_iter;
1366 }
1367
1368 PglErr WritePsam(const char* outname, const uintptr_t* sample_include, const SampleIdInfo* siip, const ParentalIdInfo* parental_id_infop, const uintptr_t* sex_nm, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const char* pheno_names, const uint32_t* new_sample_idx_to_old, const char* output_missing_pheno, uint32_t sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, PvarPsamFlags pvar_psam_flags, uint32_t psam_01) {
1369 FILE* outfile = nullptr;
1370 PglErr reterr = kPglRetSuccess;
1371 {
1372 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
1373 goto WritePsam_ret_OPEN_FAIL;
1374 }
1375 const uint32_t omp_slen = strlen(output_missing_pheno);
1376
1377 char* textbuf_flush = &(g_textbuf[kMaxMediumLine]);
1378
1379 const char* sample_ids = siip->sample_ids;
1380 const char* sids = siip->sids;
1381 const char* paternal_ids = parental_id_infop->paternal_ids;
1382 const char* maternal_ids = parental_id_infop->maternal_ids;
1383 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
1384 const uintptr_t max_sid_blen = siip->max_sid_blen;
1385 const uintptr_t max_paternal_id_blen = parental_id_infop->max_paternal_id_blen;
1386 const uintptr_t max_maternal_id_blen = parental_id_infop->max_maternal_id_blen;
1387 const uint32_t write_fid = DataFidColIsRequired(sample_include, siip, sample_ct, pvar_psam_flags / kfPsamColMaybefid);
1388 const uint32_t write_sid = DataSidColIsRequired(sample_include, sids, sample_ct, max_sid_blen, pvar_psam_flags / kfPsamColMaybesid);
1389 const uint32_t write_parents = DataParentalColsAreRequired(sample_include, siip, parental_id_infop, sample_ct, pvar_psam_flags / kfPsamColMaybeparents);
1390 const uint32_t write_sex = (pvar_psam_flags / kfPsamColSex) & 1;
1391 const uint32_t write_empty_pheno = (pvar_psam_flags & kfPsamColPheno1) && (!pheno_ct);
1392 const uint32_t write_phenos = (pvar_psam_flags & (kfPsamColPheno1 | kfPsamColPhenos)) && pheno_ct;
1393 if (write_phenos && (!(pvar_psam_flags & kfPsamColPhenos))) {
1394 pheno_ct = 1;
1395 }
1396 char* write_iter = g_textbuf;
1397 *write_iter++ = '#';
1398 if (write_fid) {
1399 write_iter = strcpya_k(write_iter, "FID\t");
1400 }
1401 write_iter = strcpya_k(write_iter, "IID");
1402 if (write_sid) {
1403 write_iter = strcpya_k(write_iter, "\tSID");
1404 }
1405 if (write_parents) {
1406 write_iter = strcpya_k(write_iter, "\tPAT\tMAT");
1407 }
1408 if (write_sex) {
1409 write_iter = strcpya_k(write_iter, "\tSEX");
1410 }
1411 if (write_phenos) {
1412 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
1413 *write_iter++ = '\t';
1414 const char* cur_pheno_name = &(pheno_names[pheno_idx * max_pheno_name_blen]);
1415 const uint32_t cur_pheno_name_slen = strlen(cur_pheno_name);
1416 if (strequal_k(cur_pheno_name, "SEX", cur_pheno_name_slen)) {
1417 if (unlikely(write_sex)) {
1418 logerrputs("Error: .psam file cannot have both a regular SEX column and a phenotype named\n'SEX'. Exclude or rename one of these columns.\n");
1419 goto WritePsam_ret_INCONSISTENT_INPUT;
1420 }
1421 // does this phenotype column conform to the SEX column format?
1422 // case/control is always ok, but quantitative or categorical needs
1423 // to be checked
1424 const PhenoCol* sex_col = &(pheno_cols[pheno_idx]);
1425 if (sex_col->type_code != kPhenoDtypeCc) {
1426 // could bitwise-and sample_include and pheno_nm before the loop
1427 const uintptr_t* pheno_nm = sex_col->nonmiss;
1428 uintptr_t sample_uidx_base = 0;
1429 uintptr_t cur_bits = sample_include[0];
1430 if (sex_col->type_code == kPhenoDtypeQt) {
1431 const double* pheno_vals = sex_col->data.qt;
1432 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1433 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
1434 if (IsSet(pheno_nm, sample_uidx)) {
1435 const double dxx = pheno_vals[sample_uidx];
1436 // tolerate '-9' and '0' as missing values, and anything in
1437 // [1, 2] (could be reasonable to represent XXY, etc. with
1438 // decimals).
1439 if (unlikely(((dxx < 1.0) && (dxx != -9.0) && (dxx != 0.0)) || (dxx > 2.0))) {
1440 logerrputs("Error: .psam numeric SEX values are expected to be in {-9, 0, 1, 2}.\n");
1441 goto WritePsam_ret_INCONSISTENT_INPUT;
1442 }
1443 }
1444 }
1445 } else {
1446 assert(sex_col->type_code == kPhenoDtypeCat);
1447 const uint32_t nonnull_cat_ct = sex_col->nonnull_category_ct;
1448 if (nonnull_cat_ct) {
1449 const char* const* cur_category_names = sex_col->category_names;
1450 // tolerate 'M' and 'm' being present simultaneously, etc.
1451 uint32_t male_cat_idx1 = 0;
1452 uint32_t male_cat_idx2 = 0;
1453 uint32_t female_cat_idx1 = 0;
1454 uint32_t female_cat_idx2 = 0;
1455 for (uint32_t cat_idx = 1; cat_idx <= nonnull_cat_ct; ++cat_idx) {
1456 const char* cur_cat_name = cur_category_names[cat_idx];
1457 if (!cur_cat_name[1]) {
1458 uint32_t first_char_code = ctou32(cur_cat_name[0]);
1459 first_char_code &= 0xdf;
1460 if (first_char_code == 70) {
1461 if (!female_cat_idx1) {
1462 female_cat_idx1 = cat_idx;
1463 } else {
1464 female_cat_idx2 = cat_idx;
1465 }
1466 } else if (first_char_code == 77) {
1467 if (!male_cat_idx1) {
1468 male_cat_idx1 = cat_idx;
1469 } else {
1470 male_cat_idx2 = cat_idx;
1471 }
1472 }
1473 }
1474 }
1475 if (S_CAST(uint32_t, (male_cat_idx1 != 0) + (male_cat_idx2 != 0) + (female_cat_idx1 != 0) + (female_cat_idx2 != 0)) < nonnull_cat_ct) {
1476 const uint32_t* pheno_vals = sex_col->data.cat;
1477 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1478 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
1479 if (IsSet(pheno_nm, sample_uidx)) {
1480 const uint32_t cur_cat_idx = pheno_vals[sample_uidx];
1481 if (unlikely((cur_cat_idx != male_cat_idx1) && (cur_cat_idx != female_cat_idx1) && (cur_cat_idx != male_cat_idx2) && (cur_cat_idx != female_cat_idx2))) {
1482 logerrputs("Error: .psam alphabetic SEX values are expected to be in {'F', 'f', 'M', 'm'}.\n");
1483 goto WritePsam_ret_INCONSISTENT_INPUT;
1484 }
1485 }
1486 }
1487 }
1488 }
1489 }
1490 }
1491 }
1492 write_iter = memcpya(write_iter, cur_pheno_name, cur_pheno_name_slen);
1493 if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
1494 goto WritePsam_ret_WRITE_FAIL;
1495 }
1496 }
1497 } else if (write_empty_pheno) {
1498 write_iter = strcpya_k(write_iter, "\tPHENO1");
1499 }
1500 AppendBinaryEoln(&write_iter);
1501
1502 const char ctrl_char = '1' - psam_01;
1503 uintptr_t sample_uidx_base = 0;
1504 uintptr_t cur_bits = sample_include[0];
1505 uint32_t sample_uidx2 = 0;
1506 // not really necessary to make sample_uidx increment dependent on
1507 // new_sample_idx_to_old == nullptr
1508 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1509 uintptr_t sample_uidx;
1510 if (!new_sample_idx_to_old) {
1511 sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
1512 } else {
1513 do {
1514 sample_uidx = new_sample_idx_to_old[sample_uidx2++];
1515 } while (!IsSet(sample_include, sample_uidx));
1516 }
1517 write_iter = AppendXid(sample_ids, sids, write_fid, write_sid, max_sample_id_blen, max_sid_blen, sample_uidx, write_iter);
1518 if (write_parents) {
1519 *write_iter++ = '\t';
1520 write_iter = strcpyax(write_iter, &(paternal_ids[max_paternal_id_blen * sample_uidx]), '\t');
1521 write_iter = strcpya(write_iter, &(maternal_ids[max_maternal_id_blen * sample_uidx]));
1522 }
1523 if (write_sex) {
1524 *write_iter++ = '\t';
1525 if (IsSet(sex_nm, sample_uidx)) {
1526 *write_iter++ = '2' - IsSet(sex_male, sample_uidx);
1527 } else {
1528 // this is better than '0' since it allows the raw column to be used
1529 // as --covar input
1530 // (can't do this for .fam export, though: not worth the
1531 // compatibility issues)
1532 write_iter = strcpya_k(write_iter, "NA");
1533 }
1534 }
1535 if (write_phenos) {
1536 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
1537 *write_iter++ = '\t';
1538 write_iter = AppendPhenoStrEx(&(pheno_cols[pheno_idx]), output_missing_pheno, omp_slen, sample_uidx, ctrl_char, write_iter);
1539 if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
1540 goto WritePsam_ret_WRITE_FAIL;
1541 }
1542 }
1543 } else {
1544 if (write_empty_pheno) {
1545 *write_iter++ = '\t';
1546 write_iter = memcpya(write_iter, output_missing_pheno, omp_slen);
1547 }
1548 if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
1549 goto WritePsam_ret_WRITE_FAIL;
1550 }
1551 }
1552 AppendBinaryEoln(&write_iter);
1553 }
1554 if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) {
1555 goto WritePsam_ret_WRITE_FAIL;
1556 }
1557 }
1558 while (0) {
1559 WritePsam_ret_OPEN_FAIL:
1560 reterr = kPglRetOpenFail;
1561 break;
1562 WritePsam_ret_WRITE_FAIL:
1563 reterr = kPglRetWriteFail;
1564 break;
1565 WritePsam_ret_INCONSISTENT_INPUT:
1566 reterr = kPglRetInconsistentInput;
1567 break;
1568 }
1569 fclose_cond(outfile);
1570 return reterr;
1571 }
1572
1573 /*
1574 // unaligned accesses here.
1575 void BitvecPermute(const uintptr_t* bitvec, const uint32_t* new_sample_idx_to_old, uint32_t sample_ct, unsigned char* writebuf) {
1576 const uint32_t sample_ctl_m1 = BitCtToWordCt(sample_ct) - 1;
1577 uint32_t widx = 0;
1578 uint32_t cur_word_entry_ct = kBitsPerWord;
1579 const uint32_t* new_sample_idx_to_old_base = new_sample_idx_to_old;
1580 uintptr_t* writebuf_walias = (uintptr_t*)writebuf;
1581 while (1) {
1582 if (widx == sample_ctl_m1) {
1583 cur_word_entry_ct = 1 + ((sample_ct - 1) % kBitsPerWord);
1584 }
1585 uintptr_t cur_word = 0;
1586 for (uint32_t uii = 0; uii != cur_word_entry_ct; ++uii) {
1587 cur_word |= IsSet(bitvec, new_sample_idx_to_old_base[uii]) << uii;
1588 }
1589 if (widx == sample_ctl_m1) {
1590 memcpy(&(writebuf_walias[widx]), &cur_word, (cur_word_entry_ct + (CHAR_BIT - 1)) / CHAR_BIT);
1591 return;
1592 }
1593 writebuf_walias[widx++] = cur_word;
1594 new_sample_idx_to_old_base = &(new_sample_idx_to_old_base[kBitsPerWord]);
1595 }
1596 }
1597 */
1598
1599 // Now assumes trailing bits of genovec have been zeroed out.
1600 // writebuf need not be word-aligned.
1601 void GenovecPermute(const uintptr_t* genovec, const uint32_t* old_sample_idx_to_new, uint32_t sample_ct, unsigned char* writebuf) {
1602 const uintptr_t most_common_geno_word = MostCommonGenoUnsafe(genovec, sample_ct) * kMask5555;
1603 const uint32_t sample_ctl2_m1 = NypCtToWordCt(sample_ct) - 1;
1604 // er, this is probably suboptimal in no-unaligned case...
1605 for (uint32_t widx = 0; widx != sample_ctl2_m1; ++widx) {
1606 CopyToUnalignedOffsetW(writebuf, &most_common_geno_word, widx);
1607 }
1608 const uint32_t trailing_bit_ct = 2 * ModNz(sample_ct, kBitsPerWordD2);
1609 SubwordStore(bzhi_max(most_common_geno_word, trailing_bit_ct), DivUp(trailing_bit_ct, CHAR_BIT), &(writebuf[sample_ctl2_m1 * kBytesPerWord]));
1610
1611 for (uint32_t widx = 0; ; ++widx) {
1612 uintptr_t geno_word_xor;
1613 if (widx >= sample_ctl2_m1) {
1614 if (widx > sample_ctl2_m1) {
1615 return;
1616 }
1617 geno_word_xor = bzhi_max(most_common_geno_word ^ genovec[widx], trailing_bit_ct);
1618 } else {
1619 geno_word_xor = most_common_geno_word ^ genovec[widx];
1620 }
1621 if (!geno_word_xor) {
1622 continue;
1623 }
1624 const uint32_t* cur_old_sample_idx_to_new = &(old_sample_idx_to_new[widx * kBitsPerWordD2]);
1625 do {
1626 const uint32_t bit_read_shift_ct = ctzw(geno_word_xor) & (kBitsPerWord - 2);
1627 const uintptr_t cur_geno_xor = (geno_word_xor >> bit_read_shift_ct) & 3;
1628 const uint32_t new_sample_idx = cur_old_sample_idx_to_new[bit_read_shift_ct / 2];
1629 const uint32_t new_byte_idx = new_sample_idx / 4;
1630 const uint32_t bit_write_shift_ct = 2 * (new_sample_idx % 4);
1631 // Value has been preset to most_common_geno, so if we xor it with
1632 // (most_common_geno ^ actual_geno), the result is actual_geno.
1633 writebuf[new_byte_idx] ^= cur_geno_xor << bit_write_shift_ct;
1634 geno_word_xor &= (~(3 * k1LU)) << bit_read_shift_ct;
1635 } while (geno_word_xor);
1636 }
1637 }
1638
1639 void GenovecPermuteSubset(const uintptr_t* genovec, const uintptr_t* sample_include, const uintptr_t* sample_include_interleaved_vec, const uint32_t* old_sample_idx_to_new, uint32_t raw_sample_ct, uint32_t sample_ct, void* writebuf) {
1640 unsigned char* writebuf_uc = S_CAST(unsigned char*, writebuf);
1641 if (sample_ct == raw_sample_ct) {
1642 GenovecPermute(genovec, old_sample_idx_to_new, sample_ct, writebuf_uc);
1643 return;
1644 }
1645 STD_ARRAY_DECL(uint32_t, 4, genocounts);
1646 GenoarrCountSubsetFreqs(genovec, sample_include_interleaved_vec, raw_sample_ct, sample_ct, genocounts);
1647 uintptr_t most_common_geno = 0;
1648 uint32_t most_common_geno_ct = genocounts[0];
1649 if (most_common_geno_ct * 2 < sample_ct) {
1650 for (uintptr_t cur_geno = 1; cur_geno != 4; ++cur_geno) {
1651 if (most_common_geno_ct < genocounts[cur_geno]) {
1652 most_common_geno = cur_geno;
1653 most_common_geno_ct = genocounts[cur_geno];
1654 }
1655 }
1656 }
1657 const uintptr_t most_common_geno_word = most_common_geno * kMask5555;
1658 const uint32_t sample_ctl2_m1 = NypCtToWordCt(sample_ct) - 1;
1659 for (uint32_t widx = 0; widx != sample_ctl2_m1; ++widx) {
1660 CopyToUnalignedOffsetW(writebuf_uc, &most_common_geno_word, widx);
1661 }
1662 const uint32_t write_trailing_bit_ct = 2 * ModNz(sample_ct, kBitsPerWordD2);
1663 SubwordStore(bzhi_max(most_common_geno_word, write_trailing_bit_ct), DivUp(write_trailing_bit_ct, CHAR_BIT), &(writebuf_uc[sample_ctl2_m1 * kBytesPerWord]));
1664 if (most_common_geno_ct == sample_ct) {
1665 return;
1666 }
1667
1668 const uint32_t raw_sample_ctl2_m1 = NypCtToWordCt(raw_sample_ct) - 1;
1669 const Halfword* sample_include_alias = DowncastKWToHW(sample_include);
1670 for (uint32_t widx = 0; ; ++widx) {
1671 uintptr_t geno_word_xor;
1672 if (widx >= raw_sample_ctl2_m1) {
1673 if (widx > raw_sample_ctl2_m1) {
1674 return;
1675 }
1676 geno_word_xor = bzhi_max(most_common_geno_word ^ genovec[widx], 2 * ModNz(raw_sample_ct, kBitsPerWordD2));
1677 } else {
1678 geno_word_xor = most_common_geno_word ^ genovec[widx];
1679 }
1680 if (!geno_word_xor) {
1681 continue;
1682 }
1683 geno_word_xor &= UnpackHalfwordToWord(sample_include_alias[widx]) * 3;
1684 if (!geno_word_xor) {
1685 continue;
1686 }
1687 const uint32_t* cur_old_sample_idx_to_new = &(old_sample_idx_to_new[widx * kBitsPerWordD2]);
1688 do {
1689 const uint32_t bit_read_shift_ct = ctzw(geno_word_xor) & (kBitsPerWord - 2);
1690 const uintptr_t cur_geno_xor = (geno_word_xor >> bit_read_shift_ct) & 3;
1691 const uint32_t new_sample_idx = cur_old_sample_idx_to_new[bit_read_shift_ct / 2];
1692 const uint32_t new_byte_idx = new_sample_idx / 4;
1693 const uint32_t bit_write_shift_ct = 2 * (new_sample_idx % 4);
1694 writebuf_uc[new_byte_idx] ^= cur_geno_xor << bit_write_shift_ct;
1695 geno_word_xor &= (~(3 * k1LU)) << bit_read_shift_ct;
1696 } while (geno_word_xor);
1697 }
1698 }
1699
1700 // Revised phaseraw:
1701 // 4 byte het_ct, 4 byte explicit_phasepresent_ct
1702 // first half, up to (1 + (het_ct / kBitsPerWord)) words
1703 // second half, rounded up to vector boundary
1704 void UnpackHphase(const uintptr_t* __restrict all_hets, const uintptr_t* __restrict phaseraw, uint32_t raw_sample_ct, uintptr_t** phasepresent_ptr, uintptr_t* __restrict phaseinfo) {
1705 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
1706 const uint32_t het_ct = S_CAST(uint32_t, phaseraw[0]);
1707 const uintptr_t* aux2a = &(phaseraw[8 / kBytesPerWord]);
1708 if (!(aux2a[0] & 1)) {
1709 // phase always present
1710 *phasepresent_ptr = nullptr;
1711 ExpandBytearr(aux2a, all_hets, raw_sample_ctl, het_ct, 1, phaseinfo);
1712 } else {
1713 // bugfix (4 Mar 2018): need to pass raw_phasepresent_ct, not het_ct
1714 #ifdef __LP64__
1715 const uint32_t raw_phasepresent_ct = phaseraw[0] >> 32;
1716 #else
1717 const uint32_t raw_phasepresent_ct = phaseraw[1];
1718 #endif
1719 const uintptr_t* aux2b = &(aux2a[1 + (het_ct / kBitsPerWord)]);
1720 ExpandBytearrNested(aux2b, aux2a, all_hets, raw_sample_ctl, raw_phasepresent_ct, 1, *phasepresent_ptr, phaseinfo);
1721 }
1722 }
1723
1724 void UnpackHphaseSubset(const uintptr_t* __restrict all_hets, const uintptr_t* __restrict phaseraw, const uintptr_t* __restrict sample_include, uint32_t sample_ct, uintptr_t** phasepresent_ptr, uintptr_t* __restrict phaseinfo) {
1725 // const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
1726 // const uint32_t het_ct = PopcountWords(all_hets, raw_sample_ctl);
1727 const uint32_t het_ct = S_CAST(uint32_t, phaseraw[0]);
1728 const uintptr_t* aux2a = &(phaseraw[8 / kBytesPerWord]);
1729 if (!(aux2a[0] & 1)) {
1730 // phase always present
1731 *phasepresent_ptr = nullptr;
1732 ExpandThenSubsetBytearr(aux2a, all_hets, sample_include, het_ct, sample_ct, 1, phaseinfo);
1733 } else {
1734 const uint32_t first_half_word_ct = 1 + (het_ct / kBitsPerWord);
1735 // const uint32_t raw_phasepresent_ct = PopcountWords(phaseraw, first_half_word_ct) - 1;
1736 #ifdef __LP64__
1737 const uint32_t raw_phasepresent_ct = phaseraw[0] >> 32;
1738 #else
1739 const uint32_t raw_phasepresent_ct = phaseraw[1];
1740 #endif
1741 const uintptr_t* aux2b = &(aux2a[first_half_word_ct]);
1742
1743 // see "if (explicit_phasepresent) {}" block in PgrGetRaw(). Could
1744 // change this convention.
1745 ExpandThenSubsetBytearrNested(aux2b, aux2a, all_hets, sample_include, sample_ct, raw_phasepresent_ct, 1, *phasepresent_ptr, phaseinfo);
1746 }
1747 }
1748
1749 void UnpackAndPermuteHphase(const uintptr_t* __restrict all_hets, const uintptr_t* __restrict phaseraw, const uintptr_t* sample_include, const uint32_t* old_sample_idx_to_new, uint32_t raw_sample_ct, uint32_t sample_ct, uintptr_t** phasepresent_ptr, uintptr_t* __restrict phaseinfo) {
1750 const uintptr_t* aux2a_iter = &(phaseraw[8 / kBytesPerWord]);
1751 const uint32_t* old_sample_idx_to_new_iter = old_sample_idx_to_new;
1752 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
1753 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
1754 uintptr_t aux2a_word = *aux2a_iter++;
1755 uint32_t read_idx_lowbits = 1;
1756 ZeroWArr(sample_ctl, phaseinfo);
1757 if (!(aux2a_word & 1)) {
1758 // phase always present
1759 *phasepresent_ptr = nullptr;
1760 for (uint32_t widx = 0; widx != raw_sample_ctl; ++widx) {
1761 uintptr_t new_phasepresent_word = all_hets[widx];
1762 const uint32_t read_idx_lowbits_end = read_idx_lowbits + PopcountWord(new_phasepresent_word);
1763 uintptr_t tmp_phaseinfo_input_word = aux2a_word >> read_idx_lowbits;
1764 if (read_idx_lowbits_end >= kBitsPerWord) {
1765 // always safe to read an extra word off the end
1766 aux2a_word = *aux2a_iter++;
1767 if (read_idx_lowbits) {
1768 tmp_phaseinfo_input_word |= aux2a_word << (kBitsPerWord - read_idx_lowbits);
1769 }
1770 }
1771 // no need to mask off top bits of tmp_phaseinfo_input_word
1772 read_idx_lowbits = read_idx_lowbits_end % kBitsPerWord;
1773 if (!sample_include) {
1774 #ifdef USE_AVX2
1775 uintptr_t phaseinfo_bits_to_set = _pdep_u64(tmp_phaseinfo_input_word, new_phasepresent_word);
1776 while (phaseinfo_bits_to_set) {
1777 const uint32_t sample_uidx_lowbits = ctzw(phaseinfo_bits_to_set);
1778 const uint32_t new_sample_idx = old_sample_idx_to_new_iter[sample_uidx_lowbits];
1779 SetBit(new_sample_idx, phaseinfo);
1780 phaseinfo_bits_to_set &= phaseinfo_bits_to_set - 1;
1781 }
1782 #else
1783 while (new_phasepresent_word) {
1784 const uint32_t sample_uidx_lowbits = ctzw(new_phasepresent_word);
1785 if (tmp_phaseinfo_input_word & 1) {
1786 const uint32_t new_sample_idx = old_sample_idx_to_new_iter[sample_uidx_lowbits];
1787 SetBit(new_sample_idx, phaseinfo);
1788 }
1789 tmp_phaseinfo_input_word >>= 1;
1790 new_phasepresent_word &= new_phasepresent_word - 1;
1791 }
1792 #endif
1793 } else {
1794 #ifdef USE_AVX2
1795 uintptr_t phaseinfo_bits_to_set = _pdep_u64(tmp_phaseinfo_input_word, new_phasepresent_word) & sample_include[widx];
1796 while (phaseinfo_bits_to_set) {
1797 const uint32_t sample_uidx_lowbits = ctzw(phaseinfo_bits_to_set);
1798 const uint32_t new_sample_idx = old_sample_idx_to_new_iter[sample_uidx_lowbits];
1799 SetBit(new_sample_idx, phaseinfo);
1800 phaseinfo_bits_to_set &= phaseinfo_bits_to_set - 1;
1801 }
1802 #else
1803 uintptr_t masked_phasepresent_word = new_phasepresent_word & sample_include[widx];
1804 while (masked_phasepresent_word) {
1805 const uint32_t sample_uidx_lowbits = ctzw(masked_phasepresent_word);
1806 const uintptr_t lowmask = (k1LU << sample_uidx_lowbits) - k1LU;
1807 if ((tmp_phaseinfo_input_word >> PopcountWord(new_phasepresent_word & lowmask)) & 1) {
1808 const uint32_t new_sample_idx = old_sample_idx_to_new_iter[sample_uidx_lowbits];
1809 SetBit(new_sample_idx, phaseinfo);
1810 }
1811 masked_phasepresent_word &= masked_phasepresent_word - 1;
1812 }
1813 #endif
1814 }
1815 old_sample_idx_to_new_iter = &(old_sample_idx_to_new_iter[kBitsPerWord]);
1816 }
1817 return;
1818 }
1819 uintptr_t* phasepresent = *phasepresent_ptr;
1820 const uint32_t het_ct = S_CAST(uint32_t, phaseraw[0]);
1821 const uintptr_t* phaseinfo_read_iter = &(phaseraw[(8 / kBytesPerWord) + 1 + (het_ct / kBitsPerWord)]);
1822 uintptr_t phaseinfo_read_word = *phaseinfo_read_iter++;
1823 uint32_t phaseinfo_read_idx_lowbits = 0;
1824 ZeroWArr(sample_ctl, phasepresent);
1825 for (uint32_t widx = 0; widx != raw_sample_ctl; ++widx) {
1826 uintptr_t geno_hets = all_hets[widx];
1827 if (geno_hets) {
1828 const uint32_t read_idx_lowbits_end = read_idx_lowbits + PopcountWord(geno_hets);
1829 uintptr_t tmp_phasepresent_input_word = aux2a_word >> read_idx_lowbits;
1830 if (read_idx_lowbits_end >= kBitsPerWord) {
1831 // always safe to read an extra word off the end, when
1832 // read_idx_lowbits_end == kBitsPerWord and we're at the last word
1833 aux2a_word = *aux2a_iter++;
1834 if (read_idx_lowbits) {
1835 tmp_phasepresent_input_word |= aux2a_word << (kBitsPerWord - read_idx_lowbits);
1836 }
1837 }
1838 tmp_phasepresent_input_word = bzhi_max(tmp_phasepresent_input_word, read_idx_lowbits_end - read_idx_lowbits);
1839 read_idx_lowbits = read_idx_lowbits_end % kBitsPerWord;
1840 if (tmp_phasepresent_input_word) {
1841 const uint32_t read_phasepresent_ct = PopcountWord(tmp_phasepresent_input_word);
1842 uintptr_t tmp_phaseinfo_input_word;
1843 // avoid reading off end of phaseinfo here
1844 if (phaseinfo_read_idx_lowbits != kBitsPerWord) {
1845 const uint32_t phaseinfo_read_idx_lowbits_end = phaseinfo_read_idx_lowbits + read_phasepresent_ct;
1846 tmp_phaseinfo_input_word = phaseinfo_read_word >> phaseinfo_read_idx_lowbits;
1847 if (phaseinfo_read_idx_lowbits_end < kBitsPerWord) {
1848 phaseinfo_read_idx_lowbits = phaseinfo_read_idx_lowbits_end;
1849 } else {
1850 phaseinfo_read_word = *phaseinfo_read_iter++;
1851 tmp_phaseinfo_input_word |= phaseinfo_read_word << (kBitsPerWord - phaseinfo_read_idx_lowbits);
1852 phaseinfo_read_idx_lowbits = phaseinfo_read_idx_lowbits_end - kBitsPerWord;
1853 }
1854 } else {
1855 // special case, can't right-shift 64
1856 phaseinfo_read_word = *phaseinfo_read_iter++;
1857 phaseinfo_read_idx_lowbits = read_phasepresent_ct;
1858 tmp_phaseinfo_input_word = phaseinfo_read_word;
1859 }
1860 // no need to mask off top bits of tmp_phaseinfo_input_word
1861 if (!sample_include) {
1862 #ifdef USE_AVX2
1863 for (uintptr_t phasepresent_bits_to_set = _pdep_u64(tmp_phasepresent_input_word, geno_hets); ; ) {
1864 const uint32_t new_sample_idx = old_sample_idx_to_new_iter[ctzw(phasepresent_bits_to_set)];
1865 const uint32_t new_sample_widx = new_sample_idx / kBitsPerWord;
1866 const uint32_t new_sample_lowbits = new_sample_idx % kBitsPerWord;
1867 const uintptr_t shifted_bit = k1LU << new_sample_lowbits;
1868 phasepresent[new_sample_widx] |= shifted_bit;
1869 if (tmp_phaseinfo_input_word & 1) {
1870 phaseinfo[new_sample_widx] |= shifted_bit;
1871 }
1872 // branchless version doesn't seem to be any better here; probably
1873 // due to additional random memory access.
1874 // phaseinfo[new_sample_widx] |= (tmp_phaseinfo_input_word & 1) << new_sample_lowbits;
1875
1876 phasepresent_bits_to_set &= phasepresent_bits_to_set - 1;
1877 if (!phasepresent_bits_to_set) {
1878 break;
1879 }
1880 tmp_phaseinfo_input_word >>= 1;
1881 }
1882 #else
1883 for (; ; tmp_phasepresent_input_word >>= 1) {
1884 if (tmp_phasepresent_input_word & 1) {
1885 const uint32_t new_sample_idx = old_sample_idx_to_new_iter[ctzw(geno_hets)];
1886 const uint32_t new_sample_widx = new_sample_idx / kBitsPerWord;
1887 const uint32_t new_sample_lowbits = new_sample_idx % kBitsPerWord;
1888 const uintptr_t shifted_bit = k1LU << new_sample_lowbits;
1889 phasepresent[new_sample_widx] |= shifted_bit;
1890 if (tmp_phaseinfo_input_word & 1) {
1891 phaseinfo[new_sample_widx] |= shifted_bit;
1892 }
1893 if (tmp_phasepresent_input_word == 1) {
1894 break;
1895 }
1896 tmp_phaseinfo_input_word >>= 1;
1897 }
1898 geno_hets &= geno_hets - 1;
1899 }
1900 #endif
1901 } else {
1902 const uintptr_t sample_include_word = sample_include[widx];
1903 #ifdef USE_AVX2
1904 const uintptr_t phasepresent_word_expanded = _pdep_u64(tmp_phasepresent_input_word, geno_hets);
1905 uintptr_t phasepresent_bits_to_set = phasepresent_word_expanded & sample_include_word;
1906 if (phasepresent_bits_to_set) {
1907 // tmp_phaseinfo_input_word gives us the phasing state of the
1908 // positions in phasepresent_word_expanded.
1909 // However, we're only iterating over the positions in
1910 // (phasepresent_word_expanded & sample_include_word).
1911 // (can replace sample_include_word with phasepresent_bits_to_set
1912 // in this expression)
1913 uintptr_t collapsed_phaseinfo_input_word = _pext_u64(tmp_phaseinfo_input_word, _pext_u64(sample_include_word, phasepresent_word_expanded));
1914 while (1) {
1915 const uint32_t new_sample_idx = old_sample_idx_to_new_iter[ctzw(phasepresent_bits_to_set)];
1916 const uint32_t new_sample_widx = new_sample_idx / kBitsPerWord;
1917 const uint32_t new_sample_lowbits = new_sample_idx % kBitsPerWord;
1918 const uintptr_t shifted_bit = k1LU << new_sample_lowbits;
1919 phasepresent[new_sample_widx] |= shifted_bit;
1920 if (collapsed_phaseinfo_input_word & 1) {
1921 phaseinfo[new_sample_widx] |= shifted_bit;
1922 }
1923
1924 phasepresent_bits_to_set &= phasepresent_bits_to_set - 1;
1925 if (!phasepresent_bits_to_set) {
1926 break;
1927 }
1928 collapsed_phaseinfo_input_word >>= 1;
1929 }
1930 }
1931 #else
1932 for (; ; tmp_phasepresent_input_word >>= 1) {
1933 if (tmp_phasepresent_input_word & 1) {
1934 const uintptr_t geno_hets_lowbit = geno_hets & (-geno_hets);
1935 if (sample_include_word & geno_hets_lowbit) {
1936 const uint32_t sample_uidx_lowbits = ctzw(geno_hets_lowbit);
1937 const uint32_t new_sample_idx = old_sample_idx_to_new_iter[sample_uidx_lowbits];
1938 const uint32_t new_sample_widx = new_sample_idx / kBitsPerWord;
1939 const uint32_t new_sample_lowbits = new_sample_idx % kBitsPerWord;
1940 const uintptr_t shifted_bit = k1LU << new_sample_lowbits;
1941 phasepresent[new_sample_widx] |= shifted_bit;
1942 if (tmp_phaseinfo_input_word & 1) {
1943 phaseinfo[new_sample_widx] |= shifted_bit;
1944 }
1945 }
1946 if (tmp_phasepresent_input_word == 1) {
1947 break;
1948 }
1949 tmp_phaseinfo_input_word >>= 1;
1950 }
1951 geno_hets &= geno_hets - 1;
1952 }
1953 #endif
1954 }
1955 }
1956 }
1957 old_sample_idx_to_new_iter = &(old_sample_idx_to_new_iter[kBitsPerWord]);
1958 }
1959 }
1960
1961
1962 // these also work on dphaseraw
1963 void CopyDosage(const uintptr_t* __restrict read_dosagepresent, const Dosage* read_dosagevals, uint32_t raw_sample_ct, uint32_t dosage_ct, uintptr_t* __restrict write_dosagepresent, Dosage* write_dosagevals, uint32_t* write_dosage_ct_ptr) {
1964 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
1965 *write_dosage_ct_ptr = dosage_ct;
1966 memcpy(write_dosagepresent, read_dosagepresent, raw_sample_ctl * sizeof(intptr_t));
1967 memcpy(write_dosagevals, read_dosagevals, dosage_ct * sizeof(Dosage));
1968 }
1969
1970 uint32_t CopyAndPermute8bit(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict src_subset, const void* __restrict src_vals, const uint32_t* __restrict old_sample_idx_to_new, uint32_t sample_ct, uint32_t val_ct, uintptr_t* __restrict dst_subset, void* __restrict dst_vals) {
1971 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
1972 ZeroWArr(sample_ctl, dst_subset);
1973 const unsigned char* src_vals_uc = S_CAST(const unsigned char*, src_vals);
1974 unsigned char* dst_vals_uc = S_CAST(unsigned char*, dst_vals);
1975
1976 uintptr_t cur_bits = src_subset[0];
1977 uint32_t new_val_ct;
1978 if (!sample_include) {
1979 uintptr_t old_sample_idx_base = 0;
1980 for (uint32_t old_val_idx = 0; old_val_idx != val_ct; ++old_val_idx) {
1981 const uint32_t old_sample_idx = BitIter1(src_subset, &old_sample_idx_base, &cur_bits);
1982 const uint32_t new_sample_idx = old_sample_idx_to_new[old_sample_idx];
1983 SetBit(new_sample_idx, dst_subset);
1984 dst_vals_uc[new_sample_idx] = src_vals_uc[old_val_idx];
1985 }
1986 new_val_ct = val_ct;
1987 } else {
1988 uintptr_t widx = 0;
1989 new_val_ct = 0;
1990 for (uint32_t old_val_idx = 0; old_val_idx != val_ct; ++old_val_idx) {
1991 const uintptr_t old_sample_idx_lowbit = BitIter1y(src_subset, &widx, &cur_bits);
1992 if (!(sample_include[widx] & old_sample_idx_lowbit)) {
1993 continue;
1994 }
1995 const uint32_t old_sample_idx = widx * kBitsPerWord + ctzw(old_sample_idx_lowbit);
1996 const uint32_t new_sample_idx = old_sample_idx_to_new[old_sample_idx];
1997 SetBit(new_sample_idx, dst_subset);
1998 dst_vals_uc[new_sample_idx] = src_vals_uc[old_val_idx];
1999 ++new_val_ct;
2000 }
2001 }
2002 uintptr_t new_sample_idx_base = 0;
2003 cur_bits = dst_subset[0];
2004 for (uint32_t new_val_idx = 0; new_val_idx != new_val_ct; ++new_val_idx) {
2005 const uint32_t new_sample_idx = BitIter1(dst_subset, &new_sample_idx_base, &cur_bits);
2006 dst_vals_uc[new_val_idx] = dst_vals_uc[new_sample_idx];
2007 }
2008 return new_val_ct;
2009 }
2010
2011 uint32_t CopyAndPermute16bit(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict src_subset, const void* __restrict src_vals, const uint32_t* __restrict old_sample_idx_to_new, uint32_t sample_ct, uint32_t val_ct, uintptr_t* __restrict dst_subset, void* __restrict dst_vals) {
2012 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
2013 ZeroWArr(sample_ctl, dst_subset);
2014 const uint16_t* src_vals_u16 = S_CAST(const uint16_t*, src_vals);
2015 uint16_t* dst_vals_u16 = S_CAST(uint16_t*, dst_vals);
2016
2017 uintptr_t cur_bits = src_subset[0];
2018 uint32_t new_val_ct;
2019 if (!sample_include) {
2020 uintptr_t old_sample_idx_base = 0;
2021 for (uint32_t old_val_idx = 0; old_val_idx != val_ct; ++old_val_idx) {
2022 const uint32_t old_sample_idx = BitIter1(src_subset, &old_sample_idx_base, &cur_bits);
2023 const uint32_t new_sample_idx = old_sample_idx_to_new[old_sample_idx];
2024 SetBit(new_sample_idx, dst_subset);
2025 dst_vals_u16[new_sample_idx] = src_vals_u16[old_val_idx];
2026 }
2027 new_val_ct = val_ct;
2028 } else {
2029 uintptr_t widx = 0;
2030 new_val_ct = 0;
2031 for (uint32_t old_val_idx = 0; old_val_idx != val_ct; ++old_val_idx) {
2032 const uintptr_t old_sample_idx_lowbit = BitIter1y(src_subset, &widx, &cur_bits);
2033 if (!(sample_include[widx] & old_sample_idx_lowbit)) {
2034 continue;
2035 }
2036 const uint32_t old_sample_idx = widx * kBitsPerWord + ctzw(old_sample_idx_lowbit);
2037 const uint32_t new_sample_idx = old_sample_idx_to_new[old_sample_idx];
2038 SetBit(new_sample_idx, dst_subset);
2039 dst_vals_u16[new_sample_idx] = src_vals_u16[old_val_idx];
2040 ++new_val_ct;
2041 }
2042 }
2043 uintptr_t new_sample_idx_base = 0;
2044 cur_bits = dst_subset[0];
2045 for (uint32_t new_val_idx = 0; new_val_idx != new_val_ct; ++new_val_idx) {
2046 const uint32_t new_sample_idx = BitIter1(dst_subset, &new_sample_idx_base, &cur_bits);
2047 dst_vals_u16[new_val_idx] = dst_vals_u16[new_sample_idx];
2048 }
2049 return new_val_ct;
2050 }
2051
2052 uint32_t Dense8bitToSparse(const uintptr_t* __restrict set, uint32_t sample_ctl, void* __restrict vals) {
2053 unsigned char* vals_uc = S_CAST(unsigned char*, vals);
2054 uint32_t write_idx = 0;
2055 for (uint32_t widx = 0; widx != sample_ctl; ++widx) {
2056 uintptr_t set_word = set[widx];
2057 if (!set_word) {
2058 continue;
2059 }
2060 unsigned char* cur_vals_read = &(vals_uc[widx * kBitsPerWord]);
2061 do {
2062 const uint32_t sample_idx_lowbits = ctzw(set_word);
2063 vals_uc[write_idx++] = cur_vals_read[sample_idx_lowbits];
2064 set_word &= set_word - 1;
2065 } while (set_word);
2066 }
2067 return write_idx;
2068 }
2069
2070 uint32_t Dense16bitToSparse(const uintptr_t* __restrict set, uint32_t sample_ctl, void* __restrict vals) {
2071 uint16_t* vals_u16 = S_CAST(uint16_t*, vals);
2072 uint32_t write_idx = 0;
2073 for (uint32_t widx = 0; widx != sample_ctl; ++widx) {
2074 uintptr_t set_word = set[widx];
2075 if (!set_word) {
2076 continue;
2077 }
2078 uint16_t* cur_vals_read = &(vals_u16[widx * kBitsPerWord]);
2079 do {
2080 const uint32_t sample_idx_lowbits = ctzw(set_word);
2081 vals_u16[write_idx++] = cur_vals_read[sample_idx_lowbits];
2082 set_word &= set_word - 1;
2083 } while (set_word);
2084 }
2085 return write_idx;
2086 }
2087
2088 // Requires trailing bits of genovec to be zeroed out.
2089 // "Flat" = don't separate one_cts and two_cts.
2090 void GetMFlatCounts64(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict sample_include_interleaved_vec, const PgenVariant* pgvp, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t allele_ct, STD_ARRAY_REF(uint32_t, 4) genocounts, uint64_t* all_dosages) {
2091 if (sample_ct == raw_sample_ct) {
2092 GenoarrCountFreqsUnsafe(pgvp->genovec, sample_ct, genocounts);
2093 } else {
2094 GenoarrCountSubsetFreqs(pgvp->genovec, sample_include_interleaved_vec, raw_sample_ct, sample_ct, genocounts);
2095 }
2096 all_dosages[0] = 2 * genocounts[0] + genocounts[1];
2097 all_dosages[1] = 2 * genocounts[2] + genocounts[1];
2098 ZeroU64Arr(allele_ct - 2, &(all_dosages[2]));
2099 const AlleleCode* patch_01_vals = pgvp->patch_01_vals;
2100 const AlleleCode* patch_10_vals = pgvp->patch_10_vals;
2101 const uint32_t patch_01_ct = pgvp->patch_01_ct;
2102 const uint32_t patch_10_ct = pgvp->patch_10_ct;
2103 if (sample_ct == raw_sample_ct) {
2104 all_dosages[1] -= patch_01_ct + 2 * patch_10_ct;
2105 for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
2106 all_dosages[patch_01_vals[uii]] += 1;
2107 }
2108 const uint32_t patch_10_ct_x2 = patch_10_ct * 2;
2109 for (uint32_t uii = 0; uii != patch_10_ct_x2; ++uii) {
2110 all_dosages[patch_10_vals[uii]] += 1;
2111 }
2112 } else {
2113 if (patch_01_ct) {
2114 const uintptr_t* patch_01_set = pgvp->patch_01_set;
2115 uintptr_t sample_widx = 0;
2116 uintptr_t patch_01_bits = patch_01_set[0];
2117 uint32_t subsetted_patch_01_ct = 0;
2118 for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
2119 const uintptr_t lowbit = BitIter1y(patch_01_set, &sample_widx, &patch_01_bits);
2120 if (sample_include[sample_widx] & lowbit) {
2121 all_dosages[patch_01_vals[uii]] += 1;
2122 ++subsetted_patch_01_ct;
2123 }
2124 }
2125 all_dosages[1] -= subsetted_patch_01_ct;
2126 }
2127 if (patch_10_ct) {
2128 const uintptr_t* patch_10_set = pgvp->patch_10_set;
2129 uintptr_t sample_widx = 0;
2130 uintptr_t patch_10_bits = patch_10_set[0];
2131 uint32_t subsetted_patch_10_ct = 0;
2132 for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
2133 const uintptr_t lowbit = BitIter1y(patch_10_set, &sample_widx, &patch_10_bits);
2134 if (sample_include[sample_widx] & lowbit) {
2135 all_dosages[patch_10_vals[2 * uii]] += 1;
2136 all_dosages[patch_10_vals[2 * uii + 1]] += 1;
2137 ++subsetted_patch_10_ct;
2138 }
2139 }
2140 all_dosages[1] -= 2 * subsetted_patch_10_ct;
2141 }
2142 }
2143 }
2144
2145 void GetMCounts64(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict sample_include_interleaved_vec, const PgenVariant* pgvp, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t allele_ct, STD_ARRAY_REF(uint32_t, 4) genocounts, uint64_t* __restrict one_cts, uint64_t* __restrict two_cts) {
2146 // This mirrors GetMultiallelicCountsAndDosage16s().
2147 if (sample_ct == raw_sample_ct) {
2148 GenoarrCountFreqsUnsafe(pgvp->genovec, sample_ct, genocounts);
2149 } else {
2150 GenoarrCountSubsetFreqs(pgvp->genovec, sample_include_interleaved_vec, raw_sample_ct, sample_ct, genocounts);
2151 }
2152 one_cts[0] = genocounts[1];
2153 one_cts[1] = genocounts[1];
2154 ZeroU64Arr(allele_ct - 2, &(one_cts[2]));
2155 two_cts[0] = genocounts[0];
2156 two_cts[1] = genocounts[2];
2157 ZeroU64Arr(allele_ct - 2, &(two_cts[2]));
2158 const AlleleCode* patch_01_vals = pgvp->patch_01_vals;
2159 const AlleleCode* patch_10_vals = pgvp->patch_10_vals;
2160 const uint32_t patch_01_ct = pgvp->patch_01_ct;
2161 const uint32_t patch_10_ct = pgvp->patch_10_ct;
2162 if (sample_ct == raw_sample_ct) {
2163 one_cts[1] -= patch_01_ct;
2164 for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
2165 one_cts[patch_01_vals[uii]] += 1;
2166 }
2167 two_cts[1] -= patch_10_ct;
2168 const AlleleCode* patch_10_vals_iter = patch_10_vals;
2169 for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
2170 const AlleleCode code_lo = *patch_10_vals_iter++;
2171 const AlleleCode code_hi = *patch_10_vals_iter++;
2172 if (code_lo == code_hi) {
2173 two_cts[code_lo] += 1;
2174 } else {
2175 one_cts[code_lo] += 1;
2176 one_cts[code_hi] += 1;
2177 }
2178 }
2179 } else {
2180 if (patch_01_ct) {
2181 const uintptr_t* patch_01_set = pgvp->patch_01_set;
2182 uintptr_t sample_widx = 0;
2183 uintptr_t patch_01_bits = patch_01_set[0];
2184 uint32_t subsetted_patch_01_ct = 0;
2185 for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
2186 const uintptr_t lowbit = BitIter1y(patch_01_set, &sample_widx, &patch_01_bits);
2187 if (sample_include[sample_widx] & lowbit) {
2188 one_cts[patch_01_vals[uii]] += 1;
2189 ++subsetted_patch_01_ct;
2190 }
2191 }
2192 one_cts[1] -= subsetted_patch_01_ct;
2193 }
2194 if (patch_10_ct) {
2195 const uintptr_t* patch_10_set = pgvp->patch_10_set;
2196 uintptr_t sample_widx = 0;
2197 uintptr_t patch_10_bits = patch_10_set[0];
2198 uint32_t subsetted_patch_10_ct = 0;
2199 for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
2200 const uintptr_t lowbit = BitIter1y(patch_10_set, &sample_widx, &patch_10_bits);
2201 if (sample_include[sample_widx] & lowbit) {
2202 ++subsetted_patch_10_ct;
2203 const AlleleCode code_lo = patch_10_vals[2 * uii];
2204 const AlleleCode code_hi = patch_10_vals[2 * uii + 1];
2205 if (code_lo == code_hi) {
2206 two_cts[code_lo] += 1;
2207 } else {
2208 one_cts[code_lo] += 1;
2209 one_cts[code_hi] += 1;
2210 }
2211 }
2212 }
2213 two_cts[1] -= subsetted_patch_10_ct;
2214 }
2215 }
2216 }
2217
2218 typedef struct LoadAlleleAndGenoCountsCtxStruct {
2219 const uintptr_t* variant_include;
2220 const ChrInfo* cip;
2221 const uintptr_t* allele_idx_offsets;
2222 const uintptr_t* sample_include;
2223 uintptr_t* sample_include_interleaved_vec;
2224 uint32_t* sample_include_cumulative_popcounts;
2225 const uintptr_t* sex_male;
2226 const uintptr_t* sex_nonfemale;
2227 uintptr_t* sex_male_interleaved_vec;
2228 uintptr_t* sex_nonfemale_interleaved_vec;
2229 uint32_t* sex_nonfemale_cumulative_popcounts;
2230 uintptr_t* nosex_interleaved_vec;
2231 const uintptr_t* founder_info;
2232 uintptr_t* founder_info_interleaved_vec;
2233 uint32_t* founder_info_cumulative_popcounts;
2234 uintptr_t* founder_male;
2235 uintptr_t* founder_nonfemale;
2236 uintptr_t* founder_male_interleaved_vec;
2237 uintptr_t* founder_nonfemale_interleaved_vec;
2238 uint32_t* founder_nonfemale_cumulative_popcounts;
2239 uintptr_t* founder_nosex_interleaved_vec;
2240 uint32_t raw_sample_ct;
2241 uint32_t sample_ct;
2242 uint32_t founder_ct;
2243 uint32_t male_ct;
2244 uint32_t nosex_ct;
2245 uint32_t chry_missingstat_sample_ct;
2246 uint32_t founder_male_ct;
2247 uint32_t founder_nosex_ct;
2248 uint32_t founder_chry_missingstat_sample_ct;
2249 uint32_t first_hap_uidx;
2250 uint32_t is_minimac3_r2;
2251
2252 PgenReader** pgr_ptrs;
2253
2254 uintptr_t** genovecs;
2255 uintptr_t** thread_read_mhc;
2256 uintptr_t** dosage_presents;
2257 Dosage** dosage_mains;
2258 uint64_t** all_dosages;
2259 uint32_t* read_variant_uidx_starts;
2260
2261 // shouldn't need array, or errno storage, since kPglRetMalformedInput is the
2262 // only possible error for now
2263 uint64_t err_info;
2264
2265 uint32_t cur_block_size;
2266
2267 unsigned char* allele_presents_bytearr;
2268 uint64_t* allele_ddosages;
2269 STD_ARRAY_PTR_DECL(uint32_t, 3, raw_geno_cts);
2270 uint32_t* variant_missing_hc_cts;
2271 uint32_t* variant_missing_dosage_cts;
2272 uint32_t* variant_hethap_cts;
2273 uint64_t* founder_allele_ddosages;
2274 STD_ARRAY_PTR_DECL(uint32_t, 3, founder_raw_geno_cts);
2275 STD_ARRAY_PTR_DECL(uint32_t, 3, x_male_geno_cts);
2276 STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_male_geno_cts);
2277 STD_ARRAY_PTR_DECL(uint32_t, 3, x_nosex_geno_cts);
2278 STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_nosex_geno_cts);
2279 double* imp_r2_vals;
2280 } LoadAlleleAndGenoCountsCtx;
2281
2282 THREAD_FUNC_DECL LoadAlleleAndGenoCountsThread(void* raw_arg) {
2283 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
2284 const uintptr_t tidx = arg->tidx;
2285 LoadAlleleAndGenoCountsCtx* ctx = S_CAST(LoadAlleleAndGenoCountsCtx*, arg->sharedp->context);
2286
2287 const uintptr_t* variant_include = ctx->variant_include;
2288 const ChrInfo* cip = ctx->cip;
2289 const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
2290 const uint32_t thread_ct = GetThreadCt(arg->sharedp);
2291 const uint32_t subset_ct = (ctx->founder_info != nullptr) + 1;
2292 const uint32_t raw_sample_ct = ctx->raw_sample_ct;
2293 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
2294 const uint32_t first_hap_uidx = ctx->first_hap_uidx;
2295 const uint32_t is_minimac3_r2 = ctx->is_minimac3_r2;
2296 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
2297 PgenReader* pgrp = ctx->pgr_ptrs[tidx];
2298 PgenVariant pgv;
2299 pgv.genovec = ctx->genovecs[tidx];
2300 SetPgvThreadMhcNull(raw_sample_ct, tidx, ctx->thread_read_mhc, &pgv);
2301 pgv.dosage_present = nullptr;
2302 pgv.dosage_main = nullptr;
2303 if (ctx->dosage_presents) {
2304 pgv.dosage_present = ctx->dosage_presents[tidx];
2305 pgv.dosage_main = ctx->dosage_mains[tidx];
2306 }
2307 uint64_t* all_dosages = nullptr;
2308 if (ctx->all_dosages) {
2309 all_dosages = ctx->all_dosages[tidx];
2310 }
2311 uint32_t is_y = 0;
2312 uint32_t is_nonxy_haploid = 0;
2313 uint32_t x_start = 0;
2314 uint32_t x_code;
2315 if (XymtExists(cip, kChrOffsetX, &x_code)) {
2316 const uint32_t x_chr_fo_idx = cip->chr_idx_to_foidx[x_code];
2317 x_start = cip->chr_fo_vidx_start[x_chr_fo_idx];
2318 }
2319 uint32_t allele_ct = 2;
2320 uint64_t new_err_info;
2321 do {
2322 const uintptr_t cur_block_size = ctx->cur_block_size;
2323 // no overflow danger since cur_block_size <= 2^16, tidx < (2^16 - 1)
2324 const uint32_t cur_idx_end = ((tidx + 1) * cur_block_size) / thread_ct;
2325 const uintptr_t* sample_include = ctx->sample_include;
2326 const uintptr_t* sample_include_interleaved_vec = ctx->sample_include_interleaved_vec;
2327 const uint32_t* sample_include_cumulative_popcounts = ctx->sample_include_cumulative_popcounts;
2328 const uintptr_t* sex_male = ctx->sex_male;
2329 const uintptr_t* sex_male_interleaved_vec = ctx->sex_male_interleaved_vec;
2330 const uintptr_t* sex_nonfemale = ctx->sex_nonfemale;
2331 const uintptr_t* sex_nonfemale_interleaved_vec = ctx->sex_nonfemale_interleaved_vec;
2332 const uint32_t* sex_nonfemale_cumulative_popcounts = ctx->sex_nonfemale_cumulative_popcounts;
2333 const uintptr_t* nosex_interleaved_vec = ctx->nosex_interleaved_vec;
2334 uint32_t sample_ct = ctx->sample_ct;
2335 uint32_t male_ct = ctx->male_ct;
2336 uint32_t nosex_ct = ctx->nosex_ct;
2337 uint32_t nonfemale_ct = male_ct + nosex_ct;
2338 uint32_t chry_missingstat_sample_ct = ctx->chry_missingstat_sample_ct;
2339 unsigned char* allele_presents_bytearr = ctx->allele_presents_bytearr;
2340 uint64_t* allele_ddosages = ctx->allele_ddosages;
2341 STD_ARRAY_PTR_DECL(uint32_t, 3, raw_geno_cts) = ctx->raw_geno_cts;
2342 uint32_t* variant_missing_hc_cts = ctx->variant_missing_hc_cts;
2343 uint32_t* variant_missing_dosage_cts = ctx->variant_missing_dosage_cts;
2344 uint32_t* variant_hethap_cts = ctx->variant_hethap_cts;
2345 STD_ARRAY_PTR_DECL(uint32_t, 3, x_male_geno_cts) = ctx->x_male_geno_cts;
2346 STD_ARRAY_PTR_DECL(uint32_t, 3, x_nosex_geno_cts) = ctx->x_nosex_geno_cts;
2347 double* imp_r2_vals = ctx->imp_r2_vals;
2348 pgv.dosage_ct = 0;
2349 for (uint32_t subset_idx = 0; ; ) {
2350 // bugfix (29 Dec 2019): this boolean can change with subset_idx
2351 const uint32_t no_multiallelic_branch = (!variant_hethap_cts) && (!allele_presents_bytearr) && (!allele_ddosages) && (!imp_r2_vals);
2352 PgrSampleSubsetIndex pssi;
2353 PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, pgrp, &pssi);
2354 uint32_t cur_idx = (tidx * cur_block_size) / thread_ct;
2355 uintptr_t variant_uidx_base;
2356 uintptr_t variant_include_bits;
2357 BitIter1Start(variant_include, ctx->read_variant_uidx_starts[tidx], &variant_uidx_base, &variant_include_bits);
2358 uint32_t chr_end = 0;
2359 uint32_t is_x_or_y = 0;
2360 STD_ARRAY_DECL(uint32_t, 4, genocounts);
2361 STD_ARRAY_DECL(uint32_t, 4, sex_specific_genocounts);
2362 for (; cur_idx != cur_idx_end; ++cur_idx) {
2363 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
2364 if (variant_uidx >= chr_end) {
2365 const uint32_t chr_fo_idx = GetVariantChrFoIdx(cip, variant_uidx);
2366 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
2367 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
2368 is_y = 0;
2369 is_nonxy_haploid = 0;
2370 if (chr_idx == x_code) {
2371 is_x_or_y = 1;
2372 PgrClearSampleSubsetIndex(pgrp, &pssi);
2373 } else if (chr_idx == y_code) {
2374 is_x_or_y = 1;
2375 is_y = 1;
2376 // ugh
2377 if ((nonfemale_ct == chry_missingstat_sample_ct) && ((!allele_presents_bytearr) || (sample_ct == nonfemale_ct))) {
2378 PgrSetSampleSubsetIndex(sex_nonfemale_cumulative_popcounts, pgrp, &pssi);
2379 } else {
2380 PgrClearSampleSubsetIndex(pgrp, &pssi);
2381 }
2382 } else {
2383 if (is_x_or_y) {
2384 PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, pgrp, &pssi);
2385 }
2386 is_x_or_y = 0;
2387 // true for MT
2388 is_nonxy_haploid = IsSet(cip->haploid_mask, chr_idx);
2389 }
2390 }
2391 uintptr_t cur_allele_idx_offset;
2392 if (!allele_idx_offsets) {
2393 cur_allele_idx_offset = 2 * variant_uidx;
2394 } else {
2395 cur_allele_idx_offset = allele_idx_offsets[variant_uidx];
2396 allele_ct = allele_idx_offsets[variant_uidx + 1] - cur_allele_idx_offset;
2397 }
2398 uint32_t hethap_ct;
2399 if ((allele_ct == 2) || no_multiallelic_branch) {
2400 uint64_t cur_dosages[2];
2401 if (!is_x_or_y) {
2402 const PglErr reterr = PgrGetDCounts(sample_include, sample_include_interleaved_vec, pssi, sample_ct, variant_uidx, is_minimac3_r2, pgrp, imp_r2_vals? (&(imp_r2_vals[variant_uidx])) : nullptr, genocounts, cur_dosages);
2403 if (unlikely(reterr)) {
2404 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
2405 goto LoadAlleleAndGenoCountsThread_err;
2406 }
2407 if (allele_presents_bytearr) {
2408 if (cur_dosages[0]) {
2409 allele_presents_bytearr[cur_allele_idx_offset] = 128;
2410 }
2411 if (cur_dosages[1]) {
2412 allele_presents_bytearr[cur_allele_idx_offset + 1] = 128;
2413 }
2414 }
2415 if (!is_nonxy_haploid) {
2416 hethap_ct = 0;
2417 if (allele_ddosages) {
2418 // ...but save all allele counts here.
2419 allele_ddosages[cur_allele_idx_offset] = cur_dosages[0] * 2;
2420 allele_ddosages[cur_allele_idx_offset + 1] = cur_dosages[1] * 2;
2421 }
2422 } else {
2423 // this hethap_ct can be inaccurate in multiallelic case
2424 hethap_ct = genocounts[1];
2425 if (imp_r2_vals && (!is_minimac3_r2)) {
2426 // Assuming the input data isn't malformed "phased haploid",
2427 // minimac3-r2 is independent of haploid/diploid state; only
2428 // mach-r2 requires a haploid correction.
2429 imp_r2_vals[variant_uidx] *= 0.5;
2430 }
2431 if (allele_ddosages) {
2432 allele_ddosages[cur_allele_idx_offset] = cur_dosages[0];
2433 allele_ddosages[cur_allele_idx_offset + 1] = cur_dosages[1];
2434 }
2435 }
2436 } else if (is_y) {
2437 if ((nonfemale_ct == chry_missingstat_sample_ct) && ((!allele_presents_bytearr) || (sample_ct == nonfemale_ct))) {
2438 const PglErr reterr = PgrGetDCounts(sex_nonfemale, sex_nonfemale_interleaved_vec, pssi, nonfemale_ct, variant_uidx, 0, pgrp, imp_r2_vals? (&(imp_r2_vals[variant_uidx])) : nullptr, genocounts, cur_dosages);
2439 if (unlikely(reterr)) {
2440 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
2441 goto LoadAlleleAndGenoCountsThread_err;
2442 }
2443 hethap_ct = genocounts[1];
2444 if (imp_r2_vals && (!is_minimac3_r2)) {
2445 // note that female is not counted here
2446 imp_r2_vals[variant_uidx] *= 0.5;
2447 }
2448 if (allele_presents_bytearr) {
2449 if (cur_dosages[0]) {
2450 allele_presents_bytearr[cur_allele_idx_offset] = 128;
2451 }
2452 if (cur_dosages[1]) {
2453 allele_presents_bytearr[cur_allele_idx_offset + 1] = 128;
2454 }
2455 }
2456 if (allele_ddosages) {
2457 allele_ddosages[cur_allele_idx_offset] = cur_dosages[0];
2458 allele_ddosages[cur_allele_idx_offset + 1] = cur_dosages[1];
2459 }
2460 if (raw_geno_cts) {
2461 STD_ARRAY_REF(uint32_t, 3) cur_raw_geno_cts = raw_geno_cts[variant_uidx];
2462 cur_raw_geno_cts[0] = genocounts[0];
2463 cur_raw_geno_cts[1] = genocounts[1];
2464 cur_raw_geno_cts[2] = genocounts[2];
2465 }
2466 } else {
2467 // females need to be counted for allele_presents, and ignored
2468 // elsewhere.
2469 // unknown-sex might need to be excluded from missing-genotype
2470 // and hethap counts.
2471 const PglErr reterr = PgrGetD(nullptr, pssi, raw_sample_ct, variant_uidx, pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &pgv.dosage_ct);
2472 if (unlikely(reterr)) {
2473 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
2474 goto LoadAlleleAndGenoCountsThread_err;
2475 }
2476 const uint32_t dosage_is_relevant = pgv.dosage_ct && ((sample_ct == raw_sample_ct) || (!IntersectionIsEmpty(sample_include, pgv.dosage_present, raw_sample_ctl)));
2477 if (allele_presents_bytearr) {
2478 if (dosage_is_relevant) {
2479 // at least one dosage value is present, that's all we need
2480 // to know
2481 allele_presents_bytearr[cur_allele_idx_offset] = 128;
2482 allele_presents_bytearr[cur_allele_idx_offset + 1] = 128;
2483 } else {
2484 // only hardcalls matter
2485 // bugfix (31 Jul 2018): forgot to initialize genocounts here
2486 // possible todo: use a specialized function which just
2487 // checks which alleles exist
2488 if (sample_ct == raw_sample_ct) {
2489 ZeroTrailingNyps(raw_sample_ct, pgv.genovec);
2490 GenoarrCountFreqsUnsafe(pgv.genovec, sample_ct, genocounts);
2491 } else {
2492 GenoarrCountSubsetFreqs(pgv.genovec, sample_include_interleaved_vec, raw_sample_ct, sample_ct, genocounts);
2493 }
2494 if (genocounts[0] || genocounts[1]) {
2495 allele_presents_bytearr[cur_allele_idx_offset] = 128;
2496 }
2497 if (genocounts[1] || genocounts[2]) {
2498 allele_presents_bytearr[cur_allele_idx_offset + 1] = 128;
2499 }
2500 }
2501 }
2502 GenoarrCountSubsetFreqs(pgv.genovec, sex_nonfemale_interleaved_vec, raw_sample_ct, nonfemale_ct, genocounts);
2503 hethap_ct = genocounts[1];
2504 // x2, x4 since this is haploid
2505 uintptr_t alt1_ct_x2 = genocounts[2] * 2 + hethap_ct;
2506 uintptr_t alt1_sq_sum_x4 = genocounts[2] * (4 * k1LU) + hethap_ct;
2507 uint64_t alt1_ddosage = 0; // in 32768ths
2508 uint64_t alt1_ddosage_sq_sum = 0;
2509 uint32_t additional_dosage_ct = 0;
2510 if (dosage_is_relevant) {
2511 uintptr_t sample_widx = 0;
2512 uintptr_t dosage_present_bits = pgv.dosage_present[0];
2513 uint32_t sample_uidx = 0;
2514 for (uint32_t dosage_idx = 0; dosage_idx != pgv.dosage_ct; ++dosage_idx) {
2515 const uintptr_t lowbit = BitIter1y(pgv.dosage_present, &sample_widx, &dosage_present_bits);
2516 if (sample_include[sample_widx] & lowbit) {
2517 const uintptr_t cur_dosage_val = pgv.dosage_main[dosage_idx];
2518 alt1_ddosage += cur_dosage_val;
2519 alt1_ddosage_sq_sum += cur_dosage_val * cur_dosage_val;
2520 const uintptr_t hardcall_code = GetNyparrEntry(pgv.genovec, sample_uidx);
2521 if (hardcall_code != 3) {
2522 alt1_ct_x2 -= hardcall_code;
2523 alt1_sq_sum_x4 -= hardcall_code * hardcall_code;
2524 } else {
2525 ++additional_dosage_ct;
2526 }
2527 }
2528 }
2529 }
2530 const uintptr_t obs_ct = nonfemale_ct + additional_dosage_ct - genocounts[3];
2531 alt1_ddosage += alt1_ct_x2 * S_CAST(uint64_t, kDosageMid);
2532 alt1_ddosage_sq_sum += alt1_sq_sum_x4 * 0x10000000LLU;
2533 cur_dosages[0] = obs_ct * S_CAST(uint64_t, kDosageMax) - alt1_ddosage;
2534 cur_dosages[1] = alt1_ddosage;
2535 if (imp_r2_vals) {
2536 // minimac3-r2 and mach-r2 are identical in haploid case
2537 const double dosage_sumd = u63tod(alt1_ddosage);
2538 const double dosage_avg = dosage_sumd / u31tod(obs_ct);
2539 const double dosage_variance = u63tod(alt1_ddosage_sq_sum) - dosage_sumd * dosage_avg;
2540 imp_r2_vals[variant_uidx] = dosage_variance / (dosage_sumd * (32768 - dosage_avg));
2541 }
2542 if (allele_ddosages) {
2543 allele_ddosages[cur_allele_idx_offset] = cur_dosages[0];
2544 allele_ddosages[cur_allele_idx_offset + 1] = alt1_ddosage;
2545 }
2546 // argh, these values must be saved before potential male-only
2547 // clobber.
2548 if (raw_geno_cts) {
2549 STD_ARRAY_REF(uint32_t, 3) cur_raw_geno_cts = raw_geno_cts[variant_uidx];
2550 cur_raw_geno_cts[0] = genocounts[0];
2551 cur_raw_geno_cts[1] = genocounts[1];
2552 cur_raw_geno_cts[2] = genocounts[2];
2553 }
2554 if (chry_missingstat_sample_ct != nonfemale_ct) {
2555 // By default, we include unknown-sex samples in
2556 // allele-frequency and imputation-r2 computations, but exclude
2557 // them from missing-rate stats (and hethap stats because they
2558 // can't be cleanly separated out)
2559 GenoarrCountSubsetFreqs(pgv.genovec, sex_male_interleaved_vec, raw_sample_ct, male_ct, genocounts);
2560 hethap_ct = genocounts[1];
2561 // cur_dosages[0] + cur_dosages[1] used later to compute
2562 // missing-dosage rate.
2563 uint32_t male_missing_ct = genocounts[3];
2564 if (dosage_is_relevant && male_missing_ct) {
2565 const uint32_t raw_sample_ctl2 = NypCtToWordCt(raw_sample_ct);
2566 const uintptr_t* genovec = pgv.genovec;
2567 const Halfword* sex_male_hwalias = DowncastKWToHW(sex_male);
2568 const Halfword* dosage_present_hwalias = DowncastWToHW(pgv.dosage_present);
2569 for (uint32_t widx = 0; widx != raw_sample_ctl2; ++widx) {
2570 const Halfword hw = Pack11ToHalfword(genovec[widx]) & sex_male_hwalias[widx] & dosage_present_hwalias[widx];
2571 if (hw) {
2572 male_missing_ct -= PopcountHW(hw);
2573 }
2574 }
2575 }
2576 const uintptr_t male_dosage_obs_ct = male_ct - male_missing_ct;
2577 cur_dosages[0] = male_dosage_obs_ct * S_CAST(uint64_t, kDosageMax);
2578 cur_dosages[1] = 0;
2579 }
2580 }
2581 } else {
2582 // chrX
2583 const PglErr reterr = PgrGetD(nullptr, pssi, raw_sample_ct, variant_uidx, pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &pgv.dosage_ct);
2584 if (unlikely(reterr)) {
2585 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
2586 goto LoadAlleleAndGenoCountsThread_err;
2587 }
2588 if (sample_ct == raw_sample_ct) {
2589 ZeroTrailingNyps(raw_sample_ct, pgv.genovec);
2590 GenoarrCountFreqsUnsafe(pgv.genovec, sample_ct, genocounts);
2591 } else {
2592 GenoarrCountSubsetFreqs(pgv.genovec, sample_include_interleaved_vec, raw_sample_ct, sample_ct, genocounts);
2593 }
2594 GenoarrCountSubsetFreqs(pgv.genovec, sex_male_interleaved_vec, raw_sample_ct, male_ct, sex_specific_genocounts);
2595 hethap_ct = sex_specific_genocounts[1];
2596 // Could compute imputation r2 iff there are no unknown-sex
2597 // samples, but probably not worth it since larger datasets could
2598 // have a small number of Klinefelter syndrome cases, etc. coded as
2599 // unknown-sex, and we don't want to discourage their inclusion;
2600 // let's delegate that chrX filter to other software for now.
2601
2602 if (allele_presents_bytearr) {
2603 if (pgv.dosage_ct && ((sample_ct == raw_sample_ct) || (!IntersectionIsEmpty(sample_include, pgv.dosage_present, raw_sample_ctl)))) {
2604 // at least one dosage value is present, that's all we need to
2605 // know
2606 allele_presents_bytearr[cur_allele_idx_offset] = 128;
2607 allele_presents_bytearr[cur_allele_idx_offset + 1] = 128;
2608 } else {
2609 // only hardcalls matter
2610 if (genocounts[0] || genocounts[1]) {
2611 allele_presents_bytearr[cur_allele_idx_offset] = 128;
2612 }
2613 if (genocounts[1] || genocounts[2]) {
2614 allele_presents_bytearr[cur_allele_idx_offset + 1] = 128;
2615 }
2616 }
2617 }
2618 if (allele_ddosages) {
2619 uintptr_t alt1_ct = 4 * genocounts[2] + 2 * genocounts[1] - 2 * sex_specific_genocounts[2] - hethap_ct; // nonmales count twice
2620 uint64_t alt1_ddosage = 0; // in 32768ths, nonmales count twice
2621 uint32_t additional_dosage_ct = 0; // missing hardcalls only; nonmales count twice
2622 // bugfix (12 Jul 2018): dosage_present may be null if dosage_ct
2623 // == 0
2624 if (pgv.dosage_ct) {
2625 uintptr_t sample_uidx_base = 0;
2626 uintptr_t dosage_present_bits = pgv.dosage_present[0];
2627 if (sample_ct == raw_sample_ct) {
2628 for (uint32_t dosage_idx = 0; dosage_idx != pgv.dosage_ct; ++dosage_idx) {
2629 const uintptr_t sample_uidx = BitIter1(pgv.dosage_present, &sample_uidx_base, &dosage_present_bits);
2630 const uintptr_t cur_dosage_val = pgv.dosage_main[dosage_idx];
2631 const uintptr_t sex_multiplier = 2 - IsSet(sex_male, sample_uidx);
2632 alt1_ddosage += cur_dosage_val * sex_multiplier;
2633
2634 // could call GenoarrCountSubsetIntersectFreqs() twice
2635 // instead, but since we've already manually extracted the
2636 // sex bit it probably doesn't help?
2637 const uintptr_t hardcall_code = GetNyparrEntry(pgv.genovec, sample_uidx);
2638 if (hardcall_code != 3) {
2639 alt1_ct -= hardcall_code * sex_multiplier;
2640 } else {
2641 additional_dosage_ct += sex_multiplier;
2642 }
2643 }
2644 } else {
2645 for (uint32_t dosage_idx = 0; dosage_idx != pgv.dosage_ct; ++dosage_idx) {
2646 const uintptr_t sample_uidx = BitIter1(pgv.dosage_present, &sample_uidx_base, &dosage_present_bits);
2647 if (IsSet(sample_include, sample_uidx)) {
2648 const uintptr_t cur_dosage_val = pgv.dosage_main[dosage_idx];
2649 const uintptr_t sex_multiplier = 2 - IsSet(sex_male, sample_uidx);
2650 alt1_ddosage += cur_dosage_val * sex_multiplier;
2651 const uintptr_t hardcall_code = GetNyparrEntry(pgv.genovec, sample_uidx);
2652 if (hardcall_code != 3) {
2653 alt1_ct -= hardcall_code * sex_multiplier;
2654 } else {
2655 additional_dosage_ct += sex_multiplier;
2656 }
2657 }
2658 }
2659 }
2660 }
2661 alt1_ddosage += alt1_ct * S_CAST(uint64_t, kDosageMid);
2662
2663 // bugfix (14 May 2018): this didn't correctly distinguish
2664 // between missing vs. 'replaced' hardcalls
2665 const uintptr_t weighted_obs_ct = (2 * (sample_ct - genocounts[3]) - male_ct + sex_specific_genocounts[3] + additional_dosage_ct) * (2 * k1LU);
2666
2667 allele_ddosages[cur_allele_idx_offset] = weighted_obs_ct * S_CAST(uint64_t, kDosageMid) - alt1_ddosage;
2668 allele_ddosages[cur_allele_idx_offset + 1] = alt1_ddosage;
2669 }
2670 if (x_male_geno_cts) {
2671 STD_ARRAY_REF(uint32_t, 3) cur_x_male_geno_cts = x_male_geno_cts[variant_uidx - x_start];
2672 cur_x_male_geno_cts[0] = sex_specific_genocounts[0];
2673 cur_x_male_geno_cts[1] = sex_specific_genocounts[1];
2674 cur_x_male_geno_cts[2] = sex_specific_genocounts[2];
2675 if (x_nosex_geno_cts) {
2676 GenoarrCountSubsetFreqs(pgv.genovec, nosex_interleaved_vec, raw_sample_ct, nosex_ct, sex_specific_genocounts);
2677 STD_ARRAY_REF(uint32_t, 3) cur_nosex_geno_cts = x_nosex_geno_cts[variant_uidx - x_start];
2678 cur_nosex_geno_cts[0] = sex_specific_genocounts[0];
2679 cur_nosex_geno_cts[1] = sex_specific_genocounts[1];
2680 cur_nosex_geno_cts[2] = sex_specific_genocounts[2];
2681 }
2682 }
2683 }
2684 if (variant_missing_dosage_cts) {
2685 uint32_t missing_dosage_ct;
2686 if (!is_x_or_y) {
2687 missing_dosage_ct = sample_ct - ((cur_dosages[0] + cur_dosages[1]) / kDosageMax);
2688 } else if (is_y) {
2689 missing_dosage_ct = chry_missingstat_sample_ct - ((cur_dosages[0] + cur_dosages[1]) / kDosageMax);
2690 } else {
2691 if (pgv.dosage_ct) {
2692 ZeroTrailingNyps(raw_sample_ct, pgv.genovec);
2693 missing_dosage_ct = GenoarrCountMissingInvsubsetUnsafe(pgv.genovec, pgv.dosage_present, raw_sample_ct);
2694 } else {
2695 missing_dosage_ct = genocounts[3];
2696 }
2697 }
2698 variant_missing_dosage_cts[variant_uidx] = missing_dosage_ct;
2699 }
2700 } else {
2701 // multiallelic cases
2702 if (!is_x_or_y) {
2703 const PglErr reterr = PgrGetMDCounts(sample_include, sample_include_interleaved_vec, pssi, sample_ct, variant_uidx, is_minimac3_r2, pgrp, imp_r2_vals? (&(imp_r2_vals[variant_uidx])) : nullptr, &hethap_ct, genocounts, all_dosages);
2704 if (unlikely(reterr)) {
2705 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
2706 goto LoadAlleleAndGenoCountsThread_err;
2707 }
2708 if (allele_presents_bytearr) {
2709 for (uintptr_t aidx = 0; aidx != allele_ct; ++aidx) {
2710 if (all_dosages[aidx]) {
2711 allele_presents_bytearr[cur_allele_idx_offset + aidx] = 128;
2712 }
2713 }
2714 }
2715 if (!is_nonxy_haploid) {
2716 hethap_ct = 0;
2717 if (allele_ddosages) {
2718 for (uintptr_t aidx = 0; aidx != allele_ct; ++aidx) {
2719 allele_ddosages[cur_allele_idx_offset + aidx] = all_dosages[aidx] * 2;
2720 }
2721 }
2722 } else {
2723 if (imp_r2_vals && (!is_minimac3_r2)) {
2724 imp_r2_vals[variant_uidx] *= 0.5;
2725 }
2726 if (allele_ddosages) {
2727 memcpy(&(allele_ddosages[cur_allele_idx_offset]), all_dosages, allele_ct * sizeof(int64_t));
2728 }
2729 }
2730 } else if (is_y) {
2731 if ((nonfemale_ct == chry_missingstat_sample_ct) && ((!allele_presents_bytearr) || (sample_ct == nonfemale_ct))) {
2732 const PglErr reterr = PgrGetMDCounts(sex_nonfemale, sex_nonfemale_interleaved_vec, pssi, nonfemale_ct, variant_uidx, 0, pgrp, imp_r2_vals? (&(imp_r2_vals[variant_uidx])) : nullptr, &hethap_ct, genocounts, all_dosages);
2733 if (unlikely(reterr)) {
2734 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
2735 goto LoadAlleleAndGenoCountsThread_err;
2736 }
2737 if (imp_r2_vals && (!is_minimac3_r2)) {
2738 imp_r2_vals[variant_uidx] *= 0.5;
2739 }
2740 if (allele_presents_bytearr) {
2741 for (uintptr_t aidx = 0; aidx != allele_ct; ++aidx) {
2742 if (all_dosages[aidx]) {
2743 allele_presents_bytearr[cur_allele_idx_offset + aidx] = 128;
2744 }
2745 }
2746 }
2747 if (allele_ddosages) {
2748 memcpy(&(allele_ddosages[cur_allele_idx_offset]), all_dosages, allele_ct * sizeof(int64_t));
2749 }
2750 if (raw_geno_cts) {
2751 STD_ARRAY_REF(uint32_t, 3) cur_raw_geno_cts = raw_geno_cts[variant_uidx];
2752 cur_raw_geno_cts[0] = genocounts[0];
2753 cur_raw_geno_cts[1] = genocounts[1];
2754 cur_raw_geno_cts[2] = genocounts[2];
2755 }
2756 } else {
2757 // females need to be counted for allele_presents, and ignored
2758 // elsewhere.
2759 // unknown-sex might need to be excluded from missing-genotype
2760 // and hethap counts.
2761 const PglErr reterr = PgrGetM(nullptr, pssi, raw_sample_ct, variant_uidx, pgrp, &pgv);
2762 if (unlikely(reterr)) {
2763 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
2764 goto LoadAlleleAndGenoCountsThread_err;
2765 }
2766 // possible todo: use a specialized function which just checks
2767 // which alleles exist
2768 ZeroTrailingNyps(raw_sample_ct, pgv.genovec);
2769 GetMFlatCounts64(sample_include, sample_include_interleaved_vec, &pgv, raw_sample_ct, sample_ct, allele_ct, genocounts, all_dosages);
2770 if (allele_presents_bytearr) {
2771 for (uintptr_t aidx = 0; aidx != allele_ct; ++aidx) {
2772 if (all_dosages[aidx]) {
2773 allele_presents_bytearr[cur_allele_idx_offset + aidx] = 128;
2774 }
2775 }
2776 }
2777
2778 uint64_t* two_cts = &(all_dosages[allele_ct]);
2779 GetMCounts64(sex_nonfemale, sex_nonfemale_interleaved_vec, &pgv, raw_sample_ct, nonfemale_ct, allele_ct, genocounts, all_dosages, two_cts);
2780 if (allele_ddosages) {
2781 for (uintptr_t aidx = 0; aidx != allele_ct; ++aidx) {
2782 allele_ddosages[cur_allele_idx_offset + aidx] = all_dosages[aidx] * kDosageMid + two_cts[aidx] * kDosageMax;
2783 }
2784 }
2785 if (imp_r2_vals) {
2786 for (uint32_t aidx = 0; aidx != allele_ct; ++aidx) {
2787 const uint64_t one_ct = allele_ddosages[aidx];
2788 const uint64_t two_ct = two_cts[aidx];
2789 // now sums
2790 allele_ddosages[aidx] = one_ct * kDosageMid + two_ct * kDosageMax;
2791 // now ssqs
2792 two_cts[aidx] = one_ct * kDosageMid * kDosageMid + two_ct * kDosageMax * kDosageMax;
2793 }
2794 imp_r2_vals[variant_uidx] = 0.5 * MultiallelicDiploidMachR2(all_dosages, two_cts, nonfemale_ct - genocounts[3], allele_ct);
2795 }
2796 // argh
2797 if (raw_geno_cts) {
2798 STD_ARRAY_REF(uint32_t, 3) cur_raw_geno_cts = raw_geno_cts[variant_uidx];
2799 cur_raw_geno_cts[0] = genocounts[0];
2800 cur_raw_geno_cts[1] = genocounts[1];
2801 cur_raw_geno_cts[2] = genocounts[2];
2802 }
2803 if (nonfemale_ct != chry_missingstat_sample_ct) {
2804 GetMCounts64(sex_male, sex_male_interleaved_vec, &pgv, raw_sample_ct, male_ct, allele_ct, genocounts, all_dosages, two_cts);
2805 }
2806 uintptr_t hethap_x2 = 0;
2807 for (uint32_t aidx = 0; aidx != allele_ct; ++aidx) {
2808 hethap_x2 += all_dosages[aidx];
2809 }
2810 hethap_ct = hethap_x2 / 2;
2811 }
2812 } else {
2813 // chrX
2814 // multiallelic dosages not supported yet
2815 const PglErr reterr = PgrGetM(nullptr, pssi, raw_sample_ct, variant_uidx, pgrp, &pgv);
2816 if (unlikely(reterr)) {
2817 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
2818 goto LoadAlleleAndGenoCountsThread_err;
2819 }
2820 ZeroTrailingNyps(raw_sample_ct, pgv.genovec);
2821 // We don't attempt to compute imp_r2 on chrX, so flat counts are
2822 // fine.
2823 GetMFlatCounts64(sample_include, sample_include_interleaved_vec, &pgv, raw_sample_ct, sample_ct, allele_ct, genocounts, all_dosages);
2824
2825 // Double all counts, then subtract male counts.
2826 for (uint32_t aidx = 0; aidx != allele_ct; ++aidx) {
2827 all_dosages[aidx] *= 2;
2828 }
2829 GenoarrCountSubsetFreqs(pgv.genovec, sex_male_interleaved_vec, raw_sample_ct, male_ct, sex_specific_genocounts);
2830 hethap_ct = sex_specific_genocounts[1];
2831 if (male_ct) {
2832 all_dosages[0] -= 2 * sex_specific_genocounts[0] + hethap_ct;
2833
2834 // may underflow
2835 all_dosages[1] -= 2 * sex_specific_genocounts[2] + hethap_ct;
2836
2837 if (pgv.patch_01_ct) {
2838 uintptr_t sample_widx = 0;
2839 uintptr_t patch_01_bits = pgv.patch_01_set[0];
2840 uint32_t male_patch_01_ct = 0;
2841 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
2842 const uintptr_t lowbit = BitIter1y(pgv.patch_01_set, &sample_widx, &patch_01_bits);
2843 if (sex_male[sample_widx] & lowbit) {
2844 ++male_patch_01_ct;
2845 all_dosages[pgv.patch_01_vals[uii]] -= 1;
2846 }
2847 }
2848 all_dosages[1] += male_patch_01_ct;
2849 }
2850 if (pgv.patch_10_ct) {
2851 uintptr_t sample_widx = 0;
2852 uintptr_t patch_10_bits = pgv.patch_10_set[0];
2853 uint32_t male_patch_10_ct = 0;
2854 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
2855 const uintptr_t lowbit = BitIter1y(pgv.patch_10_set, &sample_widx, &patch_10_bits);
2856 if (sex_male[sample_widx] & lowbit) {
2857 ++male_patch_10_ct;
2858 const AlleleCode code_lo = pgv.patch_10_vals[2 * uii];
2859 const AlleleCode code_hi = pgv.patch_10_vals[2 * uii + 1];
2860 all_dosages[code_lo] -= 1;
2861 all_dosages[code_hi] -= 1;
2862 hethap_ct += (code_lo != code_hi);
2863 }
2864 }
2865 all_dosages[1] += male_patch_10_ct * 2;
2866 }
2867 }
2868 if (allele_presents_bytearr) {
2869 for (uintptr_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
2870 if (all_dosages[allele_idx]) {
2871 allele_presents_bytearr[cur_allele_idx_offset + allele_idx] = 128;
2872 }
2873 }
2874 }
2875 if (allele_ddosages) {
2876 for (uintptr_t aidx = 0; aidx != allele_ct; ++aidx) {
2877 allele_ddosages[cur_allele_idx_offset + aidx] = all_dosages[aidx] * kDosageMid;
2878 }
2879 }
2880 if (x_male_geno_cts) {
2881 STD_ARRAY_REF(uint32_t, 3) cur_x_male_geno_cts = x_male_geno_cts[variant_uidx - x_start];
2882 cur_x_male_geno_cts[0] = sex_specific_genocounts[0];
2883 cur_x_male_geno_cts[1] = sex_specific_genocounts[1];
2884 cur_x_male_geno_cts[2] = sex_specific_genocounts[2];
2885 if (x_nosex_geno_cts) {
2886 GenoarrCountSubsetFreqs(pgv.genovec, nosex_interleaved_vec, raw_sample_ct, nosex_ct, sex_specific_genocounts);
2887 STD_ARRAY_REF(uint32_t, 3) cur_nosex_geno_cts = x_nosex_geno_cts[variant_uidx - x_start];
2888 cur_nosex_geno_cts[0] = sex_specific_genocounts[0];
2889 cur_nosex_geno_cts[1] = sex_specific_genocounts[1];
2890 cur_nosex_geno_cts[2] = sex_specific_genocounts[2];
2891 }
2892 }
2893 }
2894 if (variant_missing_dosage_cts) {
2895 // multiallelic dosage not supported yet
2896 variant_missing_dosage_cts[variant_uidx] = genocounts[3];
2897 }
2898 }
2899 if (raw_geno_cts && (!is_y)) {
2900 STD_ARRAY_REF(uint32_t, 3) cur_raw_geno_cts = raw_geno_cts[variant_uidx];
2901 cur_raw_geno_cts[0] = genocounts[0];
2902 cur_raw_geno_cts[1] = genocounts[1];
2903 cur_raw_geno_cts[2] = genocounts[2];
2904 }
2905 if (variant_missing_hc_cts) {
2906 variant_missing_hc_cts[variant_uidx] = genocounts[3];
2907 if (variant_hethap_cts && (variant_uidx >= first_hap_uidx)) {
2908 variant_hethap_cts[variant_uidx - first_hap_uidx] = hethap_ct;
2909 }
2910 }
2911 }
2912 if (++subset_idx == subset_ct) {
2913 break;
2914 }
2915 sample_include = ctx->founder_info;
2916 sample_include_interleaved_vec = ctx->founder_info_interleaved_vec;
2917 sample_include_cumulative_popcounts = ctx->founder_info_cumulative_popcounts;
2918 sex_male = ctx->founder_male;
2919 sex_male_interleaved_vec = ctx->founder_male_interleaved_vec;
2920 sex_nonfemale = ctx->founder_nonfemale;
2921 sex_nonfemale_interleaved_vec = ctx->founder_nonfemale_interleaved_vec;
2922 sex_nonfemale_cumulative_popcounts = ctx->founder_nonfemale_cumulative_popcounts;
2923
2924 nosex_interleaved_vec = ctx->founder_nosex_interleaved_vec;
2925
2926 sample_ct = ctx->founder_ct;
2927 male_ct = ctx->founder_male_ct;
2928 nosex_ct = ctx->founder_nosex_ct;
2929 nonfemale_ct = male_ct + nosex_ct;
2930 chry_missingstat_sample_ct = ctx->founder_chry_missingstat_sample_ct;
2931 allele_presents_bytearr = nullptr;
2932 allele_ddosages = ctx->founder_allele_ddosages;
2933 variant_missing_hc_cts = nullptr;
2934 variant_missing_dosage_cts = nullptr;
2935 raw_geno_cts = ctx->founder_raw_geno_cts;
2936 x_male_geno_cts = ctx->founder_x_male_geno_cts;
2937 x_nosex_geno_cts = ctx->founder_x_nosex_geno_cts;
2938 imp_r2_vals = nullptr;
2939 }
2940 while (0) {
2941 LoadAlleleAndGenoCountsThread_err:
2942 UpdateU64IfSmaller(new_err_info, &ctx->err_info);
2943 }
2944 } while (!THREAD_BLOCK_FINISH(arg));
2945 THREAD_RETURN;
2946 }
2947
2948 PglErr LoadAlleleAndGenoCounts(const uintptr_t* sample_include, const uintptr_t* founder_info, const uintptr_t* sex_nm, const uintptr_t* sex_male, const uintptr_t* variant_include, const ChrInfo* cip, const uintptr_t* allele_idx_offsets, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t founder_ct, uint32_t male_ct, uint32_t nosex_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t first_hap_uidx, uint32_t is_minimac3_r2, uint32_t y_nosex_missing_stats, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, uintptr_t* allele_presents, uint64_t* allele_ddosages, uint64_t* founder_allele_ddosages, uint32_t* variant_missing_hc_cts, uint32_t* variant_missing_dosage_cts, uint32_t* variant_hethap_cts, STD_ARRAY_PTR_DECL(uint32_t, 3, raw_geno_cts), STD_ARRAY_PTR_DECL(uint32_t, 3, founder_raw_geno_cts), STD_ARRAY_PTR_DECL(uint32_t, 3, x_male_geno_cts), STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_male_geno_cts), STD_ARRAY_PTR_DECL(uint32_t, 3, x_nosex_geno_cts), STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_nosex_geno_cts), double* imp_r2_vals) {
2949 unsigned char* bigstack_mark = g_bigstack_base;
2950 unsigned char* bigstack_end_mark = g_bigstack_end;
2951 PglErr reterr = kPglRetSuccess;
2952 ThreadGroup tg;
2953 PreinitThreads(&tg);
2954 LoadAlleleAndGenoCountsCtx ctx;
2955 {
2956 if (!variant_ct) {
2957 goto LoadAlleleAndGenoCounts_ret_1;
2958 }
2959
2960 // four cases:
2961 // 1. allele_ddosages, raw_geno_cts, and/or variant_missing_{hc,dosage}_cts
2962 // required, and that's it
2963 // 2. founder_allele_ddosages and/or founder_raw_geno_cts required, and
2964 // that's it
2965 // 3. both required, and founder_ct != sample_ct.
2966 // 4. both required, and founder_ct == sample_ct. caller is expected to
2967 // make founder_allele_ddosages and allele_ddosages point to the same
2968 // memory, ditto for founder_raw_geno_cts/raw_geno_cts.
2969 const uint32_t only_founder_cts_required = (!allele_presents) && (!allele_ddosages) && (!raw_geno_cts) && (!variant_missing_hc_cts) && (!variant_missing_dosage_cts);
2970 const uint32_t two_subsets_required = (founder_ct != sample_ct) && (!only_founder_cts_required) && (founder_allele_ddosages || founder_raw_geno_cts);
2971 ctx.cip = cip;
2972 ctx.sample_include = only_founder_cts_required? founder_info : sample_include;
2973 ctx.raw_sample_ct = raw_sample_ct;
2974 ctx.sample_ct = only_founder_cts_required? founder_ct : sample_ct;
2975 ctx.allele_ddosages = only_founder_cts_required? founder_allele_ddosages : allele_ddosages;
2976 ctx.raw_geno_cts = only_founder_cts_required? founder_raw_geno_cts : raw_geno_cts;
2977 ctx.x_male_geno_cts = only_founder_cts_required? founder_x_male_geno_cts : x_male_geno_cts;
2978 ctx.x_nosex_geno_cts = only_founder_cts_required? founder_x_nosex_geno_cts : x_nosex_geno_cts;
2979 ctx.imp_r2_vals = imp_r2_vals;
2980 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
2981 const uint32_t raw_sample_ctv = BitCtToVecCt(raw_sample_ct);
2982 if (unlikely(bigstack_alloc_w(raw_sample_ctv * kWordsPerVec, &ctx.sample_include_interleaved_vec) ||
2983 bigstack_alloc_u32(raw_sample_ctl, &ctx.sample_include_cumulative_popcounts) ||
2984 bigstack_alloc_w(raw_sample_ctv * kWordsPerVec, &ctx.sex_male_interleaved_vec) ||
2985 bigstack_alloc_u32(raw_sample_ctl, &ctx.sex_nonfemale_cumulative_popcounts))) {
2986 goto LoadAlleleAndGenoCounts_ret_NOMEM;
2987 }
2988 FillInterleavedMaskVec(ctx.sample_include, raw_sample_ctv, ctx.sample_include_interleaved_vec);
2989 FillCumulativePopcounts(ctx.sample_include, raw_sample_ctl, ctx.sample_include_cumulative_popcounts);
2990 if ((founder_ct == sample_ct) || (!only_founder_cts_required)) {
2991 ctx.sex_male = sex_male;
2992 } else {
2993 // no nonfounder counts required
2994 uintptr_t* new_sex_male;
2995 if (unlikely(bigstack_alloc_w(raw_sample_ctv * kWordsPerVec, &new_sex_male))) {
2996 goto LoadAlleleAndGenoCounts_ret_NOMEM;
2997 }
2998 BitvecAndCopy(sex_male, founder_info, raw_sample_ctl, new_sex_male);
2999 ZeroTrailingWords(raw_sample_ctl, new_sex_male);
3000 ctx.sex_male = new_sex_male;
3001 }
3002 FillInterleavedMaskVec(ctx.sex_male, raw_sample_ctv, ctx.sex_male_interleaved_vec);
3003 // slightly wasteful, but founder_male_ct isn't precomputed
3004 ctx.male_ct = PopcountWords(ctx.sex_male, raw_sample_ctl);
3005 ctx.nosex_ct = 0;
3006 if (nosex_ct) {
3007 uintptr_t* sex_nonfemale;
3008 if (unlikely(bigstack_alloc_w(raw_sample_ctv * kWordsPerVec, &sex_nonfemale) ||
3009 bigstack_alloc_w(raw_sample_ctv * kWordsPerVec, &ctx.sex_nonfemale_interleaved_vec))) {
3010 goto LoadAlleleAndGenoCounts_ret_NOMEM;
3011 }
3012 if ((founder_ct == sample_ct) || (!only_founder_cts_required)) {
3013 AlignedBitarrOrnotCopy(ctx.sex_male, sex_nm, raw_sample_ct, sex_nonfemale);
3014 } else {
3015 BitvecInvmaskCopy(founder_info, sex_nm, raw_sample_ctl, sex_nonfemale);
3016 BitvecOr(ctx.sex_male, raw_sample_ctl, sex_nonfemale);
3017 }
3018 ZeroTrailingWords(raw_sample_ctl, sex_nonfemale);
3019 ctx.sex_nonfemale = sex_nonfemale;
3020 const uint32_t nonfemale_ct = PopcountWords(sex_nonfemale, raw_sample_ctl);
3021 ctx.nosex_ct = nonfemale_ct - ctx.male_ct;
3022 FillInterleavedMaskVec(sex_nonfemale, raw_sample_ctv, ctx.sex_nonfemale_interleaved_vec);
3023 } else {
3024 ctx.sex_nonfemale = ctx.sex_male;
3025 ctx.sex_nonfemale_interleaved_vec = ctx.sex_male_interleaved_vec;
3026 }
3027 FillCumulativePopcounts(ctx.sex_nonfemale, raw_sample_ctl, ctx.sex_nonfemale_cumulative_popcounts);
3028 ctx.chry_missingstat_sample_ct = y_nosex_missing_stats? (ctx.male_ct + ctx.nosex_ct) : ctx.male_ct;
3029 ctx.nosex_interleaved_vec = nullptr;
3030 uintptr_t* nosex_buf = nullptr;
3031 if (x_nosex_geno_cts || founder_x_nosex_geno_cts) {
3032 if (unlikely(bigstack_end_alloc_w(raw_sample_ctl, &nosex_buf) ||
3033 bigstack_alloc_w(raw_sample_ctv * kWordsPerVec, &ctx.nosex_interleaved_vec))) {
3034 goto LoadAlleleAndGenoCounts_ret_NOMEM;
3035 }
3036 BitvecInvmaskCopy(ctx.sample_include, sex_nm, raw_sample_ctl, nosex_buf);
3037 ZeroTrailingWords(raw_sample_ctl, nosex_buf);
3038 FillInterleavedMaskVec(nosex_buf, raw_sample_ctv, ctx.nosex_interleaved_vec);
3039 }
3040
3041 ctx.variant_missing_hc_cts = variant_missing_hc_cts;
3042 ctx.variant_missing_dosage_cts = variant_missing_dosage_cts;
3043 ctx.variant_hethap_cts = variant_hethap_cts;
3044 ctx.first_hap_uidx = first_hap_uidx;
3045 ctx.is_minimac3_r2 = is_minimac3_r2;
3046
3047 ctx.founder_info = nullptr;
3048 ctx.founder_info_interleaved_vec = nullptr;
3049 ctx.founder_info_cumulative_popcounts = nullptr;
3050 ctx.founder_male = nullptr;
3051 ctx.founder_male_interleaved_vec = nullptr;
3052 ctx.founder_nonfemale = nullptr;
3053 ctx.founder_nonfemale_interleaved_vec = nullptr;
3054 ctx.founder_nonfemale_cumulative_popcounts = nullptr;
3055 ctx.founder_nosex_interleaved_vec = nullptr;
3056 ctx.founder_ct = 0;
3057 ctx.founder_male_ct = 0;
3058 ctx.founder_nosex_ct = 0;
3059 ctx.founder_chry_missingstat_sample_ct = 0;
3060 ctx.founder_allele_ddosages = nullptr;
3061 ctx.founder_raw_geno_cts = nullptr;
3062 ctx.founder_x_male_geno_cts = nullptr;
3063 ctx.founder_x_nosex_geno_cts = nullptr;
3064 if (two_subsets_required) {
3065 if (founder_ct) {
3066 ctx.founder_info = founder_info;
3067 if (unlikely(bigstack_alloc_w(raw_sample_ctv * kWordsPerVec, &ctx.founder_info_interleaved_vec) ||
3068 bigstack_alloc_u32(raw_sample_ctl, &ctx.founder_info_cumulative_popcounts) ||
3069 bigstack_alloc_w(raw_sample_ctv * kWordsPerVec, &ctx.founder_male) ||
3070 bigstack_alloc_w(raw_sample_ctv * kWordsPerVec, &ctx.founder_male_interleaved_vec) ||
3071 bigstack_alloc_u32(raw_sample_ctl, &ctx.founder_nonfemale_cumulative_popcounts))) {
3072 goto LoadAlleleAndGenoCounts_ret_NOMEM;
3073 }
3074 FillInterleavedMaskVec(founder_info, raw_sample_ctv, ctx.founder_info_interleaved_vec);
3075 FillCumulativePopcounts(founder_info, raw_sample_ctl, ctx.founder_info_cumulative_popcounts);
3076 BitvecAndCopy(sex_male, founder_info, raw_sample_ctl, ctx.founder_male);
3077 ZeroTrailingWords(raw_sample_ctl, ctx.founder_male);
3078 FillInterleavedMaskVec(ctx.founder_male, raw_sample_ctv, ctx.founder_male_interleaved_vec);
3079 ctx.founder_male_ct = PopcountWords(ctx.founder_male, raw_sample_ctl);
3080 if (ctx.nosex_ct) {
3081 if (unlikely(bigstack_alloc_w(raw_sample_ctv * kWordsPerVec, &ctx.founder_nonfemale) ||
3082 bigstack_alloc_w(raw_sample_ctv * kWordsPerVec, &ctx.founder_nonfemale_interleaved_vec))) {
3083 goto LoadAlleleAndGenoCounts_ret_NOMEM;
3084 }
3085 BitvecInvmaskCopy(founder_info, sex_nm, raw_sample_ctl, ctx.founder_nonfemale);
3086 BitvecOr(ctx.founder_male, raw_sample_ctl, ctx.founder_nonfemale);
3087 ZeroTrailingWords(raw_sample_ctl, ctx.founder_nonfemale);
3088 const uint32_t founder_nonfemale_ct = PopcountWords(ctx.founder_nonfemale, raw_sample_ctl);
3089 ctx.founder_nosex_ct = founder_nonfemale_ct - ctx.founder_male_ct;
3090 FillInterleavedMaskVec(ctx.founder_nonfemale, raw_sample_ctv, ctx.founder_nonfemale_interleaved_vec);
3091 } else {
3092 ctx.founder_nonfemale = ctx.founder_male;
3093 ctx.founder_nonfemale_interleaved_vec = ctx.founder_male_interleaved_vec;
3094 }
3095 FillCumulativePopcounts(ctx.founder_nonfemale, raw_sample_ctl, ctx.founder_nonfemale_cumulative_popcounts);
3096 ctx.founder_chry_missingstat_sample_ct = y_nosex_missing_stats? (ctx.founder_male_ct + ctx.founder_nosex_ct) : ctx.founder_male_ct;
3097 if (ctx.founder_nosex_ct) {
3098 // caller currently responsible for ensuring that when
3099 // founder_nosex_ct is zero, founder_x_nosex_geno_cts == nullptr
3100 if (founder_x_nosex_geno_cts) {
3101 if (unlikely(bigstack_alloc_w(raw_sample_ctv * kWordsPerVec, &ctx.founder_nosex_interleaved_vec))) {
3102 goto LoadAlleleAndGenoCounts_ret_NOMEM;
3103 }
3104 BitvecAnd(founder_info, raw_sample_ctl, nosex_buf);
3105 ZeroTrailingWords(raw_sample_ctl, nosex_buf);
3106 FillInterleavedMaskVec(nosex_buf, raw_sample_ctv, ctx.founder_nosex_interleaved_vec);
3107 ctx.founder_x_nosex_geno_cts = founder_x_nosex_geno_cts;
3108 }
3109 }
3110 ctx.founder_ct = founder_ct;
3111 ctx.founder_allele_ddosages = founder_allele_ddosages;
3112 ctx.founder_raw_geno_cts = founder_raw_geno_cts;
3113 ctx.founder_x_male_geno_cts = founder_x_male_geno_cts;
3114 } else {
3115 if (founder_allele_ddosages) {
3116 ZeroU64Arr(allele_idx_offsets? allele_idx_offsets[raw_variant_ct] : (2 * raw_variant_ct), founder_allele_ddosages);
3117 }
3118 if (founder_raw_geno_cts) {
3119 memset(founder_raw_geno_cts, 0, raw_variant_ct * (3 * sizeof(int32_t)));
3120 }
3121 }
3122 } else if (founder_ct == sample_ct) {
3123 // bugfix: some founder and some nonfounder counts required
3124 if ((!ctx.allele_ddosages) && founder_allele_ddosages) {
3125 ctx.allele_ddosages = founder_allele_ddosages;
3126 }
3127 if ((!ctx.raw_geno_cts) && founder_raw_geno_cts) {
3128 ctx.raw_geno_cts = founder_raw_geno_cts;
3129 }
3130 if ((!ctx.x_male_geno_cts) && founder_x_male_geno_cts) {
3131 ctx.x_male_geno_cts = founder_x_male_geno_cts;
3132 }
3133 if ((!ctx.x_nosex_geno_cts) && founder_x_nosex_geno_cts) {
3134 ctx.x_nosex_geno_cts = founder_x_nosex_geno_cts;
3135 }
3136 }
3137 const uintptr_t raw_allele_ct = allele_idx_offsets? allele_idx_offsets[raw_variant_ct] : (2 * raw_variant_ct);
3138 if (!ctx.sample_ct) {
3139 if (allele_presents) {
3140 ZeroWArr(BitCtToWordCt(raw_allele_ct), allele_presents);
3141 }
3142 if (ctx.allele_ddosages) {
3143 ZeroU64Arr(raw_allele_ct, ctx.allele_ddosages);
3144 }
3145 if (ctx.raw_geno_cts) {
3146 memset(ctx.raw_geno_cts, 0, raw_variant_ct * (3 * sizeof(int32_t)));
3147 }
3148 // early exit
3149 goto LoadAlleleAndGenoCounts_ret_1;
3150 }
3151 BigstackEndReset(bigstack_end_mark); // free nosex_buf
3152 if (allele_presents) {
3153 const uintptr_t raw_allele_ct_a64 = RoundUpPow2(raw_allele_ct, kCacheline);
3154 if (unlikely(bigstack_left() < raw_allele_ct_a64)) {
3155 goto LoadAlleleAndGenoCounts_ret_NOMEM;
3156 }
3157 // fill byte-array instead of bitarray so multithreading works
3158 ctx.allele_presents_bytearr = S_CAST(unsigned char*, bigstack_alloc_raw(raw_allele_ct_a64));
3159 memset(ctx.allele_presents_bytearr, 0, raw_allele_ct_a64);
3160 } else {
3161 ctx.allele_presents_bytearr = nullptr;
3162 }
3163
3164 uint32_t unused_chr_code;
3165 uint32_t unused_chr_code2;
3166 uint32_t xy_complications_present = ((allele_presents || allele_ddosages || founder_allele_ddosages || variant_missing_dosage_cts) && XymtExists(cip, kChrOffsetX, &unused_chr_code)) || (((ctx.chry_missingstat_sample_ct != ctx.male_ct + ctx.nosex_ct) || (allele_presents && (sample_ct != male_ct))) && XymtExists(cip, kChrOffsetY, &unused_chr_code2));
3167 const uint32_t xy_dosages_needed = (pgfip->gflags & kfPgenGlobalDosagePresent) && xy_complications_present;
3168
3169 // todo: check when this saturates
3170 uint32_t calc_thread_ct = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
3171 const uint32_t max_allele_ct = pgfip->max_allele_ct;
3172 uint32_t mhc_needed = 0;
3173 ctx.thread_read_mhc = nullptr;
3174 if ((max_allele_ct > 2) && (variant_hethap_cts || allele_presents || allele_ddosages || founder_allele_ddosages || imp_r2_vals)) {
3175 if (unlikely(bigstack_alloc_u64p(calc_thread_ct, &ctx.all_dosages))) {
3176 goto LoadAlleleAndGenoCounts_ret_NOMEM;
3177 }
3178 mhc_needed = (xy_complications_present || ((variant_hethap_cts || imp_r2_vals) && XymtExists(cip, kChrOffsetX, &unused_chr_code)));
3179 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
3180 // double allocation size, to leave room for chrY ssqs
3181 if (unlikely(bigstack_alloc_u64(max_allele_ct * 2, &(ctx.all_dosages[tidx])))) {
3182 goto LoadAlleleAndGenoCounts_ret_NOMEM;
3183 }
3184 }
3185 } else {
3186 ctx.all_dosages = nullptr;
3187 }
3188 STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
3189 // defensive
3190 ctx.dosage_presents = nullptr;
3191 ctx.dosage_mains = nullptr;
3192 uint32_t read_block_size;
3193 // todo: check if raw_sample_ct should be replaced with sample_ct here
3194 if (unlikely(PgenMtLoadInit(variant_include, raw_sample_ct, variant_ct, bigstack_left(), pgr_alloc_cacheline_ct, 0, 0, 0, pgfip, &calc_thread_ct, &ctx.genovecs, mhc_needed? (&ctx.thread_read_mhc) : nullptr, nullptr, nullptr, xy_dosages_needed? (&ctx.dosage_presents) : nullptr, xy_dosages_needed? (&ctx.dosage_mains) : nullptr, nullptr, nullptr, &read_block_size, nullptr, main_loadbufs, &ctx.pgr_ptrs, &ctx.read_variant_uidx_starts))) {
3195 goto LoadAlleleAndGenoCounts_ret_NOMEM;
3196 }
3197 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
3198 goto LoadAlleleAndGenoCounts_ret_NOMEM;
3199 }
3200 ctx.variant_include = variant_include;
3201 ctx.allele_idx_offsets = allele_idx_offsets;
3202 ctx.err_info = (~0LLU) << 32;
3203 SetThreadFuncAndData(LoadAlleleAndGenoCountsThread, &ctx, &tg);
3204
3205 logputs("Calculating allele frequencies... ");
3206 fputs("0%", stdout);
3207 fflush(stdout);
3208 uint32_t pct = 0;
3209
3210 uint32_t parity = 0;
3211 uint32_t read_block_idx = 0;
3212 uint32_t next_print_variant_idx = variant_ct / 100;
3213 for (uint32_t variant_idx = 0; ; ) {
3214 const uint32_t cur_block_size = MultireadNonempty(variant_include, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr);
3215 if (unlikely(reterr)) {
3216 goto LoadAlleleAndGenoCounts_ret_PGR_FAIL;
3217 }
3218 if (variant_idx) {
3219 JoinThreads(&tg);
3220 reterr = S_CAST(PglErr, ctx.err_info);
3221 if (unlikely(reterr)) {
3222 PgenErrPrintNV(reterr, ctx.err_info >> 32);
3223 goto LoadAlleleAndGenoCounts_ret_1;
3224 }
3225 }
3226 if (!IsLastBlock(&tg)) {
3227 ctx.cur_block_size = cur_block_size;
3228 ComputeUidxStartPartition(variant_include, cur_block_size, calc_thread_ct, read_block_idx * read_block_size, ctx.read_variant_uidx_starts);
3229 PgrCopyBaseAndOffset(pgfip, calc_thread_ct, ctx.pgr_ptrs);
3230 if (variant_idx + cur_block_size == variant_ct) {
3231 DeclareLastThreadBlock(&tg);
3232 }
3233 if (unlikely(SpawnThreads(&tg))) {
3234 goto LoadAlleleAndGenoCounts_ret_THREAD_CREATE_FAIL;
3235 }
3236 }
3237
3238 parity = 1 - parity;
3239 if (variant_idx == variant_ct) {
3240 break;
3241 }
3242 if (variant_idx >= next_print_variant_idx) {
3243 if (pct > 10) {
3244 putc_unlocked('\b', stdout);
3245 }
3246 pct = (variant_idx * 100LLU) / variant_ct;
3247 printf("\b\b%u%%", pct++);
3248 fflush(stdout);
3249 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
3250 }
3251
3252 ++read_block_idx;
3253 variant_idx += cur_block_size;
3254 // crucially, this is independent of the PgenReader block_base
3255 // pointers
3256 pgfip->block_base = main_loadbufs[parity];
3257 }
3258 if (allele_presents) {
3259 const uintptr_t raw_allele_ctl = BitCtToWordCt(raw_allele_ct);
3260 allele_presents[raw_allele_ctl - 1] = 0;
3261 #ifdef __LP64__
3262 // todo: better ARM implementation
3263 const uintptr_t vec_ct = DivUp(raw_allele_ct, kBytesPerVec);
3264 VecUc* bytearr_alias = R_CAST(VecUc*, ctx.allele_presents_bytearr);
3265 Vec8thUint* allele_presents_alias = R_CAST(Vec8thUint*, allele_presents);
3266 for (uintptr_t vec_idx = 0; vec_idx != vec_ct; ++vec_idx) {
3267 allele_presents_alias[vec_idx] = vecuc_movemask(bytearr_alias[vec_idx]);
3268 }
3269 #else
3270 const uintptr_t twovec_ct = DivUp(raw_allele_ct, 8);
3271 uintptr_t* bytearr_iter = R_CAST(uintptr_t*, ctx.allele_presents_bytearr);
3272 unsigned char* allele_presents_iter = R_CAST(unsigned char*, allele_presents);
3273 unsigned char* allele_presents_stop = &(allele_presents_iter[twovec_ct]);
3274 for (; allele_presents_iter != allele_presents_stop; ++allele_presents_iter) {
3275 // 31,23,15,7 -> 3,2,1,0: multiply by number with bits 0,7,14,21 set,
3276 // then right-shift
3277 uintptr_t cur_word = ((*bytearr_iter++) * 0x204081) >> 28;
3278 cur_word |= ((*bytearr_iter++) * 0x204081) >> 24;
3279 *allele_presents_iter = cur_word;
3280 }
3281 #endif
3282 }
3283 if (pct > 10) {
3284 putc_unlocked('\b', stdout);
3285 }
3286 fputs("\b\b", stdout);
3287 logputs("done.\n");
3288 }
3289 while (0) {
3290 LoadAlleleAndGenoCounts_ret_NOMEM:
3291 reterr = kPglRetNomem;
3292 break;
3293 LoadAlleleAndGenoCounts_ret_PGR_FAIL:
3294 PgenErrPrintN(reterr);
3295 break;
3296 LoadAlleleAndGenoCounts_ret_THREAD_CREATE_FAIL:
3297 reterr = kPglRetThreadCreateFail;
3298 break;
3299 }
3300 LoadAlleleAndGenoCounts_ret_1:
3301 CleanupThreads(&tg);
3302 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
3303 pgfip->block_base = nullptr;
3304 return reterr;
3305 }
3306
3307 void ApplyHardCallThresh(const uintptr_t* dosage_present, const Dosage* dosage_main, uint32_t dosage_ct, uint32_t hard_call_halfdist, uintptr_t* genovec) {
3308 uintptr_t sample_uidx_base = 0;
3309 uintptr_t cur_bits = dosage_present[0];
3310 for (uint32_t dosage_idx = 0; dosage_idx != dosage_ct; ++dosage_idx) {
3311 const uintptr_t sample_uidx = BitIter1(dosage_present, &sample_uidx_base, &cur_bits);
3312 const uint32_t dosage_int = dosage_main[dosage_idx];
3313 const uint32_t halfdist = BiallelicDosageHalfdist(dosage_int);
3314 const uintptr_t widx = sample_uidx / kBitsPerWordD2;
3315 uintptr_t prev_geno_word = genovec[widx];
3316 const uint32_t shift = (sample_uidx % kBitsPerWordD2) * 2;
3317 uintptr_t new_geno;
3318 if (halfdist < hard_call_halfdist) {
3319 new_geno = 3;
3320 } else {
3321 new_geno = (dosage_int + kDosage4th) / kDosageMid;
3322 }
3323 const uintptr_t prev_geno = (prev_geno_word >> shift) & 3;
3324 const uintptr_t geno_xor = new_geno ^ prev_geno;
3325 if (geno_xor) {
3326 genovec[widx] = prev_geno_word ^ (geno_xor << shift);
3327 }
3328 }
3329 }
3330
3331 void FillMissingFromBiallelicDosage(const uintptr_t* dosage_present, const Dosage* dosage_main, uint32_t dosage_ct, uintptr_t* genovec) {
3332 uintptr_t sample_uidx_base = 0;
3333 uintptr_t cur_bits = dosage_present[0];
3334 for (uint32_t dosage_idx = 0; dosage_idx != dosage_ct; ++dosage_idx) {
3335 const uintptr_t sample_uidx = BitIter1(dosage_present, &sample_uidx_base, &cur_bits);
3336 const uintptr_t widx = sample_uidx / kBitsPerWordD2;
3337 const uint32_t shift = 2 * (sample_uidx % kBitsPerWordD2);
3338 uintptr_t geno_word = genovec[widx];
3339 if (((geno_word >> shift) & 3) != 3) {
3340 // not missing, don't recalculate
3341 continue;
3342 }
3343 const uint32_t dosage_int = dosage_main[dosage_idx];
3344 // Ties are rounded in favor of the lower-index allele, which reduces to
3345 // rounding down in the biallelic case.
3346 // uintptr_t new_geno = (dosage_int + kDosage4th - 1) / kDosageMid;
3347 const uintptr_t three_minus_new_geno = (7 * kDosage4th - dosage_int) / kDosageMid;
3348 geno_word ^= three_minus_new_geno << shift;
3349 genovec[widx] = geno_word;
3350 }
3351 }
3352
3353 uint32_t ApplyHardCallThreshPhased(const uintptr_t* dosage_present, const Dosage* dosage_main, uint32_t dosage_ct, uint32_t hard_call_halfdist, uintptr_t* genovec, uintptr_t* phasepresent, uintptr_t* phaseinfo, uintptr_t* dphase_present, SDosage* dphase_delta, SDosage* tmp_dphase_delta) {
3354 // Generate new hphase values when we're converting a hardcall from
3355 // missing/hom to het, and abs(dphase_delta) > 0.5. Erase explicit dphase in
3356 // that case if dphase_delta is maximal.
3357 //
3358 // Erase hphase value when we're converting a hardcall from het to
3359 // missing/hom. If hardcall was previously phased and no explicit dphase
3360 // value existed, add it.
3361 //
3362 // Since both insertions and deletions are possible, we write the updated
3363 // dphase_delta to a buffer and copy it back, instead of editing in place.
3364 //
3365 // Returns final dphase_ct.
3366 //
3367 // Some extraneous phaseinfo bits may be set on return.
3368 const SDosage* dphase_read_iter = dphase_delta;
3369 SDosage* dphase_write_iter = tmp_dphase_delta;
3370 uintptr_t sample_uidx_base = 0;
3371 uintptr_t cur_bits = dosage_present[0];
3372 for (uint32_t dosage_idx = 0; dosage_idx != dosage_ct; ++dosage_idx) {
3373 const uintptr_t sample_uidx = BitIter1(dosage_present, &sample_uidx_base, &cur_bits);
3374 const uint32_t dosage_int = dosage_main[dosage_idx];
3375 const uint32_t halfdist = BiallelicDosageHalfdist(dosage_int);
3376 const uintptr_t widx = sample_uidx / kBitsPerWordD2;
3377 uintptr_t prev_geno_word = genovec[widx];
3378 const uint32_t shift = (sample_uidx % kBitsPerWordD2) * 2;
3379 uintptr_t new_geno;
3380 if (halfdist < hard_call_halfdist) {
3381 new_geno = 3;
3382 } else {
3383 new_geno = (dosage_int + kDosage4th) / kDosageMid;
3384 }
3385 const uintptr_t prev_geno = (prev_geno_word >> shift) & 3;
3386 const uintptr_t geno_xor = new_geno ^ prev_geno;
3387 const uint32_t cur_hphase_present = IsSet(phasepresent, sample_uidx);
3388 if (IsSet(dphase_present, sample_uidx)) {
3389 int32_t dphase_delta_val = *dphase_read_iter++;
3390 *dphase_write_iter++ = dphase_delta_val;
3391 if (geno_xor) {
3392 if (new_geno == 1) {
3393 const uint32_t neg_sign_bit = -(S_CAST(uint32_t, dphase_delta_val) >> 31);
3394 const uint32_t abs_dphase_delta_val = (S_CAST(uint32_t, dphase_delta_val) ^ neg_sign_bit) - neg_sign_bit;
3395 if (abs_dphase_delta_val > kDosage4th) {
3396 SetBit(sample_uidx, phasepresent);
3397 AssignBit(sample_uidx, neg_sign_bit + 1, phaseinfo);
3398 // is dphase_delta maximal?
3399 if ((abs_dphase_delta_val == dosage_int) || (abs_dphase_delta_val + dosage_int == kDosageMax)) {
3400 ClearBit(sample_uidx, dphase_present);
3401 --dphase_write_iter;
3402 }
3403 }
3404 } else {
3405 ClearBit(sample_uidx, phasepresent);
3406 }
3407 genovec[widx] = prev_geno_word ^ (geno_xor << shift);
3408 }
3409 } else {
3410 if (geno_xor) {
3411 if (cur_hphase_present) {
3412 assert(new_geno != 1);
3413 ClearBit(sample_uidx, phasepresent);
3414 SetBit(sample_uidx, dphase_present);
3415 int32_t new_dphase_delta_val = DosageHomdist(dosage_int);
3416 if (!IsSet(phaseinfo, sample_uidx)) {
3417 new_dphase_delta_val = -new_dphase_delta_val;
3418 }
3419 *dphase_write_iter++ = new_dphase_delta_val;
3420 }
3421 genovec[widx] = prev_geno_word ^ (geno_xor << shift);
3422 }
3423 }
3424 }
3425 const uint32_t dphase_ct = dphase_write_iter - tmp_dphase_delta;
3426 memcpy(dphase_delta, tmp_dphase_delta, dphase_ct * sizeof(Dosage));
3427 return dphase_ct;
3428 }
3429
3430 uint32_t FillMissingFromBiallelicDosagePhased(const uintptr_t* dosage_present, const Dosage* dosage_main, uint32_t dosage_ct, uintptr_t* genovec, uintptr_t* phasepresent, uintptr_t* phaseinfo, uintptr_t* dphase_present, SDosage* dphase_delta) {
3431 // Generate new hphase values when we're creating a new het hardcall, and
3432 // abs(dphase_delta) > 0.5. Erase explicit dphase in that case if
3433 // dphase_delta is maximal.
3434 //
3435 // Only deletions to dphase_delta[] are possible, so we edit in place.
3436 //
3437 // Returns final dphase_ct.
3438 uint32_t dphase_read_idx = 0;
3439 uint32_t dphase_write_idx = 0;
3440 uintptr_t sample_uidx_base = 0;
3441 uintptr_t cur_bits = dosage_present[0];
3442 uint32_t dosage_idx = 0;
3443 for (; dosage_idx != dosage_ct; ++dosage_idx) {
3444 const uintptr_t sample_uidx = BitIter1(dosage_present, &sample_uidx_base, &cur_bits);
3445 const uintptr_t widx = sample_uidx / kBitsPerWordD2;
3446 const uint32_t shift = 2 * (sample_uidx % kBitsPerWordD2);
3447 uintptr_t geno_word = genovec[widx];
3448 if (((geno_word >> shift) & 3) != 3) {
3449 if (IsSet(dphase_present, sample_uidx)) {
3450 if (dphase_read_idx != dphase_write_idx) {
3451 dphase_delta[dphase_write_idx] = dphase_delta[dphase_read_idx];
3452 }
3453 ++dphase_read_idx;
3454 ++dphase_write_idx;
3455 }
3456 continue;
3457 }
3458 const uint32_t dosage_int = dosage_main[dosage_idx];
3459 const uintptr_t three_minus_new_geno = (7 * kDosage4th - dosage_int) / kDosageMid;
3460 geno_word ^= three_minus_new_geno << shift;
3461 genovec[widx] = geno_word;
3462 if (!IsSet(dphase_present, sample_uidx)) {
3463 continue;
3464 }
3465 const int32_t dphase_delta_val = dphase_delta[dphase_read_idx];
3466 if (dphase_write_idx != dphase_read_idx) {
3467 dphase_delta[dphase_write_idx] = dphase_delta_val;
3468 }
3469 ++dphase_read_idx;
3470 ++dphase_write_idx;
3471 if (three_minus_new_geno != 2) {
3472 continue;
3473 }
3474 const uint32_t neg_sign_bit = -(S_CAST(uint32_t, dphase_delta_val) >> 31);
3475 const uint32_t abs_dphase_delta_val = (S_CAST(uint32_t, dphase_delta_val) ^ neg_sign_bit) - neg_sign_bit;
3476 if (abs_dphase_delta_val > kDosage4th) {
3477 SetBit(sample_uidx, phasepresent);
3478 AssignBit(sample_uidx, neg_sign_bit + 1, phaseinfo);
3479 // is dphase_delta maximal?
3480 if ((abs_dphase_delta_val == dosage_int) || (abs_dphase_delta_val + dosage_int == kDosageMax)) {
3481 ClearBit(sample_uidx, dphase_present);
3482 --dphase_write_idx;
3483 }
3484 }
3485 }
3486 return dphase_write_idx;
3487 }
3488
3489 uintptr_t InitWriteAlleleIdxOffsets(const uintptr_t* variant_include, const uintptr_t* allele_idx_offsets, const uintptr_t* allele_presents, const AlleleCode* allele_permute, const uint32_t* new_variant_idx_to_old, uint32_t variant_ct, uintptr_t* new_allele_idx_offsets) {
3490 uintptr_t cur_offset = 0;
3491 if (allele_presents) {
3492 uint32_t ref_allele_idx = 0;
3493 uintptr_t variant_uidx_base = 0;
3494 uintptr_t cur_bits = 0;
3495 if (!new_variant_idx_to_old) {
3496 cur_bits = variant_include[0];
3497 }
3498 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
3499 uint32_t variant_uidx;
3500 if (new_variant_idx_to_old) {
3501 variant_uidx = new_variant_idx_to_old[variant_idx];
3502 } else {
3503 variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
3504 }
3505 new_allele_idx_offsets[variant_idx] = cur_offset;
3506 const uintptr_t old_offset_start = allele_idx_offsets[variant_uidx];
3507 const uintptr_t old_offset_end = allele_idx_offsets[variant_uidx + 1];
3508 uint32_t cur_allele_ct = old_offset_end - old_offset_start;
3509 if (cur_allele_ct > 2) {
3510 cur_allele_ct = PopcountBitRange(allele_presents, old_offset_start, old_offset_end);
3511 if (allele_permute) {
3512 ref_allele_idx = allele_permute[old_offset_start];
3513 }
3514 if (!IsSet(allele_presents, old_offset_start + ref_allele_idx)) {
3515 ++cur_allele_ct;
3516 }
3517 if (cur_allele_ct < 2) {
3518 cur_allele_ct = 2;
3519 }
3520 }
3521 cur_offset += cur_allele_ct;
3522 }
3523 } else if (!new_variant_idx_to_old) {
3524 uintptr_t variant_uidx_base = 0;
3525 uintptr_t cur_bits = variant_include[0];
3526 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
3527 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
3528 new_allele_idx_offsets[variant_idx] = cur_offset;
3529 cur_offset += allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx];
3530 }
3531 } else {
3532 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
3533 const uint32_t variant_uidx = new_variant_idx_to_old[variant_idx];
3534 new_allele_idx_offsets[variant_idx] = cur_offset;
3535 cur_offset += allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx];
3536 }
3537 }
3538 return cur_offset;
3539 }
3540
3541 // Join behavior:
3542 // - Require sorted input .pvar for now, though it won't be difficult to lift
3543 // this restriction later. Ok for input to contain multiallelic variants.
3544 // - Don't need to do anything different when chr:pos only appears once in a
3545 // biallelic variant, or in a multiallelic variant in "+any" mode. For
3546 // multiallelic variants in +both/+snps mode, error out if the variant is
3547 // mixed SNP/non-SNP. In +both case, also error out if the variant is mixed
3548 // symbolic/non-symbolic, or it's symbolic and does not satisfy the REF or
3549 // INFO/END constraints.
3550 // - When multiple variants have the same chr:pos:
3551 // - In +snps mode, also don't need to do anything different for non-SNPs.
3552 // - Otherwise, create up to three linked lists of input variant records
3553 // (need to distinguish SNPs from non-SNPs in +both mode, and within the
3554 // non-SNP category, symbolic alleles are separate from non-symbolic).
3555 // The variant with symbolic alleles has additional constraints: a warning
3556 // is printed if INFO/END isn't defined, and an error occurs if either REF
3557 // is multi-character, or there's an INFO/END mismatch.
3558 // - Error out if REF alleles aren't all consistent, or any ALT allele is
3559 // duplicated (note that --pmerge must support the latter).
3560 // - For joined not-entirely-SNP non-symbolic variants, the final REF is the
3561 // longest of the original REFs; ALT alleles have bases added to the end if
3562 // necessary. (Yes, this causes SNPs to stop being visible to a strlen ==
3563 // 1 check in +any mode, which is why + is interpreted as +both instead.)
3564 // - Final ALT allele order is based on allele frequency (highest first),
3565 // with ties broken by natural-sort.
3566 // - ID: 1. If --set-all-var-ids specified, apply template.
3567 // 2. Otherwise, keep original variant ID if all sources identical and
3568 // nonmissing.
3569 // 3. Otherwise, if vid-join specified, check if all original IDs are
3570 // nonmissing and contain exactly one ';' per extra ALT allele. If
3571 // so, join on ';' in final ALT allele order.
3572 // 4. Otherwise, set to --set-missing-var-ids template or missing code.
3573 // - QUAL is minimum of inputs ('.' treated as positive infinity). FILTER is
3574 // natural-sorted union of non-PASS values; if all inputs were '.'/PASS,
3575 // output is PASS unless all inputs were missing.
3576 // - INFO join is based on the Number field in the key's header line. (If
3577 // there's no header line corresponding to a key, we error out.) For
3578 // Number=A, we join in the obvious manner. For Number=R (or Number=G in
3579 // the haploid case), we replace the reference allele entry with . iff
3580 // there's any string mismatch (e.g. '13' and '13.0' will be treated as
3581 // unequal), and print a warning (with more than 3 warnings, later warnings
3582 // are only written to log file). For diploid Number=G, we do the same for
3583 // the hom-ref entry. For Number=0, we error out if the header line Type
3584 // isn't Flag, and the final flag is set iff any of the original variants
3585 // have the flag set. For the other cases (Number=<fixed constant> or
3586 // '.'), we replace the value with '.' if there's any string mismatch.
3587 // The key won't appear at all iff it doesn't appear in any of the original
3588 // variants (not even a '.').
3589 // - We error out if the joined variant has total ALT dosage > ~2.02, or
3590 // either side of the total ALT phased dosage > ~1.01. (We scale the
3591 // components down if there's a <1% overflow.)
3592 // - Missing ALTs... ugh. Have to permit this in biallelic case, but don't
3593 // allow it elsewhere. This forces a SNP (if REF is single-char) and/or
3594 // non-SNP (if REF is multichar) entry to be written when no corresponding
3595 // regular ALT is present, genotype writing/merging will error out if a
3596 // missing allele has any dosage, and QUAL/FILTER/INFO is merged as usual
3597 // when there are multiple missing-ALT same-type variants at the same
3598 // position. However, when a regular ALT is present, the missing-ALT
3599 // variants are completely ignored.
3600
3601 // The simplest design involves precomputing the entire (new variant idx, new
3602 // allele idx) -> (old variant uidx, old allele idx) mapping here, and
3603 // referring to that in both the .pvar and .pgen writers. Unfortunately, that
3604 // has a rather high memory requirement of 5 bytes per allele (assuming
3605 // sizeof(AlleleCode) == 1). While that's smaller than the 8 bytes/allele we
3606 // pay for allele_storage[], and also practically always smaller than the
3607 // 21+[variant ID len] per variant we pay for variant_bps + variant_ids +
3608 // allele_idx_offsets, it's still worth some effort to avoid; in particular, we
3609 // want an 8 GiB workspace to be sufficient for most operations on the full
3610 // 1000 Genomes phase 3 variant set (~84.8 million), and that's barely true
3611 // right now, so a bit of additional complexity to avoid losing ~850 MB is
3612 // justified.
3613 //
3614 // Thus, we only save the number of alleles in each new variant here, and force
3615 // the which-allele-comes-from-where computation (as well as SNP vs. non-SNP
3616 // vs. symbolic handling) to be repeated in the .pvar and .pgen writers. This
3617 // sucks, but being forced to perform an ordinary analysis on a remote machine
3618 // rather than locally sucks a bit more.
3619 //
3620 // Incidentally, another place to look, if it's important to further reduce
3621 // memory requirements, is internal representation of the FILTER field. The
3622 // current design gains a bit of extra speed by simply storing the non-./PASS
3623 // strings without parsing them further; but we could put them into a temporary
3624 // storage location and then convert to bitarray + string table at the end of
3625 // LoadPvar(). (Note that we already use only bitarrays when all FILTER values
3626 // are ./PASS, though.)
3627
3628 ENUM_U31_DEF_START()
3629 kJoinVtypeError,
3630 kJoinVtypeSnp,
3631 kJoinVtypeNonsnp,
3632 kJoinVtypeMixedSnpNonsnp,
3633 kJoinVtypeSymbolic,
3634 kJoinVtypeEnd
3635 ENUM_U31_DEF_END(JoinVtype);
3636
3637 typedef struct JoinCountsStruct {
3638 uintptr_t snp_ct;
3639 uintptr_t nonsnp_ct;
3640 uintptr_t symbolic_ct;
3641 uint32_t missalt_snp_ct;
3642 uint32_t missalt_nonsnp_ct;
3643 } JoinCounts;
3644
3645 JoinVtype JoinCount(const char* const* cur_alleles, uintptr_t allele_ct, JoinCounts* jcp) {
3646 jcp->snp_ct = 0;
3647 jcp->symbolic_ct = 0;
3648 jcp->missalt_snp_ct = 0;
3649 jcp->missalt_nonsnp_ct = 0;
3650 if (cur_alleles[0][1] == '\0') {
3651 jcp->nonsnp_ct = 0;
3652 for (uintptr_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) {
3653 const char* cur_allele = cur_alleles[allele_idx];
3654 if (cur_allele[0] == '<') {
3655 jcp->symbolic_ct += 1;
3656 } else if (cur_allele[1] == '\0') {
3657 if (cur_allele[0] == '.') {
3658 if (allele_ct == 2) {
3659 jcp->missalt_snp_ct = 1;
3660 return kJoinVtypeSnp;
3661 }
3662 return kJoinVtypeError;
3663 }
3664 jcp->snp_ct += 1;
3665 } else {
3666 jcp->nonsnp_ct += 1;
3667 }
3668 }
3669 if (jcp->symbolic_ct) {
3670 return (jcp->symbolic_ct == allele_ct - 1)? kJoinVtypeSymbolic : kJoinVtypeError;
3671 }
3672 if (jcp->nonsnp_ct) {
3673 return jcp->snp_ct? kJoinVtypeMixedSnpNonsnp : kJoinVtypeNonsnp;
3674 }
3675 return kJoinVtypeSnp;
3676 }
3677 for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) {
3678 const char* cur_allele = cur_alleles[allele_idx];
3679 if (cur_allele[0] == '<') {
3680 return kJoinVtypeError;
3681 }
3682 if (strequal_k_unsafe(cur_allele, ".")) {
3683 if (allele_ct == 2) {
3684 jcp->nonsnp_ct = 0;
3685 jcp->missalt_nonsnp_ct = 1;
3686 return kJoinVtypeNonsnp;
3687 }
3688 return kJoinVtypeError;
3689 }
3690 }
3691 jcp->nonsnp_ct = allele_ct - 1;
3692 return kJoinVtypeNonsnp;
3693 }
3694
3695 void PlanJoinOne(uint32_t cur_alt_allele_ct, uintptr_t** write_allele_idx_offsets_iterp, uintptr_t* cur_offsetp, uint32_t* max_write_allele_ctp) {
3696 const uint32_t cur_write_allele_ct = 1 + MAXV(1, cur_alt_allele_ct);
3697 if (cur_write_allele_ct > (*max_write_allele_ctp)) {
3698 *max_write_allele_ctp = cur_write_allele_ct;
3699 }
3700 *cur_offsetp += cur_write_allele_ct;
3701 uintptr_t* write_allele_idx_offsets_iter = *write_allele_idx_offsets_iterp;
3702 *write_allele_idx_offsets_iter++ = *cur_offsetp;
3703 *write_allele_idx_offsets_iterp = write_allele_idx_offsets_iter;
3704 }
3705
3706 void PlanJoinFlushPos(const JoinCounts* jcp, MakePlink2Flags join_mode, uintptr_t** write_allele_idx_offsets_iterp, uintptr_t* cur_offsetp, uint32_t* max_write_allele_ctp, uint32_t* max_missalt_ctp) {
3707 if (join_mode == kfMakePlink2MJoinSnps) {
3708 if (!(jcp->snp_ct || jcp->missalt_snp_ct)) {
3709 // all non-SNPs at this position, which were already accounted for
3710 return;
3711 }
3712 PlanJoinOne(jcp->snp_ct, write_allele_idx_offsets_iterp, cur_offsetp, max_write_allele_ctp);
3713 if ((!jcp->snp_ct) && (jcp->missalt_snp_ct > (*max_missalt_ctp))) {
3714 *max_missalt_ctp = jcp->missalt_snp_ct;
3715 }
3716 return;
3717 }
3718 if (join_mode == kfMakePlink2MJoinBoth) {
3719 if (jcp->snp_ct || jcp->missalt_snp_ct) {
3720 PlanJoinOne(jcp->snp_ct, write_allele_idx_offsets_iterp, cur_offsetp, max_write_allele_ctp);
3721 if ((!jcp->snp_ct) && (jcp->missalt_snp_ct > (*max_missalt_ctp))) {
3722 *max_missalt_ctp = jcp->missalt_snp_ct;
3723 }
3724 }
3725 if (jcp->nonsnp_ct || jcp->missalt_nonsnp_ct) {
3726 PlanJoinOne(jcp->nonsnp_ct, write_allele_idx_offsets_iterp, cur_offsetp, max_write_allele_ctp);
3727 if ((!jcp->nonsnp_ct) && (jcp->missalt_nonsnp_ct > (*max_missalt_ctp))) {
3728 *max_missalt_ctp = jcp->missalt_nonsnp_ct;
3729 }
3730 }
3731 } else {
3732 if (jcp->snp_ct || jcp->nonsnp_ct || jcp->missalt_snp_ct || jcp->missalt_nonsnp_ct) {
3733 const uint32_t alt_allele_ct = jcp->snp_ct + jcp->nonsnp_ct;
3734 PlanJoinOne(alt_allele_ct, write_allele_idx_offsets_iterp, cur_offsetp, max_write_allele_ctp);
3735 const uint32_t missalt_ct = jcp->missalt_snp_ct + jcp->missalt_nonsnp_ct;
3736 if ((missalt_ct > (*max_missalt_ctp)) && (!alt_allele_ct)) {
3737 *max_missalt_ctp = missalt_ct;
3738 }
3739 }
3740 }
3741 if (jcp->symbolic_ct) {
3742 PlanJoinOne(jcp->symbolic_ct, write_allele_idx_offsets_iterp, cur_offsetp, max_write_allele_ctp);
3743 }
3744 }
3745
3746
3747 // *write_allele_idx_offsetsp is assumed to be initialized to nullptr.
3748 // *max_missalt_ctp is assumed to be initialized to 0.
3749 PglErr PlanMultiallelicJoin(const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, MakePlink2Flags flags, uint32_t* write_variant_ctp, const uintptr_t** write_allele_idx_offsetsp, uint32_t* max_write_allele_ctp, uint32_t* max_missalt_ctp) {
3750 uint32_t variant_uidx = 0;
3751 PglErr reterr = kPglRetSuccess;
3752 {
3753 const uint32_t variant_ct = *write_variant_ctp;
3754 uintptr_t* write_allele_idx_offsets = R_CAST(uintptr_t*, g_bigstack_base);
3755 uintptr_t* write_allele_idx_offsets_stop = R_CAST(uintptr_t*, BigstackEndRoundedDown());
3756 if (write_allele_idx_offsets == write_allele_idx_offsets_stop) {
3757 goto PlanMultiallelicJoin_ret_NOMEM;
3758 }
3759 write_allele_idx_offsets_stop = &(write_allele_idx_offsets_stop[-4]);
3760 const MakePlink2Flags join_mode = flags & kfMakePlink2MMask;
3761 uintptr_t* write_allele_idx_offsets_iter = write_allele_idx_offsets;
3762 *write_allele_idx_offsets_iter++ = 0;
3763 uintptr_t cur_offset = 0;
3764 uintptr_t variant_uidx_base = 0;
3765 uintptr_t cur_bits = variant_include[0];
3766 uint32_t chr_fo_idx = UINT32_MAX;
3767 uint32_t chr_end = 0;
3768 uint32_t prev_bp = 0;
3769 uint32_t allele_ct = 2;
3770 uint32_t max_write_allele_ct = 2;
3771 JoinCounts jc;
3772 // possible todo: track max_write_allele_ct for each subcase, instead of
3773 // having a single value
3774 jc.snp_ct = 0;
3775 jc.nonsnp_ct = 0;
3776 jc.symbolic_ct = 0;
3777 jc.missalt_snp_ct = 0;
3778 jc.missalt_nonsnp_ct = 0;
3779 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
3780 variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
3781 if (variant_uidx >= chr_end) {
3782 do {
3783 ++chr_fo_idx;
3784 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
3785 } while (variant_uidx >= chr_end);
3786 prev_bp = UINT32_MAX;
3787 }
3788 uintptr_t allele_idx_offset_base = variant_uidx * 2;
3789 if (allele_idx_offsets) {
3790 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
3791 allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
3792 }
3793 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
3794 JoinCounts cur_jc;
3795 JoinVtype jvt = JoinCount(cur_alleles, allele_ct, &cur_jc);
3796 if (unlikely(jvt == kJoinVtypeError)) {
3797 goto PlanMultiallelicJoin_ret_MIXED_SYMBOLIC;
3798 }
3799 if (unlikely((join_mode != kfMakePlink2MJoinAny) && (jvt == kJoinVtypeMixedSnpNonsnp))) {
3800 logerrprintfww("Error: Variant '%s' is mixed SNP/non-SNP; multiallelics=+both and +snps don't permit this.\n", variant_ids[variant_uidx]);
3801 goto PlanMultiallelicJoin_ret_INCONSISTENT_INPUT;
3802 }
3803 const uint32_t cur_bp = variant_bps[variant_uidx];
3804 if (cur_bp != prev_bp) {
3805 PlanJoinFlushPos(&jc, join_mode, &write_allele_idx_offsets_iter, &cur_offset, &max_write_allele_ct, max_missalt_ctp);
3806 if (join_mode == kfMakePlink2MJoinSnps) {
3807 if (cur_jc.nonsnp_ct || cur_jc.symbolic_ct || cur_jc.missalt_nonsnp_ct) {
3808 // Flush non-SNP immediately.
3809 const uint32_t cur_write_allele_ct = 1 + cur_jc.nonsnp_ct + cur_jc.symbolic_ct;
3810 cur_offset += cur_write_allele_ct;
3811 if (cur_write_allele_ct > max_write_allele_ct) {
3812 max_write_allele_ct = cur_write_allele_ct;
3813 }
3814 *write_allele_idx_offsets_iter++ = cur_offset;
3815 // Also need to reinitialize.
3816 jc.snp_ct = 0;
3817 jc.missalt_snp_ct = 0;
3818 } else {
3819 jc.snp_ct = cur_jc.snp_ct;
3820 jc.missalt_snp_ct = cur_jc.missalt_snp_ct;
3821 }
3822 } else {
3823 jc = cur_jc;
3824 }
3825 prev_bp = cur_bp;
3826 } else if ((join_mode == kfMakePlink2MJoinSnps) && (cur_jc.nonsnp_ct || cur_jc.symbolic_ct)) {
3827 // Flush non-SNP immediately.
3828 const uint32_t cur_write_allele_ct = 1 + cur_jc.nonsnp_ct + cur_jc.symbolic_ct;
3829 cur_offset += cur_write_allele_ct;
3830 if (cur_write_allele_ct > max_write_allele_ct) {
3831 max_write_allele_ct = cur_write_allele_ct;
3832 }
3833 *write_allele_idx_offsets_iter++ = cur_offset;
3834 } else {
3835 jc.snp_ct += cur_jc.snp_ct;
3836 jc.nonsnp_ct += cur_jc.nonsnp_ct;
3837 jc.symbolic_ct += cur_jc.symbolic_ct;
3838 jc.missalt_snp_ct += cur_jc.missalt_snp_ct;
3839 jc.missalt_nonsnp_ct += cur_jc.missalt_nonsnp_ct;
3840 continue;
3841 }
3842 if (write_allele_idx_offsets_iter > write_allele_idx_offsets_stop) {
3843 goto PlanMultiallelicJoin_ret_NOMEM;
3844 }
3845 }
3846 // Flush last position.
3847 PlanJoinFlushPos(&jc, join_mode, &write_allele_idx_offsets_iter, &cur_offset, &max_write_allele_ct, max_missalt_ctp);
3848 if (max_write_allele_ct > kPglMaxAlleleCt) {
3849 goto PlanMultiallelicJoin_ret_TOO_MANY_ALTS;
3850 }
3851 *write_variant_ctp = S_CAST(uintptr_t, write_allele_idx_offsets_iter - write_allele_idx_offsets) - 1;
3852 *max_write_allele_ctp = max_write_allele_ct;
3853 if (max_write_allele_ct > 2) {
3854 BigstackBaseSet(write_allele_idx_offsets_iter);
3855 *write_allele_idx_offsetsp = write_allele_idx_offsets;
3856 }
3857 }
3858 while (0) {
3859 PlanMultiallelicJoin_ret_NOMEM:
3860 reterr = kPglRetNomem;
3861 break;
3862 PlanMultiallelicJoin_ret_MIXED_SYMBOLIC:
3863 logerrprintfww("Error: Variant '%s' mixes symbolic and non-symbolic alleles in an unsupported manner.\n", variant_ids[variant_uidx]);
3864 PlanMultiallelicJoin_ret_INCONSISTENT_INPUT:
3865 reterr = kPglRetInconsistentInput;
3866 break;
3867 PlanMultiallelicJoin_ret_TOO_MANY_ALTS:
3868 logerrprintf("Error: Variant-join would create a variant with too many ALT alleles for this\nplink2 build.\n");
3869 reterr = kPglRetNotYetSupported;
3870 break;
3871 }
3872 return reterr;
3873 }
3874
3875 PglErr PlanMultiallelicSplit(const uintptr_t* variant_include, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, uint32_t max_allele_ct, MakePlink2Flags flags, uint32_t* write_variant_ctp, const uintptr_t** write_allele_idx_offsetsp) {
3876 uint32_t variant_uidx = 0;
3877 PglErr reterr = kPglRetSuccess;
3878 {
3879 const uint32_t variant_ct = *write_variant_ctp;
3880 const uint32_t only_split_snps = ((flags & kfMakePlink2MMask) == kfMakePlink2MSplitSnps);
3881 uintptr_t* write_allele_idx_offsets = nullptr;
3882 uintptr_t* write_allele_idx_offsets_stop = nullptr;
3883 uintptr_t* write_allele_idx_offsets_iter = nullptr;
3884 if (only_split_snps) {
3885 write_allele_idx_offsets = R_CAST(uintptr_t*, g_bigstack_base);
3886 write_allele_idx_offsets_stop = R_CAST(uintptr_t*, g_bigstack_end);
3887 if (S_CAST(uintptr_t, write_allele_idx_offsets_stop - write_allele_idx_offsets) <= max_allele_ct) {
3888 goto PlanMultiallelicSplit_ret_NOMEM;
3889 }
3890 write_allele_idx_offsets_stop -= max_allele_ct;
3891 write_allele_idx_offsets_iter = write_allele_idx_offsets;
3892 *write_allele_idx_offsets_iter++ = 0;
3893 }
3894 uintptr_t cur_offset = 0;
3895 uintptr_t write_variant_ct = 0;
3896 uintptr_t variant_uidx_base = 0;
3897 uintptr_t cur_bits = variant_include[0];
3898 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
3899 variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
3900 const uintptr_t allele_idx_offset_base = allele_idx_offsets[variant_uidx];
3901 const uint32_t allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
3902 if (allele_ct == 2) {
3903 if (only_split_snps) {
3904 cur_offset += 2;
3905 *write_allele_idx_offsets_iter++ = cur_offset;
3906 }
3907 ++write_variant_ct;
3908 } else {
3909 if (only_split_snps) {
3910 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
3911 uint32_t do_split = 1;
3912 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
3913 if (cur_alleles[allele_idx][1] != '\0') {
3914 do_split = 0;
3915 break;
3916 }
3917 }
3918 if (do_split) {
3919 for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) {
3920 cur_offset += 2;
3921 *write_allele_idx_offsets_iter++ = cur_offset;
3922 }
3923 write_variant_ct += allele_ct - 1;
3924 } else {
3925 cur_offset += allele_ct;
3926 *write_allele_idx_offsets_iter++ = cur_offset;
3927 ++write_variant_ct;
3928 }
3929 if (write_allele_idx_offsets_iter > write_allele_idx_offsets_stop) {
3930 goto PlanMultiallelicSplit_ret_NOMEM;
3931 }
3932 } else {
3933 write_variant_ct += allele_ct - 1;
3934 }
3935 }
3936 }
3937 if (write_variant_ct > kPglMaxVariantCt) {
3938 logerrputs("Error: " PROG_NAME_STR " does not support more than 2^31 - 3 variants. We recommend using\nother software for very deep studies of small numbers of genomes.\n");
3939 goto PlanMultiallelicSplit_ret_INCONSISTENT_INPUT;
3940 }
3941 *write_variant_ctp = write_variant_ct;
3942 if (only_split_snps && (cur_offset != 2 * write_variant_ct)) {
3943 assert(cur_offset > 2 * write_variant_ct);
3944 if (unlikely(BigstackBaseSetChecked(write_allele_idx_offsets_iter))) {
3945 goto PlanMultiallelicSplit_ret_NOMEM;
3946 }
3947 *write_allele_idx_offsetsp = write_allele_idx_offsets;
3948 }
3949 }
3950 while (0) {
3951 PlanMultiallelicSplit_ret_NOMEM:
3952 reterr = kPglRetNomem;
3953 break;
3954 PlanMultiallelicSplit_ret_INCONSISTENT_INPUT:
3955 reterr = kPglRetInconsistentInput;
3956 break;
3957 }
3958 return reterr;
3959 }
3960
3961 // Returns 1 iff there are exactly (allele_ct - 2) semicolons in
3962 // orig_variant_id, and no two are adjacent (or leading/trailing).
3963 uint32_t VaridSplitOk(const char* orig_variant_id, uint32_t allele_ct) {
3964 const char* id_iter = orig_variant_id;
3965 for (uint32_t aidx = 2; aidx != allele_ct; ++aidx) {
3966 const char* tok_end = strchr(id_iter, ';');
3967 if ((!tok_end) || (tok_end == id_iter)) {
3968 return 0;
3969 }
3970 id_iter = &(tok_end[1]);
3971 }
3972 return (*id_iter != '\0') && (!strchr(id_iter, ';'));
3973 }
3974
3975 // Similar to WriteMapOrBim(), but there are enough small differences to
3976 // justify making this a separate function instead of clogging the original
3977 // with more conditionals.
3978 PglErr WriteBimSplit(const char* outname, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const double* variant_cms, const char* varid_template_str, const char* missing_varid_match, uint32_t variant_ct, uint32_t max_allele_slen, uint32_t new_variant_id_max_allele_slen, uint32_t varid_split, uint32_t varid_dup, MiscFlags misc_flags, uint32_t output_zst, uint32_t thread_ct) {
3979 unsigned char* bigstack_mark = g_bigstack_base;
3980 char* cswritep = nullptr;
3981 CompressStreamState css;
3982 PglErr reterr = kPglRetSuccess;
3983 PreinitCstream(&css);
3984 {
3985 const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
3986 // includes trailing tab
3987 char* chr_buf;
3988 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
3989 goto WriteBimSplit_ret_NOMEM;
3990 }
3991 const uint32_t varid_dup_nosplit = varid_dup && (!varid_split);
3992 VaridTemplate* varid_templatep = nullptr;
3993 uint32_t missing_varid_slen = 0;
3994 uint32_t missing_varid_match_blen = 0; // nonzero iff --set-missing-var-ids
3995 if (varid_template_str) {
3996 if (!missing_varid_match) {
3997 missing_varid_match = &(g_one_char_strs[92]); // '.'
3998 }
3999 missing_varid_slen = strlen(missing_varid_match);
4000 if (misc_flags & kfMiscSetMissingVarIds) {
4001 missing_varid_match_blen = missing_varid_slen + 1;
4002 }
4003 if (unlikely(BIGSTACK_ALLOC_X(VaridTemplate, 1, &varid_templatep))) {
4004 goto WriteBimSplit_ret_NOMEM;
4005 }
4006 const uint32_t new_variant_id_overflow_missing = (misc_flags / kfMiscNewVarIdOverflowMissing) & 1;
4007 const uint32_t overflow_substitute_blen = new_variant_id_overflow_missing? (missing_varid_slen + 1) : 0;
4008 VaridTemplateInit(varid_template_str, missing_varid_match, chr_buf, new_variant_id_max_allele_slen, overflow_substitute_blen, varid_templatep);
4009 if (varid_dup) {
4010 for (uint32_t uii = 0; uii != varid_templatep->insert_ct; ++uii) {
4011 const uint32_t insert_type = varid_templatep->insert_types[uii];
4012 if ((insert_type == 3) || ((insert_type == 2) && (varid_templatep->allele_flags & kfVaridTemplateAlleleAsciiOrder))) {
4013 // Could define what takes precedence here, but simpler to prohibit
4014 // this combination.
4015 logputs("\n");
4016 logerrputs("Error: 'vid-[split-]dup' cannot be used with a --set-all-var-ids or\n--set-missing-var-ids template string containing a non-REF allele.\n");
4017 goto WriteBimSplit_ret_INVALID_CMDLINE;
4018 }
4019 }
4020 }
4021 }
4022 const uintptr_t overflow_buf_size = kCompressStreamBlock + kMaxIdSlen + 512 + 2 * max_allele_slen;
4023 reterr = InitCstreamAlloc(outname, 0, output_zst, thread_ct, overflow_buf_size, &css, &cswritep);
4024 if (unlikely(reterr)) {
4025 goto WriteBimSplit_ret_1;
4026 }
4027
4028 const VaridTemplate* cur_varid_templatep = nullptr;
4029 const char* varid_token_start = nullptr; // for vid-split
4030 uint32_t max_allele_overflow_slen = 0;
4031 uint32_t chr_fo_idx = UINT32_MAX;
4032 uint32_t chr_end = 0;
4033 uint32_t chr_buf_blen = 0;
4034 uintptr_t variant_uidx_base = 0;
4035 uintptr_t cur_bits = variant_include[0];
4036 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
4037 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
4038 if (variant_uidx >= chr_end) {
4039 do {
4040 ++chr_fo_idx;
4041 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
4042 } while (variant_uidx >= chr_end);
4043 char* chr_name_end = chrtoa(cip, cip->chr_file_order[chr_fo_idx], chr_buf);
4044 *chr_name_end = '\t';
4045 const uint32_t chr_slen = chr_name_end - chr_buf;
4046 chr_buf_blen = 1 + chr_slen;
4047 if (varid_templatep) {
4048 const int32_t chr_slen_delta = chr_slen - varid_templatep->chr_slen;
4049 varid_templatep->chr_slen = chr_slen;
4050 varid_templatep->base_len += chr_slen_delta;
4051 }
4052 }
4053 const uintptr_t allele_idx_offset_base = allele_idx_offsets[variant_uidx];
4054 const uint32_t orig_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
4055 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
4056 const char* orig_variant_id = variant_ids[variant_uidx];
4057 const char* ref_allele = cur_alleles[0];
4058 const uint32_t ref_allele_slen = strlen(ref_allele);
4059 uint32_t keep_orig_id = 1;
4060 if ((orig_allele_ct > 2) && (!varid_dup_nosplit)) {
4061 keep_orig_id = 0;
4062 if (varid_templatep && (!missing_varid_match_blen)) {
4063 cur_varid_templatep = varid_templatep;
4064 } else {
4065 cur_varid_templatep = nullptr;
4066 if (varid_split) {
4067 if (VaridSplitOk(orig_variant_id, orig_allele_ct)) {
4068 varid_token_start = orig_variant_id;
4069 } else if (varid_dup) {
4070 keep_orig_id = 1;
4071 } else {
4072 varid_token_start = nullptr;
4073 }
4074 }
4075 if ((!varid_token_start) && varid_templatep) {
4076 // --set-missing-var-ids usually applies here when it's specified;
4077 // the exceptions are when vid-split was also specified and the
4078 // split succeeded, or vid-split-dup was specified.
4079 // (In the latter case, this value is ignored anyway.)
4080 cur_varid_templatep = varid_templatep;
4081 }
4082 }
4083 }
4084 const uint32_t cur_bp = variant_bps[variant_uidx];
4085 // We already verified that no variants to be written have >2 alleles, so
4086 // we don't need to distinguish between '-' and '-snps'.
4087 for (uint32_t alt_allele_idx = 1; alt_allele_idx != orig_allele_ct; ++alt_allele_idx) {
4088 cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
4089 const char* cur_alt_allele = cur_alleles[alt_allele_idx];
4090 const uint32_t cur_alt_allele_slen = strlen(cur_alt_allele);
4091 if (keep_orig_id) {
4092 cswritep = strcpyax(cswritep, orig_variant_id, '\t');
4093 } else {
4094 if (cur_varid_templatep) {
4095 // Always true in --set-all-var-ids case. True in
4096 // --set-missing-var-ids case when vid-split unspecified, or split
4097 // failed.
4098 cswritep = VaridTemplateWrite(cur_varid_templatep, ref_allele, cur_alt_allele, cur_bp, ref_allele_slen, 0, cur_alt_allele_slen, &max_allele_overflow_slen, cswritep);
4099 *cswritep++ = '\t';
4100 } else if (varid_token_start) {
4101 const char* varid_token_end = strchrnul(varid_token_start, ';');
4102 // If substring matches missing code and --set-missing-var-ids is
4103 // specified, we replace it.
4104 if (varid_templatep && (S_CAST(uintptr_t, varid_token_end - varid_token_start) == missing_varid_slen) && memequal(varid_token_start, missing_varid_match, missing_varid_slen)) {
4105 cswritep = VaridTemplateWrite(varid_templatep, ref_allele, cur_alt_allele, cur_bp, ref_allele_slen, 0, cur_alt_allele_slen, &max_allele_overflow_slen, cswritep);
4106 } else {
4107 cswritep = memcpya(cswritep, varid_token_start, varid_token_end - varid_token_start);
4108 }
4109 *cswritep++ = '\t';
4110 varid_token_start = &(varid_token_end[1]);
4111 } else {
4112 cswritep = memcpyax(cswritep, missing_varid_match, missing_varid_slen, '\t');
4113 }
4114 }
4115 if (!variant_cms) {
4116 *cswritep++ = '0';
4117 } else {
4118 cswritep = dtoa_g_p8(variant_cms[variant_uidx], cswritep);
4119 }
4120 *cswritep++ = '\t';
4121 cswritep = u32toa(cur_bp, cswritep);
4122 *cswritep++ = '\t';
4123 // note that VCF ref allele corresponds to A2, not A1
4124 cswritep = memcpya(cswritep, cur_alt_allele, cur_alt_allele_slen);
4125 *cswritep++ = '\t';
4126 cswritep = memcpya(cswritep, ref_allele, ref_allele_slen);
4127 AppendBinaryEoln(&cswritep);
4128 if (unlikely(Cswrite(&css, &cswritep))) {
4129 goto WriteBimSplit_ret_WRITE_FAIL;
4130 }
4131 }
4132 }
4133 if (unlikely(CswriteCloseNull(&css, cswritep))) {
4134 goto WriteBimSplit_ret_WRITE_FAIL;
4135 }
4136 if (unlikely(max_allele_overflow_slen && (!(misc_flags & (kfMiscNewVarIdOverflowMissing | kfMiscNewVarIdOverflowTruncate))))) {
4137 logputs("\n");
4138 logerrprintf("Error: Allele code(s) too long for --set-%s-var-ids.\n", (misc_flags & kfMiscSetMissingVarIds)? "missing" : "all");
4139 // Not a precise bound, but in practice this should print the more useful
4140 // message >99% of the time.
4141 if (max_allele_overflow_slen < kMaxIdSlen / 2) {
4142 logerrprintfww("The longest observed allele code in this dataset has length %u. If you're fine with the corresponding ID length, rerun with \"--new-id-max-allele-len %u\" added to your command line.\n", max_allele_overflow_slen, max_allele_overflow_slen);
4143 } else {
4144 logerrprintfww("The longest observed allele code in this dataset has length %u. We recommend deciding on a length-limit, and then adding \"--new-id-max-allele-len <limit> missing\" to your command line to cause variants with longer allele codes to be assigned '.' IDs. (You can then process just those variants with another script, if necessary.)\n", max_allele_overflow_slen);
4145 }
4146 goto WriteBimSplit_ret_INCONSISTENT_INPUT;
4147 }
4148 }
4149 while (0) {
4150 WriteBimSplit_ret_NOMEM:
4151 reterr = kPglRetNomem;
4152 break;
4153 WriteBimSplit_ret_WRITE_FAIL:
4154 reterr = kPglRetWriteFail;
4155 break;
4156 WriteBimSplit_ret_INVALID_CMDLINE:
4157 reterr = kPglRetInvalidCmdline;
4158 break;
4159 WriteBimSplit_ret_INCONSISTENT_INPUT:
4160 reterr = kPglRetInconsistentInput;
4161 break;
4162 }
4163 WriteBimSplit_ret_1:
4164 CswriteCloseCond(&css, cswritep);
4165 BigstackReset(bigstack_mark);
4166 return reterr;
4167 }
4168
4169 BoolErr FillInfoVtypeNum(const char* numstr, uint32_t num_slen, uint32_t* info_has_g_keyp, int32_t* info_vtype_num_ptr) {
4170 if (num_slen == 1) {
4171 const char num_char = numstr[0];
4172 if (num_char < '0') {
4173 if (likely(num_char == '.')) {
4174 *info_vtype_num_ptr = kInfoVtypeUnknown;
4175 } else {
4176 return 1;
4177 }
4178 } else if (num_char > '9') {
4179 if (num_char == 'A') {
4180 *info_vtype_num_ptr = kInfoVtypeA;
4181 } else if (num_char == 'R') {
4182 *info_vtype_num_ptr = kInfoVtypeR;
4183 } else if (likely(num_char == 'G')) {
4184 *info_has_g_keyp = 1;
4185 *info_vtype_num_ptr = kInfoVtypeUnknown;
4186 } else {
4187 return 1;
4188 }
4189 } else {
4190 *info_vtype_num_ptr = num_char - '0';
4191 }
4192 return 0;
4193 }
4194 const char* numstr_iter = numstr;
4195 uint32_t val;
4196 if (unlikely(ScanmovPosintCapped(0x3fffffff, &numstr_iter, &val) || (numstr_iter != &(numstr[num_slen])))) {
4197 return 1;
4198 }
4199 *info_vtype_num_ptr = val;
4200 return 0;
4201 }
4202
4203 // info_keys[] entries point to the (variable-size) key[] member of InfoVtype
4204 // structs. We use [const_]container_of(x)->num to look up the associated
4205 // Number= value.
4206 // Assumes info_has_g_key initialized to 0.
4207 // Sets INFO/PR Flag num to kInfoVtypeSkip.
4208 PglErr ParseInfoHeader(const char* xheader, uintptr_t xheader_blen, uint32_t* info_has_g_keyp, const char* const** info_keys_ptr, uint32_t* info_key_ctp, uint32_t** info_keys_htablep, uint32_t* info_keys_htable_sizep) {
4209 unsigned char* bigstack_mark = g_bigstack_base;
4210 unsigned char* bigstack_end_mark = g_bigstack_end;
4211 PglErr reterr = kPglRetSuccess;
4212 {
4213 // Parsing loop is similar to that in ExportVcf().
4214 const char* xheader_iter = xheader;
4215 const char* xheader_end = &(xheader[xheader_blen]);
4216 const char* line_end = xheader;
4217 unsigned char* tmp_alloc_end = g_bigstack_end;
4218 const char** info_keys = R_CAST(const char**, bigstack_mark);
4219 const char** info_keys_iter = info_keys;
4220 while (line_end != xheader_end) {
4221 xheader_iter = line_end;
4222 line_end = AdvPastDelim(xheader_iter, '\n');
4223 if (!StrStartsWithUnsafe(xheader_iter, "##INFO=<")) {
4224 continue;
4225 }
4226 xheader_iter = &(xheader_iter[strlen("##INFO=<")]);
4227 const char* idval;
4228 uint32_t id_slen;
4229 if (unlikely(HkvlineIdK(&xheader_iter, &idval, &id_slen))) {
4230 goto ParseInfoHeader_ret_MALFORMED_INFO_HEADER_LINE;
4231 }
4232 if (id_slen > kMaxInfoKeySlen) {
4233 logerrputs("Error: " PROG_NAME_STR " does not support INFO keys longer than " MAX_INFO_KEY_SLEN_STR " characters.\n");
4234 // VCF spec doesn't specify a limit, so this isn't "malformed input",
4235 // and not marked as unlikely() even though it is.
4236 // We enforce a limit so we can safely print INFO keys in error
4237 // messages, etc.; it's trivial to increase the limit if it's ever
4238 // necessary.
4239 reterr = kPglRetNotYetSupported;
4240 goto ParseInfoHeader_ret_1;
4241 }
4242 const uintptr_t entry_byte_ct = RoundUpPow2(offsetof(InfoVtype, key) + 1 + id_slen, sizeof(intptr_t));
4243 if (S_CAST(uintptr_t, tmp_alloc_end - R_CAST(unsigned char*, info_keys_iter)) < entry_byte_ct + 8) {
4244 goto ParseInfoHeader_ret_NOMEM;
4245 }
4246 tmp_alloc_end -= entry_byte_ct;
4247 InfoVtype* new_entry = R_CAST(InfoVtype*, tmp_alloc_end);
4248 memcpyx(new_entry->key, idval, id_slen, '\0');
4249 *info_keys_iter++ = new_entry->key;
4250
4251 const char* numstr;
4252 uint32_t num_slen;
4253 int32_t num;
4254 if (unlikely(HkvlineFindK(xheader_iter, "Number", &numstr, &num_slen) ||
4255 FillInfoVtypeNum(numstr, num_slen, info_has_g_keyp, &num))) {
4256 goto ParseInfoHeader_ret_MALFORMED_INFO_HEADER_LINE;
4257 }
4258 if ((!num) && strequal_k(new_entry->key, "PR", id_slen)) {
4259 num = kInfoVtypeSkip;
4260 }
4261 new_entry->num = num;
4262 }
4263 const uintptr_t info_key_ct = info_keys_iter - info_keys;
4264 #ifdef __LP64__
4265 if (unlikely(info_key_ct > 0x7ffffffdU)) {
4266 logerrputs("Error: " PROG_NAME_STR " does not support more than 2^31 - 3 INFO keys.\n");
4267 reterr = kPglRetMalformedInput;
4268 goto ParseInfoHeader_ret_1;
4269 }
4270 #endif
4271 assert(info_key_ct);
4272 *info_key_ctp = info_key_ct;
4273 BigstackEndSet(tmp_alloc_end);
4274 bigstack_end_mark = g_bigstack_end;
4275 const uintptr_t info_key_ctl = BitCtToWordCt(info_key_ct);
4276 uintptr_t* dummy_include;
4277 if (unlikely(BigstackBaseSetChecked(info_keys_iter) ||
4278 bigstack_end_alloc_w(info_key_ctl, &dummy_include))) {
4279 goto ParseInfoHeader_ret_NOMEM;
4280 }
4281 SetAllBits(info_key_ct, dummy_include);
4282 reterr = AllocAndPopulateIdHtableMt(dummy_include, info_keys, info_key_ct, bigstack_left() / 32, 1, info_keys_htablep, nullptr, info_keys_htable_sizep, nullptr);
4283 if (unlikely(reterr)) {
4284 goto ParseInfoHeader_ret_1;
4285 }
4286 *info_keys_ptr = info_keys;
4287 bigstack_mark = g_bigstack_base;
4288 }
4289 while (0) {
4290 ParseInfoHeader_ret_NOMEM:
4291 reterr = kPglRetNomem;
4292 break;
4293 ParseInfoHeader_ret_MALFORMED_INFO_HEADER_LINE:
4294 logputs("\n");
4295 logerrputs("Error: Malformed or unrecognized INFO header line.\n");
4296 reterr = kPglRetMalformedInput;
4297 break;
4298 }
4299 ParseInfoHeader_ret_1:
4300 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
4301 return reterr;
4302 }
4303
4304 PglErr WritePvarSplit(const char* outname, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* qual_present, const float* quals, const uintptr_t* filter_present, const uintptr_t* filter_npass, const char* const* filter_storage, const uintptr_t* nonref_flags, const char* pvar_info_reload, const double* variant_cms, const uint32_t* contig_lens, const char* varid_template_str, const char* missing_varid_match, const char* const* info_keys, const uint32_t* info_keys_htable, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct, uint32_t max_allele_slen, uint32_t new_variant_id_max_allele_slen, uintptr_t xheader_blen, InfoFlags info_flags, uint32_t nonref_flags_storage, uint32_t max_filter_slen, uint32_t info_reload_slen, uint32_t info_key_ct, uint32_t info_keys_htable_size, MiscFlags misc_flags, MakePlink2Flags make_plink2_flags, PvarPsamFlags pvar_psam_flags, char output_missing_geno_char, uint32_t write_info, uint32_t write_info_pr, uint32_t thread_ct, char* xheader) {
4305 unsigned char* bigstack_mark = g_bigstack_base;
4306 char* cswritep = nullptr;
4307 PglErr reterr = kPglRetSuccess;
4308 CompressStreamState css;
4309 TextStream pvar_reload_txs;
4310 PreinitCstream(&css);
4311 PreinitTextStream(&pvar_reload_txs);
4312 {
4313 const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
4314 // includes trailing tab
4315 char* chr_buf;
4316
4317 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
4318 goto WritePvarSplit_ret_NOMEM;
4319 }
4320 const uint32_t new_variant_id_overflow_missing = (misc_flags / kfMiscNewVarIdOverflowMissing) & 1;
4321 const uint32_t varid_dup = (make_plink2_flags / kfMakePlink2VaridDup) & 1;
4322 VaridTemplate* varid_templatep = nullptr;
4323 if (!missing_varid_match) {
4324 missing_varid_match = &(g_one_char_strs[92]); // '.'
4325 }
4326 uint32_t missing_varid_slen = strlen(missing_varid_match);
4327 uint32_t missing_varid_match_blen = 0; // nonzero iff --set-missing-var-ids
4328 if (varid_template_str) {
4329 if (misc_flags & kfMiscSetMissingVarIds) {
4330 missing_varid_match_blen = missing_varid_slen + 1;
4331 }
4332 if (unlikely(BIGSTACK_ALLOC_X(VaridTemplate, 1, &varid_templatep))) {
4333 goto WritePvarSplit_ret_NOMEM;
4334 }
4335 const uint32_t overflow_substitute_blen = new_variant_id_overflow_missing? (missing_varid_slen + 1) : 0;
4336 VaridTemplateInit(varid_template_str, missing_varid_match, chr_buf, new_variant_id_max_allele_slen, overflow_substitute_blen, varid_templatep);
4337 if (varid_dup) {
4338 for (uint32_t uii = 0; uii != varid_templatep->insert_ct; ++uii) {
4339 const uint32_t insert_type = varid_templatep->insert_types[uii];
4340 if ((insert_type == 3) || ((insert_type == 2) && (varid_templatep->allele_flags & kfVaridTemplateAlleleAsciiOrder))) {
4341 // Could define what takes precedence here, but simpler to prohibit
4342 // this combination.
4343 logputs("\n");
4344 logerrputs("Error: 'vid-[split-]dup' cannot be used with a --set-all-var-ids or\n--set-missing-var-ids template string containing a non-REF allele.\n");
4345 goto WritePvarSplit_ret_INVALID_CMDLINE;
4346 }
4347 }
4348 }
4349 }
4350
4351 uintptr_t overflow_buf_size = kCompressStreamBlock + kMaxIdSlen + 512 + 2 * max_allele_slen + max_filter_slen + info_reload_slen;
4352 if (overflow_buf_size < 2 * kCompressStreamBlock) {
4353 overflow_buf_size = 2 * kCompressStreamBlock;
4354 }
4355 const uint32_t output_zst = (pvar_psam_flags / kfPvarZs) & 1;
4356 reterr = InitCstreamAlloc(outname, 0, output_zst, thread_ct, overflow_buf_size, &css, &cswritep);
4357 if (unlikely(reterr)) {
4358 goto WritePvarSplit_ret_1;
4359 }
4360
4361 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
4362 const uint32_t all_nonref = (nonref_flags_storage == 2);
4363
4364 char* pvar_info_line_iter = nullptr;
4365 uint32_t write_filter = 0;
4366 if (pvar_psam_flags & kfPvarColFilter) {
4367 write_filter = 1;
4368 } else if ((pvar_psam_flags & kfPvarColMaybefilter) && filter_present) {
4369 write_filter = !IntersectionIsEmpty(variant_include, filter_present, raw_variant_ctl);
4370 }
4371 uint32_t info_col_idx = 0; // could save this during first load instead
4372 const uint32_t info_pr_flag_present = (info_flags / kfInfoPrFlagPresent) & 1;
4373 if (pvar_psam_flags & (kfPvarColXheader | kfPvarColVcfheader)) {
4374 reterr = PvarXheaderWrite(variant_include, cip, contig_lens, xheader_blen, (pvar_psam_flags / kfPvarColVcfheader) & 1, write_filter, write_info, write_info_pr && (!info_pr_flag_present), xheader, &css, &cswritep);
4375 if (unlikely(reterr)) {
4376 goto WritePvarSplit_ret_1;
4377 }
4378 }
4379 // could also make this an array-of-structs
4380 uint32_t* info_key_order = nullptr;
4381 const char** info_starts = nullptr;
4382 const char** info_ends = nullptr;
4383 const char** info_curs = nullptr;
4384 uint32_t* info_ref_blens = nullptr;
4385 char* missing_comma_str = nullptr;
4386 if (pvar_info_reload) {
4387 if (unlikely(bigstack_alloc_u32(info_key_ct, &info_key_order) ||
4388 bigstack_alloc_kcp(info_key_ct, &info_starts) ||
4389 bigstack_alloc_kcp(info_key_ct, &info_ends) ||
4390 bigstack_alloc_kcp(info_key_ct, &info_curs) ||
4391 bigstack_alloc_u32(info_key_ct, &info_ref_blens) ||
4392 bigstack_alloc_c(2 * max_allele_ct, &missing_comma_str))) {
4393 goto WritePvarSplit_ret_NOMEM;
4394 }
4395 reterr = PvarInfoOpenAndReloadHeader(pvar_info_reload, 1 + (thread_ct > 1), &pvar_reload_txs, &pvar_info_line_iter, &info_col_idx);
4396 if (unlikely(reterr)) {
4397 goto WritePvarSplit_ret_TSTREAM_FAIL;
4398 }
4399 // .,.,.,
4400 u16set(missing_comma_str, 0x2c2e, max_allele_ct);
4401 }
4402 if (cip->chrset_source) {
4403 AppendChrsetLine(cip, &cswritep);
4404 }
4405 cswritep = strcpya_k(cswritep, "#CHROM\tPOS\tID\tREF\tALT");
4406
4407 uint32_t write_qual = 0;
4408 if (pvar_psam_flags & kfPvarColQual) {
4409 write_qual = 1;
4410 } else if ((pvar_psam_flags & kfPvarColMaybequal) && qual_present) {
4411 write_qual = !IntersectionIsEmpty(variant_include, qual_present, raw_variant_ctl);
4412 }
4413 if (write_qual) {
4414 cswritep = strcpya_k(cswritep, "\tQUAL");
4415 }
4416 if (write_filter) {
4417 cswritep = strcpya_k(cswritep, "\tFILTER");
4418 }
4419 if (write_info) {
4420 cswritep = strcpya_k(cswritep, "\tINFO");
4421 }
4422
4423 uint32_t write_cm = 0;
4424 if (pvar_psam_flags & kfPvarColCm) {
4425 write_cm = 1;
4426 } else if ((pvar_psam_flags & kfPvarColMaybecm) && variant_cms) {
4427 if (raw_variant_ct == variant_ct) {
4428 // nonzero_cm_present check was performed
4429 write_cm = 1;
4430 } else {
4431 uintptr_t variant_uidx_base = 0;
4432 uintptr_t cur_bits = variant_include[0];
4433 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
4434 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
4435 if (variant_cms[variant_uidx] != 0.0) {
4436 write_cm = 1;
4437 break;
4438 }
4439 }
4440 }
4441 }
4442 if (write_cm) {
4443 cswritep = strcpya_k(cswritep, "\tCM");
4444 }
4445 AppendBinaryEoln(&cswritep);
4446
4447 const VaridTemplate* cur_varid_templatep = nullptr;
4448 const char* varid_token_start = nullptr; // for vid-split
4449 const uint32_t varid_split = (make_plink2_flags / kfMakePlink2VaridSemicolon) & 1;
4450 const uint32_t varid_dup_nosplit = varid_dup && (!varid_split);
4451 const uint32_t split_just_snps = ((make_plink2_flags & (kfMakePlink2MSplitBase * 3)) == kfMakePlink2MSplitSnps);
4452 uint32_t max_allele_overflow_slen = 0;
4453 uint32_t trs_variant_uidx = 0;
4454 uintptr_t variant_uidx_base = 0;
4455 uintptr_t cur_bits = variant_include[0];
4456 uint32_t chr_fo_idx = UINT32_MAX;
4457 uint32_t chr_end = 0;
4458 uint32_t chr_buf_blen = 0;
4459 uint32_t orig_allele_ct = 2;
4460 uint32_t cur_info_key_ct = 0;
4461 uint32_t pct = 0;
4462 uint32_t next_print_variant_idx = variant_ct / 100;
4463 fputs("0%", stdout);
4464 fflush(stdout);
4465 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
4466 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
4467 if (variant_uidx >= chr_end) {
4468 do {
4469 ++chr_fo_idx;
4470 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
4471 } while (variant_uidx >= chr_end);
4472 char* chr_name_end = chrtoa(cip, cip->chr_file_order[chr_fo_idx], chr_buf);
4473 *chr_name_end = '\t';
4474 const uint32_t chr_slen = chr_name_end - chr_buf;
4475 chr_buf_blen = 1 + chr_slen;
4476 if (varid_templatep) {
4477 const int32_t chr_slen_delta = chr_slen - varid_templatep->chr_slen;
4478 varid_templatep->chr_slen = chr_slen;
4479 varid_templatep->base_len += chr_slen_delta;
4480 }
4481 }
4482 uintptr_t allele_idx_offset_base;
4483 if (!allele_idx_offsets) {
4484 allele_idx_offset_base = variant_uidx * 2;
4485 } else {
4486 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
4487 orig_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
4488 }
4489 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
4490 const char* orig_variant_id = variant_ids[variant_uidx];
4491 const char* ref_allele = cur_alleles[0];
4492 const uint32_t ref_allele_slen = strlen(ref_allele);
4493 const uint32_t cur_bp = variant_bps[variant_uidx];
4494 uint32_t split_ct_p1 = orig_allele_ct;
4495 uint32_t keep_orig_id = 1;
4496 if (orig_allele_ct > 2) {
4497 if (!varid_dup_nosplit) {
4498 keep_orig_id = 0;
4499 if (varid_templatep && (!missing_varid_match_blen)) {
4500 cur_varid_templatep = varid_templatep;
4501 } else {
4502 cur_varid_templatep = nullptr;
4503 if (varid_split) {
4504 if (VaridSplitOk(orig_variant_id, orig_allele_ct)) {
4505 varid_token_start = orig_variant_id;
4506 } else if (varid_dup) {
4507 keep_orig_id = 1;
4508 } else {
4509 varid_token_start = nullptr;
4510 }
4511 }
4512 if ((!varid_token_start) && varid_templatep) {
4513 // Note that --set-missing-var-ids almost always applies here
4514 // when it's specified; only exception is when vid-split was also
4515 // specified and the split succeeded.
4516 cur_varid_templatep = varid_templatep;
4517 }
4518 }
4519 }
4520 // Necessary to distinguish between '-' and '-snps' here.
4521 if (split_just_snps) {
4522 for (uint32_t uii = 0; uii != orig_allele_ct; ++uii) {
4523 if (cur_alleles[uii][1]) {
4524 split_ct_p1 = 2;
4525 break;
4526 }
4527 }
4528 }
4529 if ((split_ct_p1 != 2) && pvar_info_line_iter) {
4530 reterr = PvarInfoReload(info_col_idx, variant_uidx, &pvar_reload_txs, &pvar_info_line_iter, &trs_variant_uidx);
4531 if (unlikely(reterr)) {
4532 goto WritePvarSplit_ret_TSTREAM_FAIL;
4533 }
4534 char* info_subtoken_iter = pvar_info_line_iter;
4535 pvar_info_line_iter = CurTokenEnd(pvar_info_line_iter);
4536 cur_info_key_ct = 0;
4537 // special case: if entire info field is '.', treat as zero keys
4538 if ((info_subtoken_iter[0] != '.') || (pvar_info_line_iter != &(info_subtoken_iter[1]))) {
4539 while (1) {
4540 if (unlikely(cur_info_key_ct == info_key_ct)) {
4541 snprintf(g_logbuf, kLogbufSize, "Error: Too many INFO keys for variant ID '%s'.\n", orig_variant_id);
4542 goto WritePvarSplit_ret_MALFORMED_INPUT_WW;
4543 }
4544 char* info_subtoken_end = AdvToDelimOrEnd(info_subtoken_iter, pvar_info_line_iter, ';');
4545 char* key_end = AdvToDelimOrEnd(info_subtoken_iter, info_subtoken_end, '=');
4546 const uint32_t key_slen = key_end - info_subtoken_iter;
4547 const uint32_t kidx = IdHtableFindNnt(info_subtoken_iter, info_keys, info_keys_htable, key_slen, info_keys_htable_size);
4548 if (unlikely(kidx == UINT32_MAX)) {
4549 if (key_slen <= 77) {
4550 char* err_write_iter = strcpya_k(g_logbuf, "Error: INFO key '");
4551 err_write_iter = memcpya(err_write_iter, info_subtoken_iter, key_slen);
4552 err_write_iter = strcpya_k(err_write_iter, "' for variant ID '");
4553 err_write_iter = strcpya(err_write_iter, orig_variant_id);
4554 strcpy_k(err_write_iter, "' missing from header.\n");
4555 } else {
4556 snprintf(g_logbuf, kLogbufSize, "Error: INFO key for variant ID '%s' missing from header.\n", orig_variant_id);
4557 }
4558 goto WritePvarSplit_ret_MALFORMED_INPUT_WW;
4559 }
4560 const int32_t knum = const_container_of(info_keys[kidx], InfoVtype, key)->num;
4561 if (knum != kInfoVtypeSkip) {
4562 info_key_order[cur_info_key_ct] = kidx;
4563 if (key_end == info_subtoken_end) {
4564 if (unlikely(knum)) {
4565 snprintf(g_logbuf, kLogbufSize, "Error: INFO key '%s' for variant ID '%s' does not have an accompanying value.\n", info_keys[kidx], orig_variant_id);
4566 goto WritePvarSplit_ret_MALFORMED_INPUT_WW;
4567 }
4568 } else {
4569 if (unlikely(!knum)) {
4570 snprintf(g_logbuf, kLogbufSize, "Error: INFO key '%s' for variant ID '%s' has an accompanying value, despite being of type Flag.\n", info_keys[kidx], orig_variant_id);
4571 goto WritePvarSplit_ret_MALFORMED_INPUT_WW;
4572 }
4573 info_subtoken_iter = &(key_end[1]);
4574
4575 // don't actually need this for Number=A case
4576 info_starts[cur_info_key_ct] = info_subtoken_iter;
4577
4578 info_ends[cur_info_key_ct] = info_subtoken_end;
4579 if (IsInfoVtypeARSkip(knum)) {
4580 // (Don't need to do anything else for kInfoVtypeUnknown
4581 // or positive; we unconditionally copy all the text in
4582 // those cases.)
4583
4584 // Single '.' for Number=A or Number=R is acceptable input
4585 // for multiallelic variants:
4586 // https://github.com/samtools/hts-specs/issues/609
4587 // We treat this like a comma-separated list of missing
4588 // values.
4589 const uint32_t info_subtoken_slen = info_subtoken_end - info_subtoken_iter;
4590 if ((info_subtoken_slen == 1) && (info_subtoken_iter[0] == '.')) {
4591 info_starts[cur_info_key_ct] = missing_comma_str;
4592 if (knum == kInfoVtypeA) {
4593 info_ends[cur_info_key_ct] = &(missing_comma_str[split_ct_p1 * 2 - 3]);
4594 info_curs[cur_info_key_ct] = missing_comma_str;
4595 } else {
4596 info_ends[cur_info_key_ct] = &(missing_comma_str[split_ct_p1 * 2 - 1]);
4597 info_ref_blens[cur_info_key_ct] = 2;
4598 info_curs[cur_info_key_ct] = &(missing_comma_str[2]);
4599 }
4600 } else {
4601 if (knum == kInfoVtypeA) {
4602 info_curs[cur_info_key_ct] = info_subtoken_iter;
4603 } else {
4604 char* ref_value_end = S_CAST(char*, memchr(info_subtoken_iter, ',', info_subtoken_slen));
4605 if (unlikely(!ref_value_end)) {
4606 snprintf(g_logbuf, kLogbufSize, "Error: Too few values for INFO key '%s', variant ID '%s'.\n", info_keys[kidx], orig_variant_id);
4607 goto WritePvarSplit_ret_MALFORMED_INPUT_WW;
4608 }
4609 ++ref_value_end;
4610 info_ref_blens[cur_info_key_ct] = ref_value_end - info_subtoken_iter;
4611 info_curs[cur_info_key_ct] = ref_value_end;
4612 }
4613 }
4614 }
4615 }
4616 ++cur_info_key_ct;
4617 }
4618 if (info_subtoken_end == pvar_info_line_iter) {
4619 break;
4620 }
4621 info_subtoken_iter = &(info_subtoken_end[1]);
4622 }
4623 }
4624 }
4625 }
4626 for (uint32_t alt_allele_idx = 1; alt_allele_idx != split_ct_p1; ++alt_allele_idx) {
4627 cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
4628 cswritep = u32toa_x(cur_bp, '\t', cswritep);
4629 const char* cur_alt_allele = cur_alleles[alt_allele_idx];
4630 const uint32_t cur_alt_allele_slen = strlen(cur_alt_allele);
4631 if ((split_ct_p1 == 2) || keep_orig_id) {
4632 cswritep = strcpyax(cswritep, orig_variant_id, '\t');
4633 if (!strequal_k_unsafe(ref_allele, ".")) {
4634 cswritep = memcpya(cswritep, ref_allele, ref_allele_slen);
4635 } else {
4636 *cswritep++ = output_missing_geno_char;
4637 }
4638 *cswritep++ = '\t';
4639 if (!strequal_k_unsafe(cur_alt_allele, ".")) {
4640 cswritep = memcpya(cswritep, cur_alt_allele, cur_alt_allele_slen);
4641 } else {
4642 *cswritep++ = output_missing_geno_char;
4643 }
4644 if (unlikely(Cswrite(&css, &cswritep))) {
4645 goto WritePvarSplit_ret_WRITE_FAIL;
4646 }
4647 if ((orig_allele_ct > 2) && (split_ct_p1 == 2)) {
4648 // -snps non-split case
4649 for (uint32_t allele_idx = 2; allele_idx != orig_allele_ct; ++allele_idx) {
4650 *cswritep++ = ',';
4651 cswritep = strcpya(cswritep, cur_alleles[allele_idx]);
4652 if (unlikely(Cswrite(&css, &cswritep))) {
4653 goto WritePvarSplit_ret_WRITE_FAIL;
4654 }
4655 }
4656 }
4657 } else {
4658 if (cur_varid_templatep) {
4659 // Always true in --set-all-var-ids case. True in
4660 // --set-missing-var-ids case when vid-split unspecified, or split
4661 // failed.
4662 cswritep = VaridTemplateWrite(cur_varid_templatep, ref_allele, cur_alt_allele, cur_bp, ref_allele_slen, 0, cur_alt_allele_slen, &max_allele_overflow_slen, cswritep);
4663 *cswritep++ = '\t';
4664 } else if (varid_token_start) {
4665 const char* varid_token_end = strchrnul(varid_token_start, ';');
4666 // If substring matches missing code and --set-missing-var-ids is
4667 // specified, we replace it.
4668 if (varid_templatep && (S_CAST(uintptr_t, varid_token_end - varid_token_start) == missing_varid_slen) && memequal(varid_token_start, missing_varid_match, missing_varid_slen)) {
4669 cswritep = VaridTemplateWrite(varid_templatep, ref_allele, cur_alt_allele, cur_bp, ref_allele_slen, 0, cur_alt_allele_slen, &max_allele_overflow_slen, cswritep);
4670 } else {
4671 cswritep = memcpya(cswritep, varid_token_start, varid_token_end - varid_token_start);
4672 }
4673 *cswritep++ = '\t';
4674 varid_token_start = &(varid_token_end[1]);
4675 } else {
4676 cswritep = memcpyax(cswritep, missing_varid_match, missing_varid_slen, '\t');
4677 }
4678 if (!strequal_k_unsafe(ref_allele, ".")) {
4679 cswritep = memcpya(cswritep, ref_allele, ref_allele_slen);
4680 } else {
4681 *cswritep++ = output_missing_geno_char;
4682 }
4683 *cswritep++ = '\t';
4684 if (!strequal_k_unsafe(cur_alt_allele, ".")) {
4685 cswritep = memcpya(cswritep, cur_alt_allele, cur_alt_allele_slen);
4686 } else {
4687 *cswritep++ = output_missing_geno_char;
4688 }
4689 if (unlikely(Cswrite(&css, &cswritep))) {
4690 goto WritePvarSplit_ret_WRITE_FAIL;
4691 }
4692 }
4693 if (write_qual) {
4694 *cswritep++ = '\t';
4695 if ((!qual_present) || (!IsSet(qual_present, variant_uidx))) {
4696 *cswritep++ = '.';
4697 } else {
4698 cswritep = ftoa_g(quals[variant_uidx], cswritep);
4699 }
4700 }
4701
4702 if (write_filter) {
4703 *cswritep++ = '\t';
4704 if ((!filter_present) || (!IsSet(filter_present, variant_uidx))) {
4705 *cswritep++ = '.';
4706 } else if (!IsSet(filter_npass, variant_uidx)) {
4707 cswritep = strcpya_k(cswritep, "PASS");
4708 } else {
4709 cswritep = strcpya(cswritep, filter_storage[variant_uidx]);
4710 }
4711 }
4712
4713 if (write_info) {
4714 *cswritep++ = '\t';
4715 const uint32_t is_pr = all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx));
4716 if (pvar_info_line_iter) {
4717 if (split_ct_p1 == 2) {
4718 reterr = PvarInfoReloadAndWrite(info_pr_flag_present, info_col_idx, variant_uidx, is_pr, &pvar_reload_txs, &pvar_info_line_iter, &cswritep, &trs_variant_uidx);
4719 if (unlikely(reterr)) {
4720 goto WritePvarSplit_ret_TSTREAM_FAIL;
4721 }
4722 } else {
4723 if (!cur_info_key_ct) {
4724 if (is_pr) {
4725 cswritep = strcpya_k(cswritep, "PR");
4726 } else {
4727 *cswritep++ = '.';
4728 }
4729 } else {
4730 const uint32_t is_last_allele = (alt_allele_idx + 1 == split_ct_p1);
4731 for (uint32_t kpos = 0; kpos != cur_info_key_ct; ++kpos) {
4732 const uint32_t kidx = info_key_order[kpos];
4733 const char* cur_key_str = info_keys[kidx];
4734 cswritep = strcpya(cswritep, cur_key_str);
4735 const int32_t knum = const_container_of(info_keys[kidx], InfoVtype, key)->num;
4736 if (knum) {
4737 *cswritep++ = '=';
4738 const char* cur_info_start = info_starts[kpos];
4739 const char* cur_info_end = info_ends[kpos];
4740 if (!IsInfoVtypeARSkip(knum)) {
4741 cswritep = memcpya(cswritep, cur_info_start, cur_info_end - cur_info_start);
4742 } else {
4743 if (knum != kInfoVtypeA) {
4744 cswritep = memcpya(cswritep, cur_info_start, info_ref_blens[kpos]);
4745 }
4746 // okay, this needs a better name
4747 const char* cur_info_cur = info_curs[kpos];
4748
4749 const char* subtoken_end = AdvToDelimOrEnd(cur_info_cur, cur_info_end, ',');
4750 if (unlikely((subtoken_end == cur_info_end) != is_last_allele)) {
4751 snprintf(g_logbuf, kLogbufSize, "Error: Wrong number of values for INFO key '%s', variant ID '%s'.\n", cur_key_str, orig_variant_id);
4752 goto WritePvarSplit_ret_MALFORMED_INPUT_WW;
4753 }
4754 cswritep = memcpya(cswritep, cur_info_cur, subtoken_end - cur_info_cur);
4755 info_curs[kpos] = &(subtoken_end[1]);
4756 }
4757 }
4758 *cswritep++ = ';';
4759 }
4760 if (is_pr) {
4761 cswritep = strcpya_k(cswritep, "PR");
4762 } else {
4763 --cswritep;
4764 }
4765 }
4766 }
4767 } else {
4768 if (is_pr) {
4769 cswritep = strcpya_k(cswritep, "PR");
4770 } else {
4771 *cswritep++ = '.';
4772 }
4773 }
4774 }
4775
4776 if (write_cm) {
4777 *cswritep++ = '\t';
4778 if (!variant_cms) {
4779 *cswritep++ = '0';
4780 } else {
4781 cswritep = dtoa_g_p8(variant_cms[variant_uidx], cswritep);
4782 }
4783 }
4784 AppendBinaryEoln(&cswritep);
4785 }
4786 if (variant_idx >= next_print_variant_idx) {
4787 if (pct > 10) {
4788 putc_unlocked('\b', stdout);
4789 }
4790 pct = (variant_idx * 100LLU) / variant_ct;
4791 printf("\b\b%u%%", pct++);
4792 fflush(stdout);
4793 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
4794 }
4795 }
4796 if (unlikely(CswriteCloseNull(&css, cswritep))) {
4797 goto WritePvarSplit_ret_WRITE_FAIL;
4798 }
4799 if (pct > 10) {
4800 putc_unlocked('\b', stdout);
4801 }
4802 fputs("\b\b", stdout);
4803 if (unlikely(max_allele_overflow_slen && (!(misc_flags & (kfMiscNewVarIdOverflowMissing | kfMiscNewVarIdOverflowTruncate))))) {
4804 logputs("\n");
4805 logerrprintf("Error: Allele code(s) too long for --set-%s-var-ids.\n", (misc_flags & kfMiscSetMissingVarIds)? "missing" : "all");
4806 // Not a precise bound, but in practice this should print the more useful
4807 // message >99% of the time.
4808 if (max_allele_overflow_slen < kMaxIdSlen / 2) {
4809 logerrprintfww("The longest observed allele code in this dataset has length %u. If you're fine with the corresponding ID length, rerun with \"--new-id-max-allele-len %u\" added to your command line.\n", max_allele_overflow_slen, max_allele_overflow_slen);
4810 } else {
4811 logerrprintfww("The longest observed allele code in this dataset has length %u. We recommend deciding on a length-limit, and then adding \"--new-id-max-allele-len <limit> missing\" to your command line to cause variants with longer allele codes to be assigned '.' IDs. (You can then process just those variants with another script, if necessary.)\n", max_allele_overflow_slen);
4812 }
4813 goto WritePvarSplit_ret_INCONSISTENT_INPUT;
4814 }
4815 }
4816 while (0) {
4817 WritePvarSplit_ret_NOMEM:
4818 reterr = kPglRetNomem;
4819 break;
4820 WritePvarSplit_ret_TSTREAM_FAIL:
4821 TextStreamErrPrint(pvar_info_reload, &pvar_reload_txs);
4822 break;
4823 WritePvarSplit_ret_WRITE_FAIL:
4824 reterr = kPglRetWriteFail;
4825 break;
4826 WritePvarSplit_ret_INVALID_CMDLINE:
4827 reterr = kPglRetInvalidCmdline;
4828 break;
4829 WritePvarSplit_ret_MALFORMED_INPUT_WW:
4830 logputs("\n");
4831 WordWrapB(0);
4832 logerrputsb();
4833 reterr = kPglRetMalformedInput;
4834 break;
4835 WritePvarSplit_ret_INCONSISTENT_INPUT:
4836 reterr = kPglRetInconsistentInput;
4837 break;
4838 }
4839 WritePvarSplit_ret_1:
4840 CswriteCloseCond(&css, cswritep);
4841 CleanupTextStream2(pvar_info_reload, &pvar_reload_txs, &reterr);
4842 BigstackReset(bigstack_mark);
4843 return reterr;
4844 }
4845
4846 // Final filter_keys is natural-sorted.
4847 // Return values are allocated on bottom of bigstack.
4848 // Caller must initialize all return values to correspond to the null table.
4849 PglErr MakeFilterHtable(const uintptr_t* variant_include, const uintptr_t* filter_npass, const char* const* filter_storage, uint32_t variant_ct, const char*** filter_keys_ptr, uint32_t** filter_keys_htable_ptr, uint32_t* filter_key_ct_ptr, uint32_t* filter_keys_htable_size_ptr) {
4850 unsigned char* bigstack_end_mark = g_bigstack_end;
4851 PglErr reterr = kPglRetSuccess;
4852 {
4853 // Start with empty size-128 table, which will practically always be enough
4854 // while still being small relative to L1 cache. Double table size
4855 // whenever load factor reaches 0.25; there shouldn't be *that* many
4856 // distinct filters.
4857 // TODO: check if this should use strset instead
4858 // possible todo: multithread this scan, merge results at the end; can also
4859 // separate this stage from the rest of the function.
4860 uint32_t table_size = 128;
4861 uint32_t hash_shift = 25; // 32 - log2(table_size)
4862 uint32_t filter_key_ct = 0;
4863 char** filter_tokens;
4864 if (unlikely(bigstack_end_calloc_cp(table_size, &filter_tokens))) {
4865 goto MakeFilterHtable_ret_NOMEM;
4866 }
4867
4868 unsigned char* tmp_alloc_base = g_bigstack_base;
4869 unsigned char* tmp_alloc_end = g_bigstack_end;
4870 uintptr_t variant_widx = 0;
4871 uintptr_t cur_bits = variant_include[0];
4872 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
4873 const uintptr_t lowbit = BitIter1y(variant_include, &variant_widx, &cur_bits);
4874 if (lowbit & filter_npass[variant_widx]) {
4875 const char* filter_iter = filter_storage[variant_widx * kBitsPerWord + ctzw(lowbit)];
4876 while (1) {
4877 const char* token_end = strchrnul(filter_iter, ';');
4878 const uint32_t cur_id_slen = token_end - filter_iter;
4879 for (uint32_t hashval = Hash32(filter_iter, cur_id_slen) >> hash_shift; ; ) {
4880 char* cur_token_ptr = filter_tokens[hashval];
4881 if (!cur_token_ptr) {
4882 char* storage_loc;
4883 if (StoreStringAtBase(tmp_alloc_end, filter_iter, cur_id_slen, &tmp_alloc_base, &storage_loc)) {
4884 goto MakeFilterHtable_ret_NOMEM;
4885 }
4886 ++filter_key_ct;
4887 if (filter_key_ct * 4 < table_size) {
4888 filter_tokens[hashval] = storage_loc;
4889 break;
4890 }
4891 #ifdef __LP64__
4892 if (unlikely(hash_shift == 1)) {
4893 // this is technically "not yet supported", but I fail to see a
4894 // valid use case for >536 million distinct FILTER keys...
4895 logerrprintf("Error: Too many distinct FILTER keys (max 2^29 - 1).\n");
4896 goto MakeFilterHtable_ret_MALFORMED_INPUT;
4897 }
4898 #endif
4899 // It's fine for the new table to overlap the old table, since we
4900 // can iterate through all the strings by walking forward from
4901 // g_bigstack_base.
4902 const uintptr_t extra_byte_ct = table_size * sizeof(intptr_t);
4903 if (unlikely(S_CAST(uintptr_t, tmp_alloc_end - tmp_alloc_base) < extra_byte_ct)) {
4904 goto MakeFilterHtable_ret_NOMEM;
4905 }
4906 tmp_alloc_end -= extra_byte_ct;
4907 filter_tokens = R_CAST(char**, tmp_alloc_end);
4908 memset(filter_tokens, 0, 2 * extra_byte_ct);
4909 table_size *= 2;
4910 --hash_shift;
4911 char* rehash_iter = R_CAST(char*, g_bigstack_base);
4912 for (uint32_t uii = 0; uii != filter_key_ct; ++uii) {
4913 char* rehash_token_end = strnul(rehash_iter);
4914 const uint32_t rehash_id_slen = rehash_token_end - rehash_iter;
4915 for (uint32_t rehashval = Hash32(rehash_iter, rehash_id_slen) >> hash_shift; ; ) {
4916 if (!filter_tokens[rehashval]) {
4917 filter_tokens[rehashval] = rehash_iter;
4918 break;
4919 }
4920 if (++rehashval == table_size) {
4921 rehashval = 0;
4922 }
4923 }
4924 rehash_iter = &(rehash_token_end[1]);
4925 }
4926 break;
4927 }
4928 if (strequal_unsafe(filter_iter, cur_token_ptr, cur_id_slen)) {
4929 break;
4930 }
4931 if (++hashval == table_size) {
4932 hashval = 0;
4933 }
4934 }
4935 if (!(*token_end)) {
4936 break;
4937 }
4938 filter_iter = &(token_end[1]);
4939 }
4940 }
4941 }
4942 if (!filter_key_ct) {
4943 // All nonpassing variants were already filtered out.
4944 // Caller already initialized null table.
4945 goto MakeFilterHtable_ret_1;
4946 }
4947 char* token_iter = R_CAST(char*, g_bigstack_base);
4948 const uint32_t filter_keys_htable_size = GetHtableFastSize(filter_key_ct);
4949 if (unlikely(BigstackBaseSetChecked(tmp_alloc_base) ||
4950 bigstack_alloc_kcp(filter_key_ct, filter_keys_ptr) ||
4951 bigstack_alloc_u32(filter_keys_htable_size, filter_keys_htable_ptr))) {
4952 goto MakeFilterHtable_ret_NOMEM;
4953 }
4954 const char** filter_keys = *filter_keys_ptr;
4955 for (uint32_t uii = 0; uii != filter_key_ct; ++uii) {
4956 filter_keys[uii] = token_iter;
4957 char* token_end = strnul(token_iter);
4958 token_iter = &(token_end[1]);
4959 }
4960 StrptrArrNsort(filter_key_ct, filter_keys);
4961 *filter_key_ct_ptr = filter_key_ct;
4962 *filter_keys_htable_size_ptr = filter_keys_htable_size;
4963 uint32_t* filter_keys_htable = *filter_keys_htable_ptr;
4964 SetAllU32Arr(filter_keys_htable_size, filter_keys_htable);
4965 for (uint32_t uii = 0; uii != filter_key_ct; ++uii) {
4966 HtableAddNondup(filter_keys[uii], strlen(filter_keys[uii]), filter_keys_htable_size, uii, filter_keys_htable);
4967 }
4968 }
4969 while (0) {
4970 MakeFilterHtable_ret_NOMEM:
4971 reterr = kPglRetNomem;
4972 break;
4973 #ifdef __LP64__
4974 MakeFilterHtable_ret_MALFORMED_INPUT:
4975 reterr = kPglRetMalformedInput;
4976 break;
4977 #endif
4978 }
4979 MakeFilterHtable_ret_1:
4980 BigstackEndReset(bigstack_end_mark);
4981 return reterr;
4982 }
4983
4984 /*
4985 PglErr WritePvarJoin(const char* outname, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* qual_present, const float* quals, const uintptr_t* filter_present, const uintptr_t* filter_npass, const char* const* filter_storage, const uintptr_t* nonref_flags, const char* pvar_info_reload, const double* variant_cms, const uint32_t* contig_lens, const char* varid_template_str, const char* missing_varid_match, const char* const* info_keys, const uint32_t* info_keys_htable, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_slen, uint32_t new_variant_id_max_allele_slen, uint32_t max_write_allele_ct, uint32_t max_missalt_ct, uintptr_t xheader_blen, InfoFlags info_flags, uint32_t nonref_flags_storage, uint32_t max_filter_slen, uint32_t info_reload_slen, uint32_t info_key_ct, uint32_t info_keys_htable_size, MiscFlags misc_flags, MakePlink2Flags make_plink2_flags, PvarPsamFlags pvar_psam_flags, uint32_t write_info, uint32_t write_info_pr, uint32_t thread_ct, char* xheader) {
4986 unsigned char* bigstack_mark = g_bigstack_base;
4987 char* cswritep = nullptr;
4988 PglErr reterr = kPglRetSuccess;
4989 CompressStreamState css;
4990 TextStream pvar_reload_txs;
4991 PreinitCstream(&css);
4992 PreinitTextStream(&pvar_reload_txs);
4993 {
4994 const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
4995 // includes trailing tab
4996 char* chr_buf;
4997
4998 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
4999 goto WritePvarJoin_ret_NOMEM;
5000 }
5001 const uint32_t new_variant_id_overflow_missing = (misc_flags / kfMiscNewVarIdOverflowMissing) & 1;
5002 const uint32_t varid_dup = (make_plink2_flags / kfMakePlink2VaridDup) & 1;
5003 VaridTemplate* varid_templatep = nullptr;
5004 if (!missing_varid_match) {
5005 missing_varid_match = &(g_one_char_strs[92]); // '.'
5006 }
5007 uint32_t missing_varid_slen = strlen(missing_varid_match);
5008 uint32_t missing_varid_match_blen = 0; // nonzero iff --set-missing-var-ids
5009 if (varid_template_str) {
5010 if (misc_flags & kfMiscSetMissingVarIds) {
5011 missing_varid_match_blen = missing_varid_slen + 1;
5012 }
5013 if (unlikely(BIGSTACK_ALLOC_X(VaridTemplate, 1, &varid_templatep))) {
5014 goto WritePvarJoin_ret_NOMEM;
5015 }
5016 const uint32_t overflow_substitute_blen = new_variant_id_overflow_missing? (missing_varid_slen + 1) : 0;
5017 VaridTemplateInit(varid_template_str, missing_varid_match, chr_buf, new_variant_id_max_allele_slen, overflow_substitute_blen, varid_templatep);
5018 if (varid_dup) {
5019 for (uint32_t uii = 0; uii != varid_templatep->insert_ct; ++uii) {
5020 const uint32_t insert_type = varid_templatep->insert_types[uii];
5021 if ((insert_type == 3) || ((insert_type == 2) && (varid_templatep->allele_flags & & kfVaridTemplateAlleleAsciiOrder))) {
5022 // Could define what takes precedence here, but simpler to prohibit
5023 // this combination.
5024 logerrputs("Error: 'vid-[split-]dup' cannot be used with a --set-all-var-ids or\n--set-missing-var-ids template string containing a non-REF allele.\n");
5025 goto WritePvarJoin_ret_INVALID_CMDLINE;
5026 }
5027 }
5028 }
5029 }
5030
5031 uintptr_t overflow_buf_size = kCompressStreamBlock + kMaxIdSlen + 512 + 2 * max_allele_slen + max_filter_slen + S_CAST(uintptr_t, info_reload_slen) * (max_write_allele_ct - 1);
5032 if (overflow_buf_size < 2 * kCompressStreamBlock) {
5033 overflow_buf_size = 2 * kCompressStreamBlock;
5034 }
5035 const uint32_t output_zst = (pvar_psam_flags / kfPvarZs) & 1;
5036 reterr = InitCstreamAlloc(outname, 0, output_zst, thread_ct, overflow_buf_size, &css, &cswritep);
5037 if (unlikely(reterr)) {
5038 goto WritePvarJoin_ret_1;
5039 }
5040
5041 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
5042 const uint32_t all_nonref = (nonref_flags_storage == 2);
5043
5044 char* pvar_info_line_iter = nullptr;
5045 uint32_t write_filter = 0;
5046 if (pvar_psam_flags & kfPvarColFilter) {
5047 write_filter = 1;
5048 } else if ((pvar_psam_flags & kfPvarColMaybefilter) && filter_present) {
5049 write_filter = !IntersectionIsEmpty(variant_include, filter_present, raw_variant_ctl);
5050 }
5051 uint32_t info_col_idx = 0; // could save this during first load instead
5052 const uint32_t info_pr_flag_present = (info_flags / kfInfoPrFlagPresent) & 1;
5053 if (pvar_psam_flags & (kfPvarColXheader | kfPvarColVcfheader)) {
5054 reterr = PvarXheaderWrite(variant_include, cip, contig_lens, xheader_blen, (pvar_psam_flags / kfPvarColVcfheader) & 1, write_filter, write_info, write_info_pr && (!info_pr_flag_present), xheader, &css, &cswritep);
5055 if (unlikely(reterr)) {
5056 goto WritePvarJoin_ret_1;
5057 }
5058 }
5059 const uint32_t join_mode = (make_plink2_flags & (kfMakePlink2MSplitBase * 7));
5060 uintptr_t info_cache_size = max_missalt_ct + max_write_allele_ct - 1;
5061 if (join_mode != kfMakePlink2MJoinSnps) {
5062 info_cache_size *= 3;
5063 }
5064 #ifndef __LP64__
5065 if (S_CAST(uint64_t, info_cache_size) * info_key_ct * sizeof(intptr_t) > 0x7fffffff) {
5066 goto WritePvarJoin_ret_NOMEM;
5067 }
5068 #endif
5069
5070 if (cip->chrset_source) {
5071 AppendChrsetLine(cip, &cswritep);
5072 }
5073 cswritep = strcpya_k(cswritep, "#CHROM\tPOS\tID\tREF\tALT");
5074
5075 uint32_t write_qual = 0;
5076 if (pvar_psam_flags & kfPvarColQual) {
5077 write_qual = 1;
5078 } else if ((pvar_psam_flags & kfPvarColMaybequal) && qual_present) {
5079 write_qual = !IntersectionIsEmpty(variant_include, qual_present, raw_variant_ctl);
5080 }
5081 if (write_qual) {
5082 cswritep = strcpya_k(cswritep, "\tQUAL");
5083 }
5084 const char** filter_keys = nullptr;
5085 uint32_t* filter_keys_htable = nullptr;
5086 uintptr_t* cur_filter_keys = nullptr;
5087 uint32_t filter_keys_htable_size = 0;
5088 uint32_t filter_key_ct = 0;
5089 uint32_t filter_key_ctl = 0;
5090 if (write_filter) {
5091 // The VCF spec doesn't require ##FILTER= header lines, and unlike the
5092 // case with INFO Number=A/R/G, we can join correctly without header
5093 // information. It's slightly more expensive, but INFO and genotype
5094 // joining costs are more significant.
5095 if (filter_npass) {
5096 reterr = MakeFilterHtable(variant_include, filter_npass, filter_storage, variant_ct, &filter_keys, &filter_keys_htable, &filter_key_ct, &filter_keys_htable_size);
5097 if (unlikely(reterr)) {
5098 goto WritePvarJoin_ret_1;
5099 }
5100 if (filter_key_ct) {
5101 filter_key_ctl = BitCtToWordCt(filter_key_ct);
5102 if (unlikely(bigstack_alloc_w(filter_key_ctl, &cur_filter_keys))) {
5103 goto WritePvarJoin_ret_1;
5104 }
5105 }
5106 }
5107 cswritep = strcpya_k(cswritep, "\tFILTER");
5108 }
5109
5110 char** info_bufs = nullptr;
5111 const char** info_starts = nullptr;
5112 const char** info_ends = nullptr; // ugh, this is not related to INFO/END
5113 const char** info_curs = nullptr;
5114 uint32_t info_end_key_idx = UINT32_MAX;
5115 if (pvar_info_reload) {
5116 if (unlikely(bigstack_alloc_cp(info_cache_size, &info_bufs) ||
5117 bigstack_alloc_kcp(info_key_ct * info_cache_size, &info_starts) ||
5118 bigstack_alloc_kcp(info_key_ct * info_cache_size, &info_ends) ||
5119 bigstack_alloc_kcp(info_key_ct * info_cache_size, &info_curs))) {
5120 goto WritePvarJoin_ret_NOMEM;
5121 }
5122 reterr = PvarInfoOpenAndReloadHeader(pvar_info_reload, 1 + (thread_ct > 1), &pvar_reload_txs, &pvar_info_line_iter, &info_col_idx);
5123 if (unlikely(reterr)) {
5124 goto WritePvarJoin_ret_TSTREAM_FAIL;
5125 }
5126 info_end_key_idx = IdHtableFind("END", info_keys, info_keys_htable, strlen("END"), info_keys_htable_size);
5127 if (info_end_key_idx != UINT32_MAX) {
5128 const int32_t knum = const_container_of(info_keys[info_end_key_idx], InfoVtype, key)->num;
5129 if ((knum != 1) && (knum != kInfoVtypeUnknown)) {
5130 // TODO: verify type instead.
5131 // but if number is not . or 1, this is not the INFO/END we're
5132 // looking for.
5133 info_end_key_idx = UINT32_MAX;
5134 }
5135 }
5136 }
5137 if (write_info) {
5138 cswritep = strcpya_k(cswritep, "\tINFO");
5139 }
5140
5141 uint32_t write_cm = 0;
5142 if (pvar_psam_flags & kfPvarColCm) {
5143 write_cm = 1;
5144 } else if ((pvar_psam_flags & kfPvarColMaybecm) && variant_cms) {
5145 if (raw_variant_ct == variant_ct) {
5146 // nonzero_cm_present check was performed
5147 write_cm = 1;
5148 } else {
5149 uintptr_t variant_uidx_base = 0;
5150 uintptr_t cur_bits = variant_include[0];
5151 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
5152 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
5153 if (variant_cms[variant_uidx] != 0.0) {
5154 write_cm = 1;
5155 break;
5156 }
5157 }
5158 }
5159 }
5160 if (write_cm) {
5161 cswritep = strcpya_k(cswritep, "\tCM");
5162 }
5163 AppendBinaryEoln(&cswritep);
5164
5165 const VaridTemplate* cur_varid_templatep = nullptr;
5166 const char* varid_token_start = nullptr; // for vid-split
5167 const uint32_t varid_split = (make_plink2_flags / kfMakePlink2VaridSemicolon) & 1;
5168 const uint32_t varid_dup_nosplit = varid_dup && (!varid_split);
5169 uint32_t next_variant_idx = 0;
5170 uint32_t trs_variant_uidx = 0;
5171 uint32_t next_variant_uidx = 0;
5172 uintptr_t next_variant_uidx_base = 0;
5173 uintptr_t next_bits = variant_include[0];
5174 uint32_t chr_fo_idx = UINT32_MAX;
5175 uint32_t chr_end = 0;
5176 uint32_t chr_buf_blen = 0;
5177 uint32_t prev_bp = 0;
5178 uint32_t cur_bp = 0;
5179 uint32_t bp_start_variant_idx = 0;
5180 uint32_t bp_start_variant_uidx = 0;
5181 uintptr_t bp_start_variant_uidx_base = 0;
5182 uintptr_t bp_start_bits = variant_include[0];
5183 uint32_t allele_ct = 2;
5184 uint32_t pct = 0;
5185 uint32_t next_print_variant_idx = variant_ct / 100;
5186 JoinCounts jc;
5187 jc.snp_ct = 0;
5188 jc.nonsnp_ct = 0;
5189 jc.symbolic_ct = 0;
5190 jc.missalt_snp_ct = 0;
5191 jc.missalt_nonsnp_ct = 0;
5192 JoinCounts next_jc = jc;
5193 fputs("0%", stdout);
5194 fflush(stdout);
5195 while (1) {
5196 for (; next_variant_idx != variant_ct; ++next_variant_idx) {
5197 next_variant_uidx = BitIter1(variant_include, &next_variant_uidx_base, &next_bits);
5198 if (next_variant_uidx >= chr_end) {
5199 do {
5200 ++chr_fo_idx;
5201 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
5202 } while (next_variant_uidx >= chr_end);
5203 char* chr_name_end = chrtoa(cip, cip->chr_file_order[chr_fo_idx], chr_buf);
5204 *chr_name_end = '\t';
5205 const uint32_t chr_slen = chr_name_end - chr_buf;
5206 chr_buf_blen = 1 + chr_slen;
5207 if (varid_templatep) {
5208 const int32_t chr_slen_delta = chr_slen - varid_templatep->chr_slen;
5209 varid_templatep->chr_slen = chr_slen;
5210 varid_templatep->base_len += chr_slen_delta;
5211 }
5212 prev_bp = UINT32_MAX;
5213 }
5214 cur_bp = variant_bps[next_variant_uidx];
5215 if (cur_bp != prev_bp) {
5216 break;
5217 }
5218 uintptr_t allele_idx_offset_base;
5219 if (!allele_idx_offsets) {
5220 allele_idx_offset_base = next_variant_uidx * 2;
5221 } else {
5222 allele_idx_offset_base = allele_idx_offsets[next_variant_uidx];
5223 allele_ct = allele_idx_offsets[next_variant_uidx + 1] - allele_idx_offset_base;
5224 }
5225 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
5226 JoinVtype jvt = JoinCount(cur_alleles, allele_ct, &next_jc);
5227 // previously validated
5228 // if ((join_mode == kfMakePlink2MJoinSnps) && ()) {
5229 // }
5230
5231 // TODO
5232 jc.snp_ct += next_jc.snp_ct;
5233 jc.nonsnp_ct += next_jc.nonsnp_ct;
5234 jc.symbolic_ct += next_jc.symbolic_ct;
5235 jc.missalt_snp_ct += next_jc.missalt_snp_ct;
5236 jc.missalt_nonsnp_ct += next_jc.missalt_nonsnp_ct;
5237 }
5238 if (next_variant_idx == bp_start_variant_idx + 1) {
5239 // No join needed. This is usually the common case, so we duplicate a
5240 // bunch of code for the sake of avoiding slowdown here.
5241 cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
5242 cswritep = u32toa_x(variant_bps[bp_start_variant_uidx], '\t', cswritep);
5243 cswritep = strcpyax(cswritep, variant_ids[bp_start_variant_uidx], '\t');
5244 uintptr_t allele_idx_offset_base;
5245 if (!allele_idx_offsets) {
5246 allele_idx_offset_base = bp_start_variant_uidx * 2;
5247 } else {
5248 allele_idx_offset_base = allele_idx_offsets[bp_start_variant_uidx];
5249 allele_ct = allele_idx_offsets[bp_start_variant_uidx + 1] - allele_idx_offset_base;
5250 }
5251 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
5252 cswritep = strcpyax(cswritep, cur_alleles[0], '\t');
5253 cswritep = strcpya(cswritep, cur_alleles[1]);
5254 if (unlikely(Cswrite(&css, &cswritep))) {
5255 goto WritePvarJoin_ret_WRITE_FAIL;
5256 }
5257 for (uint32_t allele_idx = 2; allele_idx != allele_ct; ++allele_idx) {
5258 *cswritep++ = ',';
5259 cswritep = strcpya(cswritep, cur_alleles[allele_idx]);
5260 if (unlikely(Cswrite(&css, &cswritep))) {
5261 goto WritePvarJoin_ret_WRITE_FAIL;
5262 }
5263 }
5264
5265 if (write_qual) {
5266 *cswritep++ = '\t';
5267 if ((!qual_present) || (!IsSet(qual_present, bp_start_variant_uidx))) {
5268 *cswritep++ = '.';
5269 } else {
5270 cswritep = ftoa_g(quals[bp_start_variant_uidx], cswritep);
5271 }
5272 }
5273
5274 if (write_filter) {
5275 *cswritep++ = '\t';
5276 if ((!filter_present) || (!IsSet(filter_present, bp_start_variant_uidx))) {
5277 *cswritep++ = '.';
5278 } else if (!IsSet(filter_npass, bp_start_variant_uidx)) {
5279 cswritep = strcpya_k(cswritep, "PASS");
5280 } else {
5281 cswritep = strcpya(cswritep, filter_storage[bp_start_variant_uidx]);
5282 }
5283 }
5284
5285 if (write_info) {
5286 *cswritep++ = '\t';
5287 const uint32_t is_pr = all_nonref || (nonref_flags && IsSet(nonref_flags, bp_start_variant_uidx));
5288 if (pvar_info_line_iter) {
5289 reterr = PvarInfoReloadAndWrite(info_pr_flag_present, info_col_idx, bp_start_variant_uidx, is_pr, &pvar_reload_txs, &pvar_info_line_iter, &cswritep, &trs_variant_uidx);
5290 if (unlikely(reterr)) {
5291 goto WritePvarJoin_ret_TSTREAM_FAIL;
5292 }
5293 } else {
5294 if (is_pr) {
5295 cswritep = strcpya_k(cswritep, "PR");
5296 } else {
5297 *cswritep++ = '.';
5298 }
5299 }
5300 }
5301
5302 if (write_cm) {
5303 *cswritep++ = '\t';
5304 if (!variant_cms) {
5305 *cswritep++ = '0';
5306 } else {
5307 cswritep = dtoa_g_p8(variant_cms[bp_start_variant_uidx], cswritep);
5308 }
5309 }
5310 AppendBinaryEoln(&cswritep);
5311 // next_jc guaranteed to be zero-initialized
5312 } else if (next_variant_idx) {
5313 // TODO
5314 ;;;;
5315 const char* orig_variant_id = variant_ids[variant_uidx];
5316 const char* ref_allele = cur_alleles[0];
5317 const uint32_t ref_allele_slen = strlen(ref_allele);
5318 uint32_t split_ct_p1 = allele_ct;
5319 if (allele_ct > 2) {
5320 if (!varid_dup) {
5321 if (varid_templatep && (!missing_varid_match_blen)) {
5322 cur_varid_templatep = varid_templatep;
5323 } else {
5324 cur_varid_templatep = nullptr;
5325 if (varid_split) {
5326 if (VaridSplitOk(orig_variant_id, allele_ct)) {
5327 varid_token_start = orig_variant_id;
5328 } else {
5329 varid_token_start = nullptr;
5330 }
5331 }
5332 if ((!varid_token_start) && varid_templatep) {
5333 // Note that --set-missing-var-ids almost always applies here
5334 // when it's specified; only exception is when vid-split was also
5335 // specified and the split succeeded.
5336 cur_varid_templatep = varid_templatep;
5337 }
5338 }
5339 }
5340 }
5341 ;;;;
5342 next_jc.snp_ct = 0;
5343 next_jc.nonsnp_ct = 0;
5344 next_jc.symbolic_ct = 0;
5345 next_jc.missalt_snp_ct = 0;
5346 next_jc.missalt_nonsnp_ct = 0;
5347 }
5348 if (next_variant_idx == variant_ct) {
5349 break;
5350 }
5351 // this_pos_write_variant_ct = 0;
5352 jc = next_jc;
5353 prev_bp = cur_bp;
5354 bp_start_variant_idx = next_variant_idx;
5355 bp_start_variant_uidx = next_variant_uidx;
5356 if (next_variant_idx >= next_print_variant_idx) {
5357 if (pct > 10) {
5358 putc_unlocked('\b', stdout);
5359 }
5360 pct = (next_variant_idx * 100LLU) / variant_ct;
5361 printf("\b\b%u%%", pct++);
5362 fflush(stdout);
5363 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
5364 }
5365 }
5366 if (unlikely(CswriteCloseNull(&css, cswritep))) {
5367 goto WritePvarJoin_ret_WRITE_FAIL;
5368 }
5369 if (pct > 10) {
5370 putc_unlocked('\b', stdout);
5371 }
5372 fputs("\b\b", stdout);
5373 }
5374 while (0) {
5375 WritePvarJoin_ret_NOMEM:
5376 reterr = kPglRetNomem;
5377 break;
5378 WritePvarJoin_ret_TSTREAM_FAIL:
5379 TextStreamErrPrint(pvar_info_reload, &pvar_reload_txs);
5380 break;
5381 WritePvarJoin_ret_WRITE_FAIL:
5382 reterr = kPglRetWriteFail;
5383 break;
5384 WritePvarJoin_ret_INVALID_CMDLINE:
5385 reterr = kPglRetInvalidCmdline;
5386 break;
5387 }
5388 WritePvarJoin_ret_1:
5389 CswriteCloseCond(&css, cswritep);
5390 CleanupTextStream2(pvar_info_reload, &pvar_reload_txs, &reterr);
5391 BigstackReset(bigstack_mark);
5392 return reterr;
5393 }
5394 */
5395
5396 void FillAllelePermuteSubset(const AlleleCode* allele_permute, const uintptr_t* variant_include, const uintptr_t* allele_idx_offsets, const uint32_t* new_variant_idx_to_old, uint32_t variant_ct, AlleleCode* write_allele_permute) {
5397 if (!new_variant_idx_to_old) {
5398 uintptr_t variant_uidx_base = 0;
5399 uintptr_t cur_bits = variant_include[0];
5400 if (!allele_idx_offsets) {
5401 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
5402 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
5403 memcpy(&(write_allele_permute[variant_idx * 2]), &(allele_permute[variant_uidx * 2]), 2 * sizeof(AlleleCode));
5404 }
5405 return;
5406 }
5407 AlleleCode* write_allele_permute_iter = write_allele_permute;
5408 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
5409 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
5410 const uintptr_t allele_idx_offset_base = allele_idx_offsets[variant_uidx];
5411 const uint32_t allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
5412 memcpy(write_allele_permute_iter, &(allele_permute[allele_idx_offset_base]), allele_ct * sizeof(AlleleCode));
5413 write_allele_permute_iter = &(write_allele_permute_iter[allele_ct]);
5414 }
5415 return;
5416 }
5417 if (!allele_idx_offsets) {
5418 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
5419 const uintptr_t variant_uidx = new_variant_idx_to_old[variant_idx];
5420 memcpy(&(write_allele_permute[variant_idx * 2]), &(allele_permute[variant_uidx * 2]), 2 * sizeof(AlleleCode));
5421 }
5422 return;
5423 }
5424 AlleleCode* write_allele_permute_iter = write_allele_permute;
5425 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
5426 const uintptr_t variant_uidx = new_variant_idx_to_old[variant_idx];
5427 const uintptr_t allele_idx_offset_base = allele_idx_offsets[variant_uidx];
5428 const uint32_t allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
5429 memcpy(write_allele_permute_iter, &(allele_permute[allele_idx_offset_base]), allele_ct * sizeof(AlleleCode));
5430 write_allele_permute_iter = &(write_allele_permute_iter[allele_ct]);
5431 }
5432 }
5433
5434
5435 FLAGSET_DEF_START()
5436 kfPlink2Write0,
5437 kfPlink2WriteSetInvalidHaploidMissing = (1 << 0),
5438 kfPlink2WriteSetInvalidHaploidMissingKeepDosage = (1 << 1),
5439 kfPlink2WriteSetMixedMtMissing = (1 << 2),
5440 kfPlink2WriteSetMixedMtMissingKeepDosage = (1 << 3),
5441 kfPlink2WriteMeMissing = (1 << 4),
5442 kfPlink2WriteZeroCluster = (1 << 5),
5443 kfPlink2WriteFillRef = (1 << 6),
5444 kfPlink2WriteLateDosageErase = (1 << 7),
5445 kfPlink2WriteFillMissingFromDosage = (1 << 8),
5446 // no need for sample_sort, determined by collapsed_sort_map != nullptr?
5447 kfPlink2WritePlink1 = (1 << 9)
5448 FLAGSET_DEF_END(Plink2WriteFlags);
5449 // todo: add .pgen-specific stuff
5450
5451 typedef struct MakeCommonStruct {
5452 const ChrInfo* cip;
5453 const uintptr_t* sample_include;
5454 uintptr_t* sex_male_collapsed_interleaved;
5455 uintptr_t* sex_female_collapsed_interleaved;
5456 const AlleleCode* write_allele_permute;
5457 uint32_t raw_sample_ct;
5458 uint32_t sample_ct;
5459 Plink2WriteFlags plink2_write_flags;
5460 uint32_t hard_call_halfdist;
5461 } MakeCommon;
5462
5463 typedef struct MakeBedlikeCtxStruct {
5464 const MakeCommon* mcp;
5465
5466 const uintptr_t* variant_include;
5467 uint32_t* sample_include_cumulative_popcounts;
5468 // unlike MakePgenCtx, old_sample_idx is subsetted here
5469 const uint32_t* old_sample_idx_to_new;
5470
5471 PgenReader** pgr_ptrs;
5472
5473 uint32_t* read_variant_uidx_starts;
5474 uint32_t cur_block_write_ct;
5475
5476 uintptr_t** genovecs;
5477 uintptr_t** dosage_presents;
5478 Dosage** dosage_mains;
5479
5480 unsigned char* writebufs[2];
5481 uint64_t err_info;
5482 } MakeBedlikeCtx;
5483
5484
5485 THREAD_FUNC_DECL MakeBedlikeThread(void* raw_arg) {
5486 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
5487 const uintptr_t tidx = arg->tidx;
5488 MakeBedlikeCtx* ctx = S_CAST(MakeBedlikeCtx*, arg->sharedp->context);
5489
5490 PgenReader* pgrp = ctx->pgr_ptrs[tidx];
5491 uintptr_t* genovec = ctx->genovecs[tidx];
5492 const MakeCommon* mcp = ctx->mcp;
5493 uintptr_t* dosage_present = nullptr;
5494 Dosage* dosage_main = nullptr;
5495 uint32_t hard_call_halfdist = 0;
5496 if (ctx->dosage_presents) {
5497 dosage_present = ctx->dosage_presents[tidx];
5498 dosage_main = ctx->dosage_mains[tidx];
5499 hard_call_halfdist = mcp->hard_call_halfdist;
5500 }
5501 const uintptr_t* variant_include = ctx->variant_include;
5502 const ChrInfo* cip = mcp->cip;
5503 const uintptr_t* sample_include = mcp->sample_include;
5504 PgrSampleSubsetIndex pssi;
5505 PgrSetSampleSubsetIndex(ctx->sample_include_cumulative_popcounts, pgrp, &pssi);
5506 const uintptr_t* sex_male_collapsed_interleaved = mcp->sex_male_collapsed_interleaved;
5507 const uintptr_t* sex_female_collapsed_interleaved = mcp->sex_female_collapsed_interleaved;
5508 const uint32_t* old_sample_idx_to_new = ctx->old_sample_idx_to_new;
5509 const Plink2WriteFlags plink2_write_flags = mcp->plink2_write_flags;
5510 const uint32_t set_invalid_haploid_missing = plink2_write_flags & kfPlink2WriteSetInvalidHaploidMissing;
5511 const uint32_t set_mixed_mt_missing = plink2_write_flags & kfPlink2WriteSetMixedMtMissing;
5512 const uint32_t write_plink1 = plink2_write_flags & kfPlink2WritePlink1;
5513 const uint32_t sample_ct = mcp->sample_ct;
5514 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
5515 const uint32_t sample_ctv2 = NypCtToVecCt(sample_ct);
5516 // bugfix (5 Jan 2024): (write_idx * sample_ct4) could overflow when
5517 // sample_ct4 was a uint32_t
5518 const uintptr_t sample_ct4 = NypCtToByteCt(sample_ct);
5519 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
5520 const AlleleCode* write_allele_permute_iter = mcp->write_allele_permute;
5521 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
5522 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
5523 const uint32_t mt_code = cip->xymt_codes[kChrOffsetMT];
5524 uint32_t parity = 0;
5525 uint64_t new_err_info = 0;
5526 do {
5527 const uintptr_t cur_block_write_ct = ctx->cur_block_write_ct;
5528 uint32_t write_idx = (tidx * cur_block_write_ct) / calc_thread_ct;
5529 const uint32_t write_idx_end = ((tidx + 1) * cur_block_write_ct) / calc_thread_ct;
5530 unsigned char* writebuf_iter = &(ctx->writebufs[parity][write_idx * sample_ct4]);
5531 uintptr_t variant_uidx_base;
5532 uintptr_t cur_bits;
5533 BitIter1Start(variant_include, ctx->read_variant_uidx_starts[tidx], &variant_uidx_base, &cur_bits);
5534 uint32_t chr_end = 0;
5535 uint32_t is_x = 0;
5536 uint32_t is_y = 0;
5537 uint32_t is_haploid_nonmt = 0;
5538 uint32_t is_mt = 0;
5539 for (; write_idx != write_idx_end; ++write_idx) {
5540 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
5541 if (variant_uidx >= chr_end) {
5542 const uint32_t chr_fo_idx = GetVariantChrFoIdx(cip, variant_uidx);
5543 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
5544 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
5545 is_x = (chr_idx == x_code);
5546 is_y = (chr_idx == y_code);
5547 is_mt = (chr_idx == mt_code);
5548 is_haploid_nonmt = IsSet(cip->haploid_mask, chr_idx) && (!is_mt);
5549 }
5550 // todo: Multiallelic -> two-specific-alleles downcode.
5551 // This is pretty straightforward if we're just saving hardcalls:
5552 // with 1 copy of one allele and zero copies of the other allele, we
5553 // default to saving a missing call (in the diploid case).
5554 // If dosages are involved, things are a bit less obvious: what if the
5555 // unincluded alleles have a total dosage of 0.1? 0.5? It'll be
5556 // necessary to define a new flag allowing this threshold to be
5557 // configured.
5558 // I'm currently inclined to set unincluded dosage >= 0.5 to missing, and
5559 // otherwise the dosages are scaled up to sum to 2.
5560 // (Note that the multiallelic split operation won't work this way; it
5561 // has to use the convention that REF = anything other than the current
5562 // ALT allele. Probably also want to support that here.)
5563 if (!hard_call_halfdist) {
5564 // if multiallelic:
5565 // if split: call PgrGet1()
5566 // otherwise, if erase-alt2+: call PgrGet2()
5567 // otherwise, error out
5568 const PglErr reterr = PgrGet(sample_include, pssi, sample_ct, variant_uidx, pgrp, genovec);
5569 if (unlikely(reterr)) {
5570 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
5571 goto MakeBedlikeThread_err;
5572 }
5573 } else {
5574 // this isn't fully implemented yet.
5575
5576 // quasi-bugfix (4 Dec 2017): it's user-hostile to make
5577 // --hard-call-threshold not apply here.
5578 uint32_t dosage_ct;
5579 // if multiallelic:
5580 // if split: call PgrGet1D()
5581 // otherwise, if allele_permute + erase-alt2+: call PgrGetMD(),
5582 // rescale
5583 // otherwise, error out
5584 const PglErr reterr = PgrGetD(sample_include, pssi, sample_ct, variant_uidx, pgrp, genovec, dosage_present, dosage_main, &dosage_ct);
5585 if (unlikely(reterr)) {
5586 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
5587 goto MakeBedlikeThread_err;
5588 }
5589 ApplyHardCallThresh(dosage_present, dosage_main, dosage_ct, hard_call_halfdist, genovec);
5590 }
5591 // may need to change this when trim-alts implemented
5592 if (write_allele_permute_iter && write_allele_permute_iter[write_idx * 2]) {
5593 assert(write_allele_permute_iter[write_idx * 2] == 1);
5594 GenovecInvertUnsafe(sample_ct, genovec);
5595 }
5596 if (set_invalid_haploid_missing && is_haploid_nonmt) {
5597 if (is_x) {
5598 SetMaleHetMissing(sex_male_collapsed_interleaved, sample_ctv2, genovec);
5599 } else {
5600 // all hets to missing
5601 SetHetMissing(sample_ctl2, genovec);
5602 if (is_y) {
5603 InterleavedSetMissing(sex_female_collapsed_interleaved, sample_ctv2, genovec);
5604 }
5605 }
5606 } else if (set_mixed_mt_missing && is_mt) {
5607 // all hets to missing
5608 SetHetMissing(sample_ctl2, genovec);
5609 }
5610 // todo: --set-me-missing, --zero-cluster, --fill-missing-with-ref
5611 // (--set-me-missing should happen after --set-invalid-haploid-missing)
5612 if (write_plink1) {
5613 PgrPlink2ToPlink1InplaceUnsafe(sample_ct, genovec);
5614 }
5615 ZeroTrailingNyps(sample_ct, genovec);
5616 if (!old_sample_idx_to_new) {
5617 writebuf_iter = memcpyua(writebuf_iter, genovec, sample_ct4);
5618 } else {
5619 GenovecPermute(genovec, old_sample_idx_to_new, sample_ct, writebuf_iter);
5620 writebuf_iter = &(writebuf_iter[sample_ct4]);
5621 }
5622 }
5623 parity = 1 - parity;
5624 if (write_allele_permute_iter) {
5625 write_allele_permute_iter = &(write_allele_permute_iter[cur_block_write_ct * 2]);
5626 }
5627 while (0) {
5628 MakeBedlikeThread_err:
5629 UpdateU64IfSmaller(new_err_info, &ctx->err_info);
5630 }
5631 } while (!THREAD_BLOCK_FINISH(arg));
5632 THREAD_RETURN;
5633 }
5634
5635 // initialized mcp fields: cip, sex_male_collapsed_interleaved,
5636 // sex_female_collapsed_interleaved, write_allele_permute, raw_sample_ct,
5637 // sample_ct, plink2_write_flags
5638 PglErr MakeBedlikeMain(const uintptr_t* sample_include, const uint32_t* new_sample_idx_to_old, const uintptr_t* variant_include, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_thread_ct, uint32_t hard_call_thresh, MakePlink2Flags make_plink2_flags, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, MakeCommon* mcp, char* outname, char* outname_end) {
5639 FILE* outfile = nullptr;
5640 PglErr reterr = kPglRetSuccess;
5641 ThreadGroup tg;
5642 PreinitThreads(&tg);
5643 MakeBedlikeCtx ctx;
5644 {
5645 assert(variant_ct);
5646 const uint32_t sample_ct = mcp->sample_ct;
5647 assert(sample_ct);
5648 if (make_plink2_flags & kfMakePlink2MMask) {
5649 logerrputs("Error: Multiallelic-split fixed-width output is not implemented yet.\n");
5650 reterr = kPglRetNotYetSupported;
5651 goto MakeBedlikeMain_ret_1;
5652 }
5653 // fixed-width
5654 const uint32_t make_pgen = make_plink2_flags & kfMakePgen;
5655 if (make_pgen) {
5656 snprintf(outname_end, kMaxOutfnameExtBlen, ".pgen");
5657 } else {
5658 snprintf(outname_end, kMaxOutfnameExtBlen, ".bed");
5659 }
5660 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
5661 goto MakeBedlikeMain_ret_OPEN_FAIL;
5662 }
5663 if (make_pgen) {
5664 fwrite_unlocked("l\x1b\x02", 3, 1, outfile);
5665 fwrite_unlocked(&variant_ct, 4, 1, outfile);
5666 fwrite_unlocked(&sample_ct, 4, 1, outfile);
5667 if (!pgfip->nonref_flags) {
5668 const PgenGlobalFlags gflags = pgfip->gflags;
5669 uint32_t uii = 64;
5670 if (gflags & kfPgenGlobalAllNonref) {
5671 uii = 128;
5672 }
5673 putc_unlocked(uii, outfile);
5674 } else {
5675 putc_unlocked(192, outfile);
5676 fwrite_unlocked(pgfip->nonref_flags, DivUp(variant_ct, CHAR_BIT), 1, outfile);
5677 }
5678 if (unlikely(ferror_unlocked(outfile))) {
5679 goto MakeBedlikeMain_ret_WRITE_FAIL;
5680 }
5681 } else {
5682 if (unlikely(fwrite_checked("l\x1b\x01", 3, outfile))) {
5683 goto MakeBedlikeMain_ret_WRITE_FAIL;
5684 }
5685 }
5686 logprintfww5("Writing %s ... ", outname);
5687 fputs("0%", stdout);
5688 fflush(stdout);
5689 uint32_t pct = 0;
5690 const uint32_t raw_sample_ct = mcp->raw_sample_ct;
5691 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
5692 const uintptr_t sample_ct4 = NypCtToByteCt(sample_ct);
5693 if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &ctx.sample_include_cumulative_popcounts))) {
5694 goto MakeBedlikeMain_ret_NOMEM;
5695 }
5696 FillCumulativePopcounts(sample_include, raw_sample_ctl, ctx.sample_include_cumulative_popcounts);
5697 // tried more threads, pointless since this is too I/O-bound
5698 // (exception: reordering samples)
5699 uint32_t calc_thread_ct = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
5700 ctx.old_sample_idx_to_new = nullptr;
5701 if (!new_sample_idx_to_old) {
5702 // Without BMI2 instructions, subsetting is most expensive with
5703 // sample_ct near 2/3 of raw_sample_ct; up to ~7 compute threads are
5704 // useful in that case. (See CopyNyparrNonemptySubset().)
5705 // With them, 1-2 compute threads appear to suffice.
5706 #ifdef USE_AVX2
5707 const uint32_t calc_thread_max = 2;
5708 #else
5709 uint64_t numer;
5710 if (sample_ct * (3 * k1LU) <= raw_sample_ct * (2 * k1LU)) {
5711 numer = sample_ct * (9 * k1LU);
5712 } else {
5713 numer = (raw_sample_ct - sample_ct) * (18 * k1LU);
5714 }
5715 const uint32_t calc_thread_max = 1 + (numer / raw_sample_ct);
5716 #endif
5717 if (calc_thread_max < calc_thread_ct) {
5718 calc_thread_ct = calc_thread_max;
5719 }
5720 } else {
5721 uint32_t* old_sample_idx_to_new;
5722 if (unlikely(bigstack_alloc_u32(raw_sample_ct, &old_sample_idx_to_new))) {
5723 goto MakeBedlikeMain_ret_NOMEM;
5724 }
5725 if (sample_ct == raw_sample_ct) {
5726 for (uint32_t new_sample_idx = 0; new_sample_idx != sample_ct; ++new_sample_idx) {
5727 old_sample_idx_to_new[new_sample_idx_to_old[new_sample_idx]] = new_sample_idx;
5728 }
5729 } else {
5730 for (uint32_t new_sample_idx = 0; new_sample_idx != sample_ct; ++new_sample_idx) {
5731 const uint32_t old_sample_uidx = new_sample_idx_to_old[new_sample_idx];
5732 old_sample_idx_to_new[RawToSubsettedPos(sample_include, ctx.sample_include_cumulative_popcounts, old_sample_uidx)] = new_sample_idx;
5733 }
5734 }
5735 ctx.old_sample_idx_to_new = old_sample_idx_to_new;
5736 }
5737
5738 if (make_plink2_flags & kfMakeBed) {
5739 mcp->plink2_write_flags |= kfPlink2WritePlink1;
5740 }
5741
5742 mcp->hard_call_halfdist = 0;
5743 if ((hard_call_thresh != UINT32_MAX) && (pgfip->gflags & (kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent))) {
5744 mcp->hard_call_halfdist = kDosage4th - hard_call_thresh;
5745 }
5746 STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
5747 ctx.dosage_presents = nullptr;
5748 ctx.dosage_mains = nullptr;
5749 uint32_t read_block_size;
5750 if (unlikely(PgenMtLoadInit(variant_include, sample_ct, variant_ct, bigstack_left(), pgr_alloc_cacheline_ct, 0, 2 * (sample_ct4 + 1), 0, pgfip, &calc_thread_ct, &ctx.genovecs, nullptr, nullptr, nullptr, mcp->hard_call_halfdist? (&ctx.dosage_presents) : nullptr, mcp->hard_call_halfdist? (&ctx.dosage_mains) : nullptr, nullptr, nullptr, &read_block_size, nullptr, main_loadbufs, &ctx.pgr_ptrs, &ctx.read_variant_uidx_starts))) {
5751 goto MakeBedlikeMain_ret_NOMEM;
5752 }
5753 if (unlikely(bigstack_alloc_uc(sample_ct4 * read_block_size, &(ctx.writebufs[0])) ||
5754 bigstack_alloc_uc(sample_ct4 * read_block_size, &(ctx.writebufs[1])))) {
5755 // shouldn't be possible for this to fail
5756 goto MakeBedlikeMain_ret_NOMEM;
5757 }
5758 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
5759 goto MakeBedlikeMain_ret_NOMEM;
5760 }
5761
5762 ctx.variant_include = variant_include;
5763 mcp->sample_include = sample_include;
5764 mcp->sample_ct = sample_ct;
5765 ctx.mcp = mcp;
5766 ctx.err_info = (~0LLU) << 32;
5767 SetThreadFuncAndData(MakeBedlikeThread, &ctx, &tg);
5768
5769 // Main workflow:
5770 // 1. Set n=0, load/skip block 0
5771 //
5772 // 2. Spawn threads processing block n
5773 // 3. If n>0, write results for block (n-1)
5774 // 4. Increment n by 1
5775 // 5. Load/skip block n unless eof
5776 // 6. Join threads
5777 // 7. Goto step 2 unless eof
5778 //
5779 // 8. Write results for last block
5780 uint32_t parity = 0;
5781 uint32_t read_block_idx = 0;
5782 uint32_t prev_variant_idx = 0;
5783 uint32_t next_print_variant_idx = variant_ct / 100;
5784 for (uint32_t variant_idx = 0; ; ) {
5785 const uint32_t cur_block_write_ct = MultireadNonempty(variant_include, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr);
5786 if (unlikely(reterr)) {
5787 goto MakeBedlikeMain_ret_PGR_FAIL;
5788 }
5789 if (variant_idx) {
5790 JoinThreads(&tg);
5791 reterr = S_CAST(PglErr, ctx.err_info);
5792 if (unlikely(reterr)) {
5793 // this should only be possible in MakePgenRobust()
5794 assert(reterr != kPglRetWriteFail);
5795 PgenErrPrintNV(reterr, ctx.err_info >> 32);
5796 goto MakeBedlikeMain_ret_1;
5797 }
5798 }
5799 if (!IsLastBlock(&tg)) {
5800 ctx.cur_block_write_ct = cur_block_write_ct;
5801 ComputeUidxStartPartition(variant_include, cur_block_write_ct, calc_thread_ct, read_block_idx * read_block_size, ctx.read_variant_uidx_starts);
5802 PgrCopyBaseAndOffset(pgfip, calc_thread_ct, ctx.pgr_ptrs);
5803 if (variant_idx + cur_block_write_ct == variant_ct) {
5804 DeclareLastThreadBlock(&tg);
5805 }
5806 if (unlikely(SpawnThreads(&tg))) {
5807 goto MakeBedlikeMain_ret_THREAD_CREATE_FAIL;
5808 }
5809 }
5810 parity = 1 - parity;
5811 if (variant_idx) {
5812 // write *previous* block results
5813 if (unlikely(fwrite_checked(ctx.writebufs[parity], (variant_idx - prev_variant_idx) * sample_ct4, outfile))) {
5814 goto MakeBedlikeMain_ret_WRITE_FAIL;
5815 }
5816 if (variant_idx == variant_ct) {
5817 break;
5818 }
5819 if (variant_idx >= next_print_variant_idx) {
5820 if (pct > 10) {
5821 putc_unlocked('\b', stdout);
5822 }
5823 pct = (variant_idx * 100LLU) / variant_ct;
5824 printf("\b\b%u%%", pct++);
5825 fflush(stdout);
5826 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
5827 }
5828 prev_variant_idx = variant_idx;
5829 }
5830 ++read_block_idx;
5831 variant_idx += cur_block_write_ct;
5832 // crucially, this is independent of the PgenReader block_base pointers
5833 pgfip->block_base = main_loadbufs[parity];
5834 }
5835 if (unlikely(fclose_null(&outfile))) {
5836 goto MakeBedlikeMain_ret_WRITE_FAIL;
5837 }
5838 if (pct > 10) {
5839 putc_unlocked('\b', stdout);
5840 }
5841 fputs("\b\b", stdout);
5842 logputs("done.\n");
5843 // BigstackReset(bigstack_mark);
5844 }
5845 while (0) {
5846 MakeBedlikeMain_ret_NOMEM:
5847 reterr = kPglRetNomem;
5848 break;
5849 MakeBedlikeMain_ret_OPEN_FAIL:
5850 reterr = kPglRetOpenFail;
5851 break;
5852 MakeBedlikeMain_ret_PGR_FAIL:
5853 PgenErrPrintN(reterr);
5854 break;
5855 MakeBedlikeMain_ret_WRITE_FAIL:
5856 reterr = kPglRetWriteFail;
5857 break;
5858 MakeBedlikeMain_ret_THREAD_CREATE_FAIL:
5859 reterr = kPglRetThreadCreateFail;
5860 break;
5861 }
5862 MakeBedlikeMain_ret_1:
5863 CleanupThreads(&tg);
5864 fclose_cond(outfile);
5865 // parent will free memory
5866 return reterr;
5867 }
5868
5869 typedef struct MakePgenCtxStruct {
5870 MakeCommon* mcp;
5871
5872 uint32_t* old_sample_idx_to_new;
5873 uintptr_t* sample_include_interleaved_vec;
5874 // combine existing chr_mask/xymt_codes/haploid_mask/chr_idx_to_foidx with
5875 // new collapsed chromosome boundary table
5876 uint32_t* write_chr_fo_vidx_start;
5877 const uintptr_t* write_allele_idx_offsets;
5878 const uintptr_t* sex_male_collapsed;
5879 const uintptr_t* sex_female_collapsed;
5880 uint32_t dosage_erase_halfdist;
5881
5882 uintptr_t** loadbuf_thread_starts[2];
5883 // phase, dosage
5884 unsigned char* loaded_vrtypes[2];
5885
5886 uint32_t cur_block_write_ct;
5887
5888 STPgenWriter* spgwp;
5889 PgenWriterCommon** pwcs;
5890 uintptr_t** thread_write_genovecs;
5891 uintptr_t** thread_write_mhc;
5892 AlleleCode** thread_ac_remap;
5893 AlleleCode** thread_ac_rotate;
5894 uintptr_t** thread_ac_flipped;
5895 uintptr_t** thread_write_phasepresents;
5896 uintptr_t** thread_write_phaseinfos;
5897 uintptr_t** thread_all_hets;
5898 uintptr_t** thread_write_dosagepresents;
5899 Dosage** thread_write_dosagevals;
5900 uintptr_t** thread_write_dphasepresents;
5901 SDosage** thread_write_dphasedeltas;
5902 PglErr write_reterr;
5903 int32_t write_errno;
5904 } MakePgenCtx;
5905
5906 // One-thread-per-vblock is sensible for possibly-phased biallelic data, where
5907 // subsetting and LD-compression are a substantial fraction of processing time,
5908 // and memory requirements tend to be low enough that it's actually reasonable
5909 // for each thread job to comprise 64k variants.
5910 // Beyond that... the VCF/.pgen division of labor looks nice, but far too much
5911 // of the work is usually being done in the initial PgrGetRaw() call, so just
5912 // fall back on single-threaded invocation of the same function; only
5913 // difference is that the worker thread owns the writer object.
5914 //
5915 // Possible todo: it doesn't come up frequently, but sorting a .pgen that is
5916 // thoroughly out of order can be very slow due to all the nonsequential I/O.
5917 // That could be accelerated with the pvar-INFO temporary-file strategy (split
5918 // into remaining-workspace-sized original-order shard files, then load one
5919 // entire shard at a time and write it out in the correct order).
5920 // May want to benchmark on Linux first to see if this is a real problem; the
5921 // horrible benchmark result motivating this comment was on macOS, which is
5922 // known to have a sketchy filesystem.
5923 THREAD_FUNC_DECL MakePgenThread(void* raw_arg) {
5924 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
5925 const uintptr_t tidx = arg->tidx;
5926 MakePgenCtx* ctx = S_CAST(MakePgenCtx*, arg->sharedp->context);
5927
5928 const uint32_t* old_sample_idx_to_new = ctx->old_sample_idx_to_new;
5929 const MakeCommon* mcp = ctx->mcp;
5930 const ChrInfo* cip = mcp->cip;
5931 const uint32_t* write_chr_fo_vidx_start = ctx->write_chr_fo_vidx_start;
5932 const uintptr_t* write_allele_idx_offsets = ctx->write_allele_idx_offsets;
5933 const AlleleCode* write_allele_permute = mcp->write_allele_permute;
5934 const uintptr_t* sample_include = mcp->sample_include;
5935 const uintptr_t* sample_include_interleaved_vec = ctx->sample_include_interleaved_vec;
5936
5937 const uintptr_t* sex_male_collapsed = ctx->sex_male_collapsed;
5938
5939 const uintptr_t* sex_male_collapsed_interleaved = mcp->sex_male_collapsed_interleaved;
5940 const uintptr_t* sex_female_collapsed = ctx->sex_female_collapsed;
5941 const uintptr_t* sex_female_collapsed_interleaved = mcp->sex_female_collapsed_interleaved;
5942 const uint32_t raw_sample_ct = mcp->raw_sample_ct;
5943 const uint32_t sample_ct = mcp->sample_ct;
5944 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
5945 const uint32_t sample_ctv2 = NypCtToVecCt(sample_ct);
5946 const uint32_t raw_sample_ctaw2 = NypCtToAlignedWordCt(raw_sample_ct);
5947 const uint32_t raw_sample_ctaw = BitCtToAlignedWordCt(raw_sample_ct);
5948 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
5949 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
5950 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
5951 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
5952 const uint32_t mt_code = cip->xymt_codes[kChrOffsetMT];
5953
5954 const Plink2WriteFlags plink2_write_flags = mcp->plink2_write_flags;
5955 const uint32_t set_invalid_haploid_missing = plink2_write_flags & kfPlink2WriteSetInvalidHaploidMissing;
5956 const uint32_t set_invalid_haploid_missing_keep_dosage = plink2_write_flags & kfPlink2WriteSetInvalidHaploidMissingKeepDosage;
5957 const uint32_t set_mixed_mt_missing = plink2_write_flags & kfPlink2WriteSetMixedMtMissing;
5958 const uint32_t set_mixed_mt_missing_keep_dosage = plink2_write_flags & kfPlink2WriteSetMixedMtMissingKeepDosage;
5959 const uint32_t late_dosage_erase = plink2_write_flags & kfPlink2WriteLateDosageErase;
5960 const uint32_t fill_missing_from_dosage = plink2_write_flags & kfPlink2WriteFillMissingFromDosage;
5961
5962 const uint32_t hard_call_halfdist = mcp->hard_call_halfdist;
5963 const uint32_t dosage_erase_halfdist = ctx->dosage_erase_halfdist;
5964 const uintptr_t dosageraw_word_ct = kWordsPerVec * (BitCtToVecCt(raw_sample_ct) + DivUp(raw_sample_ct, (kBytesPerVec / sizeof(Dosage))));
5965
5966 STPgenWriter* spgwp = ctx->spgwp;
5967 PgenWriterCommon* pwcp;
5968 if (spgwp) {
5969 // make this function stand out as an intrusive one
5970 pwcp = &GET_PRIVATE(*spgwp, pwc);
5971 } else {
5972 pwcp = ctx->pwcs[tidx];
5973 }
5974 uintptr_t* write_genovec = nullptr;
5975 // assumes sample_include == nullptr if sample_ct == raw_sample_ct
5976 if (old_sample_idx_to_new || sample_include) {
5977 write_genovec = ctx->thread_write_genovecs[tidx];
5978 write_genovec[sample_ctl2 - 1] = 0;
5979 }
5980 uintptr_t* write_patch_01_set = nullptr;
5981 AlleleCode* write_patch_01_vals = nullptr;
5982 uintptr_t* write_patch_10_set = nullptr;
5983 AlleleCode* write_patch_10_vals = nullptr;
5984 AlleleCode* ac_remap = nullptr;
5985 AlleleCode* ac_rotate = nullptr;
5986 uintptr_t* ac_flipped = nullptr;
5987 if (ctx->thread_write_mhc) {
5988 ExpandMhc(sample_ct, ctx->thread_write_mhc[tidx], &write_patch_01_set, &write_patch_01_vals, &write_patch_10_set, &write_patch_10_vals);
5989 if (ctx->thread_ac_remap) {
5990 ac_remap = ctx->thread_ac_remap[tidx];
5991 ac_rotate = ctx->thread_ac_rotate[tidx];
5992 ac_flipped = ctx->thread_ac_flipped[tidx];
5993 }
5994 }
5995 uintptr_t* write_phasepresent = nullptr;
5996 uintptr_t* write_phaseinfo = nullptr;
5997 uintptr_t* all_hets = nullptr;
5998 if (ctx->thread_write_phasepresents) {
5999 write_phasepresent = ctx->thread_write_phasepresents[tidx];
6000 write_phaseinfo = ctx->thread_write_phaseinfos[tidx];
6001 if (ctx->thread_all_hets) {
6002 all_hets = ctx->thread_all_hets[tidx];
6003 }
6004 }
6005 uintptr_t* write_dosagepresent = nullptr;
6006 Dosage* write_dosagevals = nullptr;
6007 uintptr_t* write_dphasepresent = nullptr;
6008 SDosage* write_dphasedeltas = nullptr;
6009 SDosage* tmp_dphasedeltas = nullptr;
6010 if (ctx->thread_write_dosagepresents) {
6011 write_dosagepresent = ctx->thread_write_dosagepresents[tidx];
6012 write_dosagevals = ctx->thread_write_dosagevals[tidx];
6013 if (ctx->thread_write_dphasepresents) {
6014 write_dphasepresent = ctx->thread_write_dphasepresents[tidx];
6015 write_dphasedeltas = ctx->thread_write_dphasedeltas[tidx];
6016 tmp_dphasedeltas = &(write_dphasedeltas[RoundUpPow2(sample_ct, kCacheline / 2)]);
6017 }
6018 }
6019 uint32_t variant_idx_offset = 0;
6020 uint32_t allele_ct = 2;
6021 uint32_t parity = 0;
6022 do {
6023 const uintptr_t cur_block_write_ct = ctx->cur_block_write_ct;
6024 uint32_t write_idx = tidx * kPglVblockSize;
6025 const uint32_t write_idx_end = MINV(write_idx + kPglVblockSize, cur_block_write_ct);
6026 uintptr_t* loadbuf_iter = ctx->loadbuf_thread_starts[parity][tidx];
6027 unsigned char* loaded_vrtypes = ctx->loaded_vrtypes[parity];
6028 uint32_t loaded_vrtype = 0;
6029 uint32_t chr_end_bidx = 0;
6030 uint32_t is_x = 0;
6031 uint32_t is_y = 0;
6032 uint32_t is_haploid_nonmt = 0;
6033 uint32_t is_mt = 0;
6034 // write_idx may start larger than write_idx_end
6035 for (; write_idx < write_idx_end; ++write_idx) {
6036 if (loaded_vrtypes) {
6037 loaded_vrtype = loaded_vrtypes[write_idx];
6038 }
6039 if (write_idx >= chr_end_bidx) {
6040 // const uint32_t chr_fo_idx = LastLeqU32(write_chr_fo_vidx_start, 0, cip->chr_ct, write_idx + variant_idx_offset);
6041 const uint32_t chr_fo_idx = LowerBoundNonemptyU32(&(write_chr_fo_vidx_start[1]), cip->chr_ct, write_idx + variant_idx_offset + 1);
6042 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
6043 chr_end_bidx = write_chr_fo_vidx_start[chr_fo_idx + 1] - variant_idx_offset;
6044 is_x = (chr_idx == x_code);
6045 is_y = (chr_idx == y_code);
6046 is_mt = (chr_idx == mt_code);
6047 is_haploid_nonmt = IsSet(cip->haploid_mask, chr_idx) && (!is_mt);
6048 }
6049 uintptr_t* cur_vrec_end = &(loadbuf_iter[raw_sample_ctaw2]);
6050 uintptr_t write_allele_idx_offset_base = (write_idx + variant_idx_offset) * 2;
6051 if (write_allele_idx_offsets) {
6052 write_allele_idx_offset_base = write_allele_idx_offsets[write_idx + variant_idx_offset];
6053 allele_ct = write_allele_idx_offsets[write_idx + variant_idx_offset + 1] - write_allele_idx_offset_base;
6054 }
6055 const uint32_t is_mhc = loaded_vrtype & 8;
6056 uint32_t read_rare01_ct = 0;
6057 uint32_t read_rare10_ct = 0;
6058 uintptr_t* read_patch_01_set = nullptr;
6059 AlleleCode* read_patch_01_vals = nullptr;
6060 uintptr_t* read_patch_10_set = nullptr;
6061 AlleleCode* read_patch_10_vals = nullptr;
6062 if (is_mhc) {
6063 assert(allele_ct > 2);
6064 read_rare01_ct = cur_vrec_end[0];
6065 read_rare10_ct = cur_vrec_end[1];
6066 cur_vrec_end = &(cur_vrec_end[RoundUpPow2(2, kWordsPerVec)]);
6067 if (read_rare01_ct) {
6068 read_patch_01_set = cur_vrec_end;
6069 cur_vrec_end = &(cur_vrec_end[raw_sample_ctl]);
6070 read_patch_01_vals = R_CAST(AlleleCode*, cur_vrec_end);
6071 cur_vrec_end = &(cur_vrec_end[DivUp(read_rare01_ct, kBytesPerWord / sizeof(AlleleCode))]);
6072 AlignWToVec(&cur_vrec_end);
6073 }
6074 if (read_rare10_ct) {
6075 read_patch_10_set = cur_vrec_end;
6076 cur_vrec_end = &(cur_vrec_end[raw_sample_ctl]);
6077 read_patch_10_vals = R_CAST(AlleleCode*, cur_vrec_end);
6078 cur_vrec_end = &(cur_vrec_end[DivUp(read_rare10_ct, kBytesPerWord / (2 * sizeof(AlleleCode)))]);
6079 AlignWToVec(&cur_vrec_end);
6080 }
6081 }
6082 uint32_t is_hphase = loaded_vrtype & 0x10;
6083 uintptr_t* cur_phaseraw = nullptr;
6084 if (is_hphase) {
6085 // tried skipping this and using ExpandThenSubsetBytearr in simplest
6086 // case, not worthwhile
6087 if (!read_rare10_ct) {
6088 PgrDetectGenoarrHets(loadbuf_iter, raw_sample_ct, all_hets);
6089 } else {
6090 PgrDetectGenoarrHetsMultiallelic(loadbuf_iter, read_patch_10_set, read_patch_10_vals, raw_sample_ct, all_hets);
6091 }
6092 cur_phaseraw = cur_vrec_end;
6093 const uint32_t het_ct = S_CAST(uint32_t, cur_phaseraw[0]);
6094 #ifdef __LP64__
6095 const uint32_t explicit_phasepresent_ct = cur_phaseraw[0] >> 32;
6096 #else
6097 const uint32_t explicit_phasepresent_ct = cur_phaseraw[1];
6098 #endif
6099 const uint32_t phaseraw_word_ct = (8 / kBytesPerWord) + 1 + (het_ct / kBitsPerWord) + DivUp(explicit_phasepresent_ct, kBitsPerWord);
6100 cur_vrec_end = &(cur_vrec_end[RoundUpPow2(phaseraw_word_ct, kWordsPerVec)]);
6101 }
6102 const uint32_t is_dosage = loaded_vrtype & 0x60;
6103 const uint32_t is_dphase = loaded_vrtype & 0x80;
6104 uintptr_t* cur_write_phasepresent = write_phasepresent;
6105 uintptr_t* cur_dosagepresent = nullptr;
6106 Dosage* cur_dosagevals = nullptr;
6107 uintptr_t* cur_dphasepresent = nullptr;
6108 SDosage* cur_dphasedelta = nullptr;
6109 uint32_t read_dosage_ct = 0;
6110 uint32_t read_dphase_ct = 0;
6111 if (is_dosage) {
6112 // multiallelic dosage not implemented yet
6113 assert(allele_ct == 2);
6114
6115 // this should have length dependent on dosage_ct
6116 cur_dosagepresent = cur_vrec_end;
6117 cur_dosagevals = R_CAST(Dosage*, &(cur_dosagepresent[raw_sample_ctaw]));
6118 read_dosage_ct = PopcountWords(cur_dosagepresent, raw_sample_ctl);
6119
6120 // temporary
6121 cur_vrec_end = &(cur_vrec_end[dosageraw_word_ct]);
6122
6123 if (is_dphase) {
6124 cur_dphasepresent = cur_vrec_end;
6125 cur_dphasedelta = R_CAST(SDosage*, &(cur_dphasepresent[raw_sample_ctaw]));
6126 read_dphase_ct = PopcountWords(cur_dphasepresent, raw_sample_ctl);
6127
6128 // temporary
6129 cur_vrec_end = &(cur_vrec_end[dosageraw_word_ct]);
6130 }
6131 }
6132 uint32_t write_rare01_ct = 0;
6133 uint32_t write_rare10_ct = 0;
6134 uint32_t write_dosage_ct = 0;
6135 uint32_t write_dphase_ct = 0;
6136 if (old_sample_idx_to_new) {
6137 ZeroTrailingNyps(raw_sample_ct, loadbuf_iter);
6138 GenovecPermuteSubset(loadbuf_iter, sample_include, sample_include_interleaved_vec, old_sample_idx_to_new, raw_sample_ct, sample_ct, write_genovec);
6139 // bugfix (22 Apr 2022): need to pass sample_ct rather than
6140 // raw_sample_ct to these functions.
6141 if (read_rare01_ct) {
6142 write_rare01_ct = CopyAndPermute8bit(sample_include, read_patch_01_set, read_patch_01_vals, old_sample_idx_to_new, sample_ct, read_rare01_ct, write_patch_01_set, write_patch_01_vals);
6143 }
6144 if (read_rare10_ct) {
6145 write_rare10_ct = CopyAndPermute16bit(sample_include, read_patch_10_set, read_patch_10_vals, old_sample_idx_to_new, sample_ct, read_rare10_ct, write_patch_10_set, write_patch_10_vals);
6146 }
6147 if (is_hphase) {
6148 UnpackAndPermuteHphase(all_hets, cur_phaseraw, sample_include, old_sample_idx_to_new, raw_sample_ct, sample_ct, &cur_write_phasepresent, write_phaseinfo);
6149 }
6150 if (is_dosage) {
6151 write_dosage_ct = CopyAndPermute16bit(sample_include, cur_dosagepresent, cur_dosagevals, old_sample_idx_to_new, sample_ct, read_dosage_ct, write_dosagepresent, write_dosagevals);
6152 if (is_dphase) {
6153 write_dphase_ct = CopyAndPermute16bit(sample_include, cur_dphasepresent, cur_dphasedelta, old_sample_idx_to_new, sample_ct, read_dphase_ct, write_dphasepresent, write_dphasedeltas);
6154 }
6155 }
6156 } else if (sample_include) {
6157 CopyNyparrNonemptySubset(loadbuf_iter, sample_include, raw_sample_ct, sample_ct, write_genovec);
6158 if (is_mhc) {
6159 write_rare01_ct = Copy1bit8Subset(read_patch_01_set, read_patch_01_vals, sample_include, read_rare01_ct, sample_ct, write_patch_01_set, write_patch_01_vals);
6160 write_rare10_ct = Copy1bit16Subset(read_patch_10_set, read_patch_10_vals, sample_include, read_rare10_ct, sample_ct, write_patch_10_set, write_patch_10_vals);
6161 }
6162 if (is_hphase) {
6163 UnpackHphaseSubset(all_hets, cur_phaseraw, sample_include, sample_ct, &cur_write_phasepresent, write_phaseinfo);
6164 }
6165 if (is_dosage) {
6166 write_dosage_ct = Copy1bit16Subset(cur_dosagepresent, cur_dosagevals, sample_include, read_dosage_ct, sample_ct, write_dosagepresent, write_dosagevals);
6167 if (is_dphase) {
6168 write_dphase_ct = Copy1bit16Subset(cur_dphasepresent, cur_dphasedelta, sample_include, read_dphase_ct, sample_ct, write_dphasepresent, write_dphasedeltas);
6169 }
6170 }
6171 } else {
6172 // This thread is permitted to mutate the input. But we need to be
6173 // careful about variable-size components like
6174 // write_patch_{01,10}_vals.
6175 write_genovec = loadbuf_iter;
6176 if (is_mhc) {
6177 write_rare01_ct = read_rare01_ct;
6178 write_rare10_ct = read_rare10_ct;
6179 if (!write_allele_permute) {
6180 write_patch_01_set = read_patch_01_set;
6181 write_patch_10_set = read_patch_10_set;
6182 write_patch_01_vals = read_patch_01_vals;
6183 write_patch_10_vals = read_patch_10_vals;
6184 } else {
6185 if (write_rare01_ct) {
6186 memcpy(write_patch_01_set, read_patch_01_set, sample_ctl * sizeof(intptr_t));
6187 memcpy(write_patch_01_vals, read_patch_01_vals, sizeof(AlleleCode) * write_rare01_ct);
6188 } else {
6189 ZeroWArr(sample_ctl, write_patch_01_set);
6190 }
6191 if (write_rare10_ct) {
6192 memcpy(write_patch_10_set, read_patch_10_set, sample_ctl * sizeof(intptr_t));
6193 memcpy(write_patch_10_vals, read_patch_10_vals, 2 * sizeof(AlleleCode) * write_rare10_ct);
6194 } else {
6195 ZeroWArr(sample_ctl, write_patch_10_set);
6196 }
6197 }
6198 }
6199 if (is_hphase) {
6200 UnpackHphase(all_hets, cur_phaseraw, sample_ct, &cur_write_phasepresent, write_phaseinfo);
6201 }
6202 if (is_dosage) {
6203 CopyDosage(cur_dosagepresent, cur_dosagevals, sample_ct, read_dosage_ct, write_dosagepresent, write_dosagevals, &write_dosage_ct);
6204 if (is_dphase) {
6205 CopyDosage(cur_dphasepresent, R_CAST(Dosage*, cur_dphasedelta), sample_ct, read_dphase_ct, write_dphasepresent, R_CAST(Dosage*, write_dphasedeltas), &write_dphase_ct);
6206 }
6207 }
6208 }
6209 // multiallelic -> biallelic split:
6210 // main thread will probably compute split mapping in advance (bitarray
6211 // with filtered-and-split variant indices, set bit = unsplit variant
6212 // or last variant in a split group)? same pre-split variant can be
6213 // loaded multiple times.
6214 // biallelic -> multiallelic merge:
6215 // could require no multiallelic variants in remainder of dataset?
6216 // if handled with pgenlib, PgfiMultiread,
6217 // PgfiMultireadGetCachelineReq, and PgrGetRaw would need to be
6218 // extended to take a merge-info parameter. +both will be tricky...
6219 // probably not worth it.
6220 // compute merge pattern in MakePgenRobust() before main loop instead.
6221 // main thread also performs the actual merge.
6222 // both should require sorted .pvar.
6223 // neither should require any handling in this function.
6224 if (write_allele_permute) {
6225 const AlleleCode* cur_write_allele_permute = &(write_allele_permute[write_allele_idx_offset_base]);
6226 uint32_t allele_order_changed = 0;
6227 for (uint32_t aidx = 0; aidx != allele_ct; ++aidx) {
6228 if (cur_write_allele_permute[aidx] != aidx) {
6229 allele_order_changed = 1;
6230 break;
6231 }
6232 }
6233 if (allele_order_changed) {
6234 if (allele_ct == 2) {
6235 GenovecInvertUnsafe(sample_ct, write_genovec);
6236 if (is_hphase) {
6237 // trailing bits don't matter
6238 BitvecInvert(sample_ctl, write_phaseinfo);
6239 }
6240 if (write_dosage_ct) {
6241 BiallelicDosage16Invert(write_dosage_ct, write_dosagevals);
6242 if (write_dphase_ct) {
6243 BiallelicDphase16Invert(write_dphase_ct, write_dphasedeltas);
6244 }
6245 }
6246 } else {
6247 // cur_write_allele_permute[write_aidx] is read_aidx. Invert.
6248 for (uint32_t write_aidx = 0; write_aidx != allele_ct; ++write_aidx) {
6249 const uint32_t read_aidx = cur_write_allele_permute[write_aidx];
6250 ac_remap[read_aidx] = write_aidx;
6251 }
6252 PglMultiallelicSparseToDense(write_genovec, write_patch_01_set, write_patch_01_vals, write_patch_10_set, write_patch_10_vals, ac_remap, sample_ct, write_rare01_ct, write_rare10_ct, ac_flipped, ac_rotate);
6253 if (is_hphase) {
6254 BitvecXor(ac_flipped, sample_ctl, write_phaseinfo);
6255 }
6256 PglMultiallelicDenseToSparse(ac_rotate, sample_ct, write_genovec, write_patch_01_set, write_patch_01_vals, write_patch_10_set, write_patch_10_vals, &write_rare01_ct, &write_rare10_ct);
6257 }
6258 }
6259 }
6260 if (write_dosage_ct) {
6261 assert((!write_rare01_ct) && (!write_rare10_ct));
6262 if (hard_call_halfdist || fill_missing_from_dosage || (dosage_erase_halfdist < kDosage4th)) {
6263 if (is_hphase && (!cur_write_phasepresent)) {
6264 // explicit phasepresent required for these
6265 cur_write_phasepresent = write_phasepresent;
6266 // unsafe to just copy all_hets, because we may have resorted
6267 // todo: multiallelic dosage
6268 PgrDetectGenoarrHets(write_genovec, sample_ct, write_phasepresent);
6269 }
6270 if (write_dphasepresent && is_hphase && (!write_dphase_ct)) {
6271 // bugfix (29 Apr 2019): write_dphasepresent not guaranteed to be
6272 // non-null.
6273 ZeroWArr(sample_ctl, write_dphasepresent);
6274 }
6275 if (hard_call_halfdist) {
6276 if ((!is_hphase) && (!write_dphase_ct)) {
6277 ApplyHardCallThresh(write_dosagepresent, write_dosagevals, write_dosage_ct, hard_call_halfdist, write_genovec);
6278 } else {
6279 if (!is_hphase) {
6280 ZeroWArr(sample_ctl, write_phasepresent);
6281 }
6282 write_dphase_ct = ApplyHardCallThreshPhased(write_dosagepresent, write_dosagevals, write_dosage_ct, hard_call_halfdist, write_genovec, write_phasepresent, write_phaseinfo, write_dphasepresent, write_dphasedeltas, tmp_dphasedeltas);
6283 is_hphase = !AllWordsAreZero(write_phasepresent, sample_ctl);
6284 }
6285 }
6286 if (fill_missing_from_dosage) {
6287 if ((!is_hphase) && (!write_dphase_ct)) {
6288 FillMissingFromBiallelicDosage(write_dosagepresent, write_dosagevals, write_dosage_ct, write_genovec);
6289 } else {
6290 if (!is_hphase) {
6291 ZeroWArr(sample_ctl, write_phasepresent);
6292 }
6293 write_dphase_ct = FillMissingFromBiallelicDosagePhased(write_dosagepresent, write_dosagevals, write_dosage_ct, write_genovec, write_phasepresent, write_phaseinfo, write_dphasepresent, write_dphasedeltas);
6294 is_hphase = !AllWordsAreZero(write_phasepresent, sample_ctl);
6295 }
6296 }
6297 if (dosage_erase_halfdist < kDosage4th) {
6298 if (!is_hphase) {
6299 ZeroWArr(sample_ctl, write_phasepresent);
6300 }
6301 uint32_t dosage_read_idx = 0;
6302 uintptr_t sample_widx = 0;
6303 uintptr_t cur_bits = write_dosagepresent[0];
6304 uint32_t dosage_write_idx;
6305 if (!write_dphase_ct) {
6306 // If hardcall-phase and dosage present, threshold/2 applies
6307 // thanks to implicit dosage-phase value
6308 // const uint32_t dosage_erase_halfdist2 = (dosage_erase_halfdist + kDosage4th + 1) / 2;
6309 const uint32_t halfdist_extra = (kDosage4th + 1 - dosage_erase_halfdist) / 2;
6310 for (; dosage_read_idx != write_dosage_ct; ++dosage_read_idx) {
6311 const uint32_t sample_uidx_lowbits = BitIter1x(write_dosagepresent, &sample_widx, &cur_bits);
6312 const uint32_t dosage_int = write_dosagevals[dosage_read_idx];
6313 const uint32_t halfdist = BiallelicDosageHalfdist(dosage_int);
6314 if (halfdist >= dosage_erase_halfdist + ((write_phasepresent[sample_widx] >> sample_uidx_lowbits) & 1) * halfdist_extra) {
6315 write_dosagepresent[sample_widx] ^= k1LU << sample_uidx_lowbits;
6316 break;
6317 }
6318 }
6319 dosage_write_idx = dosage_read_idx;
6320 while (++dosage_read_idx < write_dosage_ct) {
6321 const uint32_t sample_uidx_lowbits = BitIter1x(write_dosagepresent, &sample_widx, &cur_bits);
6322 const uint32_t dosage_int = write_dosagevals[dosage_read_idx];
6323 const uint32_t halfdist = BiallelicDosageHalfdist(dosage_int);
6324 if (halfdist < dosage_erase_halfdist + ((write_phasepresent[sample_widx] >> sample_uidx_lowbits) & 1) * halfdist_extra) {
6325 write_dosagevals[dosage_write_idx++] = dosage_int;
6326 } else {
6327 write_dosagepresent[sample_widx] ^= k1LU << sample_uidx_lowbits;
6328 }
6329 }
6330 } else {
6331 // Only erase dosage if both sides are less than threshold/2
6332 // away from an integer.
6333 const uint32_t halfdist_extra = (kDosage4th + 1 - dosage_erase_halfdist) / 2;
6334 const uint32_t dosage_erase_halfdist2 = dosage_erase_halfdist + halfdist_extra;
6335 uint32_t dphase_read_idx = 0;
6336 uintptr_t lowbit = 0;
6337 for (; dosage_read_idx != write_dosage_ct; ++dosage_read_idx) {
6338 lowbit = BitIter1y(write_dosagepresent, &sample_widx, &cur_bits);
6339 const uint32_t dosage_int = write_dosagevals[dosage_read_idx];
6340 if (!(write_dphasepresent[sample_widx] & lowbit)) {
6341 // necessary for this to be separate to handle odd
6342 // dosage_int, missing phase case correctly
6343 const uint32_t halfdist = BiallelicDosageHalfdist(dosage_int);
6344 if (halfdist >= dosage_erase_halfdist + ((write_phasepresent[sample_widx] & lowbit) != 0) * halfdist_extra) {
6345 break;
6346 }
6347 } else {
6348 const int32_t dphase_delta = write_dphasedeltas[dphase_read_idx++];
6349 const uint32_t halfdist1 = HaploidDosageHalfdist((dosage_int + dphase_delta) >> 1);
6350 const uint32_t halfdist2 = HaploidDosageHalfdist((dosage_int - dphase_delta) >> 1);
6351 if ((halfdist1 >= dosage_erase_halfdist2) && (halfdist2 >= dosage_erase_halfdist2)) {
6352 break;
6353 }
6354 }
6355 }
6356 dosage_write_idx = dosage_read_idx;
6357 if (dosage_read_idx < write_dosage_ct) {
6358 uint32_t dphase_write_idx = dphase_read_idx;
6359 if (write_dphasepresent[sample_widx] & lowbit) {
6360 --dphase_write_idx;
6361 write_dphasepresent[sample_widx] ^= lowbit;
6362 }
6363 write_dosagepresent[sample_widx] ^= lowbit;
6364 while (++dosage_read_idx < write_dosage_ct) {
6365 lowbit = BitIter1y(write_dosagepresent, &sample_widx, &cur_bits);
6366 const uint32_t dosage_int = write_dosagevals[dosage_read_idx];
6367 if (!(write_dphasepresent[sample_widx] & lowbit)) {
6368 const uint32_t halfdist = BiallelicDosageHalfdist(dosage_int);
6369 if (halfdist < dosage_erase_halfdist + ((write_phasepresent[sample_widx] & lowbit) != 0) * halfdist_extra) {
6370 write_dosagevals[dosage_write_idx++] = dosage_int;
6371 } else {
6372 write_dosagepresent[sample_widx] ^= lowbit;
6373 }
6374 } else {
6375 const int32_t dphase_delta = write_dphasedeltas[dphase_read_idx++];
6376 const uint32_t halfdist1 = HaploidDosageHalfdist((dosage_int + dphase_delta) >> 1);
6377 const uint32_t halfdist2 = HaploidDosageHalfdist((dosage_int - dphase_delta) >> 1);
6378 if ((halfdist1 < dosage_erase_halfdist2) || (halfdist2 < dosage_erase_halfdist2)) {
6379 write_dosagevals[dosage_write_idx++] = dosage_int;
6380 write_dphasedeltas[dphase_write_idx++] = dphase_delta;
6381 } else {
6382 write_dosagepresent[sample_widx] ^= lowbit;
6383 write_dphasepresent[sample_widx] ^= lowbit;
6384 }
6385 }
6386 }
6387 write_dphase_ct = dphase_write_idx;
6388 }
6389 }
6390 write_dosage_ct = dosage_write_idx;
6391 }
6392 }
6393 if (late_dosage_erase) {
6394 write_dosage_ct = 0;
6395 write_dphase_ct = 0;
6396 }
6397 }
6398 // moved after --hard-call-threshold, since it makes sense to
6399 // immediately erase fresh het haploid calls
6400 if (set_invalid_haploid_missing && is_haploid_nonmt) {
6401 if (is_x) {
6402 EraseMaleDphases(sex_male_collapsed, &write_dphase_ct, write_dphasepresent, write_dphasedeltas);
6403 if (!set_invalid_haploid_missing_keep_dosage) {
6404 // need to erase dosages associated with the hardcalls we're
6405 // about to clear
6406
6407 // male 0/x hets to missing
6408 SetMaleHetMissingCleardosage(sex_male_collapsed, sex_male_collapsed_interleaved, sample_ctv2, write_genovec, &write_dosage_ct, write_dosagepresent, write_dosagevals);
6409 // male x/y hets to missing
6410 if (write_rare10_ct) {
6411 uintptr_t sample_widx = 0;
6412 uintptr_t patch_10_bits = write_patch_10_set[0];
6413 uint32_t read_patch_10_idx = 0;
6414 for (; read_patch_10_idx != write_rare10_ct; ++read_patch_10_idx) {
6415 uintptr_t lowbit = BitIter1y(write_patch_10_set, &sample_widx, &patch_10_bits);
6416 AlleleCode lo_code = write_patch_10_vals[read_patch_10_idx * 2];
6417 AlleleCode hi_code = write_patch_10_vals[read_patch_10_idx * 2 + 1];
6418 if ((sex_male_collapsed[sample_widx] & lowbit) && (lo_code != hi_code)) {
6419 write_patch_10_set[sample_widx] ^= lowbit;
6420 uint32_t write_patch_10_idx = read_patch_10_idx;
6421 ++read_patch_10_idx;
6422 for (; read_patch_10_idx != write_rare10_ct; ++read_patch_10_idx) {
6423 lowbit = BitIter1y(write_patch_10_set, &sample_widx, &patch_10_bits);
6424 lo_code = write_patch_10_vals[read_patch_10_idx * 2];
6425 hi_code = write_patch_10_vals[read_patch_10_idx * 2 + 1];
6426 if ((sex_male_collapsed[sample_widx] & lowbit) && (lo_code != hi_code)) {
6427 write_patch_10_set[sample_widx] ^= lowbit;
6428 } else {
6429 write_patch_10_vals[write_patch_10_idx * 2] = lo_code;
6430 write_patch_10_vals[write_patch_10_idx * 2 + 1] = hi_code;
6431 ++write_patch_10_idx;
6432 }
6433 }
6434 write_rare10_ct = write_patch_10_idx;
6435 break;
6436 }
6437 }
6438 }
6439 } else {
6440 assert(!write_rare01_ct);
6441 assert(!write_rare10_ct);
6442 // need to generate a new unphased dosage for each cleared
6443 // hardcall lacking a dosage entry
6444 SetMaleHetMissingKeepdosage(sex_male_collapsed, sex_male_collapsed_interleaved, sample_ctl2, write_genovec, &write_dosage_ct, write_dosagepresent, write_dosagevals);
6445 }
6446 if (is_hphase && cur_write_phasepresent) {
6447 // bugfix (28 Jul 2018): I was on crack when I moved this code
6448 // before SetMaleHetMissing{Clear,Keep}dosage() on 31 Mar
6449 if (!write_rare10_ct) {
6450 MaskGenoarrHetsUnsafe(write_genovec, sample_ctl2, cur_write_phasepresent);
6451 } else {
6452 MaskGenoarrHetsMultiallelicUnsafe(write_genovec, write_patch_10_set, write_patch_10_vals, sample_ctl2, cur_write_phasepresent);
6453 }
6454 is_hphase = !AllWordsAreZero(write_phasepresent, sample_ctl);
6455 }
6456 if (write_rare01_ct) {
6457 ClearGenoarrMissing1bit8Unsafe(write_genovec, &write_rare01_ct, write_patch_01_set, write_patch_01_vals);
6458 }
6459 if (write_rare10_ct) {
6460 ClearGenoarrMissing1bit16Unsafe(write_genovec, &write_rare10_ct, write_patch_10_set, write_patch_10_vals);
6461 }
6462 } else {
6463 // all hets to missing
6464 // may want to move is_hphase zeroing in front
6465 if (!set_invalid_haploid_missing_keep_dosage) {
6466 SetHetMissingCleardosage(sample_ctl2, write_genovec, &write_dosage_ct, write_dosagepresent, write_dosagevals);
6467 } else {
6468 SetHetMissingKeepdosage(sample_ctl2, write_genovec, &write_dosage_ct, write_dosagepresent, write_dosagevals);
6469 }
6470 if (is_y) {
6471 InterleavedSetMissingCleardosage(sex_female_collapsed, sex_female_collapsed_interleaved, sample_ctv2, write_genovec, &write_dosage_ct, write_dosagepresent, write_dosagevals);
6472 }
6473 is_hphase = 0;
6474 write_rare01_ct = 0;
6475 if (write_rare10_ct) {
6476 ClearGenoarrMissing1bit16Unsafe(write_genovec, &write_rare10_ct, write_patch_10_set, write_patch_10_vals);
6477 }
6478 write_dphase_ct = 0;
6479 }
6480 } else if (set_mixed_mt_missing && is_mt) {
6481 if (!set_mixed_mt_missing_keep_dosage) {
6482 // all hets to missing
6483 SetHetMissingCleardosage(sample_ctl2, write_genovec, &write_dosage_ct, write_dosagepresent, write_dosagevals);
6484 } else {
6485 SetHetMissingKeepdosage(sample_ctl2, write_genovec, &write_dosage_ct, write_dosagepresent, write_dosagevals);
6486 }
6487 is_hphase = 0;
6488 write_rare01_ct = 0;
6489 if (write_rare10_ct) {
6490 ClearGenoarrMissing1bit16Unsafe(write_genovec, &write_rare10_ct, write_patch_10_set, write_patch_10_vals);
6491 }
6492 write_dphase_ct = 0;
6493 }
6494 ZeroTrailingNyps(sample_ct, write_genovec);
6495 // todo: --set-me-missing, --zero-cluster, --fill-missing-with-ref
6496 if (spgwp) {
6497 if (pwcp->fwrite_bufp >= &(pwcp->fwrite_buf[kPglFwriteBlockSize])) {
6498 const uintptr_t cur_byte_ct = pwcp->fwrite_bufp - pwcp->fwrite_buf;
6499 if (unlikely(fwrite_checked(pwcp->fwrite_buf, cur_byte_ct, GET_PRIVATE(*spgwp, pgen_outfile)))) {
6500 ctx->write_reterr = kPglRetWriteFail;
6501 ctx->write_errno = errno;
6502 break;
6503 }
6504 // printf("vblock_fpos_offset: %llu\n", pwcp->vblock_fpos_offset);
6505 pwcp->vblock_fpos_offset += cur_byte_ct;
6506 // printf("%u %llu\n", write_idx + variant_idx_offset, pwcp->vblock_fpos_offset);
6507 pwcp->fwrite_bufp = pwcp->fwrite_buf;
6508 }
6509 }
6510 if ((!write_rare01_ct) && (!write_rare10_ct)) {
6511 if ((!is_hphase) && (!write_dphase_ct)) {
6512 if (unlikely(PwcAppendBiallelicGenovecDosage16(write_genovec, write_dosagepresent, write_dosagevals, write_dosage_ct, pwcp))) {
6513 ctx->write_reterr = kPglRetVarRecordTooLarge;
6514 break;
6515 }
6516 } else {
6517 if (!is_hphase) {
6518 ZeroWArr(sample_ctl, write_phasepresent);
6519 }
6520 // extraneous phaseinfo bits may be set
6521 if (unlikely(PwcAppendBiallelicGenovecDphase16(write_genovec, cur_write_phasepresent, write_phaseinfo, write_dosagepresent, write_dphasepresent, write_dosagevals, write_dphasedeltas, write_dosage_ct, write_dphase_ct, pwcp))) {
6522 ctx->write_reterr = kPglRetVarRecordTooLarge;
6523 break;
6524 }
6525 }
6526 } else {
6527 // multiallelic dosage not supported
6528 if (!is_hphase) {
6529 if (unlikely(PwcAppendMultiallelicSparse(write_genovec, write_patch_01_set, write_patch_01_vals, write_patch_10_set, write_patch_10_vals, allele_ct, write_rare01_ct, write_rare10_ct, pwcp))) {
6530 ctx->write_reterr = kPglRetVarRecordTooLarge;
6531 break;
6532 }
6533 } else {
6534 if (unlikely(PwcAppendMultiallelicGenovecHphase(write_genovec, write_patch_01_set, write_patch_01_vals, write_patch_10_set, write_patch_10_vals, cur_write_phasepresent, write_phaseinfo, allele_ct, write_rare01_ct, write_rare10_ct, pwcp))) {
6535 ctx->write_reterr = kPglRetVarRecordTooLarge;
6536 break;
6537 }
6538 }
6539 }
6540 loadbuf_iter = cur_vrec_end;
6541 }
6542 parity = 1 - parity;
6543 variant_idx_offset += cur_block_write_ct;
6544 } while (!THREAD_BLOCK_FINISH(arg));
6545 THREAD_RETURN;
6546 }
6547
6548 void SplitNonrefFlags() {
6549 logerrputs("Provisional-reference flag split is not implemented yet.\n");
6550 exit(S_CAST(int32_t, kPglRetNotYetSupported));
6551 }
6552
6553 void JoinNonrefFlags() {
6554 logerrputs("Provisional-reference flag join is not implemented yet.\n");
6555 exit(S_CAST(int32_t, kPglRetNotYetSupported));
6556 }
6557
6558 // Single-output-thread implementation. Allows variants to be unsorted.
6559 // (Note that MakePlink2NoVsort() currently requires enough memory for 64k * 2
6560 // variants per output thread, due to LD compression. This is faster in the
6561 // common case, but once you have 150k+ samples with dosage data...)
6562 //
6563 // initialized mcp fields: cip, sex_male_collapsed_interleaved,
6564 // sex_female_collapsed_interleaved, write_allele_permute, raw_sample_ct,
6565 // sample_ct, plink2_write_flags
6566 PglErr MakePgenRobust(const uintptr_t* sample_include, const uint32_t* new_sample_idx_to_old, const uintptr_t* variant_include, const uintptr_t* allele_idx_offsets, __maybe_unused const uintptr_t* allele_presents, const uintptr_t* write_allele_idx_offsets, const uint32_t* new_variant_idx_to_old, const uintptr_t* sex_male_collapsed, const uintptr_t* sex_female_collapsed, const char* writer_ver, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t write_variant_ct, uint32_t max_read_allele_ct, uint32_t hard_call_thresh, uint32_t dosage_erase_thresh, MakePlink2Flags make_plink2_flags, MakeCommon* mcp, PgenReader* simple_pgrp, char* outname, char* outname_end) {
6567 // variant_uidx_new_to_old[] can be nullptr
6568
6569 unsigned char* bigstack_mark = g_bigstack_base;
6570 PglErr reterr = kPglRetSuccess;
6571 ThreadGroup tg;
6572 PreinitThreads(&tg);
6573 STPgenWriter spgw;
6574 PreinitSpgw(&spgw);
6575 PgenExtensionLl ext_slot; // shouldn't have shorter lifetime than spgw
6576 MakePgenCtx ctx;
6577 {
6578 // plink2_write_flags assumed to include --set-hh-missing and
6579 // --set-mixed-mt-missing
6580 // sex_{fe}male_collapsed_interleaved assumed to be initialized if
6581 // necessary
6582
6583 if (unlikely(SetThreadCt(1, &tg))) {
6584 goto MakePgenRobust_ret_NOMEM;
6585 }
6586 ctx.spgwp = &spgw;
6587 const uint32_t raw_sample_ct = mcp->raw_sample_ct;
6588 const uint32_t sample_ct = mcp->sample_ct;
6589 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
6590 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
6591 mcp->sample_include = subsetting_required? sample_include : nullptr;
6592 ctx.sex_male_collapsed = sex_male_collapsed;
6593 ctx.sex_female_collapsed = sex_female_collapsed;
6594 ctx.write_reterr = kPglRetSuccess;
6595 if ((make_plink2_flags & kfMakeBed) || ((make_plink2_flags & (kfMakePgen | (kfMakePgenFormatBase * 3))) == (kfMakePgen | kfMakePgenFormatBase))) {
6596 logerrputs("Error: Fixed-width .bed/.pgen output doesn't support sorting yet. Generate a\nregular sorted .pgen first, and then reformat it.\n");
6597 reterr = kPglRetNotYetSupported;
6598 goto MakePgenRobust_ret_1;
6599 } else {
6600 const uint32_t input_biallelic = (!allele_idx_offsets);
6601 // output_biallelic: test write_allele_idx_offsets equality to null
6602 ctx.write_allele_idx_offsets = write_allele_idx_offsets;
6603 if ((variant_ct == raw_variant_ct) || new_variant_idx_to_old) {
6604 ctx.write_chr_fo_vidx_start = mcp->cip->chr_fo_vidx_start;
6605 } else {
6606 if (unlikely(AllocAndFillSubsetChrFoVidxStart(variant_include, mcp->cip, &ctx.write_chr_fo_vidx_start))) {
6607 goto MakePgenRobust_ret_NOMEM;
6608 }
6609 }
6610 PgenGlobalFlags read_gflags = PgrGetGflags(simple_pgrp) & (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent);
6611 if (make_plink2_flags & (kfMakePlink2MJoin | kfMakePlink2EraseAlt2Plus)) {
6612 logerrputs("Error: multiallelic-join and 'erase-alt2+' modifiers are under development.\n");
6613 reterr = kPglRetNotYetSupported;
6614 goto MakePgenRobust_ret_1;
6615 }
6616 if (make_plink2_flags & kfMakePgenErasePhase) {
6617 read_gflags &= ~(kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePhasePresent);
6618 }
6619 const uint32_t fill_missing_from_dosage = (make_plink2_flags & kfMakePgenFillMissingFromDosage) && (read_gflags & kfPgenGlobalDosagePresent);
6620 if (fill_missing_from_dosage) {
6621 mcp->plink2_write_flags |= kfPlink2WriteFillMissingFromDosage;
6622 }
6623 if (make_plink2_flags & kfMakePgenEraseDosage) {
6624 if ((hard_call_thresh == UINT32_MAX) && (!fill_missing_from_dosage)) {
6625 read_gflags &= ~(kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent);
6626 } else {
6627 // bugfix (11 Apr 2018): this was in the wrong branch
6628 mcp->plink2_write_flags |= kfPlink2WriteLateDosageErase;
6629 }
6630 }
6631 if (read_gflags && (variant_ct < raw_variant_ct)) {
6632 read_gflags &= GflagsVfilter(variant_include, PgrGetVrtypes(simple_pgrp), raw_variant_ct, PgrGetGflags(simple_pgrp));
6633 }
6634 if (!input_biallelic) {
6635 // todo: conditional erase-alt2+ exception
6636 read_gflags |= kfPgenGlobalMultiallelicHardcallFound;
6637 }
6638 const uint32_t read_dosage_present = (read_gflags / kfPgenGlobalDosagePresent) & 1;
6639 // bugfix (25 Jul 2018): left expression needs ||, not &&
6640 mcp->hard_call_halfdist = ((hard_call_thresh == UINT32_MAX) || (!read_dosage_present))? 0 : (kDosage4th - hard_call_thresh);
6641 ctx.dosage_erase_halfdist = kDosage4th - dosage_erase_thresh;
6642 // bugfix/simplification (10 Mar 2020): it is possible for dosage-phase
6643 // to be present in the input without hardcall-phase. Don't try to treat
6644 // that differently than the usual scenario where hardcall-phase is
6645 // present.
6646 const uint32_t read_phase_present = !!(read_gflags & (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePhasePresent));
6647 const uint32_t read_dphase_present = (read_gflags / kfPgenGlobalDosagePhasePresent) & 1;
6648 PgenGlobalFlags write_gflags = read_gflags;
6649 // When --hard-call-threshold is specified, if either hphase or dphase
6650 // values exist, the other can be generated.
6651 uint32_t read_or_write_phase_present = read_phase_present;
6652 uint32_t read_or_write_dphase_present = read_dphase_present;
6653 if ((mcp->hard_call_halfdist || fill_missing_from_dosage) && (read_phase_present || read_or_write_dphase_present)) {
6654 read_or_write_phase_present = 1;
6655 read_or_write_dphase_present = 1;
6656 write_gflags |= kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePhasePresent;
6657 } else if (dosage_erase_thresh && read_dosage_present) {
6658 // need write_phasepresent, pretty harmless to allocate write_phaseinfo
6659 read_or_write_phase_present = 1;
6660 }
6661 uint32_t read_or_write_dosage_present = read_dosage_present;
6662 if (mcp->plink2_write_flags & kfPlink2WriteLateDosageErase) {
6663 write_gflags &= ~(kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent);
6664 } else if (mcp->plink2_write_flags & (kfPlink2WriteSetInvalidHaploidMissingKeepDosage | kfPlink2WriteSetMixedMtMissingKeepDosage)) {
6665 // bugfix (25 Jul 2018): this needs to check plink2_write_flags, not
6666 // make_plink2_flags
6667
6668 // command-line parser guarantees erase-dosage and
6669 // --set-hh-missing/--set-mixed-mt-missing keep-dosage aren't used
6670 // together
6671 read_or_write_dosage_present = 1;
6672
6673 // could verify at least one het haploid is present before setting this
6674 // flag...
6675 write_gflags |= kfPgenGlobalDosagePresent;
6676 }
6677 if ((write_gflags & (kfPgenGlobalMultiallelicHardcallFound | kfPgenGlobalDosagePresent)) == (kfPgenGlobalMultiallelicHardcallFound | kfPgenGlobalDosagePresent)) {
6678 logerrputs("Error: Multiallelic dosages aren't supported yet.\n");
6679 reterr = kPglRetNotYetSupported;
6680 goto MakePgenRobust_ret_1;
6681 }
6682
6683 uint32_t nonref_flags_storage = 3;
6684 uintptr_t* nonref_flags_write = PgrGetNonrefFlags(simple_pgrp);
6685 if (!nonref_flags_write) {
6686 nonref_flags_storage = (PgrGetGflags(simple_pgrp) & kfPgenGlobalAllNonref)? 2 : 1;
6687 } else if ((variant_ct < raw_variant_ct) || new_variant_idx_to_old) {
6688 // bugfix (9 Jun 2024): nonref_flags reorder may be necessary when
6689 // variant_ct == raw_variant_ct
6690 const uint32_t write_variant_ctl = BitCtToWordCt(write_variant_ct);
6691 uintptr_t* old_nonref_flags = nonref_flags_write;
6692 if (bigstack_alloc_w(write_variant_ctl, &nonref_flags_write)) {
6693 goto MakePgenRobust_ret_NOMEM;
6694 }
6695 if ((variant_ct == write_variant_ct) && (!new_variant_idx_to_old)) {
6696 CopyBitarrSubset(old_nonref_flags, variant_include, variant_ct, nonref_flags_write);
6697 } else {
6698 ZeroWArr(write_variant_ctl, nonref_flags_write);
6699 if (variant_ct == write_variant_ct) {
6700 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
6701 const uintptr_t variant_uidx = new_variant_idx_to_old[variant_idx];
6702 if (IsSet(old_nonref_flags, variant_uidx)) {
6703 SetBit(variant_idx, nonref_flags_write);
6704 }
6705 }
6706 } else if (!input_biallelic) {
6707 SplitNonrefFlags();
6708 } else {
6709 JoinNonrefFlags();
6710 }
6711 }
6712 if (nonref_flags_write[0] & 1) {
6713 if (AllBitsAreOne(nonref_flags_write, write_variant_ct)) {
6714 BigstackReset(nonref_flags_write);
6715 nonref_flags_write = nullptr;
6716 nonref_flags_storage = 2;
6717 }
6718 } else if (AllWordsAreZero(nonref_flags_write, write_variant_ctl)) {
6719 BigstackReset(nonref_flags_write);
6720 nonref_flags_write = nullptr;
6721 nonref_flags_storage = 1;
6722 }
6723 } else {
6724 if (nonref_flags_write[0] & 1) {
6725 if (AllBitsAreOne(nonref_flags_write, raw_variant_ct)) {
6726 nonref_flags_write = nullptr;
6727 nonref_flags_storage = 2;
6728 }
6729 } else if (AllWordsAreZero(nonref_flags_write, BitCtToWordCt(raw_variant_ct))) {
6730 nonref_flags_write = nullptr;
6731 nonref_flags_storage = 1;
6732 }
6733 }
6734 snprintf(outname_end, kMaxOutfnameExtBlen, ".pgen");
6735 PgenExtensionLl* header_exts = nullptr;
6736 if (writer_ver) {
6737 ext_slot.next = nullptr;
6738 ext_slot.size = strlen(writer_ver);
6739 ext_slot.contents = R_CAST(unsigned char*, K_CAST(char*, writer_ver));
6740 ext_slot.type_idx = 1;
6741 header_exts = &ext_slot;
6742 }
6743 uintptr_t spgw_alloc_cacheline_ct;
6744 uint32_t max_vrec_len;
6745 reterr = SpgwInitPhase1Ex(outname, write_allele_idx_offsets, nonref_flags_write, header_exts, nullptr, write_variant_ct, sample_ct, 0, kPgenWriteBackwardSeek, write_gflags, nonref_flags_storage, ctx.spgwp, &spgw_alloc_cacheline_ct, &max_vrec_len);
6746 if (unlikely(reterr)) {
6747 if (reterr == kPglRetOpenFail) {
6748 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
6749 }
6750 goto MakePgenRobust_ret_1;
6751 }
6752 unsigned char* spgw_alloc;
6753 if (unlikely(bigstack_alloc_wp(1, &(ctx.loadbuf_thread_starts[0])) ||
6754 bigstack_alloc_wp(1, &(ctx.loadbuf_thread_starts[1])) ||
6755 bigstack_alloc_uc(spgw_alloc_cacheline_ct * kCacheline, &spgw_alloc))) {
6756 goto MakePgenRobust_ret_NOMEM;
6757 }
6758 SpgwInitPhase2(max_vrec_len, ctx.spgwp, spgw_alloc);
6759
6760 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
6761 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
6762 ctx.thread_write_genovecs = nullptr;
6763 ctx.old_sample_idx_to_new = nullptr;
6764 ctx.sample_include_interleaved_vec = nullptr;
6765 const AlleleCode* write_allele_permute = mcp->write_allele_permute;
6766 uint32_t write_mhc_needed = write_allele_permute && (!input_biallelic);
6767 if (new_sample_idx_to_old || subsetting_required) {
6768 if (unlikely(bigstack_alloc_wp(1, &ctx.thread_write_genovecs))) {
6769 goto MakePgenRobust_ret_NOMEM;
6770 }
6771 if (new_sample_idx_to_old) {
6772 if (unlikely(bigstack_alloc_u32(raw_sample_ct, &ctx.old_sample_idx_to_new))) {
6773 goto MakePgenRobust_ret_NOMEM;
6774 }
6775 if (subsetting_required) {
6776 const uint32_t raw_sample_ctv = BitCtToVecCt(raw_sample_ct);
6777 if (unlikely(bigstack_alloc_w(raw_sample_ctv * kWordsPerVec, &ctx.sample_include_interleaved_vec))) {
6778 goto MakePgenRobust_ret_NOMEM;
6779 }
6780 FillInterleavedMaskVec(sample_include, raw_sample_ctv, ctx.sample_include_interleaved_vec);
6781 }
6782 for (uint32_t new_sample_idx = 0; new_sample_idx != sample_ct; ++new_sample_idx) {
6783 ctx.old_sample_idx_to_new[new_sample_idx_to_old[new_sample_idx]] = new_sample_idx;
6784 }
6785 }
6786 if (unlikely(bigstack_alloc_w(sample_ctl2, &(ctx.thread_write_genovecs[0])))) {
6787 goto MakePgenRobust_ret_NOMEM;
6788 }
6789 if (!input_biallelic) {
6790 write_mhc_needed = 1;
6791 }
6792 }
6793 ctx.thread_write_mhc = nullptr;
6794 ctx.thread_ac_remap = nullptr;
6795 ctx.thread_ac_rotate = nullptr;
6796 ctx.thread_ac_flipped = nullptr;
6797 if (write_mhc_needed) {
6798 if (unlikely(bigstack_alloc_wp(1, &ctx.thread_write_mhc))) {
6799 goto MakePgenRobust_ret_NOMEM;
6800 }
6801 const uintptr_t mhcwrite_word_ct = GetMhcWordCt(sample_ct);
6802 if (unlikely(bigstack_alloc_w(mhcwrite_word_ct, &(ctx.thread_write_mhc[0])))) {
6803 goto MakePgenRobust_ret_NOMEM;
6804 }
6805 if (write_allele_permute) {
6806 if (unlikely(bigstack_alloc_acp(1, &ctx.thread_ac_remap) ||
6807 bigstack_alloc_acp(1, &ctx.thread_ac_rotate) ||
6808 bigstack_alloc_wp(1, &ctx.thread_ac_flipped) ||
6809 bigstack_alloc_ac(max_read_allele_ct, &(ctx.thread_ac_remap[0])) ||
6810 bigstack_alloc_ac(2 * sample_ct, &(ctx.thread_ac_rotate[0])) ||
6811 bigstack_alloc_w(sample_ctl, &(ctx.thread_ac_flipped[0])))) {
6812 goto MakePgenRobust_ret_NOMEM;
6813 }
6814 }
6815 }
6816 ctx.thread_write_phasepresents = nullptr;
6817 ctx.thread_all_hets = nullptr;
6818 if (read_or_write_phase_present) {
6819 if (unlikely(bigstack_alloc_wp(1, &ctx.thread_write_phasepresents) ||
6820 bigstack_alloc_wp(1, &ctx.thread_write_phaseinfos) ||
6821 bigstack_alloc_w(sample_ctl, &(ctx.thread_write_phasepresents[0])) ||
6822 bigstack_alloc_w(sample_ctl, &(ctx.thread_write_phaseinfos[0])))) {
6823 goto MakePgenRobust_ret_NOMEM;
6824 }
6825 if (read_phase_present) {
6826 if (unlikely(bigstack_alloc_wp(1, &ctx.thread_all_hets) ||
6827 bigstack_alloc_w(raw_sample_ctl, &(ctx.thread_all_hets[0])))) {
6828 goto MakePgenRobust_ret_NOMEM;
6829 }
6830 }
6831 }
6832 ctx.thread_write_dosagepresents = nullptr;
6833 ctx.thread_write_dphasepresents = nullptr;
6834 if (read_or_write_dosage_present) {
6835 if (unlikely(bigstack_alloc_wp(1, &ctx.thread_write_dosagepresents) ||
6836 bigstack_alloc_dosagep(1, &ctx.thread_write_dosagevals) ||
6837 bigstack_alloc_w(sample_ctl, &(ctx.thread_write_dosagepresents[0])) ||
6838 bigstack_alloc_dosage(sample_ct, &(ctx.thread_write_dosagevals[0])))) {
6839 goto MakePgenRobust_ret_NOMEM;
6840 }
6841 if (read_or_write_dphase_present) {
6842 if (unlikely(bigstack_alloc_wp(1, &ctx.thread_write_dphasepresents) ||
6843 bigstack_alloc_dphasep(1, &ctx.thread_write_dphasedeltas) ||
6844 bigstack_alloc_w(sample_ctl, &(ctx.thread_write_dphasepresents[0])) ||
6845 bigstack_alloc_dphase(sample_ct + RoundUpPow2(sample_ct, kCacheline / 2), &(ctx.thread_write_dphasedeltas[0])))) {
6846 goto MakePgenRobust_ret_NOMEM;
6847 }
6848 }
6849 }
6850 ctx.mcp = mcp;
6851 const uint32_t raw_sample_ctl2 = NypCtToWordCt(raw_sample_ct);
6852 PgenVariant pgv;
6853 PreinitPgv(&pgv);
6854 uint32_t* alt_regular_one_cts = nullptr;
6855 uint32_t* alt_invphase_one_cts = nullptr;
6856 uint32_t* alt_two_cts = nullptr;
6857 uint32_t* alt_sample_idx_buf = nullptr;
6858 uint32_t** alt_regular_one_sample_idx_starts = nullptr;
6859 uint32_t** alt_invphase_one_sample_idx_starts = nullptr;
6860 uint32_t** alt_two_sample_idx_starts = nullptr;
6861 if (make_plink2_flags & (kfMakePlink2MSplitBase * 7)) {
6862 // split or join
6863 // this is currently for split with no dosages
6864 if (unlikely(bigstack_alloc_w(raw_sample_ctl2, &pgv.genovec) ||
6865 bigstack_alloc_w(raw_sample_ctl, &pgv.patch_01_set) ||
6866 bigstack_alloc_ac(raw_sample_ct, &pgv.patch_01_vals) ||
6867 bigstack_alloc_w(raw_sample_ctl, &pgv.patch_10_set) ||
6868 bigstack_alloc_ac(2 * raw_sample_ct, &pgv.patch_10_vals) ||
6869 bigstack_alloc_u32(max_read_allele_ct, &alt_regular_one_cts) ||
6870 bigstack_alloc_u32(max_read_allele_ct, &alt_two_cts) ||
6871 bigstack_alloc_u32(2 * raw_sample_ct + 1, &alt_sample_idx_buf) ||
6872 bigstack_alloc_u32p(max_read_allele_ct + 1, &alt_regular_one_sample_idx_starts) ||
6873 bigstack_alloc_u32p(max_read_allele_ct + 1, &alt_two_sample_idx_starts))) {
6874 goto MakePgenRobust_ret_NOMEM;
6875 }
6876 if (read_phase_present) {
6877 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &pgv.phasepresent) ||
6878 bigstack_alloc_w(raw_sample_ctl, &pgv.phaseinfo) ||
6879 bigstack_alloc_u32(max_read_allele_ct, &alt_invphase_one_cts) ||
6880 bigstack_alloc_u32p(max_read_allele_ct + 1, &alt_invphase_one_sample_idx_starts))) {
6881 goto MakePgenRobust_ret_NOMEM;
6882 }
6883 }
6884 if (read_dosage_present) {
6885 logerrputs("Error: Multiallelic dosages aren't supported yet.\n");
6886 reterr = kPglRetNotYetSupported;
6887 goto MakePgenRobust_ret_1;
6888 }
6889 }
6890
6891 const uint32_t raw_sample_ctv2 = NypCtToVecCt(raw_sample_ct);
6892 uintptr_t load_variant_vec_ct = raw_sample_ctv2;
6893 // bugfix (8 Jun 2021): forgot to include multiallelic track in
6894 // load_variant_vec_ct computation
6895 uint32_t loaded_vrtypes_needed = 0;
6896 if (read_gflags & kfPgenGlobalMultiallelicHardcallFound) {
6897 loaded_vrtypes_needed = 1;
6898 // raw format:
6899 // rare01_ct, padded out to a word
6900 // rare10_ct, padded out to a word
6901 // [round up to vector boundary, for patch_01_set]
6902 // aux1a, if not mode 15:
6903 // patch_01_set as bitarray, raw_sample_ctl words
6904 // patch_01_vals (raw_sample_ct * sizeof(AlleleCode)), round up to
6905 // word boundary
6906 // [round up to vector boundary, for patch_10_set]
6907 // aux1b, if not mode 15:
6908 // patch_10_set as bitarray, raw_sample_ctl words
6909 // patch_10_vals (raw_sample_ct * 2 * sizeof(AlleleCode)), round up
6910 // to word boundary
6911 const uintptr_t multiallelic_raw_vec_ct = WordCtToVecCt(2) + WordCtToVecCt(raw_sample_ctl + DivUp(raw_sample_ct * sizeof(AlleleCode), kBytesPerWord)) + WordCtToVecCt(raw_sample_ctl + DivUp(raw_sample_ct * 2 * sizeof(AlleleCode), kBytesPerWord));
6912 load_variant_vec_ct += WordCtToVecCt(multiallelic_raw_vec_ct);
6913 }
6914 if (read_phase_present || read_dosage_present) {
6915 loaded_vrtypes_needed = 1;
6916 if (read_phase_present) {
6917 // phaseraw has three parts:
6918 // 1. het_ct as uint32_t, and explicit_phasepresent_ct as uint32_t.
6919 // 2. vec-aligned bitarray of up to (raw_sample_ct + 1) bits. first
6920 // bit is set iff phasepresent is explicitly stored at all (if
6921 // not, all hets are assumed to be phased), if yes the remaining
6922 // bits store packed phasepresent values for all hets, if no the
6923 // remaining bits store packed phaseinfo values for all hets.
6924 // 3. word-aligned bitarray of up to raw_sample_ct bits, storing
6925 // phaseinfo values. (end of this array is vec-aligned.)
6926 const uintptr_t phaseraw_word_ct = (8 / kBytesPerWord) + kWordsPerVec + RoundDownPow2(raw_sample_ct / kBitsPerWordD2, kWordsPerVec);
6927 load_variant_vec_ct += WordCtToVecCt(phaseraw_word_ct);
6928 }
6929 if (read_dosage_present) {
6930 // biallelic dosageraw has two parts:
6931 // 1. vec-aligned bitarray of up to raw_sample_ct bits, storing which
6932 // samples have dosages.
6933 // 2. word-aligned array of uint16s with 0..32768 fixed-point
6934 // dosages.
6935 // dphaseraw has the same structure, with the uint16s replaced with
6936 // an int16 array of (left - right) values.
6937 const uintptr_t dosageraw_word_ct = kWordsPerVec * (BitCtToVecCt(raw_sample_ct) + DivUp(raw_sample_ct, (kBytesPerVec / sizeof(Dosage))));
6938 load_variant_vec_ct += WordCtToVecCt(dosageraw_word_ct) * (1 + read_dphase_present);
6939 }
6940 }
6941
6942 uintptr_t bytes_left = bigstack_left();
6943 if (unlikely(bytes_left < 7 * kCacheline)) {
6944 goto MakePgenRobust_ret_NOMEM;
6945 }
6946 bytes_left -= 7 * kCacheline; // defend against adverse rounding
6947 uintptr_t ulii = bytes_left / (2 * (kBytesPerVec * load_variant_vec_ct + loaded_vrtypes_needed));
6948 if (unlikely(!ulii)) {
6949 goto MakePgenRobust_ret_NOMEM;
6950 }
6951 if (ulii > MINV(kPglVblockSize, write_variant_ct)) {
6952 ulii = MINV(kPglVblockSize, write_variant_ct);
6953 }
6954 const uint32_t write_block_size = ulii;
6955 uintptr_t* main_loadbufs[2];
6956 main_loadbufs[0] = S_CAST(uintptr_t*, bigstack_alloc_raw_rd(load_variant_vec_ct * kBytesPerVec * write_block_size));
6957 main_loadbufs[1] = S_CAST(uintptr_t*, bigstack_alloc_raw_rd(load_variant_vec_ct * kBytesPerVec * write_block_size));
6958
6959 // todo: multiallelic trim-alts support
6960
6961 if (loaded_vrtypes_needed) {
6962 ctx.loaded_vrtypes[0] = S_CAST(unsigned char*, bigstack_alloc_raw_rd(write_block_size));
6963 ctx.loaded_vrtypes[1] = S_CAST(unsigned char*, bigstack_alloc_raw_rd(write_block_size));
6964 } else {
6965 ctx.loaded_vrtypes[0] = nullptr;
6966 ctx.loaded_vrtypes[1] = nullptr;
6967 }
6968 SetThreadFuncAndData(MakePgenThread, &ctx, &tg);
6969
6970 logprintfww5("Writing %s ... ", outname);
6971 fputs("0%", stdout);
6972 fflush(stdout);
6973
6974 // Main workflow:
6975 // 1. Set n=0, load first write_block_size post-filtering variants
6976 //
6977 // 2. Spawn single thread processing batch n
6978 // 3. Load batch (n+1) unless eof
6979 // 4. Join thread
6980 // 5. Increment n by 1
6981 // 6. Goto step 2 unless eof
6982 const uint32_t* new_variant_idx_to_old_iter = new_variant_idx_to_old;
6983 const uintptr_t* cur_write_allele_idx_offsets = nullptr;
6984 const uint32_t batch_ct_m1 = (write_variant_ct - 1) / write_block_size;
6985 uint32_t pct = 0;
6986 uint32_t parity = 0;
6987 uint32_t cur_batch_size = write_block_size;
6988 uint32_t next_print_write_variant_idx = write_variant_ct / 100;
6989 uint32_t cur_read_allele_ct = 2;
6990 uint32_t cur_write_allele_ct = 2;
6991 uint32_t cur_het_ct = 0;
6992 uintptr_t read_variant_uidx_base = 0;
6993
6994 // now need to retain these across loop iterations in case a split is
6995 // interrupted by batch-end
6996 uint32_t read_variant_uidx = 0;
6997 uint32_t write_aidx = 1;
6998
6999 uintptr_t cur_bits = variant_include[0];
7000 PgrSampleSubsetIndex null_pssi;
7001 PgrClearSampleSubsetIndex(simple_pgrp, &null_pssi);
7002 for (uint32_t read_batch_idx = 0; ; ++read_batch_idx) {
7003 if (!IsLastBlock(&tg)) {
7004 if (read_batch_idx == batch_ct_m1) {
7005 cur_batch_size = write_variant_ct - (read_batch_idx * write_block_size);
7006 }
7007 uintptr_t* cur_loadbuf = main_loadbufs[parity];
7008 uintptr_t* loadbuf_iter = cur_loadbuf;
7009 unsigned char* cur_loaded_vrtypes = ctx.loaded_vrtypes[parity];
7010 ctx.loadbuf_thread_starts[parity][0] = loadbuf_iter;
7011 if (write_allele_idx_offsets) {
7012 cur_write_allele_idx_offsets = &(write_allele_idx_offsets[read_batch_idx * write_block_size]);
7013 }
7014 for (uint32_t block_widx = 0; block_widx != cur_batch_size; ) {
7015 if (write_aidx == 1) {
7016 if (!new_variant_idx_to_old_iter) {
7017 read_variant_uidx = BitIter1(variant_include, &read_variant_uidx_base, &cur_bits);
7018 } else {
7019 read_variant_uidx = *new_variant_idx_to_old_iter++;
7020 }
7021 // todo: multiallelic trim-alts
7022 // todo: multiallelic merge
7023 // split: load to buffer instead of loadbuf_iter, have function
7024 // for writing to loadbuf_iter given buffer contents, this
7025 // should work if split is 'interrupted' by batch boundary
7026 // in middle
7027 // merge: track loadbuf_iter location at beginning of
7028 // same-position block... (finish writing this later)
7029 if (allele_idx_offsets) {
7030 cur_read_allele_ct = allele_idx_offsets[read_variant_uidx + 1] - allele_idx_offsets[read_variant_uidx];
7031 }
7032 }
7033 if (cur_write_allele_idx_offsets) {
7034 cur_write_allele_ct = cur_write_allele_idx_offsets[block_widx + 1] - cur_write_allele_idx_offsets[block_widx];
7035 }
7036 if (cur_read_allele_ct == cur_write_allele_ct) {
7037 reterr = PgrGetRaw(read_variant_uidx, read_gflags, simple_pgrp, &loadbuf_iter, cur_loaded_vrtypes? (&(cur_loaded_vrtypes[block_widx])) : nullptr);
7038 if (unlikely(reterr)) {
7039 PgenErrPrintNV(reterr, read_variant_uidx);
7040 goto MakePgenRobust_ret_1;
7041 }
7042 ++block_widx;
7043 continue;
7044 } else if (cur_write_allele_ct == 2) {
7045 if (write_aidx == 1) {
7046 // 1. read into normal, not raw representation
7047 if (read_phase_present) {
7048 reterr = PgrGetMDp(nullptr, null_pssi, raw_sample_ct, read_variant_uidx, simple_pgrp, &pgv);
7049 } else {
7050 reterr = PgrGetMD(nullptr, null_pssi, raw_sample_ct, read_variant_uidx, simple_pgrp, &pgv);
7051 }
7052 if (unlikely(reterr)) {
7053 PgenErrPrintNV(reterr, read_variant_uidx);
7054 goto MakePgenRobust_ret_1;
7055 }
7056
7057 // 2a. count # of each alt
7058 // 2b. create het and hom lists for each alt
7059 uintptr_t* genovec = pgv.genovec;
7060 ZeroTrailingNyps(raw_sample_ct, genovec);
7061 uint32_t raw_01_ct;
7062 uint32_t raw_10_ct;
7063 GenovecCount12Unsafe(genovec, raw_sample_ct, &raw_01_ct, &raw_10_ct);
7064 ZeroU32Arr(cur_read_allele_ct, alt_regular_one_cts);
7065 alt_regular_one_cts[1] = raw_01_ct - pgv.patch_01_ct;
7066 for (uint32_t rarealt_idx = 0; rarealt_idx != pgv.patch_01_ct; ++rarealt_idx) {
7067 alt_regular_one_cts[pgv.patch_01_vals[rarealt_idx]] += 1;
7068 }
7069 ZeroU32Arr(cur_read_allele_ct, alt_two_cts);
7070 if (!pgv.phasepresent_ct) {
7071 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
7072 const AlleleCode ac0 = pgv.patch_10_vals[2 * uii];
7073 const AlleleCode ac1 = pgv.patch_10_vals[2 * uii + 1];
7074 if (ac0 == ac1) {
7075 alt_two_cts[ac0] += 1;
7076 } else {
7077 alt_regular_one_cts[ac0] += 1;
7078 alt_regular_one_cts[ac1] += 1;
7079 }
7080 }
7081 } else {
7082 ZeroU32Arr(cur_read_allele_ct, alt_invphase_one_cts);
7083 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
7084 const AlleleCode ac0 = pgv.patch_10_vals[2 * uii];
7085 const AlleleCode ac1 = pgv.patch_10_vals[2 * uii + 1];
7086 if (ac0 == ac1) {
7087 alt_two_cts[ac0] += 1;
7088 } else {
7089 alt_invphase_one_cts[ac0] += 1;
7090 alt_regular_one_cts[ac1] += 1;
7091 }
7092 }
7093 }
7094
7095 alt_two_cts[1] = raw_10_ct - pgv.patch_10_ct;
7096 cur_het_ct = raw_01_ct + pgv.patch_10_ct;
7097 for (uint32_t aidx = 2; aidx != cur_read_allele_ct; ++aidx) {
7098 cur_het_ct -= alt_two_cts[aidx];
7099 }
7100
7101 uint32_t* sample_idx_buf_iter = alt_sample_idx_buf;
7102 alt_regular_one_sample_idx_starts[0] = alt_sample_idx_buf;
7103 for (uint32_t aidx = 1; aidx != cur_read_allele_ct; ++aidx) {
7104 alt_regular_one_sample_idx_starts[aidx] = sample_idx_buf_iter;
7105 sample_idx_buf_iter = &(sample_idx_buf_iter[alt_regular_one_cts[aidx]]);
7106 }
7107 alt_regular_one_sample_idx_starts[cur_read_allele_ct] = sample_idx_buf_iter;
7108 if (pgv.phasepresent_ct) {
7109 alt_invphase_one_sample_idx_starts[0] = sample_idx_buf_iter;
7110 for (uint32_t aidx = 1; aidx != cur_read_allele_ct - 1; ++aidx) {
7111 alt_invphase_one_sample_idx_starts[aidx] = sample_idx_buf_iter;
7112 sample_idx_buf_iter = &(sample_idx_buf_iter[alt_invphase_one_cts[aidx]]);
7113 }
7114 alt_invphase_one_sample_idx_starts[cur_read_allele_ct - 1] = sample_idx_buf_iter;
7115 alt_invphase_one_sample_idx_starts[cur_read_allele_ct] = sample_idx_buf_iter;
7116 }
7117 alt_two_sample_idx_starts[0] = sample_idx_buf_iter;
7118 for (uint32_t aidx = 1; aidx != cur_read_allele_ct; ++aidx) {
7119 alt_two_sample_idx_starts[aidx] = sample_idx_buf_iter;
7120 sample_idx_buf_iter = &(sample_idx_buf_iter[alt_two_cts[aidx]]);
7121 }
7122 alt_two_sample_idx_starts[cur_read_allele_ct] = sample_idx_buf_iter;
7123
7124 Halfword* patch_01_set_alias = R_CAST(Halfword*, pgv.patch_01_set);
7125 Halfword* patch_10_set_alias = R_CAST(Halfword*, pgv.patch_10_set);
7126 uint32_t idx_01 = 0;
7127 uint32_t idx_10 = 0;
7128 for (uint32_t widx = 0; widx != raw_sample_ctl2; ++widx) {
7129 const uintptr_t geno_word = genovec[widx];
7130 const uint32_t sample_idx_offset = widx * kBitsPerWordD2;
7131 uintptr_t geno_01 = Word01(geno_word);
7132 if (geno_01) {
7133 if (!pgv.patch_01_ct) {
7134 // patch_01_set not initialized in this case
7135 do {
7136 const uint32_t sample_idx = sample_idx_offset + ctzw(geno_01) / 2;
7137 alt_regular_one_sample_idx_starts[1][0] = sample_idx;
7138 alt_regular_one_sample_idx_starts[1] += 1;
7139 geno_01 &= geno_01 - 1;
7140 } while (geno_01);
7141 } else {
7142 uint32_t geno_01_hw = PackWordToHalfword(geno_01);
7143 const uint32_t patch_01_hw = patch_01_set_alias[widx];
7144 do {
7145 const uint32_t lowbit = geno_01_hw & (-geno_01_hw);
7146 const uint32_t sample_idx = sample_idx_offset + ctzu32(lowbit);
7147 if (lowbit & patch_01_hw) {
7148 AlleleCode ac = pgv.patch_01_vals[idx_01];
7149 alt_regular_one_sample_idx_starts[ac][0] = sample_idx;
7150 alt_regular_one_sample_idx_starts[ac] += 1;
7151 ++idx_01;
7152 } else {
7153 alt_regular_one_sample_idx_starts[1][0] = sample_idx;
7154 alt_regular_one_sample_idx_starts[1] += 1;
7155 }
7156 geno_01_hw ^= lowbit;
7157 } while (geno_01_hw);
7158 }
7159 }
7160 uintptr_t geno_10 = Word10(geno_word);
7161 if (geno_10) {
7162 if (!pgv.patch_10_ct) {
7163 // patch_10_set not initialized in this case
7164 do {
7165 const uint32_t sample_idx = sample_idx_offset + ctzw(geno_10) / 2;
7166 alt_two_sample_idx_starts[1][0] = sample_idx;
7167 alt_two_sample_idx_starts[1] += 1;
7168 geno_10 &= geno_10 - 1;
7169 } while (geno_10);
7170 } else {
7171 uint32_t geno_10_hw = PackWordToHalfword(geno_10);
7172 const uint32_t patch_10_hw = patch_10_set_alias[widx];
7173 if (!pgv.phasepresent_ct) {
7174 do {
7175 const uint32_t lowbit = geno_10_hw & (-geno_10_hw);
7176 const uint32_t sample_idx = sample_idx_offset + ctzu32(lowbit);
7177 if (lowbit & patch_10_hw) {
7178 AlleleCode ac0 = pgv.patch_10_vals[2 * idx_10];
7179 AlleleCode ac1 = pgv.patch_10_vals[2 * idx_10 + 1];
7180 if (ac0 == ac1) {
7181 alt_two_sample_idx_starts[ac0][0] = sample_idx;
7182 alt_two_sample_idx_starts[ac0] += 1;
7183 } else {
7184 alt_regular_one_sample_idx_starts[ac0][0] = sample_idx;
7185 alt_regular_one_sample_idx_starts[ac0] += 1;
7186 alt_regular_one_sample_idx_starts[ac1][0] = sample_idx;
7187 alt_regular_one_sample_idx_starts[ac1] += 1;
7188 }
7189 ++idx_10;
7190 } else {
7191 alt_two_sample_idx_starts[1][0] = sample_idx;
7192 alt_two_sample_idx_starts[1] += 1;
7193 }
7194 geno_10_hw ^= lowbit;
7195 } while (geno_10_hw);
7196 } else {
7197 do {
7198 const uint32_t lowbit = geno_10_hw & (-geno_10_hw);
7199 const uint32_t sample_idx = sample_idx_offset + ctzu32(lowbit);
7200 if (lowbit & patch_10_hw) {
7201 AlleleCode ac0 = pgv.patch_10_vals[2 * idx_10];
7202 AlleleCode ac1 = pgv.patch_10_vals[2 * idx_10 + 1];
7203 if (ac0 == ac1) {
7204 alt_two_sample_idx_starts[ac0][0] = sample_idx;
7205 alt_two_sample_idx_starts[ac0] += 1;
7206 } else {
7207 alt_invphase_one_sample_idx_starts[ac0][0] = sample_idx;
7208 alt_invphase_one_sample_idx_starts[ac0] += 1;
7209 alt_regular_one_sample_idx_starts[ac1][0] = sample_idx;
7210 alt_regular_one_sample_idx_starts[ac1] += 1;
7211 }
7212 ++idx_10;
7213 } else {
7214 alt_two_sample_idx_starts[1][0] = sample_idx;
7215 alt_two_sample_idx_starts[1] += 1;
7216 }
7217 geno_10_hw ^= lowbit;
7218 } while (geno_10_hw);
7219 }
7220 }
7221 }
7222 }
7223 for (uint32_t aidx = cur_read_allele_ct - 1; aidx; --aidx) {
7224 alt_regular_one_sample_idx_starts[aidx] = alt_regular_one_sample_idx_starts[aidx - 1];
7225 alt_two_sample_idx_starts[aidx] = alt_two_sample_idx_starts[aidx - 1];
7226 }
7227 if (pgv.phasepresent_ct) {
7228 for (uint32_t aidx = cur_read_allele_ct - 1; aidx; --aidx) {
7229 alt_invphase_one_sample_idx_starts[aidx] = alt_invphase_one_sample_idx_starts[aidx - 1];
7230 }
7231 }
7232 // todo: multiallelic dosage
7233
7234 for (uint32_t widx = 0; widx != raw_sample_ctl2; ++widx) {
7235 // keep 3s, set 1s and 2s to 0
7236 genovec[widx] = Word11(genovec[widx]) * 3;
7237 }
7238 }
7239 const uint32_t split_stop = MINV(cur_batch_size + 1 - block_widx, cur_read_allele_ct);
7240 for (; write_aidx != split_stop; ++write_aidx, ++block_widx) {
7241 // 3. synthesize raw
7242 // (save to loaded_vrtypes if necessary)
7243 // genovec, vector-aligned
7244 // if hphase present and relevant:
7245 // (compute het_ct; het_ctdl := het_ct / kBitsPerWord)
7246 // (first_half_byte_ct := 1 + (het_ct / CHAR_BIT))
7247 // <uint32 het_ct>
7248 // <uint32 raw_phasepresent_ct if explicit>
7249 // <first_half_byte_ct phasepresent or phaseinfo bytes>
7250 // <0-pad up to word boundary, to make popcount safe>
7251 // [if explicit phasepresent, i.e. lowest bit set:
7252 // (second_half_byte_ct := DivUp(raw_phasepresent_ct, 8))
7253 // <second_half_byte_ct phaseinfo contents>
7254 // ]
7255 // align up to vector boundary
7256 uintptr_t* new_genovec = loadbuf_iter;
7257 memcpy(new_genovec, pgv.genovec, raw_sample_ctl2 * sizeof(intptr_t));
7258 loadbuf_iter = &(loadbuf_iter[raw_sample_ctv2 * kWordsPerVec]);
7259 uint32_t new_phasepresent_ct = 0;
7260 uint32_t new_het_ct = 0;
7261 uint32_t* regular_stop = alt_regular_one_sample_idx_starts[write_aidx + 1];
7262 if (pgv.phasepresent_ct) {
7263 uint32_t* regular_iter = alt_regular_one_sample_idx_starts[write_aidx];
7264 uint32_t* invphase_iter = alt_invphase_one_sample_idx_starts[write_aidx];
7265 uint32_t* invphase_stop = alt_invphase_one_sample_idx_starts[write_aidx + 1];
7266 new_het_ct = (regular_stop - regular_iter) + (invphase_stop - invphase_iter);
7267 if (pgv.phasepresent_ct == cur_het_ct) {
7268 new_phasepresent_ct = new_het_ct;
7269 } else {
7270 uintptr_t* phasepresent = pgv.phasepresent;
7271 for (; regular_iter != regular_stop; ++regular_iter) {
7272 new_phasepresent_ct += IsSet(phasepresent, *regular_iter);
7273 }
7274 for (; invphase_iter != invphase_stop; ++invphase_iter) {
7275 new_phasepresent_ct += IsSet(phasepresent, *invphase_iter);
7276 }
7277 }
7278 }
7279 uint32_t* two_stop = alt_two_sample_idx_starts[write_aidx + 1];
7280 for (uint32_t* two_iter = alt_two_sample_idx_starts[write_aidx]; two_iter != two_stop; ++two_iter) {
7281 const uint32_t sample_uidx = *two_iter;
7282 SetBit(sample_uidx * 2 + 1, new_genovec);
7283 }
7284 uint32_t* regular_iter = alt_regular_one_sample_idx_starts[write_aidx];
7285 if (!new_phasepresent_ct) {
7286 for (; regular_iter != regular_stop; ++regular_iter) {
7287 const uint32_t sample_uidx = *regular_iter;
7288 SetBit(sample_uidx * 2, new_genovec);
7289 }
7290 if (pgv.phasepresent_ct) {
7291 uint32_t* invphase_stop = alt_invphase_one_sample_idx_starts[write_aidx + 1];
7292 for (uint32_t* invphase_iter = alt_invphase_one_sample_idx_starts[write_aidx]; invphase_iter != invphase_stop; ++invphase_iter) {
7293 const uint32_t sample_uidx = *invphase_iter;
7294 SetBit(sample_uidx * 2, new_genovec);
7295 }
7296 }
7297 if (cur_loaded_vrtypes) {
7298 cur_loaded_vrtypes[block_widx] = 0;
7299 }
7300 } else {
7301 // need to write raw hphase
7302 const uint32_t het_ctdl = new_het_ct / kBitsPerWord;
7303 uintptr_t* shifted_part1 = &(loadbuf_iter[8 / kBytesPerWord]);
7304 uintptr_t* part1_end = &(shifted_part1[1 + het_ctdl]);
7305 uint32_t* invphase_iter = alt_invphase_one_sample_idx_starts[write_aidx];
7306 uint32_t* invphase_stop = alt_invphase_one_sample_idx_starts[write_aidx + 1];
7307 const uint32_t orig_regular_end = *regular_stop;
7308 const uint32_t orig_invphase_end = *invphase_stop;
7309 // sentinel value to simplify the next loop.
7310 *invphase_stop = UINT32_MAX;
7311 // must grab this before setting *regular_stop, in case
7312 // they overlap; and after setting *invphase_stop, in case
7313 // this list is empty
7314 uint32_t invphase_idx = *invphase_iter++;
7315
7316 *regular_stop = UINT32_MAX;
7317 uint32_t regular_idx = *regular_iter++;
7318 uint32_t shifted_het_idx = 1;
7319 if (new_phasepresent_ct == new_het_ct) {
7320 loadbuf_iter[0] = new_het_ct;
7321 #ifndef __LP64__
7322 loadbuf_iter[1] = 0;
7323 #endif
7324 // shifted_part1 is phaseinfo
7325 shifted_part1[0] = 0;
7326 shifted_part1[het_ctdl] = 0;
7327 while (regular_idx != invphase_idx) {
7328 uintptr_t is_inverted = (invphase_idx < regular_idx);
7329 uint32_t sample_uidx;
7330 if (is_inverted) {
7331 sample_uidx = invphase_idx;
7332 invphase_idx = *invphase_iter++;
7333 } else {
7334 sample_uidx = regular_idx;
7335 regular_idx = *regular_iter++;
7336 }
7337 SetBit(sample_uidx * 2, new_genovec);
7338 AssignBit(shifted_het_idx, is_inverted ^ IsSet(pgv.phaseinfo, sample_uidx), shifted_part1);
7339 ++shifted_het_idx;
7340 }
7341 assert(shifted_het_idx == new_het_ct + 1);
7342 loadbuf_iter = part1_end;
7343 } else {
7344 #ifdef __LP64__
7345 loadbuf_iter[0] = new_het_ct | (S_CAST(uint64_t, new_phasepresent_ct) << 32);
7346 #else
7347 loadbuf_iter[0] = new_het_ct;
7348 loadbuf_iter[1] = new_phasepresent_ct;
7349 #endif
7350 shifted_part1[0] = 1;
7351 memset(shifted_part1, 0, (1 + het_ctdl) * sizeof(intptr_t));
7352 // shifted_part1 is phasepresent
7353 // part1_end is start of phaseinfo
7354 const uint32_t new_phasepresent_ctl = BitCtToWordCt(new_phasepresent_ct);
7355 part1_end[new_phasepresent_ctl - 1] = 0;
7356 uint32_t phasepresent_idx = 0;
7357 while (regular_idx != invphase_idx) {
7358 uintptr_t is_inverted = (invphase_idx < regular_idx);
7359 uint32_t sample_uidx;
7360 if (is_inverted) {
7361 sample_uidx = invphase_idx;
7362 invphase_idx = *invphase_iter++;
7363 } else {
7364 sample_uidx = regular_idx;
7365 regular_idx = *regular_iter++;
7366 }
7367 SetBit(sample_uidx * 2, new_genovec);
7368 if (IsSet(pgv.phasepresent, sample_uidx)) {
7369 SetBit(shifted_het_idx, shifted_part1);
7370 AssignBit(phasepresent_idx, is_inverted ^ IsSet(pgv.phaseinfo, sample_uidx), part1_end);
7371 ++phasepresent_idx;
7372 }
7373 ++shifted_het_idx;
7374 }
7375 assert(phasepresent_idx == new_phasepresent_ct);
7376 }
7377 assert(regular_idx == UINT32_MAX);
7378 *regular_stop = orig_regular_end;
7379 *invphase_stop = orig_invphase_end;
7380 AlignWToVec(&loadbuf_iter);
7381 if (cur_loaded_vrtypes) {
7382 cur_loaded_vrtypes[block_widx] = 0x10;
7383 }
7384 }
7385 }
7386 if (split_stop != cur_read_allele_ct) {
7387 break;
7388 }
7389 write_aidx = 1;
7390 } else {
7391 // merge; todo
7392 logerrputs("\nnot implemented yet\n");
7393 exit(1);
7394 }
7395 }
7396 }
7397 if (read_batch_idx) {
7398 JoinThreads(&tg);
7399 reterr = ctx.write_reterr;
7400 if (unlikely(reterr)) {
7401 if (reterr == kPglRetWriteFail) {
7402 errno = ctx.write_errno;
7403 }
7404 goto MakePgenRobust_ret_1;
7405 }
7406 }
7407 if (!IsLastBlock(&tg)) {
7408 ctx.cur_block_write_ct = cur_batch_size;
7409 if (read_batch_idx == batch_ct_m1) {
7410 DeclareLastThreadBlock(&tg);
7411 }
7412 if (unlikely(SpawnThreads(&tg))) {
7413 goto MakePgenRobust_ret_THREAD_CREATE_FAIL;
7414 }
7415 }
7416 parity = 1 - parity;
7417 if (read_batch_idx) {
7418 if (read_batch_idx > batch_ct_m1) {
7419 break;
7420 }
7421 const uint32_t write_idx_end = read_batch_idx * write_block_size;
7422 if (write_idx_end >= next_print_write_variant_idx) {
7423 if (pct > 10) {
7424 putc_unlocked('\b', stdout);
7425 }
7426 pct = (write_idx_end * 100LLU) / write_variant_ct;
7427 printf("\b\b%u%%", pct++);
7428 fflush(stdout);
7429 next_print_write_variant_idx = (pct * S_CAST(uint64_t, write_variant_ct)) / 100;
7430 }
7431 }
7432 }
7433 reterr = SpgwFinish(ctx.spgwp);
7434 if (unlikely(reterr)) {
7435 goto MakePgenRobust_ret_1;
7436 }
7437 if (pct > 10) {
7438 putc_unlocked('\b', stdout);
7439 }
7440 fputs("\b\b", stdout);
7441 logputs("done.\n");
7442 }
7443 }
7444 while (0) {
7445 MakePgenRobust_ret_NOMEM:
7446 reterr = kPglRetNomem;
7447 break;
7448 MakePgenRobust_ret_THREAD_CREATE_FAIL:
7449 reterr = kPglRetThreadCreateFail;
7450 break;
7451 }
7452 MakePgenRobust_ret_1:
7453 CleanupThreads(&tg);
7454 CleanupSpgw(&spgw, &reterr);
7455 BigstackReset(bigstack_mark);
7456 return reterr;
7457 }
7458
7459 // allele_presents should be nullptr iff trim_alts not true
7460 PglErr MakePlink2NoVsort(const uintptr_t* sample_include, const PedigreeIdInfo* piip, const uintptr_t* sex_nm, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const char* pheno_names, const uint32_t* new_sample_idx_to_old, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* allele_presents, const AlleleCode* allele_permute, const uintptr_t* pvar_qual_present, const float* pvar_quals, const uintptr_t* pvar_filter_present, const uintptr_t* pvar_filter_npass, const char* const* pvar_filter_storage, const char* pvar_info_reload, const double* variant_cms, const char* varid_template_str, __maybe_unused const char* varid_multi_template_str, __maybe_unused const char* varid_multi_nonsnp_template_str, const char* missing_varid_match, const char* output_missing_pheno, const char* legacy_output_missing_pheno, const uint32_t* contig_lens, const char* writer_ver, uintptr_t xheader_blen, InfoFlags info_flags, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct, uint32_t max_allele_slen, uint32_t max_filter_slen, uint32_t info_reload_slen, char output_missing_geno_char, uint32_t max_thread_ct, uint32_t hard_call_thresh, uint32_t dosage_erase_thresh, uint32_t new_variant_id_max_allele_slen, MiscFlags misc_flags, MakePlink2Flags make_plink2_flags, PvarPsamFlags pvar_psam_flags, uintptr_t pgr_alloc_cacheline_ct, char* xheader, PgenFileInfo* pgfip, PgenReader* simple_pgrp, char* outname, char* outname_end) {
7461 unsigned char* bigstack_mark = g_bigstack_base;
7462 FILE* outfile = nullptr;
7463 PglErr reterr = kPglRetSuccess;
7464 ThreadGroup tg;
7465 PreinitThreads(&tg);
7466 MTPgenWriter* mpgwp = nullptr;
7467 PgenExtensionLl ext_slot; // shouldn't have shorter lifetime than mpgwp
7468 MakePgenCtx ctx;
7469 {
7470 if (make_plink2_flags & kfMakeFam) {
7471 snprintf(outname_end, kMaxOutfnameExtBlen, ".fam");
7472 logprintfww5("Writing %s ... ", outname);
7473 fflush(stdout);
7474 reterr = WriteFam(outname, sample_include, piip, sex_nm, sex_male, pheno_cols, new_sample_idx_to_old, legacy_output_missing_pheno, sample_ct, pheno_ct, '\t');
7475 if (unlikely(reterr)) {
7476 goto MakePlink2NoVsort_ret_1;
7477 }
7478 logputs("done.\n");
7479 }
7480 if (make_plink2_flags & kfMakePsam) {
7481 snprintf(outname_end, kMaxOutfnameExtBlen, ".psam");
7482 logprintfww5("Writing %s ... ", outname);
7483 fflush(stdout);
7484 reterr = WritePsam(outname, sample_include, &(piip->sii), &(piip->parental_id_info), sex_nm, sex_male, pheno_cols, pheno_names, new_sample_idx_to_old, output_missing_pheno, sample_ct, pheno_ct, max_pheno_name_blen, pvar_psam_flags, 0);
7485 if (unlikely(reterr)) {
7486 goto MakePlink2NoVsort_ret_1;
7487 }
7488 logputs("done.\n");
7489 }
7490 const uint32_t input_biallelic = (!allele_idx_offsets);
7491 // output_biallelic: test write_allele_idx_offsets equality to null
7492 PgenGlobalFlags read_gflags = pgfip->gflags & (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent);
7493 if (!input_biallelic) {
7494 // Can only skip this when there are actually zero copies of alt2+.
7495 // Otherwise, even with erase-alt2+, we still need to distinguish alt1
7496 // from alt2 so we can set calls involving the latter to missing.
7497 read_gflags |= kfPgenGlobalMultiallelicHardcallFound;
7498 }
7499 const uintptr_t* write_allele_idx_offsets = nullptr;
7500 uint32_t write_variant_ct = variant_ct;
7501 uint32_t max_write_allele_ct = max_allele_ct;
7502 uint32_t max_missalt_ct = 0;
7503 if (make_plink2_flags & kfMakePlink2MMask) {
7504 // Enforced by command-line parser.
7505 assert((!allele_permute) && (!allele_presents));
7506 if (make_plink2_flags & kfMakePlink2MJoin) {
7507 reterr = PlanMultiallelicJoin(variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, make_plink2_flags, &write_variant_ct, &write_allele_idx_offsets, &max_write_allele_ct, &max_missalt_ct);
7508 } else if (!allele_idx_offsets) {
7509 // no splitting to do
7510 logputs("Note: All variants are biallelic; nothing to split.\n");
7511 } else {
7512 reterr = PlanMultiallelicSplit(variant_include, allele_idx_offsets, allele_storage, max_allele_ct, make_plink2_flags, &write_variant_ct, &write_allele_idx_offsets);
7513 }
7514 if (unlikely(reterr)) {
7515 goto MakePlink2NoVsort_ret_1;
7516 }
7517 } else if (allele_idx_offsets) {
7518 if (allele_presents) {
7519 fputs("multiallelic variants + trim-alts not yet supported\n", stderr);
7520 exit(S_CAST(int32_t, kPglRetNotYetSupported));
7521 }
7522 if (variant_ct < raw_variant_ct) {
7523 uintptr_t* new_allele_idx_offsets;
7524 if (bigstack_alloc_w(variant_ct + 1, &new_allele_idx_offsets)) {
7525 goto MakePlink2NoVsort_ret_NOMEM;
7526 }
7527 const uintptr_t final_offset = InitWriteAlleleIdxOffsets(variant_include, allele_idx_offsets, nullptr, allele_permute, nullptr, variant_ct, new_allele_idx_offsets);
7528 if (final_offset != 2 * variant_ct) {
7529 new_allele_idx_offsets[variant_ct] = final_offset;
7530 write_allele_idx_offsets = new_allele_idx_offsets;
7531 } else {
7532 BigstackReset(new_allele_idx_offsets);
7533 }
7534 } else {
7535 write_allele_idx_offsets = allele_idx_offsets;
7536 }
7537 }
7538 if (make_plink2_flags & kfMakeBim) {
7539 const uint32_t bim_zst = (make_plink2_flags / kfMakeBimZs) & 1;
7540 OutnameZstSet(".bim", bim_zst, outname_end);
7541 logprintfww5("Writing %s ... ", outname);
7542 fflush(stdout);
7543 if (unlikely(write_allele_idx_offsets)) {
7544 logputs("\n");
7545 logerrprintf("Error: %s cannot contain multiallelic variants.\n", outname);
7546 goto MakePlink2NoVsort_ret_INCONSISTENT_INPUT;
7547 }
7548 if (write_variant_ct == variant_ct) {
7549 reterr = WriteMapOrBim(outname, variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, allele_presents, allele_permute, variant_cms, variant_ct, max_allele_slen, '\t', output_missing_geno_char, bim_zst, max_thread_ct);
7550 } else {
7551 assert(write_variant_ct > variant_ct);
7552 reterr = WriteBimSplit(outname, variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, variant_cms, varid_template_str, missing_varid_match, variant_ct, max_allele_slen, new_variant_id_max_allele_slen, (make_plink2_flags / kfMakePlink2VaridSemicolon) & 1, (make_plink2_flags / kfMakePlink2VaridDup) & 1, misc_flags, bim_zst, max_thread_ct);
7553 }
7554 if (unlikely(reterr)) {
7555 goto MakePlink2NoVsort_ret_1;
7556 }
7557 logputs("done.\n");
7558 }
7559 if (make_plink2_flags & kfMakePvar) {
7560 uint32_t nonref_flags_storage = 3;
7561 if (!pgfip->nonref_flags) {
7562 nonref_flags_storage = (pgfip->gflags & kfPgenGlobalAllNonref)? 2 : 1;
7563 }
7564 uint32_t write_info;
7565 uint32_t write_info_pr;
7566 if (unlikely(PvarInfoWriteStatus(variant_include, pgfip->nonref_flags, raw_variant_ct, info_flags, nonref_flags_storage, pvar_psam_flags, &pvar_info_reload, &write_info, &write_info_pr))) {
7567 logerrputs("Error: Conflicting INFO/PR definitions. Either fix all REF alleles so that the\n\"provisional reference\" flag is no longer needed, or remove/rename the other\nuse of the INFO/PR key.\n");
7568 goto MakePlink2NoVsort_ret_INCONSISTENT_INPUT;
7569 }
7570
7571 uint32_t info_has_g_key = 0;
7572 const char* const* info_keys = nullptr;
7573 uint32_t info_key_ct = 0;
7574 uint32_t* info_keys_htable = nullptr;
7575 uint32_t info_keys_htable_size = 0;
7576 if (pvar_info_reload) {
7577 reterr = ParseInfoHeader(xheader, xheader_blen, &info_has_g_key, &info_keys, &info_key_ct, &info_keys_htable, &info_keys_htable_size);
7578 if (reterr) {
7579 goto MakePlink2NoVsort_ret_1;
7580 }
7581 if (info_has_g_key && (allele_permute || (write_variant_ct != variant_ct))) {
7582 logerrputs("Warning: INFO key(s) with Number=G present; " PROG_NAME_STR " does not try to update the\ncorresponding value(s) when alleles are permuted, or variants are split or\njoined. You may want to remove or redo these annotations.\n");
7583 }
7584 }
7585 OutnameZstSet(".pvar", pvar_psam_flags & kfPvarZs, outname_end);
7586 logprintfww5("Writing %s ... ", outname);
7587 fflush(stdout);
7588 if (write_variant_ct == variant_ct) {
7589 reterr = WritePvar(outname, variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, allele_presents, allele_permute, pvar_qual_present, pvar_quals, pvar_filter_present, pvar_filter_npass, pvar_filter_storage, pgfip->nonref_flags, pvar_info_reload, variant_cms, contig_lens, info_keys, info_keys_htable, raw_variant_ct, variant_ct, max_allele_ct, max_allele_slen, xheader_blen, info_flags, nonref_flags_storage, max_filter_slen, info_reload_slen, info_keys_htable_size, pvar_psam_flags, output_missing_geno_char, write_info, write_info_pr, max_thread_ct, xheader);
7590 } else {
7591 if (write_variant_ct > variant_ct) {
7592 reterr = WritePvarSplit(outname, variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, pvar_qual_present, pvar_quals, pvar_filter_present, pvar_filter_npass, pvar_filter_storage, pgfip->nonref_flags, pvar_info_reload, variant_cms, contig_lens, varid_template_str, missing_varid_match, info_keys, info_keys_htable, raw_variant_ct, variant_ct, max_allele_ct, max_allele_slen, new_variant_id_max_allele_slen, xheader_blen, info_flags, nonref_flags_storage, max_filter_slen, info_reload_slen, info_key_ct, info_keys_htable_size, misc_flags, make_plink2_flags, pvar_psam_flags, output_missing_geno_char, write_info, write_info_pr, max_thread_ct, xheader);
7593 } else {
7594 logerrputs("Error: Multiallelic join is under development.\n");
7595 reterr = kPglRetNotYetSupported;
7596 goto MakePlink2NoVsort_ret_1;
7597 // reterr = WritePvarJoin(outname, variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, pvar_qual_present, pvar_quals, pvar_filter_present, pvar_filter_npass, pvar_filter_storage, pgfip->nonref_flags, pvar_info_reload, variant_cms, contig_lens, varid_template_str, missing_varid_match, info_keys, info_keys_htable, raw_variant_ct, variant_ct, max_allele_slen, new_variant_id_max_allele_slen, max_write_allele_ct, max_missalt_ct, xheader_blen, info_flags, nonref_flags_storage, max_filter_slen, info_reload_slen, info_key_ct, info_keys_htable_size, misc_flags, make_plink2_flags, pvar_psam_flags, write_info, write_info_pr, max_thread_ct, xheader);
7598 }
7599 }
7600 if (unlikely(reterr)) {
7601 goto MakePlink2NoVsort_ret_1;
7602 }
7603 logputs("done.\n");
7604 }
7605 MakeCommon mc;
7606 mc.plink2_write_flags = kfPlink2Write0;
7607 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
7608 ctx.sex_male_collapsed = nullptr; // defensive
7609 if (make_plink2_flags & kfMakePlink2SetInvalidHaploidMissing) {
7610 const uint32_t sample_ctv = BitCtToVecCt(sample_ct);
7611 uintptr_t* new_sex_male;
7612 uintptr_t* new_sex_female;
7613 if (unlikely(bigstack_alloc_w(sample_ctv * kWordsPerVec, &new_sex_male) ||
7614 bigstack_alloc_w(sample_ctv * kWordsPerVec, &mc.sex_male_collapsed_interleaved) ||
7615 bigstack_alloc_w(sample_ctv * kWordsPerVec, &new_sex_female) ||
7616 bigstack_alloc_w(sample_ctv * kWordsPerVec, &mc.sex_female_collapsed_interleaved))) {
7617 goto MakePlink2NoVsort_ret_NOMEM;
7618 }
7619 CopyBitarrSubset(sex_male, sample_include, sample_ct, new_sex_male);
7620 ZeroTrailingWords(sample_ctl, new_sex_male);
7621 ctx.sex_male_collapsed = new_sex_male;
7622 FillInterleavedMaskVec(ctx.sex_male_collapsed, sample_ctv, mc.sex_male_collapsed_interleaved);
7623
7624 CopyBitarrSubset(sex_nm, sample_include, sample_ct, new_sex_female);
7625 BitvecInvmask(new_sex_male, sample_ctl, new_sex_female);
7626 ZeroTrailingWords(sample_ctl, new_sex_female);
7627 ctx.sex_female_collapsed = new_sex_female;
7628 FillInterleavedMaskVec(ctx.sex_female_collapsed, sample_ctv, mc.sex_female_collapsed_interleaved);
7629
7630 mc.plink2_write_flags |= kfPlink2WriteSetInvalidHaploidMissing;
7631 if (make_plink2_flags & kfMakePlink2SetInvalidHaploidMissingKeepDosage) {
7632 mc.plink2_write_flags |= kfPlink2WriteSetInvalidHaploidMissingKeepDosage;
7633 }
7634 } else {
7635 // defensive
7636 mc.sex_male_collapsed_interleaved = nullptr;
7637 mc.sex_female_collapsed_interleaved = nullptr;
7638 }
7639 mc.write_allele_permute = allele_permute;
7640 if (allele_permute && (variant_ct < raw_variant_ct)) {
7641 // might want inner loop to map variant uidx -> idx instead
7642 const uintptr_t write_total_allele_ct = write_allele_idx_offsets? write_allele_idx_offsets[write_variant_ct] : (2 * write_variant_ct);
7643 AlleleCode* write_allele_permute;
7644 if (bigstack_alloc_ac(write_total_allele_ct, &write_allele_permute)) {
7645 goto MakePlink2NoVsort_ret_NOMEM;
7646 }
7647 FillAllelePermuteSubset(allele_permute, variant_include, allele_idx_offsets, nullptr, variant_ct, write_allele_permute);
7648 mc.write_allele_permute = write_allele_permute;
7649 }
7650 if (make_plink2_flags & kfMakePlink2SetMixedMtMissing) {
7651 mc.plink2_write_flags |= kfPlink2WriteSetMixedMtMissing;
7652 if (make_plink2_flags & kfMakePlink2SetMixedMtMissingKeepDosage) {
7653 mc.plink2_write_flags |= kfPlink2WriteSetMixedMtMissingKeepDosage;
7654 }
7655 }
7656 mc.cip = cip;
7657 mc.raw_sample_ct = raw_sample_ct;
7658 mc.sample_ct = sample_ct;
7659 unsigned char* bigstack_mark2 = g_bigstack_base;
7660 const uint32_t make_pgen = make_plink2_flags & kfMakePgen;
7661 // todo: prohibit .pgen + .bim write when data is multiallelic without
7662 // either multiallelic split or erase-alt2+ specified
7663 // (--make-bed = automatic erase-alt2+?)
7664 if ((make_plink2_flags & kfMakeBed) || ((make_plink2_flags & (kfMakePgen | (kfMakePgenFormatBase * 3))) == (kfMakePgen | kfMakePgenFormatBase))) {
7665 reterr = MakeBedlikeMain(sample_include, new_sample_idx_to_old, variant_include, raw_variant_ct, variant_ct, max_thread_ct, hard_call_thresh, make_plink2_flags, pgr_alloc_cacheline_ct, pgfip, &mc, outname, outname_end);
7666 } else if (make_pgen) {
7667 assert(variant_ct);
7668 assert(sample_ct);
7669 if (make_plink2_flags & (kfMakePlink2MSplitBase * 7)) {
7670 // don't duplicate complicated multiallelic split/merge/trim-alts logic
7671 // here for now.
7672 // (also auto-punt multiallelic dosage?)
7673 goto MakePlink2NoVsort_fallback;
7674 }
7675 ctx.write_allele_idx_offsets = write_allele_idx_offsets;
7676 if (variant_ct == raw_variant_ct) {
7677 ctx.write_chr_fo_vidx_start = cip->chr_fo_vidx_start;
7678 } else {
7679 if (AllocAndFillSubsetChrFoVidxStart(variant_include, cip, &ctx.write_chr_fo_vidx_start)) {
7680 goto MakePlink2NoVsort_fallback;
7681 }
7682 }
7683 if (make_plink2_flags & kfMakePgenErasePhase) {
7684 read_gflags &= ~(kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePhasePresent);
7685 }
7686 const uint32_t fill_missing_from_dosage = (make_plink2_flags & kfMakePgenFillMissingFromDosage) && (read_gflags & kfPgenGlobalDosagePresent);
7687 if (fill_missing_from_dosage) {
7688 mc.plink2_write_flags |= kfPlink2WriteFillMissingFromDosage;
7689 }
7690 if (make_plink2_flags & kfMakePgenEraseDosage) {
7691 if ((hard_call_thresh == UINT32_MAX) && (!fill_missing_from_dosage)) {
7692 read_gflags &= ~(kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent);
7693 } else {
7694 // erase-dosage + --hard-call-threshold currently requires dosages to
7695 // be read, and only thrown away at the last minute
7696 // (alternatively, we could build --hard-call-threshold directly into
7697 // pgr_read_raw?)
7698 mc.plink2_write_flags |= kfPlink2WriteLateDosageErase;
7699 }
7700 }
7701 if (read_gflags && (variant_ct < raw_variant_ct)) {
7702 // did we e.g. filter out all the phased variants?
7703 // do not check for multiallelic-hc here for now
7704 // (write_allele_idx_offsets check above serves the same purpose)
7705 read_gflags &= kfPgenGlobalMultiallelicHardcallFound | GflagsVfilter(variant_include, pgfip->vrtypes, raw_variant_ct, pgfip->gflags);
7706 }
7707 // could check if all the phased samples were also filtered out, but
7708 // that's already caught by running --make-pgen twice, so not a big deal
7709
7710 const uint32_t read_dosage_present = (read_gflags / kfPgenGlobalDosagePresent) & 1;
7711 mc.hard_call_halfdist = ((hard_call_thresh == UINT32_MAX) || (!read_dosage_present))? 0 : (kDosage4th - hard_call_thresh);
7712 ctx.dosage_erase_halfdist = kDosage4th - dosage_erase_thresh;
7713 const uint32_t read_phase_present = !!(read_gflags & (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePhasePresent));
7714 const uint32_t read_dphase_present = (read_gflags / kfPgenGlobalDosagePhasePresent) & 1;
7715 PgenGlobalFlags write_gflags = read_gflags;
7716 uint32_t read_or_write_phase_present = read_phase_present;
7717 uint32_t read_or_write_dphase_present = read_dphase_present;
7718 if ((mc.hard_call_halfdist || fill_missing_from_dosage) && (read_phase_present || read_or_write_dphase_present)) {
7719 read_or_write_phase_present = 1;
7720 read_or_write_dphase_present = 1;
7721 write_gflags |= kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePhasePresent;
7722 } else if (dosage_erase_thresh && read_dosage_present) {
7723 read_or_write_phase_present = 1;
7724 }
7725 uint32_t read_or_write_dosage_present = read_dosage_present;
7726 if (mc.plink2_write_flags & kfPlink2WriteLateDosageErase) {
7727 write_gflags &= ~(kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent);
7728 } else if (mc.plink2_write_flags & (kfPlink2WriteSetInvalidHaploidMissingKeepDosage | kfPlink2WriteSetMixedMtMissingKeepDosage)) {
7729 read_or_write_dosage_present = 1;
7730 write_gflags |= kfPgenGlobalDosagePresent;
7731 }
7732 if ((write_gflags & (kfPgenGlobalMultiallelicHardcallFound | kfPgenGlobalDosagePresent)) == (kfPgenGlobalMultiallelicHardcallFound | kfPgenGlobalDosagePresent)) {
7733 logerrputs("Error: Multiallelic dosages aren't supported yet.\n");
7734 reterr = kPglRetNotYetSupported;
7735 goto MakePlink2NoVsort_ret_1;
7736 }
7737 write_gflags &= ~kfPgenGlobalMultiallelicHardcallFound;
7738 uintptr_t alloc_base_cacheline_ct;
7739 uint64_t mpgw_per_thread_cacheline_ct;
7740 uint32_t vrec_len_byte_ct;
7741 uint64_t vblock_cacheline_ct;
7742 // may want to have a load_sample_ct which is raw_sample_ct when e.g.
7743 // sample_ct > 0.1 * raw_sample_ct, and sample_ct otherwise.
7744 MpgwInitPhase1(write_allele_idx_offsets, variant_ct, sample_ct, write_gflags, &alloc_base_cacheline_ct, &mpgw_per_thread_cacheline_ct, &vrec_len_byte_ct, &vblock_cacheline_ct);
7745
7746 // bugfix: each variant currently needs to be vector-aligned
7747 // bugfix?: need to use raw_sample_ct here, not sample_ct
7748 const uint32_t raw_sample_ctv2 = NypCtToVecCt(raw_sample_ct);
7749 const uint32_t max_vblock_size = MINV(kPglVblockSize, variant_ct);
7750 uint64_t load_vblock_cacheline_ct = VecCtToCachelineCtU64(S_CAST(uint64_t, raw_sample_ctv2) * max_vblock_size);
7751
7752 if (make_plink2_flags & ((kfMakePlink2MSplitBase * 7) | kfMakePlink2EraseAlt2Plus)) {
7753 logerrputs("Error: 'multiallelics=' and 'erase-alt2+' modifiers are under development.\n");
7754 reterr = kPglRetNotYetSupported;
7755 goto MakePlink2NoVsort_ret_NOMEM;
7756 }
7757 if (read_gflags & kfPgenGlobalMultiallelicHardcallFound) {
7758 // raw multiallelic hardcall track has three parts:
7759 // 1. two words with rare01_ct and rare10_ct.
7760 // 2. (vector-aligned) patch_01_set and patch_01_vals.
7761 // 3. (vector-aligned) patch_10_set and patch_10_vals.
7762 const uintptr_t mhcraw_word_ct = RoundUpPow2(2, kWordsPerVec) + GetMhcWordCt(raw_sample_ct);
7763 load_vblock_cacheline_ct += WordCtToCachelineCtU64(S_CAST(uint64_t, mhcraw_word_ct) * max_vblock_size);
7764 }
7765 if (read_phase_present) {
7766 // could make this bound tighter when lots of unphased variants are
7767 // mixed in among the phased variants, but this isn't nearly as
7768 // important as the analogous multiallelic optimization
7769
7770 // phaseraw has three parts:
7771 // 1. het_ct as uint32_t, and explicit_phasepresent_ct as uint32_t.
7772 // 2. vec-aligned bitarray of up to (raw_sample_ct + 1) bits. first
7773 // bit is set iff phasepresent is explicitly stored at all (if not,
7774 // all hets are assumed to be phased), if yes the remaining bits
7775 // store packed phasepresent values for all hets, if no the
7776 // remaining bits store packed phaseinfo values for all hets.
7777 // 3. word-aligned bitarray of up to raw_sample_ct bits, storing
7778 // phaseinfo values. (end of this array is vec-aligned.)
7779 const uintptr_t phaseraw_word_ct = (8 / kBytesPerWord) + kWordsPerVec + RoundDownPow2(raw_sample_ct / kBitsPerWordD2, kWordsPerVec);
7780 load_vblock_cacheline_ct += WordCtToCachelineCtU64(S_CAST(uint64_t, phaseraw_word_ct) * max_vblock_size);
7781 }
7782 if (read_dosage_present) {
7783 // biallelic dosageraw has two parts:
7784 // 1. vec-aligned bitarray of up to raw_sample_ct bits, storing which
7785 // samples have dosages.
7786 // 2. word-aligned array of uint16s with 0..32768 fixed-point dosages.
7787 // dphaseraw has the same structure, with the uint16s replaced with an
7788 // int16 array of (left - right) values.
7789 const uintptr_t dosageraw_word_ct = kWordsPerVec * (BitCtToVecCt(raw_sample_ct) + DivUp(raw_sample_ct, kBytesPerVec / sizeof(Dosage)));
7790 load_vblock_cacheline_ct += WordCtToCachelineCtU64(dosageraw_word_ct * S_CAST(uint64_t, max_vblock_size)) * (1 + read_dphase_present);
7791 }
7792
7793 #ifndef __LP64__
7794 if ((mpgw_per_thread_cacheline_ct > (0x7fffffff / kCacheline)) || (load_vblock_cacheline_ct > (0x7fffffff / kCacheline))) {
7795 goto MakePlink2NoVsort_fallback;
7796 }
7797 #endif
7798 uint32_t calc_thread_ct = DivUp(variant_ct, kPglVblockSize);
7799 if (calc_thread_ct >= max_thread_ct) {
7800 calc_thread_ct = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
7801 }
7802 const uint32_t subsetting_required = (sample_ct != raw_sample_ct);
7803 if (!new_sample_idx_to_old) {
7804 // hphase doesn't seem to affect read:write ratio much
7805 #ifdef USE_AVX2
7806 const uint32_t max_calc_thread_ct = 3;
7807 #else
7808 const uint32_t max_calc_thread_ct = 3 + subsetting_required;
7809 #endif
7810 if (calc_thread_ct > max_calc_thread_ct) {
7811 calc_thread_ct = max_calc_thread_ct;
7812 }
7813 }
7814 // this is frequently I/O-bound even when resorting, but I'll postpone
7815 // tuning thread count there
7816 uint32_t write_mhc_needed = allele_permute && (!input_biallelic);
7817 mpgwp = S_CAST(MTPgenWriter*, bigstack_alloc((calc_thread_ct + DivUp(sizeof(MTPgenWriter), kBytesPerWord)) * sizeof(intptr_t)));
7818 if (!mpgwp) {
7819 goto MakePlink2NoVsort_fallback;
7820 }
7821 PreinitMpgw(mpgwp);
7822 if (bigstack_alloc_wp(calc_thread_ct, &(ctx.loadbuf_thread_starts[0])) ||
7823 bigstack_alloc_wp(calc_thread_ct, &(ctx.loadbuf_thread_starts[1]))) {
7824 goto MakePlink2NoVsort_fallback;
7825 }
7826 uint32_t nonref_flags_storage = 3;
7827 uintptr_t* nonref_flags_write = pgfip->nonref_flags;
7828 if (!nonref_flags_write) {
7829 nonref_flags_storage = (pgfip->gflags & kfPgenGlobalAllNonref)? 2 : 1;
7830 } else if (variant_ct < raw_variant_ct) {
7831 const uint32_t write_variant_ctl = BitCtToWordCt(write_variant_ct);
7832 uintptr_t* old_nonref_flags = nonref_flags_write;
7833 if (bigstack_alloc_w(write_variant_ctl, &nonref_flags_write)) {
7834 goto MakePlink2NoVsort_fallback;
7835 }
7836 if (variant_ct == write_variant_ct) {
7837 CopyBitarrSubset(old_nonref_flags, variant_include, variant_ct, nonref_flags_write);
7838 } else {
7839 ZeroWArr(write_variant_ctl, nonref_flags_write);
7840 if (input_biallelic) {
7841 SplitNonrefFlags();
7842 } else {
7843 JoinNonrefFlags();
7844 }
7845 }
7846 if (nonref_flags_write[0] & 1) {
7847 if (AllBitsAreOne(nonref_flags_write, write_variant_ct)) {
7848 BigstackReset(nonref_flags_write);
7849 nonref_flags_write = nullptr;
7850 nonref_flags_storage = 2;
7851 }
7852 } else if (AllWordsAreZero(nonref_flags_write, write_variant_ctl)) {
7853 BigstackReset(nonref_flags_write);
7854 nonref_flags_write = nullptr;
7855 nonref_flags_storage = 1;
7856 }
7857 } else {
7858 if (nonref_flags_write[0] & 1) {
7859 if (AllBitsAreOne(nonref_flags_write, raw_variant_ct)) {
7860 nonref_flags_write = nullptr;
7861 nonref_flags_storage = 2;
7862 }
7863 } else if (AllWordsAreZero(nonref_flags_write, BitCtToWordCt(raw_variant_ct))) {
7864 nonref_flags_write = nullptr;
7865 nonref_flags_storage = 1;
7866 }
7867 }
7868 ctx.pwcs = &(mpgwp->pwcs[0]);
7869 ctx.thread_write_genovecs = nullptr;
7870 ctx.thread_write_mhc = nullptr;
7871
7872 // Each worker thread handles with 64k loaded variants at a time, while
7873 // the I/O thread loads the next (64k * thread_ct).
7874 uintptr_t other_per_thread_cacheline_ct = 2 * load_vblock_cacheline_ct;
7875
7876 ctx.old_sample_idx_to_new = nullptr;
7877 ctx.sample_include_interleaved_vec = nullptr;
7878
7879 if (new_sample_idx_to_old || subsetting_required) {
7880 if (bigstack_alloc_wp(calc_thread_ct, &ctx.thread_write_genovecs)) {
7881 goto MakePlink2NoVsort_fallback;
7882 }
7883 if (new_sample_idx_to_old) {
7884 if (unlikely(bigstack_alloc_u32(raw_sample_ct, &ctx.old_sample_idx_to_new))) {
7885 goto MakePlink2NoVsort_fallback;
7886 }
7887 if (subsetting_required) {
7888 const uint32_t raw_sample_ctv = BitCtToVecCt(raw_sample_ct);
7889 if (unlikely(bigstack_alloc_w(raw_sample_ctv * kWordsPerVec, &ctx.sample_include_interleaved_vec))) {
7890 goto MakePlink2NoVsort_fallback;
7891 }
7892 FillInterleavedMaskVec(sample_include, raw_sample_ctv, ctx.sample_include_interleaved_vec);
7893 }
7894 for (uint32_t new_sample_idx = 0; new_sample_idx != sample_ct; ++new_sample_idx) {
7895 ctx.old_sample_idx_to_new[new_sample_idx_to_old[new_sample_idx]] = new_sample_idx;
7896 }
7897 }
7898 // ctx.thread_write_genovecs
7899 other_per_thread_cacheline_ct += NypCtToCachelineCt(sample_ct);
7900
7901 if (!input_biallelic) {
7902 write_mhc_needed = 1;
7903 }
7904 }
7905 ctx.thread_ac_remap = nullptr;
7906 ctx.thread_ac_rotate = nullptr;
7907 ctx.thread_ac_flipped = nullptr;
7908 uintptr_t write_mhcraw_cacheline_ct = 0;
7909 uintptr_t write_ac_remap_cacheline_ct = 0;
7910 uintptr_t write_ac_rotate_cacheline_ct = 0;
7911 uintptr_t write_ac_flipped_cacheline_ct = 0;
7912 if (write_mhc_needed) {
7913 if (bigstack_alloc_wp(calc_thread_ct, &ctx.thread_write_mhc)) {
7914 goto MakePlink2NoVsort_fallback;
7915 }
7916 const uintptr_t mhcwrite_word_ct = GetMhcWordCt(sample_ct);
7917 write_mhcraw_cacheline_ct = DivUp(mhcwrite_word_ct, kWordsPerCacheline);
7918 other_per_thread_cacheline_ct += write_mhcraw_cacheline_ct;
7919 if (allele_permute) {
7920 if (bigstack_alloc_acp(calc_thread_ct, &ctx.thread_ac_remap) ||
7921 bigstack_alloc_acp(calc_thread_ct, &ctx.thread_ac_rotate) ||
7922 bigstack_alloc_wp(calc_thread_ct, &ctx.thread_ac_flipped)) {
7923 goto MakePlink2NoVsort_fallback;
7924 }
7925 write_ac_remap_cacheline_ct = DivUp(max_allele_ct, kCacheline / sizeof(AlleleCode));
7926 write_ac_rotate_cacheline_ct = DivUp(sample_ct, kCacheline / (2 * sizeof(AlleleCode)));
7927 write_ac_flipped_cacheline_ct = BitCtToCachelineCt(sample_ct);
7928 other_per_thread_cacheline_ct += write_ac_remap_cacheline_ct + write_ac_rotate_cacheline_ct + write_ac_flipped_cacheline_ct;
7929 }
7930 }
7931 ctx.thread_write_phasepresents = nullptr;
7932 ctx.thread_all_hets = nullptr;
7933 ctx.thread_write_dosagepresents = nullptr;
7934 ctx.thread_write_dphasepresents = nullptr;
7935 if (read_or_write_phase_present || read_or_write_dosage_present) {
7936 if (read_or_write_phase_present) {
7937 if (bigstack_alloc_wp(calc_thread_ct, &ctx.thread_write_phasepresents) ||
7938 bigstack_alloc_wp(calc_thread_ct, &ctx.thread_write_phaseinfos)) {
7939 goto MakePlink2NoVsort_fallback;
7940 }
7941 if (read_phase_present) {
7942 if (bigstack_alloc_wp(calc_thread_ct, &ctx.thread_all_hets)) {
7943 goto MakePlink2NoVsort_fallback;
7944 }
7945 other_per_thread_cacheline_ct += BitCtToCachelineCt(raw_sample_ct);
7946 }
7947 // phasepresent, phaseinfo
7948 other_per_thread_cacheline_ct += 2 * BitCtToCachelineCt(sample_ct);
7949 }
7950 if (read_or_write_dosage_present) {
7951 if (bigstack_alloc_wp(calc_thread_ct, &ctx.thread_write_dosagepresents) ||
7952 bigstack_alloc_dosagep(calc_thread_ct, &ctx.thread_write_dosagevals)) {
7953 goto MakePlink2NoVsort_fallback;
7954 }
7955 if (read_or_write_dphase_present) {
7956 if (bigstack_alloc_wp(calc_thread_ct, &ctx.thread_write_dphasepresents) ||
7957 bigstack_alloc_dphasep(calc_thread_ct, &ctx.thread_write_dphasedeltas)) {
7958 goto MakePlink2NoVsort_fallback;
7959 }
7960 }
7961 // dosage_present, dphase_present
7962 other_per_thread_cacheline_ct += BitCtToCachelineCt(sample_ct) * (1 + read_or_write_dphase_present);
7963
7964 // dosage_main, dphase_delta
7965 other_per_thread_cacheline_ct += DivUp(sample_ct, (kCacheline / sizeof(Dosage))) * (1 + 2 * read_or_write_dphase_present);
7966
7967 // todo: multiallelic dosage
7968 }
7969 }
7970 if (read_or_write_phase_present || read_dosage_present || (read_gflags & kfPgenGlobalMultiallelicHardcallFound)) {
7971 // ctx.loaded_vrtypes
7972 other_per_thread_cacheline_ct += 2 * (kPglVblockSize / kCacheline);
7973 }
7974 const uintptr_t cachelines_avail = bigstack_left() / kCacheline;
7975 if (cachelines_avail < alloc_base_cacheline_ct + (mpgw_per_thread_cacheline_ct + other_per_thread_cacheline_ct) * calc_thread_ct) {
7976 if (cachelines_avail < alloc_base_cacheline_ct + mpgw_per_thread_cacheline_ct + other_per_thread_cacheline_ct) {
7977 goto MakePlink2NoVsort_fallback;
7978 }
7979 calc_thread_ct = (cachelines_avail - alloc_base_cacheline_ct) / (mpgw_per_thread_cacheline_ct + other_per_thread_cacheline_ct);
7980 }
7981 unsigned char* cur_alloc_end_expected = &(g_bigstack_base[kCacheline * (alloc_base_cacheline_ct + calc_thread_ct * (mpgw_per_thread_cacheline_ct + other_per_thread_cacheline_ct))]);
7982 uintptr_t* main_loadbufs[2];
7983 main_loadbufs[0] = S_CAST(uintptr_t*, bigstack_alloc_raw(load_vblock_cacheline_ct * calc_thread_ct * kCacheline));
7984 main_loadbufs[1] = S_CAST(uintptr_t*, bigstack_alloc_raw(load_vblock_cacheline_ct * calc_thread_ct * kCacheline));
7985 ctx.loaded_vrtypes[0] = nullptr;
7986 ctx.loaded_vrtypes[1] = nullptr;
7987 if (read_or_write_phase_present || read_dosage_present || (read_gflags & kfPgenGlobalMultiallelicHardcallFound)) {
7988 ctx.loaded_vrtypes[0] = S_CAST(unsigned char*, bigstack_alloc_raw(kPglVblockSize * calc_thread_ct));
7989 ctx.loaded_vrtypes[1] = S_CAST(unsigned char*, bigstack_alloc_raw(kPglVblockSize * calc_thread_ct));
7990 }
7991 if (read_or_write_phase_present || read_or_write_dosage_present) {
7992 const uint32_t bitvec_writebuf_byte_ct = BitCtToCachelineCt(sample_ct) * kCacheline;
7993 const uintptr_t dosagevals_writebuf_byte_ct = DivUp(sample_ct, (kCacheline / 2)) * kCacheline;
7994 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
7995 if (read_or_write_phase_present) {
7996 ctx.thread_write_phasepresents[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(bitvec_writebuf_byte_ct));
7997 ctx.thread_write_phaseinfos[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(bitvec_writebuf_byte_ct));
7998
7999 if (read_phase_present) {
8000 ctx.thread_all_hets[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(BitCtToCachelineCt(raw_sample_ct) * kCacheline));
8001 }
8002 }
8003 if (read_or_write_dosage_present) {
8004 ctx.thread_write_dosagepresents[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(bitvec_writebuf_byte_ct));
8005 ctx.thread_write_dosagevals[tidx] = S_CAST(Dosage*, bigstack_alloc_raw(dosagevals_writebuf_byte_ct));
8006 if (read_or_write_dphase_present) {
8007 ctx.thread_write_dphasepresents[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(bitvec_writebuf_byte_ct));
8008 ctx.thread_write_dphasedeltas[tidx] = S_CAST(SDosage*, bigstack_alloc_raw(2 * dosagevals_writebuf_byte_ct));
8009 }
8010 }
8011 }
8012 }
8013 if (new_sample_idx_to_old || subsetting_required) {
8014 const uintptr_t writebuf_byte_ct = RoundUpPow2(NypCtToByteCt(sample_ct), kCacheline);
8015 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
8016 ctx.thread_write_genovecs[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(writebuf_byte_ct));
8017 }
8018 }
8019 if (write_mhc_needed) {
8020 const uintptr_t ac_remap_byte_ct = write_ac_remap_cacheline_ct * kCacheline;
8021 const uintptr_t ac_rotate_byte_ct = write_ac_rotate_cacheline_ct * kCacheline;
8022 const uintptr_t ac_flipped_byte_ct = write_ac_flipped_cacheline_ct * kCacheline;
8023 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
8024 ctx.thread_write_mhc[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(write_mhcraw_cacheline_ct * kCacheline));
8025 if (allele_permute) {
8026 ctx.thread_ac_remap[tidx] = S_CAST(AlleleCode*, bigstack_alloc_raw(ac_remap_byte_ct));
8027 ctx.thread_ac_rotate[tidx] = S_CAST(AlleleCode*, bigstack_alloc_raw(ac_rotate_byte_ct));
8028 ctx.thread_ac_flipped[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(ac_flipped_byte_ct));
8029 }
8030 }
8031 }
8032 snprintf(outname_end, kMaxOutfnameExtBlen, ".pgen");
8033 logprintfww5("Writing %s ... ", outname);
8034 fputs("0%", stdout);
8035 fflush(stdout);
8036 unsigned char* mpgw_alloc = S_CAST(unsigned char*, bigstack_alloc_raw((alloc_base_cacheline_ct + mpgw_per_thread_cacheline_ct * calc_thread_ct) * kCacheline));
8037 if (unlikely(g_bigstack_base != cur_alloc_end_expected)) {
8038 logerrprintf("Error: MakePlink2NoVsort(): memory miscalculation. This is a plink2 bug; if you\nreport the error on GitHub or the plink2-users Google group (make sure to\ninclude the full .log file in your report), we'll try to address it.\n");
8039 reterr = kPglRetInternalError;
8040 goto MakePlink2NoVsort_ret_1;
8041 }
8042 assert(g_bigstack_base <= g_bigstack_end);
8043 PgenExtensionLl* header_exts = nullptr;
8044 if (writer_ver) {
8045 ext_slot.next = nullptr;
8046 ext_slot.size = strlen(writer_ver);
8047 ext_slot.contents = R_CAST(unsigned char*, K_CAST(char*, writer_ver));
8048 ext_slot.type_idx = 1;
8049 header_exts = &ext_slot;
8050 }
8051 reterr = MpgwInitPhase2Ex(outname, nonref_flags_write, header_exts, nullptr, variant_ct, sample_ct, kPgenWriteBackwardSeek, write_gflags, nonref_flags_storage, vrec_len_byte_ct, vblock_cacheline_ct, calc_thread_ct, mpgw_alloc, mpgwp);
8052 if (unlikely(reterr)) {
8053 if (reterr == kPglRetOpenFail) {
8054 logputs("\n");
8055 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
8056 }
8057 goto MakePlink2NoVsort_ret_1;
8058 }
8059 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
8060 goto MakePlink2NoVsort_ret_NOMEM;
8061 }
8062 mc.sample_include = subsetting_required? sample_include : nullptr;
8063 ctx.mcp = &mc;
8064 ctx.spgwp = nullptr;
8065 ctx.write_reterr = kPglRetSuccess;
8066 SetThreadFuncAndData(MakePgenThread, &ctx, &tg);
8067
8068 // Main workflow:
8069 // 1. Set n=0, load first calc_thread_ct * kPglVblockSize
8070 // *post-filtering* variants.
8071 // This doesn't play well with blockload when any variants are
8072 // filtered out, so we don't use it. (todo: look into special-casing
8073 // variant_ct == raw_variant_ct.)
8074 //
8075 // 2. Spawn threads processing batch n
8076 // 3. Load batch (n+1) unless eof
8077 // 4. Join threads
8078 // 5. Flush results for batch n (must happen here since we aren't using
8079 // two output buffers. this may be a mistake, revisit this choice...)
8080 // 6. Increment n by 1
8081 // 7. Goto step 2 unless eof
8082 const uint32_t batch_ct_m1 = (variant_ct - 1) / (kPglVblockSize * calc_thread_ct);
8083 uint32_t pct = 0;
8084 uint32_t parity = 0;
8085 uint32_t read_batch_idx = 0;
8086 uint32_t cur_batch_size = kPglVblockSize * calc_thread_ct;
8087 uint32_t next_print_variant_idx = variant_ct / 100;
8088 uintptr_t read_variant_uidx_base = 0;
8089 uintptr_t cur_bits = variant_include[0];
8090 PgrClearLdCache(simple_pgrp);
8091 for (uint32_t write_idx_end = 0; ; ++read_batch_idx, write_idx_end += cur_batch_size) {
8092 if (read_batch_idx) {
8093 ctx.cur_block_write_ct = cur_batch_size;
8094 if (write_idx_end == variant_ct) {
8095 DeclareLastThreadBlock(&tg);
8096 }
8097 if (unlikely(SpawnThreads(&tg))) {
8098 goto MakePlink2NoVsort_ret_THREAD_CREATE_FAIL;
8099 }
8100 }
8101 if (!IsLastBlock(&tg)) {
8102 if (read_batch_idx == batch_ct_m1) {
8103 cur_batch_size = variant_ct - (read_batch_idx * kPglVblockSize * calc_thread_ct);
8104 }
8105 uintptr_t* cur_loadbuf = main_loadbufs[parity];
8106 uintptr_t* loadbuf_iter = cur_loadbuf;
8107 unsigned char* cur_loaded_vrtypes = ctx.loaded_vrtypes[parity];
8108 for (uint32_t uii = 0; uii != cur_batch_size; ++uii) {
8109 if (!(uii % kPglVblockSize)) {
8110 ctx.loadbuf_thread_starts[parity][uii / kPglVblockSize] = loadbuf_iter;
8111 }
8112 const uintptr_t read_variant_uidx = BitIter1(variant_include, &read_variant_uidx_base, &cur_bits);
8113 reterr = PgrGetRaw(read_variant_uidx, read_gflags, simple_pgrp, &loadbuf_iter, cur_loaded_vrtypes? (&(cur_loaded_vrtypes[uii])) : nullptr);
8114 if (unlikely(reterr)) {
8115 PgenErrPrintNV(reterr, read_variant_uidx);
8116 goto MakePlink2NoVsort_ret_1;
8117 }
8118 }
8119 }
8120 if (read_batch_idx) {
8121 JoinThreads(&tg);
8122 reterr = ctx.write_reterr;
8123 if (unlikely(reterr)) {
8124 // only possible error is kPglRetVarRecordTooLarge?
8125 goto MakePlink2NoVsort_ret_1;
8126 }
8127 }
8128 parity = 1 - parity;
8129 if (write_idx_end) {
8130 reterr = MpgwFlush(mpgwp);
8131 if (unlikely(reterr)) {
8132 goto MakePlink2NoVsort_ret_WRITE_FAIL;
8133 }
8134 if (write_idx_end == variant_ct) {
8135 mpgwp = nullptr;
8136 break;
8137 }
8138 if (write_idx_end >= next_print_variant_idx) {
8139 if (pct > 10) {
8140 putc_unlocked('\b', stdout);
8141 }
8142 pct = (write_idx_end * 100LLU) / variant_ct;
8143 printf("\b\b%u%%", pct++);
8144 fflush(stdout);
8145 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
8146 }
8147 }
8148 }
8149 if (pct > 10) {
8150 putc_unlocked('\b', stdout);
8151 }
8152 fputs("\b\b", stdout);
8153 logputs("done.\n");
8154 // BigstackReset(bigstack_mark);
8155 } else if (0) {
8156 MakePlink2NoVsort_fallback:
8157 g_failed_alloc_attempt_size = 0;
8158 mpgwp = nullptr;
8159 BigstackReset(bigstack_mark2);
8160 reterr = MakePgenRobust(sample_include, new_sample_idx_to_old, variant_include, allele_idx_offsets, allele_presents, write_allele_idx_offsets, nullptr, ctx.sex_male_collapsed, ctx.sex_female_collapsed, writer_ver, raw_variant_ct, variant_ct, write_variant_ct, max_allele_ct, hard_call_thresh, dosage_erase_thresh, make_plink2_flags, &mc, simple_pgrp, outname, outname_end);
8161 if (unlikely(reterr)) {
8162 goto MakePlink2NoVsort_ret_1;
8163 }
8164 if (variant_ct != write_variant_ct) {
8165 logprintfww("Multiallelic %s: %u variant%s written.\n", (variant_ct < write_variant_ct)? "split" : "join", write_variant_ct, (write_variant_ct == 1)? "" : "s");
8166 }
8167 }
8168 }
8169 while (0) {
8170 MakePlink2NoVsort_ret_NOMEM:
8171 reterr = kPglRetNomem;
8172 break;
8173 MakePlink2NoVsort_ret_WRITE_FAIL:
8174 reterr = kPglRetWriteFail;
8175 break;
8176 MakePlink2NoVsort_ret_INCONSISTENT_INPUT:
8177 reterr = kPglRetInconsistentInput;
8178 break;
8179 MakePlink2NoVsort_ret_THREAD_CREATE_FAIL:
8180 reterr = kPglRetThreadCreateFail;
8181 break;
8182 }
8183 MakePlink2NoVsort_ret_1:
8184 CleanupMpgw(mpgwp, &reterr);
8185 CleanupThreads(&tg);
8186 fclose_cond(outfile);
8187 pgfip->block_base = nullptr;
8188 BigstackReset(bigstack_mark);
8189 return reterr;
8190 }
8191
8192 PglErr UpdateChr(const uintptr_t* variant_include, const char* const* variant_ids, const TwoColParams* params, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_variant_id_slen, uint32_t prohibit_extra_chrs, uint32_t max_thread_ct, ChrInfo* cip, ChrIdx* chr_idxs) {
8193 // See e.g. UpdateVarBps().
8194 unsigned char* bigstack_mark = g_bigstack_base;
8195 uintptr_t line_idx = 0;
8196 PglErr reterr = kPglRetSuccess;
8197 TextStream txs;
8198 PreinitTextStream(&txs);
8199 {
8200 // possible todo: if cip->name_ct > 0, try to prune here, so we can handle
8201 // more new names
8202
8203 uintptr_t* already_seen;
8204 if (unlikely(bigstack_calloc_w(BitCtToWordCt(raw_variant_ct), &already_seen))) {
8205 goto UpdateChr_ret_NOMEM;
8206 }
8207
8208 uint32_t* variant_id_htable;
8209 uint32_t variant_id_htable_size;
8210 reterr = AllocAndPopulateIdHtableMt(variant_include, variant_ids, variant_ct, bigstack_left() / 8, max_thread_ct, &variant_id_htable, nullptr, &variant_id_htable_size, nullptr);
8211 if (unlikely(reterr)) {
8212 goto UpdateChr_ret_1;
8213 }
8214
8215 // This could be pointed at a file containing allele codes, so don't limit
8216 // line length to minimum value.
8217 reterr = SizeAndInitTextStream(params->fname, bigstack_left(), MAXV(max_thread_ct - 1, 1), &txs);
8218 if (unlikely(reterr)) {
8219 goto UpdateChr_ret_TSTREAM_FAIL;
8220 }
8221 reterr = TextSkip(params->skip_ct, &txs);
8222 if (unlikely(reterr)) {
8223 if (reterr == kPglRetEof) {
8224 snprintf(g_logbuf, kLogbufSize, "Error: Fewer lines than expected in %s.\n", params->fname);
8225 goto UpdateChr_ret_INCONSISTENT_INPUT_WW;
8226 }
8227 goto UpdateChr_ret_TSTREAM_FAIL;
8228 }
8229 line_idx = params->skip_ct;
8230 const uint32_t colid_first = (params->colid < params->colx);
8231 uint32_t colmin;
8232 uint32_t coldiff;
8233 if (colid_first) {
8234 colmin = params->colid - 1;
8235 coldiff = params->colx - params->colid;
8236 } else {
8237 colmin = params->colx - 1;
8238 coldiff = params->colid - params->colx;
8239 }
8240 const char skipchar = params->skipchar;
8241 uintptr_t miss_ct = 0;
8242 uint32_t hit_ct = 0;
8243 while (1) {
8244 ++line_idx;
8245 char* line_start = TextGet(&txs);
8246 if (!line_start) {
8247 if (likely(!TextStreamErrcode2(&txs, &reterr))) {
8248 break;
8249 }
8250 goto UpdateChr_ret_TSTREAM_FAIL;
8251 }
8252 char cc = *line_start;
8253 if (cc == skipchar) {
8254 continue;
8255 }
8256 char* colid_ptr;
8257 char* colchr_ptr;
8258 if (colid_first) {
8259 colid_ptr = NextTokenMult0(line_start, colmin);
8260 colchr_ptr = NextTokenMult(colid_ptr, coldiff);
8261 if (unlikely(!colchr_ptr)) {
8262 goto UpdateChr_ret_MISSING_TOKENS;
8263 }
8264 } else {
8265 colchr_ptr = NextTokenMult0(line_start, colmin);
8266 colid_ptr = NextTokenMult(colchr_ptr, coldiff);
8267 if (unlikely(!colid_ptr)) {
8268 goto UpdateChr_ret_MISSING_TOKENS;
8269 }
8270 }
8271 const uint32_t varid_slen = strlen_se(colid_ptr);
8272 const uint32_t variant_uidx = VariantIdDupflagHtableFind(colid_ptr, variant_ids, variant_id_htable, varid_slen, variant_id_htable_size, max_variant_id_slen);
8273 if (variant_uidx >> 31) {
8274 if (unlikely(variant_uidx != UINT32_MAX)) {
8275 snprintf(g_logbuf, kLogbufSize, "Error: --update-chr variant ID '%s' appears multiple times in dataset.\n", variant_ids[variant_uidx & 0x7fffffff]);
8276 goto UpdateChr_ret_INCONSISTENT_INPUT_WW;
8277 }
8278 ++miss_ct;
8279 continue;
8280 }
8281 const char* cur_var_id = variant_ids[variant_uidx];
8282 if (unlikely(IsSet(already_seen, variant_uidx))) {
8283 snprintf(g_logbuf, kLogbufSize, "Error: Variant ID '%s' appears multiple times in --update-chr file.\n", cur_var_id);
8284 goto UpdateChr_ret_INCONSISTENT_INPUT_WW;
8285 }
8286 SetBit(variant_uidx, already_seen);
8287
8288 char* chr_code_end = CurTokenEnd(colchr_ptr);
8289 uint32_t cur_chr_code;
8290 reterr = GetOrAddChrCodeDestructive("--update-chr file", line_idx, prohibit_extra_chrs, colchr_ptr, chr_code_end, cip, &cur_chr_code);
8291 if (unlikely(reterr)) {
8292 goto UpdateChr_ret_1;
8293 }
8294 chr_idxs[variant_uidx] = cur_chr_code;
8295 ++hit_ct;
8296 }
8297 if (miss_ct) {
8298 snprintf(g_logbuf, kLogbufSize, "--update-chr: %u value%s updated, %" PRIuPTR " variant ID%s not present.\n", hit_ct, (hit_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s");
8299 } else {
8300 snprintf(g_logbuf, kLogbufSize, "--update-chr: %u value%s updated.\n", hit_ct, (hit_ct == 1)? "" : "s");
8301 }
8302 logputsb();
8303 }
8304 while (0) {
8305 UpdateChr_ret_NOMEM:
8306 reterr = kPglRetNomem;
8307 break;
8308 UpdateChr_ret_TSTREAM_FAIL:
8309 TextStreamErrPrint("--update-map file", &txs);
8310 break;
8311 UpdateChr_ret_MISSING_TOKENS:
8312 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-map file has fewer tokens than expected.\n", line_idx);
8313 UpdateChr_ret_INCONSISTENT_INPUT_WW:
8314 WordWrapB(0);
8315 logerrputsb();
8316 reterr = kPglRetInconsistentInput;
8317 break;
8318 }
8319 UpdateChr_ret_1:
8320 CleanupTextStream2("--update-chr file", &txs, &reterr);
8321 BigstackReset(bigstack_mark);
8322 return reterr;
8323 }
8324
8325 BoolErr SortChr(const ChrInfo* cip, const uint32_t* chr_idx_to_size, uint32_t use_nsort, ChrInfo* write_cip) {
8326 // Finishes initialization of write_cip. Assumes chr_fo_vidx_start is
8327 // allocated and initialized to all-bits-one, chr_file_order/chr_idx_to_foidx
8328 // are unallocated, and chr_ct is uninitialized.
8329 const uint32_t max_code = cip->max_code;
8330 const uint32_t chr_code_end = max_code + 1 + cip->name_ct;
8331 uint32_t new_chr_ct = 0;
8332 for (uint32_t chr_idx = 0; chr_idx != chr_code_end; ++chr_idx) {
8333 const uint32_t cur_chr_size = chr_idx_to_size[chr_idx];
8334 if (cur_chr_size) {
8335 ++new_chr_ct;
8336 }
8337 }
8338 // bugfix (25 Nov 2019): must add 1 for chr_fo_vidx_start
8339 if (bigstack_alloc_u32(new_chr_ct, &(write_cip->chr_file_order)) ||
8340 bigstack_alloc_u32(new_chr_ct + 1, &(write_cip->chr_fo_vidx_start))) {
8341 return 1;
8342 }
8343 write_cip->chr_ct = new_chr_ct;
8344 // now for the actual sorting.
8345 // autosomes and PAR1/X/PAR2/Y/XY/MT come first, then contig names.
8346 const uint32_t autosome_ct = cip->autosome_ct;
8347 const uint32_t xymt_ct = max_code - autosome_ct;
8348 const uint32_t autosome_ct_p1 = autosome_ct + 1;
8349
8350 STD_ARRAY_KREF(uint32_t, kChrOffsetCt) xymt_codes = cip->xymt_codes;
8351 const uintptr_t xymt_idx_to_chr_sort_offset[kChrOffsetCt] = {1, 3, 4, 5, 0, 2};
8352
8353 // chr_sort_idx in high bits, original chr_idx in low
8354 uint64_t* std_sortbuf;
8355 uint64_t* std_sortbuf_iter;
8356 if (bigstack_alloc_u64(max_code + 1, &std_sortbuf)) {
8357 return 1;
8358 }
8359 std_sortbuf_iter = std_sortbuf;
8360 for (uintptr_t chr_idx = 0; chr_idx <= autosome_ct; ++chr_idx) {
8361 if (chr_idx_to_size[chr_idx]) {
8362 *std_sortbuf_iter++ = chr_idx * 0x100000001LLU;
8363 }
8364 }
8365 for (uint32_t xymt_idx = 0; xymt_idx != xymt_ct; ++xymt_idx) {
8366 const uint32_t xymt_code = xymt_codes[xymt_idx];
8367 if (!IsI32Neg(xymt_code)) {
8368 if (chr_idx_to_size[xymt_idx + autosome_ct_p1]) {
8369 *std_sortbuf_iter++ = (S_CAST(uint64_t, xymt_idx_to_chr_sort_offset[xymt_idx] + autosome_ct_p1) << 32) | (xymt_idx + autosome_ct_p1);
8370 }
8371 }
8372 }
8373 const uint32_t std_sortbuf_len = std_sortbuf_iter - std_sortbuf;
8374 STD_SORT(std_sortbuf_len, u64cmp, std_sortbuf);
8375 uint32_t write_vidx = 0;
8376 write_cip->chr_fo_vidx_start[0] = 0;
8377 for (uint32_t new_chr_fo_idx = 0; new_chr_fo_idx != std_sortbuf_len; ++new_chr_fo_idx) {
8378 const uint64_t cur_entry = std_sortbuf[new_chr_fo_idx];
8379 const uintptr_t chr_idx = S_CAST(uint32_t, cur_entry);
8380 const uint32_t chr_size = chr_idx_to_size[chr_idx];
8381 write_cip->chr_file_order[new_chr_fo_idx] = chr_idx;
8382 write_vidx += chr_size;
8383 write_cip->chr_fo_vidx_start[new_chr_fo_idx + 1] = write_vidx;
8384 write_cip->chr_idx_to_foidx[chr_idx] = new_chr_fo_idx;
8385 }
8386
8387 const uint32_t new_nonstd_ct = new_chr_ct - std_sortbuf_len;
8388 if (new_nonstd_ct) {
8389 StrSortIndexedDeref* nonstd_sort_buf = S_CAST(StrSortIndexedDeref*, bigstack_alloc(new_nonstd_ct * sizeof(StrSortIndexedDeref)));
8390 if (!nonstd_sort_buf) {
8391 return 1;
8392 }
8393 const char** nonstd_names = cip->nonstd_names;
8394 uint32_t str_idx = 0;
8395 for (uint32_t chr_idx = max_code + 1; chr_idx != chr_code_end; ++chr_idx) {
8396 if (chr_idx_to_size[chr_idx]) {
8397 nonstd_sort_buf[str_idx].strptr = nonstd_names[chr_idx];
8398 nonstd_sort_buf[str_idx].orig_idx = chr_idx;
8399 ++str_idx;
8400 }
8401 }
8402 assert(str_idx == new_nonstd_ct);
8403 // nonstd_names are not allocated in main workspace, so can't overread.
8404 StrptrArrSortMain(new_nonstd_ct, 0, use_nsort, nonstd_sort_buf);
8405 uint32_t new_chr_fo_idx = std_sortbuf_len;
8406 for (str_idx = 0; str_idx != new_nonstd_ct; ++str_idx, ++new_chr_fo_idx) {
8407 const uint32_t chr_idx = nonstd_sort_buf[str_idx].orig_idx;
8408 const uint32_t chr_size = chr_idx_to_size[chr_idx];
8409 write_cip->chr_file_order[new_chr_fo_idx] = chr_idx;
8410 write_vidx += chr_size;
8411 write_cip->chr_fo_vidx_start[new_chr_fo_idx + 1] = write_vidx;
8412 write_cip->chr_idx_to_foidx[chr_idx] = new_chr_fo_idx;
8413 }
8414 }
8415 BigstackReset(std_sortbuf);
8416 return 0;
8417 }
8418
8419 // hybrid of WriteMapOrBim() and write_pvar_resorted()
8420 PglErr WriteBimResorted(const char* outname, const ChrInfo* write_cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* allele_presents, const AlleleCode* allele_permute, const double* variant_cms, const uint32_t* new_variant_idx_to_old, uint32_t variant_ct, uint32_t max_allele_slen, uint32_t output_zst, char output_missing_geno_char, uint32_t thread_ct) {
8421 // allele_presents must be nullptr unless we're trimming alt alleles
8422 unsigned char* bigstack_mark = g_bigstack_base;
8423 char* cswritep = nullptr;
8424 CompressStreamState css;
8425 PglErr reterr = kPglRetSuccess;
8426 PreinitCstream(&css);
8427 {
8428 const uint32_t max_chr_blen = GetMaxChrSlen(write_cip) + 1;
8429 // includes trailing tab
8430 char* chr_buf;
8431
8432 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
8433 goto WriteBimResorted_ret_NOMEM;
8434 }
8435 const uintptr_t overflow_buf_size = kCompressStreamBlock + kMaxIdSlen + 512 + 2 * max_allele_slen;
8436 reterr = InitCstreamAlloc(outname, 0, output_zst, thread_ct, overflow_buf_size, &css, &cswritep);
8437 if (unlikely(reterr)) {
8438 goto WriteBimResorted_ret_1;
8439 }
8440
8441 uint32_t chr_fo_idx = UINT32_MAX;
8442 uint32_t chr_end = 0;
8443 uint32_t chr_buf_blen = 0;
8444 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
8445 const uint32_t variant_uidx = new_variant_idx_to_old[variant_idx];
8446 if (variant_idx >= chr_end) {
8447 do {
8448 ++chr_fo_idx;
8449 chr_end = write_cip->chr_fo_vidx_start[chr_fo_idx + 1];
8450 } while (variant_idx >= chr_end);
8451 char* chr_name_end = chrtoa(write_cip, write_cip->chr_file_order[chr_fo_idx], chr_buf);
8452 *chr_name_end = '\t';
8453 chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
8454 }
8455 cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
8456 cswritep = strcpyax(cswritep, variant_ids[variant_uidx], '\t');
8457 if (!variant_cms) {
8458 *cswritep++ = '0';
8459 } else {
8460 cswritep = dtoa_g_p8(variant_cms[variant_uidx], cswritep);
8461 }
8462 *cswritep++ = '\t';
8463 cswritep = u32toa(variant_bps[variant_uidx], cswritep);
8464 *cswritep++ = '\t';
8465 const uintptr_t allele_idx_offset_base = allele_idx_offsets? allele_idx_offsets[variant_uidx] : (variant_uidx * 2);
8466 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
8467 // note that VCF ref allele corresponds to A2, not A1
8468 if (!allele_permute) {
8469 if ((!allele_presents) || IsSet(allele_presents, 1 + allele_idx_offset_base)) {
8470 cswritep = strcpya(cswritep, cur_alleles[1]);
8471 } else {
8472 *cswritep++ = output_missing_geno_char;
8473 }
8474 *cswritep++ = '\t';
8475 cswritep = strcpya(cswritep, cur_alleles[0]);
8476 } else {
8477 const AlleleCode* cur_allele_permute = &(allele_permute[allele_idx_offset_base]);
8478 if ((!allele_presents) || IsSet(allele_presents, cur_allele_permute[1] + allele_idx_offset_base)) {
8479 cswritep = strcpya(cswritep, cur_alleles[cur_allele_permute[1]]);
8480 } else {
8481 *cswritep++ = output_missing_geno_char;
8482 }
8483 *cswritep++ = '\t';
8484 cswritep = strcpya(cswritep, cur_alleles[cur_allele_permute[0]]);
8485 }
8486 AppendBinaryEoln(&cswritep);
8487 if (unlikely(Cswrite(&css, &cswritep))) {
8488 goto WriteBimResorted_ret_WRITE_FAIL;
8489 }
8490 }
8491 if (unlikely(CswriteCloseNull(&css, cswritep))) {
8492 goto WriteBimResorted_ret_WRITE_FAIL;
8493 }
8494 }
8495 while (0) {
8496 WriteBimResorted_ret_NOMEM:
8497 reterr = kPglRetNomem;
8498 break;
8499 WriteBimResorted_ret_WRITE_FAIL:
8500 reterr = kPglRetWriteFail;
8501 break;
8502 }
8503 WriteBimResorted_ret_1:
8504 CswriteCloseCond(&css, cswritep);
8505 BigstackReset(bigstack_mark);
8506 return reterr;
8507 }
8508
8509 PglErr PvarInfoLoadAll(const uint32_t* old_variant_uidx_to_new, uint32_t variant_ct, TextStream* pvar_reload_txsp, char** pvar_info_strs) {
8510 // We assume no more dynamic allocations are needed after this; otherwise,
8511 // str_store_iter should be returned.
8512 PglErr reterr = TextRewind(pvar_reload_txsp);
8513 if (unlikely(reterr)) {
8514 return reterr;
8515 }
8516 char* str_store_iter = R_CAST(char*, g_bigstack_base);
8517 char* line_iter;
8518 uint32_t info_col_idx;
8519 reterr = PvarInfoReloadHeader(pvar_reload_txsp, &line_iter, &info_col_idx);
8520 if (unlikely(reterr)) {
8521 return reterr;
8522 }
8523 uint32_t old_variant_idx = 0;
8524 for (uint32_t variant_uidx = 0; ; ++variant_uidx) {
8525 reterr = TextNextLineLstrip(pvar_reload_txsp, &line_iter);
8526 if (unlikely(reterr)) {
8527 return reterr;
8528 }
8529 const uint32_t new_variant_idx_offset = old_variant_uidx_to_new[variant_uidx];
8530 // exploit wraparound, UINT32_MAX null value
8531 if (new_variant_idx_offset >= variant_ct) {
8532 continue;
8533 }
8534 line_iter = NextTokenMultFar(line_iter, info_col_idx);
8535 if (!line_iter) {
8536 return kPglRetRewindFail;
8537 }
8538 char* info_end = CurTokenEnd(line_iter);
8539 const uint32_t info_slen = info_end - line_iter;
8540 pvar_info_strs[new_variant_idx_offset] = str_store_iter;
8541 str_store_iter = memcpyax(str_store_iter, line_iter, info_slen, '\0');
8542 line_iter = info_end;
8543 if (++old_variant_idx == variant_ct) {
8544 break;
8545 }
8546 }
8547 assert(str_store_iter <= R_CAST(char*, g_bigstack_end));
8548 return kPglRetSuccess;
8549 }
8550
8551 typedef struct InfoWriteTmpStruct {
8552 char* cswritep;
8553 CompressStreamState css;
8554 } InfoWriteTmp;
8555
8556 CONSTI32(kMaxPvarInfoTmp, kMaxOpenFiles - 12);
8557
8558 PglErr PvarInfoSplitTmp(const uint32_t* old_variant_uidx_to_new, uint32_t variant_ct, uint32_t batch_size, uint32_t batch_ct, uint32_t info_reload_blen, TextStream* pvar_reload_txsp, char* outname, char* outname_end) {
8559 InfoWriteTmp* info_write_tmps = nullptr;
8560 uint32_t outfile_ct = 0;
8561 PglErr reterr = kPglRetSuccess;
8562 {
8563 char* line_iter;
8564 uint32_t info_col_idx;
8565 reterr = PvarInfoReloadHeader(pvar_reload_txsp, &line_iter, &info_col_idx);
8566 if (unlikely(reterr)) {
8567 return reterr;
8568 }
8569 // fast division by batch_size
8570 uint64_t mult;
8571 uint32_t pre_shift;
8572 uint32_t post_shift;
8573 uint32_t incr;
8574 DivisionMagicNums(batch_size, &mult, &pre_shift, &post_shift, &incr);
8575
8576 outfile_ct = MINV(batch_ct, kMaxPvarInfoTmp);
8577 uint32_t* batch_offset_to_outfile_idx;
8578 if (unlikely(BIGSTACK_ALLOC_X(InfoWriteTmp, outfile_ct, &info_write_tmps) ||
8579 bigstack_alloc_u32(batch_ct, &batch_offset_to_outfile_idx))) {
8580 goto PvarInfoSplitTmp_ret_NOMEM;
8581 }
8582 for (uint32_t batch_idx = 0; batch_idx != batch_ct; ++batch_idx) {
8583 batch_offset_to_outfile_idx[batch_idx] = (batch_idx * S_CAST(uint64_t, outfile_ct)) / batch_ct;
8584 }
8585 for (uint32_t outfile_idx = 0; outfile_idx != outfile_ct; ++outfile_idx) {
8586 PreinitCstream(&(info_write_tmps[outfile_idx].css));
8587 info_write_tmps[outfile_idx].cswritep = nullptr;
8588 }
8589 const uintptr_t overflow_buf_size = kCompressStreamBlock + info_reload_blen;
8590 char* outname_continued = strcpya(outname_end, ".info.tmp.");
8591 uint32_t prev_batch_idx_end = 0;
8592 for (uintptr_t outfile_idx = 0; outfile_idx != outfile_ct; ++outfile_idx) {
8593 const uint32_t batch_idx_end = (S_CAST(uint64_t, outfile_idx + 1) * batch_ct) / outfile_ct;
8594 for (uint32_t batch_idx = prev_batch_idx_end; batch_idx != batch_idx_end; ++batch_idx) {
8595 batch_offset_to_outfile_idx[batch_idx] = outfile_idx;
8596 }
8597 char* outname_iter = u32toa(prev_batch_idx_end, outname_continued);
8598 if (prev_batch_idx_end + 1 < batch_idx_end) {
8599 *outname_iter++ = '-';
8600 outname_iter = u32toa(batch_idx_end - 1, outname_iter);
8601 }
8602 strcpy_k(outname_iter, ".zst");
8603 reterr = InitCstreamAlloc(outname, 0, 1, 1, overflow_buf_size, &(info_write_tmps[outfile_idx].css), &(info_write_tmps[outfile_idx].cswritep));
8604 if (unlikely(reterr)) {
8605 goto PvarInfoSplitTmp_ret_1;
8606 }
8607 prev_batch_idx_end = batch_idx_end;
8608 }
8609
8610 uint32_t old_variant_idx = 0;
8611 for (uint32_t variant_uidx = 0; ; ++variant_uidx) {
8612 reterr = TextNextLineLstrip(pvar_reload_txsp, &line_iter);
8613 if (unlikely(reterr)) {
8614 return reterr;
8615 }
8616 const uint32_t new_variant_idx = old_variant_uidx_to_new[variant_uidx];
8617 // UINT32_MAX serves as null value
8618 if (new_variant_idx >= variant_ct) {
8619 continue;
8620 }
8621 line_iter = NextTokenMultFar(line_iter, info_col_idx);
8622 if (!line_iter) {
8623 return kPglRetRewindFail;
8624 }
8625 char* info_end = CurTokenEnd(line_iter);
8626 const uint32_t info_slen = info_end - line_iter;
8627 const uint32_t batch_idx = (mult * ((new_variant_idx >> pre_shift) + incr)) >> post_shift;
8628 const uint32_t outfile_idx = batch_offset_to_outfile_idx[batch_idx];
8629 // these are temporary files, so don't bother writing \r\n on Windows
8630 info_write_tmps[outfile_idx].cswritep = memcpyax(info_write_tmps[outfile_idx].cswritep, line_iter, info_slen, '\n');
8631 if (unlikely(Cswrite(&(info_write_tmps[outfile_idx].css), &(info_write_tmps[outfile_idx].cswritep)))) {
8632 goto PvarInfoSplitTmp_ret_WRITE_FAIL;
8633 }
8634 line_iter = info_end;
8635 if (++old_variant_idx == variant_ct) {
8636 break;
8637 }
8638 }
8639 for (uint32_t outfile_idx = 0; outfile_idx != outfile_ct; ++outfile_idx) {
8640 if (unlikely(CswriteCloseNull(&(info_write_tmps[outfile_idx].css), info_write_tmps[outfile_idx].cswritep))) {
8641 goto PvarInfoSplitTmp_ret_WRITE_FAIL;
8642 }
8643 }
8644 }
8645 while (0) {
8646 PvarInfoSplitTmp_ret_NOMEM:
8647 reterr = kPglRetNomem;
8648 break;
8649 PvarInfoSplitTmp_ret_WRITE_FAIL:
8650 reterr = kPglRetWriteFail;
8651 break;
8652 }
8653 PvarInfoSplitTmp_ret_1:
8654 if (info_write_tmps) {
8655 for (uint32_t outfile_idx = 0; outfile_idx != outfile_ct; ++outfile_idx) {
8656 CswriteCloseCond(&(info_write_tmps[outfile_idx].css), info_write_tmps[outfile_idx].cswritep);
8657 }
8658 }
8659 // caller expected to reset wkspace
8660 return reterr;
8661 }
8662
8663 PglErr PvarInfoResplitTmp(const uint32_t* new_variant_idx_to_old, uint32_t variant_ct, uint32_t batch_size, uint32_t batch_ct, uint32_t info_reload_blen, TextStream* pvar_reload_txsp, char* outname, char* outname_end) {
8664 unsigned char* bigstack_mark = g_bigstack_base;
8665 InfoWriteTmp* info_write_tmps = nullptr;
8666 uint32_t max_outfile_ct = 0;
8667 PglErr reterr = kPglRetSuccess;
8668 {
8669 max_outfile_ct = 1 + (batch_ct - 1) / kMaxPvarInfoTmp;
8670 // could implement recursion below this level, but I don't expect batch_ct
8671 // > 57600 to actually come up.
8672 if (max_outfile_ct > kMaxPvarInfoTmp) {
8673 logputs("\n");
8674 logerrputs("Error: INFO column is too large for current --sort-vars implementation and\nworkspace size.\n");
8675 reterr = kPglRetNotYetSupported;
8676 goto PvarInfoResplitTmp_ret_1;
8677 }
8678
8679 uint64_t* old_variant_idx_map = nullptr;
8680 unsigned char* bigstack_mark2 = nullptr;
8681 char* outname_continued = strcpya(outname_end, ".info.tmp.");
8682 char* prev_inname = g_textbuf;
8683 char* prev_inname_continued = memcpya(prev_inname, outname, outname_continued - outname);
8684 const uintptr_t overflow_buf_size = kCompressStreamBlock + info_reload_blen;
8685 uint32_t prev_batch_idx_end = 0;
8686 for (uint32_t outer_outfile_idx = 0; outer_outfile_idx != kMaxPvarInfoTmp; ++outer_outfile_idx) {
8687 const uint32_t batch_idx_end = (S_CAST(uint64_t, outer_outfile_idx + 1) * batch_ct) / kMaxPvarInfoTmp;
8688 const uint32_t cur_outfile_ct = batch_idx_end - prev_batch_idx_end;
8689 if (cur_outfile_ct > 1) {
8690 char* inname_iter = u32toa_x(prev_batch_idx_end, '-', outname_continued);
8691 inname_iter = u32toa(batch_idx_end - 1, inname_iter);
8692 inname_iter = memcpya(inname_iter, ".zst", strlen(".zst") + 1);
8693 if (!info_write_tmps) {
8694 // pvar_reload_txs, info_write_tmps uninitialized.
8695 // We wait until this point so we can initialize pvar_reload_txs to
8696 // the first temporary file we need to resplit, and then make
8697 // temporary allocations on top of it.
8698 reterr = InitTextStream(outname, MAXV(info_reload_blen, kTextStreamBlenFast), 1, pvar_reload_txsp);
8699 if (unlikely(reterr)) {
8700 goto PvarInfoResplitTmp_ret_TSTREAM_FAIL;
8701 }
8702 bigstack_mark = g_bigstack_base;
8703 if (unlikely(bigstack_alloc_u64(max_outfile_ct * batch_size, &old_variant_idx_map) ||
8704 BIGSTACK_ALLOC_X(InfoWriteTmp, max_outfile_ct, &info_write_tmps))) {
8705 goto PvarInfoResplitTmp_ret_NOMEM;
8706 }
8707 bigstack_mark2 = g_bigstack_base;
8708 for (uint32_t outfile_idx = 0; outfile_idx != max_outfile_ct; ++outfile_idx) {
8709 PreinitCstream(&(info_write_tmps[outfile_idx].css));
8710 info_write_tmps[outfile_idx].cswritep = nullptr;
8711 }
8712 } else {
8713 BigstackReset(bigstack_mark2);
8714 reterr = TextRetarget(outname, pvar_reload_txsp);
8715 if (unlikely(reterr)) {
8716 goto PvarInfoResplitTmp_ret_TSTREAM_FAIL;
8717 }
8718 if (unlikely(unlink(prev_inname))) {
8719 logputs("\n");
8720 logerrprintfww("Error: Failed to delete %s .\n", prev_inname);
8721 goto PvarInfoResplitTmp_ret_WRITE_FAIL;
8722 }
8723 }
8724 // Save filename so we can unlink it later.
8725 memcpy(prev_inname_continued, outname_continued, inname_iter - outname_continued);
8726 for (uint32_t outfile_idx = 0; outfile_idx != cur_outfile_ct; ++outfile_idx) {
8727 char* outname_iter = u32toa(outfile_idx + prev_batch_idx_end, outname_continued);
8728 strcpy_k(outname_iter, ".zst");
8729 reterr = InitCstreamAlloc(outname, 0, 1, 1, overflow_buf_size, &(info_write_tmps[outfile_idx].css), &(info_write_tmps[outfile_idx].cswritep));
8730 if (unlikely(reterr)) {
8731 goto PvarInfoResplitTmp_ret_1;
8732 }
8733 }
8734 // Determine ordering of variants in the temporary input file.
8735 const uint32_t variant_idx_start = prev_batch_idx_end * batch_size;
8736 uint32_t variant_idx_end = MINV(batch_idx_end * batch_size, variant_ct);
8737 const uintptr_t shard_variant_ct = variant_idx_end - variant_idx_start;
8738 const uint32_t* shard_new_variant_idx_to_old = &(new_variant_idx_to_old[variant_idx_start]);
8739 uint32_t shard_variant_idx = 0;
8740 for (uintptr_t outfile_idx = 0; outfile_idx != cur_outfile_ct; ++outfile_idx) {
8741 const uint32_t shard_variant_idx_stop = MINV(shard_variant_idx + batch_size, shard_variant_ct);
8742 for (; shard_variant_idx != shard_variant_idx_stop; ++shard_variant_idx) {
8743 const uint64_t old_variant_uidx = shard_new_variant_idx_to_old[shard_variant_idx];
8744 old_variant_idx_map[shard_variant_idx] = (old_variant_uidx << 32) | outfile_idx;
8745 }
8746 }
8747 STD_SORT_PAR_UNSEQ(shard_variant_ct, u64cmp, old_variant_idx_map);
8748
8749 // Now we know how to split them.
8750 char* line_iter;
8751 for (uintptr_t shard_old_variant_idx = 0; shard_old_variant_idx != shard_variant_ct; ++shard_old_variant_idx) {
8752 reterr = TextNextLine(pvar_reload_txsp, &line_iter);
8753 if (unlikely(reterr)) {
8754 goto PvarInfoResplitTmp_ret_TSTREAM_FAIL;
8755 }
8756 char* line_end = TextLineEnd(pvar_reload_txsp);
8757 const uint32_t info_slen = line_end - line_iter;
8758 const uint32_t outfile_idx = S_CAST(uint32_t, old_variant_idx_map[shard_old_variant_idx]);
8759 info_write_tmps[outfile_idx].cswritep = memcpya(info_write_tmps[outfile_idx].cswritep, line_iter, info_slen);
8760 if (unlikely(Cswrite(&(info_write_tmps[outfile_idx].css), &(info_write_tmps[outfile_idx].cswritep)))) {
8761 goto PvarInfoResplitTmp_ret_WRITE_FAIL;
8762 }
8763 }
8764
8765 for (uint32_t outfile_idx = 0; outfile_idx != cur_outfile_ct; ++outfile_idx) {
8766 if (unlikely(CswriteCloseNull(&(info_write_tmps[outfile_idx].css), info_write_tmps[outfile_idx].cswritep))) {
8767 goto PvarInfoResplitTmp_ret_WRITE_FAIL;
8768 }
8769 }
8770 }
8771 prev_batch_idx_end = batch_idx_end;
8772 }
8773 }
8774 while (0) {
8775 PvarInfoResplitTmp_ret_NOMEM:
8776 reterr = kPglRetNomem;
8777 break;
8778 PvarInfoResplitTmp_ret_WRITE_FAIL:
8779 reterr = kPglRetWriteFail;
8780 break;
8781 PvarInfoResplitTmp_ret_TSTREAM_FAIL:
8782 logputs("\n");
8783 TextStreamErrPrint("--sort-vars temporary INFO file", pvar_reload_txsp);
8784 break;
8785 }
8786 PvarInfoResplitTmp_ret_1:
8787 if (info_write_tmps) {
8788 for (uint32_t outfile_idx = 0; outfile_idx != max_outfile_ct; ++outfile_idx) {
8789 CswriteCloseCond(&(info_write_tmps[outfile_idx].css), info_write_tmps[outfile_idx].cswritep);
8790 }
8791 }
8792 BigstackReset(bigstack_mark);
8793 return reterr;
8794 }
8795
8796 PglErr PvarInfoReloadInterval(const uint32_t* new_variant_idx_to_old, uint32_t variant_idx_start, uint32_t variant_idx_end, TextStream* pvar_reload_txsp, char** pvar_info_strs, uint32_t* variant_order_in_shard) {
8797 // We assume the batch size was chosen such that there's no risk of
8798 // scribbling past g_bigstack_end (barring pathological cases like another
8799 // process modifying the temporary file).
8800 // We assume no more dynamic allocations are needed after this; otherwise,
8801 // str_store_iter should be returned.
8802 uint64_t* old_variant_idx_map = R_CAST(uint64_t*, g_bigstack_base);
8803 const uintptr_t shard_variant_ct = variant_idx_end - variant_idx_start;
8804 const uint32_t* shard_new_variant_idx_to_old = &(new_variant_idx_to_old[variant_idx_start]);
8805 for (uintptr_t shard_new_variant_idx = 0; shard_new_variant_idx != shard_variant_ct; ++shard_new_variant_idx) {
8806 const uint64_t old_variant_uidx = shard_new_variant_idx_to_old[shard_new_variant_idx];
8807 old_variant_idx_map[shard_new_variant_idx] = (old_variant_uidx << 32) | shard_new_variant_idx;
8808 }
8809
8810 STD_SORT_PAR_UNSEQ(shard_variant_ct, u64cmp, old_variant_idx_map);
8811 for (uintptr_t shard_old_variant_idx = 0; shard_old_variant_idx != shard_variant_ct; ++shard_old_variant_idx) {
8812 variant_order_in_shard[shard_old_variant_idx] = S_CAST(uint32_t, old_variant_idx_map[shard_old_variant_idx]);
8813 }
8814 // now we can scribble over old_variant_idx_map
8815 char* str_store_iter = R_CAST(char*, g_bigstack_base);
8816 char* line_iter;
8817 for (uintptr_t shard_old_variant_idx = 0; shard_old_variant_idx != shard_variant_ct; ++shard_old_variant_idx) {
8818 PglErr reterr = TextNextLine(pvar_reload_txsp, &line_iter);
8819 if (unlikely(reterr)) {
8820 return reterr;
8821 }
8822 char* line_end = TextLineEnd(pvar_reload_txsp);
8823 pvar_info_strs[variant_order_in_shard[shard_old_variant_idx]] = str_store_iter;
8824 str_store_iter = memcpya(str_store_iter, line_iter, line_end - line_iter);
8825 }
8826 return kPglRetSuccess;
8827 }
8828
8829 PglErr WritePvarResortedInterval(const ChrInfo* write_cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* allele_presents, const AlleleCode* allele_permute, const uintptr_t* qual_present, const float* quals, const uintptr_t* filter_present, const uintptr_t* filter_npass, const char* const* filter_storage, const uintptr_t* nonref_flags, const double* variant_cms, const uint32_t* new_variant_idx_to_old, const char* const* info_keys, const uint32_t* info_keys_htable, uint32_t variant_idx_start, uint32_t variant_idx_end, uint32_t info_pr_flag_present, uint32_t write_qual, uint32_t write_filter, uint32_t write_info, uint32_t all_nonref, uint32_t write_cm, uint32_t info_keys_htable_size, char output_missing_geno_char, char** pvar_info_strs, CompressStreamState* cssp, char** cswritepp, uint32_t* chr_fo_idxp, uint32_t* chr_endp, uint32_t* chr_buf_blenp, char* chr_buf, const char** info_allele_val_starts, uint32_t* info_allele_val_slens) {
8830 char* cswritep = *cswritepp;
8831 uint32_t chr_fo_idx = *chr_fo_idxp;
8832 uint32_t chr_end = *chr_endp;
8833 uint32_t chr_buf_blen = *chr_buf_blenp;
8834 PglErr reterr = kPglRetSuccess;
8835 {
8836 const AlleleCode* cur_allele_permute = nullptr;
8837 uint32_t ref_allele_idx = 0;
8838 uint32_t alt1_allele_idx = 1;
8839 uint32_t cur_allele_ct = 2;
8840 uint32_t alleles_permuted = 0;
8841 for (uint32_t variant_idx = variant_idx_start; variant_idx != variant_idx_end; ++variant_idx) {
8842 const uint32_t variant_uidx = new_variant_idx_to_old[variant_idx];
8843 if (variant_idx == chr_end) {
8844 ++chr_fo_idx;
8845 chr_end = write_cip->chr_fo_vidx_start[chr_fo_idx + 1];
8846 assert(variant_idx < chr_end);
8847 char* chr_name_end = chrtoa(write_cip, write_cip->chr_file_order[chr_fo_idx], chr_buf);
8848 *chr_name_end = '\t';
8849 chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
8850 }
8851 cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
8852 cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep);
8853 const char* variant_id = variant_ids[variant_uidx];
8854 cswritep = strcpyax(cswritep, variant_id, '\t');
8855 uintptr_t allele_idx_offset_base;
8856 if (!allele_idx_offsets) {
8857 allele_idx_offset_base = variant_uidx * 2;
8858 } else {
8859 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
8860 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
8861 }
8862 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
8863 if (allele_permute) {
8864 cur_allele_permute = &(allele_permute[allele_idx_offset_base]);
8865 ref_allele_idx = cur_allele_permute[0];
8866 alt1_allele_idx = cur_allele_permute[1];
8867 }
8868 if (!strequal_k_unsafe(cur_alleles[ref_allele_idx], ".")) {
8869 cswritep = strcpya(cswritep, cur_alleles[ref_allele_idx]);
8870 } else {
8871 *cswritep++ = output_missing_geno_char;
8872 }
8873 *cswritep++ = '\t';
8874 uint32_t alt_allele_written = 0;
8875 if ((!allele_presents) || IsSet(allele_presents, allele_idx_offset_base + alt1_allele_idx)) {
8876 if (!strequal_k_unsafe(cur_alleles[alt1_allele_idx], ".")) {
8877 cswritep = strcpya(cswritep, cur_alleles[alt1_allele_idx]);
8878 } else {
8879 *cswritep++ = output_missing_geno_char;
8880 }
8881 alt_allele_written = 1;
8882 }
8883 if (unlikely(Cswrite(cssp, &cswritep))) {
8884 goto WritePvarResortedInterval_ret_WRITE_FAIL;
8885 }
8886 for (uint32_t aidx = 2; aidx != cur_allele_ct; ++aidx) {
8887 const uint32_t write_aidx = cur_allele_permute? cur_allele_permute[aidx] : aidx;
8888 if (allele_presents && (!IsSet(allele_presents, allele_idx_offset_base + write_aidx))) {
8889 continue;
8890 }
8891 if (alt_allele_written) {
8892 *cswritep++ = ',';
8893 }
8894 alt_allele_written = 1;
8895 cswritep = strcpya(cswritep, cur_alleles[write_aidx]);
8896 if (unlikely(Cswrite(cssp, &cswritep))) {
8897 goto WritePvarResortedInterval_ret_WRITE_FAIL;
8898 }
8899 }
8900 if (!alt_allele_written) {
8901 *cswritep++ = output_missing_geno_char;
8902 }
8903
8904 if (write_qual) {
8905 *cswritep++ = '\t';
8906 if ((!qual_present) || (!IsSet(qual_present, variant_uidx))) {
8907 *cswritep++ = '.';
8908 } else {
8909 cswritep = ftoa_g(quals[variant_uidx], cswritep);
8910 }
8911 }
8912
8913 if (write_filter) {
8914 *cswritep++ = '\t';
8915 if ((!filter_present) || (!IsSet(filter_present, variant_uidx))) {
8916 *cswritep++ = '.';
8917 } else if (!IsSet(filter_npass, variant_uidx)) {
8918 cswritep = strcpya_k(cswritep, "PASS");
8919 } else {
8920 cswritep = strcpya(cswritep, filter_storage[variant_uidx]);
8921 }
8922 }
8923
8924 if (write_info) {
8925 *cswritep++ = '\t';
8926 const uint32_t is_pr = all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx));
8927 if (pvar_info_strs) {
8928 if (cur_allele_permute) {
8929 alleles_permuted = 0;
8930 for (uint32_t aidx = 0; aidx != cur_allele_ct; ++aidx) {
8931 if (cur_allele_permute[aidx] != aidx) {
8932 alleles_permuted = 1;
8933 break;
8934 }
8935 }
8936 }
8937 if (!alleles_permuted) {
8938 PvarInfoWrite(info_pr_flag_present, is_pr, pvar_info_strs[variant_idx - variant_idx_start], &cswritep);
8939 } else {
8940 reterr = PvarInfoPermuteWrite(cur_allele_permute, info_keys, info_keys_htable, variant_id, pvar_info_strs[variant_idx - variant_idx_start], info_keys_htable_size, cur_allele_ct, is_pr, &cswritep, info_allele_val_starts, info_allele_val_slens);
8941 if (unlikely(reterr)) {
8942 goto WritePvarResortedInterval_ret_1;
8943 }
8944 }
8945 } else {
8946 if (is_pr) {
8947 cswritep = strcpya_k(cswritep, "PR");
8948 } else {
8949 *cswritep++ = '.';
8950 }
8951 }
8952 }
8953
8954 if (write_cm) {
8955 *cswritep++ = '\t';
8956 if (!variant_cms) {
8957 *cswritep++ = '0';
8958 } else {
8959 cswritep = dtoa_g_p8(variant_cms[variant_uidx], cswritep);
8960 }
8961 }
8962 AppendBinaryEoln(&cswritep);
8963 }
8964
8965 }
8966 while (0) {
8967 WritePvarResortedInterval_ret_WRITE_FAIL:
8968 reterr = kPglRetWriteFail;
8969 break;
8970 }
8971 WritePvarResortedInterval_ret_1:
8972 *cswritepp = cswritep;
8973 *chr_fo_idxp = chr_fo_idx;
8974 *chr_endp = chr_end;
8975 *chr_buf_blenp = chr_buf_blen;
8976 return reterr;
8977 }
8978
8979 // allele_presents must be nullptr unless we're trimming alt alleles.
8980 //
8981 // The annoying part of this is handling a sequence of INFO strings that don't
8982 // fit in memory; we use a multipass approach for that. File creation,
8983 // allocation of buffers, and generating the header line occurs directly in
8984 // this function, while loading the next pvar_info_strs batch and writing the
8985 // next .pvar line batch are one level down.
8986 PglErr WritePvarResorted(const uintptr_t* variant_include, const ChrInfo* write_cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* allele_presents, const AlleleCode* allele_permute, const uintptr_t* qual_present, const float* quals, const uintptr_t* filter_present, const uintptr_t* filter_npass, const char* const* filter_storage, const uintptr_t* nonref_flags, const char* pvar_info_reload, const double* variant_cms, const uint32_t* new_variant_idx_to_old, const char* const* info_keys, const uint32_t* info_keys_htable, const uint32_t* contig_lens, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct, uint32_t max_allele_slen, uintptr_t xheader_blen, InfoFlags info_flags, uint32_t nonref_flags_storage, uint32_t max_filter_slen, uint32_t info_reload_slen, uint32_t info_keys_htable_size, PvarPsamFlags pvar_psam_flags, char output_missing_geno_char, uint32_t write_info, uint32_t write_info_pr, uint32_t thread_ct, char* xheader, char* outname, char* outname_end) {
8987 unsigned char* bigstack_mark = g_bigstack_base;
8988 char* cswritep = nullptr;
8989 PglErr reterr = kPglRetSuccess;
8990 CompressStreamState css;
8991 TextStream pvar_reload_txs;
8992 PreinitCstream(&css);
8993 PreinitTextStream(&pvar_reload_txs);
8994 {
8995 const uint32_t max_chr_blen = GetMaxChrSlen(write_cip) + 1;
8996 // includes trailing tab
8997 char* chr_buf;
8998
8999 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
9000 goto WritePvarResorted_ret_NOMEM;
9001 }
9002 const char** info_allele_val_starts = nullptr;
9003 uint32_t* info_allele_val_slens = nullptr;
9004 if (allele_permute && write_info) {
9005 if (unlikely(bigstack_alloc_kcp(max_allele_ct, &info_allele_val_starts) ||
9006 bigstack_alloc_u32(max_allele_ct, &info_allele_val_slens))) {
9007 goto WritePvarResorted_ret_NOMEM;
9008 }
9009 }
9010 uintptr_t overflow_buf_size = kCompressStreamBlock + kMaxIdSlen + 512 + 2 * max_allele_slen + max_filter_slen + info_reload_slen;
9011 if (overflow_buf_size < 2 * kCompressStreamBlock) {
9012 overflow_buf_size = 2 * kCompressStreamBlock;
9013 }
9014 const uint32_t output_zst = (pvar_psam_flags / kfPvarZs) & 1;
9015 reterr = InitCstreamAlloc(outname, 0, output_zst, thread_ct, overflow_buf_size, &css, &cswritep);
9016 if (unlikely(reterr)) {
9017 goto WritePvarResorted_ret_1;
9018 }
9019 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
9020 const uint32_t all_nonref = (nonref_flags_storage == 2);
9021
9022 uint32_t write_filter = 0;
9023 if (pvar_psam_flags & kfPvarColFilter) {
9024 write_filter = 1;
9025 } else if ((pvar_psam_flags & kfPvarColMaybefilter) && filter_present) {
9026 write_filter = !IntersectionIsEmpty(variant_include, filter_present, raw_variant_ctl);
9027 }
9028 const uint32_t info_pr_flag_present = (info_flags / kfInfoPrFlagPresent) & 1;
9029 if (pvar_psam_flags & (kfPvarColXheader | kfPvarColVcfheader)) {
9030 reterr = PvarXheaderWrite(nullptr, write_cip, contig_lens, xheader_blen, (pvar_psam_flags / kfPvarColVcfheader) & 1, write_filter, write_info, write_info_pr && (!info_pr_flag_present), xheader, &css, &cswritep);
9031 if (unlikely(reterr)) {
9032 goto WritePvarResorted_ret_1;
9033 }
9034 }
9035 if (write_cip->chrset_source) {
9036 AppendChrsetLine(write_cip, &cswritep);
9037 }
9038 cswritep = strcpya_k(cswritep, "#CHROM\tPOS\tID\tREF\tALT");
9039
9040 uint32_t write_qual = 0;
9041 if (pvar_psam_flags & kfPvarColQual) {
9042 write_qual = 1;
9043 } else if ((pvar_psam_flags & kfPvarColMaybequal) && qual_present) {
9044 write_qual = !IntersectionIsEmpty(variant_include, qual_present, raw_variant_ctl);
9045 }
9046 if (write_qual) {
9047 cswritep = strcpya_k(cswritep, "\tQUAL");
9048 }
9049
9050 if (write_filter) {
9051 cswritep = strcpya_k(cswritep, "\tFILTER");
9052 }
9053
9054 if (write_info) {
9055 cswritep = strcpya_k(cswritep, "\tINFO");
9056 }
9057
9058 uint32_t write_cm = 0;
9059 if (pvar_psam_flags & kfPvarColCm) {
9060 write_cm = 1;
9061 } else if ((pvar_psam_flags & kfPvarColMaybecm) && variant_cms) {
9062 if (raw_variant_ct == variant_ct) {
9063 // nonzero_cm_present check was performed
9064 write_cm = 1;
9065 } else {
9066 uintptr_t variant_uidx_base = 0;
9067 uintptr_t cur_bits = variant_include[0];
9068 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
9069 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
9070 if (variant_cms[variant_uidx] != 0.0) {
9071 write_cm = 1;
9072 break;
9073 }
9074 }
9075 }
9076 }
9077 if (write_cm) {
9078 cswritep = strcpya_k(cswritep, "\tCM");
9079 }
9080 AppendBinaryEoln(&cswritep);
9081
9082 char** pvar_info_strs = nullptr;
9083 uint32_t* variant_order_in_shard = nullptr;
9084 const uint32_t info_reload_blen = info_reload_slen + 1;
9085 uint32_t batch_size = variant_ct;
9086 uint32_t batch_ct = 1;
9087 // Original algorithm for handling an INFO column too large to fit in
9088 // memory was to re-iterate through the .pvar/VCF many times, scraping only
9089 // the INFO entries needed for the current batch each time.
9090 // This was done because it reused existing INFO-reloading code, but
9091 // unfortunately it has a quadratic cost, and this matters since huge INFO
9092 // columns are pretty common (see e.g. gnomAD). So it's time to rework
9093 // this.
9094 // New approach:
9095 // - If, knowing info_reload_slen, we know all relevant INFO strings will
9096 // fit in 3/4 of remaining memory, fill pvar_info_strs upfront.
9097 // - Otherwise, scrape the INFO strings in order and append them to
9098 // compressed temporary files, each sized to fit in remaining memory
9099 // after decompression. (If more than 240 shards are required, then we
9100 // shard recursively to avoid having too many files open at once.) Then
9101 // process the shards in order.
9102 if (pvar_info_reload) {
9103 uintptr_t bytes_left = bigstack_left();
9104 // 1. array of uint64s, old_uidx in high bits, new_idx in low
9105 // 2. sort this
9106 // 3. extract new_idx sequence
9107
9108 uint32_t decompress_thread_ct = 1;
9109 if (!output_zst) {
9110 decompress_thread_ct = thread_ct - 1;
9111 if (!decompress_thread_ct) {
9112 decompress_thread_ct = 1;
9113 }
9114 }
9115 unsigned char* bigstack_mark2 = g_bigstack_base;
9116 // Long line-length limit, because with e.g. "plink2 --vcf <filename>
9117 // --make-just-pvar", the VCF is simply reinterpreted as a .pvar even if
9118 // it's multisample.
9119 reterr = SizeAndInitTextStream(pvar_info_reload, bytes_left / 4, decompress_thread_ct, &pvar_reload_txs);
9120 if (unlikely(reterr)) {
9121 goto WritePvarResorted_ret_TSTREAM_FAIL;
9122 }
9123
9124 uint32_t* old_variant_uidx_to_new = S_CAST(uint32_t*, bigstack_alloc_raw_rd(raw_variant_ct * sizeof(int32_t)));
9125 SetAllU32Arr(raw_variant_ct, old_variant_uidx_to_new);
9126 for (uint32_t new_variant_idx = 0; new_variant_idx != variant_ct; ++new_variant_idx) {
9127 const uint32_t old_variant_uidx = new_variant_idx_to_old[new_variant_idx];
9128 old_variant_uidx_to_new[old_variant_uidx] = new_variant_idx;
9129 }
9130
9131 const uintptr_t no_reload_bytes_left = bigstack_left();
9132 uint32_t single_variant_byte_ct = info_reload_blen + sizeof(intptr_t);
9133 // bugfix (2 Oct 2023): left term needs to be uintptr_t, not uint32_t
9134 if (S_CAST(uintptr_t, variant_ct) * single_variant_byte_ct + kCacheline <= no_reload_bytes_left) {
9135 pvar_info_strs = S_CAST(char**, bigstack_alloc_raw_rd(batch_size * sizeof(intptr_t)));
9136 reterr = PvarInfoLoadAll(old_variant_uidx_to_new, variant_ct, &pvar_reload_txs, pvar_info_strs);
9137 if (unlikely(reterr)) {
9138 goto WritePvarResorted_ret_TSTREAM_FAIL;
9139 }
9140 } else {
9141 if (info_reload_blen < sizeof(int64_t) + sizeof(int32_t)) {
9142 single_variant_byte_ct = sizeof(int64_t) + sizeof(int32_t) + sizeof(intptr_t);
9143 }
9144 const uintptr_t expected_text_stream_alloc = MAXV(RoundUpPow2(info_reload_blen + kDecompressChunkSize, kCacheline), kTextStreamBlenFast + kDecompressChunkSize);
9145 if (unlikely(bytes_left < expected_text_stream_alloc + 2 * kCacheline + single_variant_byte_ct)) {
9146 goto WritePvarResorted_ret_NOMEM;
9147 }
9148 bytes_left -= expected_text_stream_alloc + 2 * kCacheline;
9149 if (S_CAST(uintptr_t, variant_ct) * single_variant_byte_ct > bytes_left) {
9150 batch_size = bytes_left / single_variant_byte_ct;
9151 batch_ct = 1 + (variant_ct - 1) / batch_size;
9152 }
9153 const uint32_t usual_zst_level = g_zst_level;
9154 g_zst_level = 1;
9155 reterr = PvarInfoSplitTmp(old_variant_uidx_to_new, variant_ct, batch_size, batch_ct, info_reload_blen, &pvar_reload_txs, outname, outname_end);
9156 if (unlikely(reterr)) {
9157 goto WritePvarResorted_ret_1;
9158 }
9159 g_zst_level = usual_zst_level;
9160 }
9161 if (unlikely(CleanupTextStream2(pvar_info_reload, &pvar_reload_txs, &reterr))) {
9162 goto WritePvarResorted_ret_1;
9163 }
9164 BigstackReset(bigstack_mark2);
9165 if (!pvar_info_strs) {
9166 if (batch_ct > kMaxPvarInfoTmp) {
9167 reterr = PvarInfoResplitTmp(new_variant_idx_to_old, variant_ct, batch_size, batch_ct, info_reload_blen, &pvar_reload_txs, outname, outname_end);
9168 if (unlikely(reterr)) {
9169 goto WritePvarResorted_ret_1;
9170 }
9171 }
9172 snprintf(outname_end, kMaxOutfnameExtBlen, ".info.tmp.0.zst");
9173 if (batch_ct <= kMaxPvarInfoTmp) {
9174 reterr = InitTextStream(outname, MAXV(info_reload_blen, kTextStreamBlenFast), 1, &pvar_reload_txs);
9175 if (unlikely(reterr)) {
9176 goto WritePvarResorted_ret_TSTREAM_FAIL_2;
9177 }
9178 } else {
9179 reterr = TextRetarget(outname, &pvar_reload_txs);
9180 if (unlikely(reterr)) {
9181 goto WritePvarResorted_ret_TSTREAM_FAIL_2;
9182 }
9183 if (unlikely(unlink(g_textbuf))) {
9184 logputs("\n");
9185 logerrprintfww("Error: Failed to delete %s .\n", g_textbuf);
9186 goto WritePvarResorted_ret_WRITE_FAIL;
9187 }
9188 }
9189 variant_order_in_shard = S_CAST(uint32_t*, bigstack_alloc_raw_rd(batch_size * sizeof(int32_t)));
9190 pvar_info_strs = S_CAST(char**, bigstack_alloc_raw_rd(batch_size * sizeof(intptr_t)));
9191 }
9192 }
9193
9194 uint32_t variant_idx_start = 0;
9195 uint32_t chr_fo_idx = UINT32_MAX;
9196 uint32_t chr_end = 0;
9197 uint32_t chr_buf_blen = 0;
9198 uint32_t pct = 0;
9199 uint32_t next_print_variant_idx = variant_ct / 100;
9200 fputs("0%", stdout);
9201 fflush(stdout);
9202 for (uint32_t batch_idx = 0; batch_idx != batch_ct; ++batch_idx) {
9203 if (variant_idx_start >= next_print_variant_idx) {
9204 if (pct > 10) {
9205 putc_unlocked('\b', stdout);
9206 }
9207 pct = (variant_idx_start * 100LLU) / variant_ct;
9208 printf("\b\b%u%%", pct++);
9209 fflush(stdout);
9210 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
9211 }
9212 uint32_t variant_idx_end = MINV(variant_idx_start + batch_size, variant_ct);
9213 if (pvar_info_reload && variant_order_in_shard) {
9214 reterr = PvarInfoReloadInterval(new_variant_idx_to_old, variant_idx_start, variant_idx_end, &pvar_reload_txs, pvar_info_strs, variant_order_in_shard);
9215 if (unlikely(reterr)) {
9216 goto WritePvarResorted_ret_TSTREAM_FAIL;
9217 }
9218 const uint32_t fname_slen = S_CAST(uintptr_t, outname_end - outname) + strlen(outname_end);
9219 memcpy(g_textbuf, outname, fname_slen + 1);
9220 if (batch_idx + 1 < batch_ct) {
9221 char* write_iter = strcpya(outname_end, ".info.tmp.");
9222 write_iter = u32toa(batch_idx + 1, write_iter);
9223 strcpy_k(write_iter, ".zst");
9224 reterr = TextRetarget(outname, &pvar_reload_txs);
9225 if (unlikely(reterr)) {
9226 goto WritePvarResorted_ret_TSTREAM_FAIL_2;
9227 }
9228 }
9229 if (unlikely(unlink(g_textbuf))) {
9230 logputs("\n");
9231 logerrprintfww("Error: Failed to delete %s .\n", g_textbuf);
9232 goto WritePvarResorted_ret_WRITE_FAIL;
9233 }
9234 }
9235 reterr = WritePvarResortedInterval(write_cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, allele_presents, allele_permute, qual_present, quals, filter_present, filter_npass, filter_storage, nonref_flags, variant_cms, new_variant_idx_to_old, info_keys, info_keys_htable, variant_idx_start, variant_idx_end, info_pr_flag_present, write_qual, write_filter, write_info, all_nonref, write_cm, info_keys_htable_size, output_missing_geno_char, pvar_info_strs, &css, &cswritep, &chr_fo_idx, &chr_end, &chr_buf_blen, chr_buf, info_allele_val_starts, info_allele_val_slens);
9236 if (unlikely(reterr)) {
9237 goto WritePvarResorted_ret_1;
9238 }
9239 variant_idx_start = variant_idx_end;
9240 }
9241
9242 if (unlikely(CswriteCloseNull(&css, cswritep))) {
9243 goto WritePvarResorted_ret_WRITE_FAIL;
9244 }
9245 if (pct > 10) {
9246 putc_unlocked('\b', stdout);
9247 }
9248 fputs("\b\b", stdout);
9249 }
9250 while (0) {
9251 WritePvarResorted_ret_NOMEM:
9252 reterr = kPglRetNomem;
9253 break;
9254 WritePvarResorted_ret_TSTREAM_FAIL:
9255 logputs("\n");
9256 TextStreamErrPrint(pvar_info_reload, &pvar_reload_txs);
9257 break;
9258 WritePvarResorted_ret_TSTREAM_FAIL_2:
9259 logputs("\n");
9260 TextStreamErrPrint(outname, &pvar_reload_txs);
9261 break;
9262 WritePvarResorted_ret_WRITE_FAIL:
9263 reterr = kPglRetWriteFail;
9264 break;
9265 }
9266 WritePvarResorted_ret_1:
9267 CswriteCloseCond(&css, cswritep);
9268 CleanupTextStream2(pvar_info_reload, &pvar_reload_txs, &reterr);
9269 BigstackReset(bigstack_mark);
9270 return reterr;
9271 }
9272
9273 PglErr MakePlink2Vsort(const uintptr_t* sample_include, const PedigreeIdInfo* piip, const uintptr_t* sex_nm, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const char* pheno_names, const uint32_t* new_sample_idx_to_old, const uintptr_t* variant_include, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* allele_presents, const AlleleCode* allele_permute, const uintptr_t* pvar_qual_present, const float* pvar_quals, const uintptr_t* pvar_filter_present, const uintptr_t* pvar_filter_npass, const char* const* pvar_filter_storage, const char* pvar_info_reload, const double* variant_cms, const char* output_missing_pheno, const char* legacy_output_missing_pheno, const uint32_t* contig_lens, const TwoColParams* update_chr_flag, const char* writer_ver, uintptr_t xheader_blen, InfoFlags info_flags, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct, uint32_t max_variant_id_slen, uint32_t max_allele_slen, uint32_t max_filter_slen, uint32_t info_reload_slen, char output_missing_geno_char, uint32_t max_thread_ct, uint32_t hard_call_thresh, uint32_t dosage_erase_thresh, MiscFlags misc_flags, MakePlink2Flags make_plink2_flags, uint32_t use_nsort, PvarPsamFlags pvar_psam_flags, ChrInfo* cip, char* xheader, ChrIdx* chr_idxs, PgenReader* simple_pgrp, char* outname, char* outname_end) {
9274 unsigned char* bigstack_mark = g_bigstack_base;
9275 unsigned char* bigstack_end_mark = g_bigstack_end;
9276 PglErr reterr = kPglRetSuccess;
9277 {
9278 // Resort the variants.
9279 // 1. Apply --update-chr if necessary.
9280 // 2. Count number of remaining variants in each chromosome, then sort the
9281 // chromosomes.
9282 // 3. Within each chromosome, sort by position. Could add 0.5 for
9283 // non-SNPs (not currently implemented)? Could multithread this by
9284 // chromosome, and/or use C++17 multithreaded sort, but INFO-reload is a
9285 // much bigger bottleneck in practice.
9286 // 4. Scan for position ties, sort on ID (according to --sort-vars setting,
9287 // defaults to natural-sort but can be ASCII).
9288 // 5. Fill new_variant_idx_to_old, free sort buffers.
9289
9290 if (update_chr_flag) {
9291 if (!chr_idxs) {
9292 if (unlikely(BIGSTACK_ALLOC_X(ChrIdx, raw_variant_ct, &chr_idxs))) {
9293 goto MakePlink2Vsort_ret_NOMEM;
9294 }
9295 const uint32_t chr_ct = cip->chr_ct;
9296 uint32_t prev_end_vidx = 0;
9297 for (uint32_t chr_fo_idx = 0; chr_fo_idx != chr_ct; ++chr_fo_idx) {
9298 const uint32_t cur_end_vidx = cip->chr_fo_vidx_start[chr_fo_idx + 1];
9299 ChrIdx* chr_idxs_write_base = &(chr_idxs[prev_end_vidx]);
9300 const uint32_t vidx_ct = cur_end_vidx - prev_end_vidx;
9301 const ChrIdx cur_chr_idx = cip->chr_file_order[chr_fo_idx];
9302 for (uint32_t uii = 0; uii != vidx_ct; ++uii) {
9303 chr_idxs_write_base[uii] = cur_chr_idx;
9304 }
9305 prev_end_vidx = cur_end_vidx;
9306 }
9307 }
9308 reterr = UpdateChr(variant_include, variant_ids, update_chr_flag, raw_variant_ct, variant_ct, max_variant_id_slen, (misc_flags / kfMiscProhibitExtraChr) & 1, max_thread_ct, cip, chr_idxs);
9309 if (unlikely(reterr)) {
9310 goto MakePlink2Vsort_ret_1;
9311 }
9312 }
9313
9314 // possible todo: put this in a "copy constructor" function
9315 ChrInfo write_chr_info;
9316
9317 write_chr_info.haploid_mask = K_CAST(uintptr_t*, cip->haploid_mask);
9318 write_chr_info.nonstd_names = K_CAST(const char**, cip->nonstd_names);
9319 write_chr_info.nonstd_id_htable = K_CAST(uint32_t*, cip->nonstd_id_htable);
9320 write_chr_info.chrset_source = cip->chrset_source;
9321 memcpy(write_chr_info.chr_exclude, cip->chr_exclude, kChrExcludeWords * sizeof(intptr_t));
9322 STD_ARRAY_COPY(cip->xymt_codes, kChrOffsetCt, write_chr_info.xymt_codes);
9323 write_chr_info.max_numeric_code = cip->max_numeric_code;
9324 write_chr_info.max_code = cip->max_code;
9325 write_chr_info.autosome_ct = cip->autosome_ct;
9326 write_chr_info.zero_extra_chrs = cip->zero_extra_chrs;
9327 write_chr_info.name_ct = cip->name_ct;
9328 write_chr_info.incl_excl_name_stack = K_CAST(LlStr*, cip->incl_excl_name_stack);
9329 write_chr_info.is_include_stack = cip->is_include_stack;
9330 write_chr_info.output_encoding = cip->output_encoding;
9331
9332 const uint32_t chr_code_end = cip->max_code + 1 + cip->name_ct;
9333 uint32_t* chr_idx_to_size;
9334 if (unlikely(bigstack_calloc_w(kChrMaskWords, &write_chr_info.chr_mask) ||
9335 bigstack_alloc_u32(chr_code_end, &write_chr_info.chr_idx_to_foidx) ||
9336 bigstack_end_calloc_u32(chr_code_end, &chr_idx_to_size))) {
9337 goto MakePlink2Vsort_ret_NOMEM;
9338 }
9339 SetAllU32Arr(chr_code_end, write_chr_info.chr_idx_to_foidx);
9340 if (chr_idxs) {
9341 uintptr_t variant_uidx_base = 0;
9342 uintptr_t cur_base = variant_include[0];
9343 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
9344 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_base);
9345 chr_idx_to_size[chr_idxs[variant_uidx]] += 1;
9346 }
9347 for (uint32_t chr_idx = 0; chr_idx != chr_code_end; ++chr_idx) {
9348 if (chr_idx_to_size[chr_idx]) {
9349 SetBit(chr_idx, write_chr_info.chr_mask);
9350 }
9351 }
9352 // bugfix: chr_file_order is invalid
9353 } else {
9354 const uint32_t* chr_fo_vidx_start = cip->chr_fo_vidx_start;
9355 const uint32_t orig_chr_ct = cip->chr_ct;
9356 uint32_t vidx_start = 0;
9357 for (uint32_t chr_fo_idx = 0; chr_fo_idx != orig_chr_ct; ++chr_fo_idx) {
9358 const uint32_t vidx_end = chr_fo_vidx_start[chr_fo_idx + 1];
9359 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
9360 chr_idx_to_size[chr_idx] = PopcountBitRange(variant_include, vidx_start, vidx_end);
9361 if (chr_idx_to_size[chr_idx]) {
9362 SetBit(chr_idx, write_chr_info.chr_mask);
9363 }
9364 vidx_start = vidx_end;
9365 }
9366 }
9367 if (unlikely(SortChr(cip, chr_idx_to_size, use_nsort, &write_chr_info))) {
9368 goto MakePlink2Vsort_ret_NOMEM;
9369 }
9370
9371 uint32_t* new_variant_idx_to_old;
9372
9373 // pos_vidx_sort_buf has variant_bp in high bits, variant_uidx in low
9374 uint64_t* pos_vidx_sort_buf;
9375 if (unlikely(bigstack_alloc_u32(variant_ct, &new_variant_idx_to_old) ||
9376 bigstack_alloc_u64(variant_ct + 1, &pos_vidx_sort_buf))) {
9377 goto MakePlink2Vsort_ret_NOMEM;
9378 }
9379 pos_vidx_sort_buf[variant_ct] = ~0LLU;
9380 const uint32_t new_chr_ct = write_chr_info.chr_ct;
9381 if (chr_idxs) {
9382 uint32_t* next_write_vidxs;
9383 if (unlikely(bigstack_alloc_u32(chr_code_end, &next_write_vidxs))) {
9384 goto MakePlink2Vsort_ret_NOMEM;
9385 }
9386 for (uint32_t new_chr_fo_idx = 0; new_chr_fo_idx != new_chr_ct; ++new_chr_fo_idx) {
9387 const uint32_t chr_idx = write_chr_info.chr_file_order[new_chr_fo_idx];
9388 next_write_vidxs[chr_idx] = write_chr_info.chr_fo_vidx_start[new_chr_fo_idx];
9389 }
9390 uintptr_t variant_uidx_base = 0;
9391 uintptr_t cur_bits = variant_include[0];
9392 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
9393 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
9394 const uint32_t chr_idx = chr_idxs[variant_uidx];
9395 const uint32_t write_vidx = next_write_vidxs[chr_idx];
9396 pos_vidx_sort_buf[write_vidx] = (S_CAST(uint64_t, variant_bps[variant_uidx]) << 32) | variant_uidx;
9397 next_write_vidxs[chr_idx] += 1;
9398 }
9399 BigstackReset(next_write_vidxs);
9400 } else {
9401 uint32_t old_chr_fo_idx = UINT32_MAX;
9402 uint32_t chr_end = 0;
9403 uintptr_t variant_uidx_base = 0;
9404 uintptr_t cur_bits = variant_include[0];
9405 uint32_t chr_idx = 0;
9406 uint32_t write_vidx = 0;
9407 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx, ++write_vidx) {
9408 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
9409 if (variant_uidx >= chr_end) {
9410 do {
9411 ++old_chr_fo_idx;
9412 chr_end = cip->chr_fo_vidx_start[old_chr_fo_idx + 1];
9413 } while (variant_uidx >= chr_end);
9414 chr_idx = cip->chr_file_order[old_chr_fo_idx];
9415 // bugfix (8 Sep 2018): write_vidx was set to the wrong value here
9416 const uint32_t new_chr_fo_idx = write_chr_info.chr_idx_to_foidx[chr_idx];
9417 write_vidx = write_chr_info.chr_fo_vidx_start[new_chr_fo_idx];
9418 }
9419 pos_vidx_sort_buf[write_vidx] = (S_CAST(uint64_t, variant_bps[variant_uidx]) << 32) | variant_uidx;
9420 }
9421 }
9422
9423 StrSortIndexedDeref* same_pos_sort_buf = R_CAST(StrSortIndexedDeref*, g_bigstack_base);
9424 const uintptr_t same_pos_sort_buf_size = bigstack_left() / sizeof(StrSortIndexedDeref);
9425
9426 uint32_t vidx_start = 0;
9427 uint32_t* new_variant_idx_to_old_iter = new_variant_idx_to_old;
9428 for (uint32_t new_chr_fo_idx = 0; new_chr_fo_idx != new_chr_ct; ++new_chr_fo_idx) {
9429 const uint32_t vidx_end = write_chr_info.chr_fo_vidx_start[new_chr_fo_idx + 1];
9430 const uint32_t chr_size = vidx_end - vidx_start;
9431 const uint64_t post_entry = pos_vidx_sort_buf[vidx_end];
9432 pos_vidx_sort_buf[vidx_end] = ~0LLU; // simplify end-of-chromosome logic
9433 uint64_t* pos_vidx_sort_chr = &(pos_vidx_sort_buf[vidx_start]);
9434 STD_SORT_PAR_UNSEQ(chr_size, u64cmp, pos_vidx_sort_chr);
9435 uint32_t prev_pos = pos_vidx_sort_chr[0] >> 32;
9436 uint32_t prev_variant_uidx = S_CAST(uint32_t, pos_vidx_sort_chr[0]);
9437 uint32_t prev_cidx = 0;
9438 uint32_t cidx = 1;
9439 // is chr_size == 0 possible here? document if this code is revisited.
9440 for (; cidx < chr_size; ++cidx) {
9441 uint64_t cur_entry = pos_vidx_sort_chr[cidx];
9442 uint32_t cur_pos = cur_entry >> 32;
9443 if (cur_pos == prev_pos) {
9444 same_pos_sort_buf[0].strptr = variant_ids[prev_variant_uidx];
9445 same_pos_sort_buf[0].orig_idx = prev_variant_uidx;
9446 uint32_t equal_pos_ct = 1;
9447 const uint64_t* pos_vidx_sort_chr2 = &(pos_vidx_sort_chr[prev_cidx]);
9448 do {
9449 if (unlikely(equal_pos_ct >= same_pos_sort_buf_size)) {
9450 goto MakePlink2Vsort_ret_NOMEM;
9451 }
9452 const uint32_t variant_uidx = S_CAST(uint32_t, cur_entry);
9453 same_pos_sort_buf[equal_pos_ct].strptr = variant_ids[variant_uidx];
9454 same_pos_sort_buf[equal_pos_ct].orig_idx = variant_uidx;
9455 cur_entry = pos_vidx_sort_chr2[++equal_pos_ct];
9456 cur_pos = cur_entry >> 32;
9457 } while (cur_pos == prev_pos);
9458 StrptrArrSortMain(equal_pos_ct, 1, use_nsort, same_pos_sort_buf);
9459 for (uint32_t equal_pos_idx = 0; equal_pos_idx != equal_pos_ct; ++equal_pos_idx) {
9460 *new_variant_idx_to_old_iter++ = same_pos_sort_buf[equal_pos_idx].orig_idx;
9461 }
9462 cidx += equal_pos_ct - 1;
9463 } else {
9464 *new_variant_idx_to_old_iter++ = prev_variant_uidx;
9465 }
9466 prev_pos = cur_pos;
9467 prev_cidx = cidx;
9468 prev_variant_uidx = S_CAST(uint32_t, cur_entry);
9469 }
9470 if (cidx == chr_size) {
9471 // if [cidx - 1] is part of an identical-bp batch, cidx will actually
9472 // be chr_size + 1 after loop exit. It's equal to chr_size iff we
9473 // haven't written the last entry to new_variant_idx_to_old[].
9474 *new_variant_idx_to_old_iter++ = prev_variant_uidx;
9475 }
9476 vidx_start = vidx_end;
9477 pos_vidx_sort_buf[vidx_end] = post_entry;
9478 }
9479 BigstackReset(pos_vidx_sort_buf);
9480
9481 if (make_plink2_flags & kfMakeBim) {
9482 const uint32_t bim_zst = (make_plink2_flags / kfMakeBimZs) & 1;
9483 OutnameZstSet(".bim", bim_zst, outname_end);
9484 logprintfww5("Writing %s ... ", outname);
9485 fflush(stdout);
9486
9487 reterr = WriteBimResorted(outname, &write_chr_info, variant_bps, variant_ids, allele_idx_offsets, allele_storage, allele_presents, allele_permute, variant_cms, new_variant_idx_to_old, variant_ct, max_allele_slen, bim_zst, output_missing_geno_char, max_thread_ct);
9488 if (unlikely(reterr)) {
9489 goto MakePlink2Vsort_ret_1;
9490 }
9491 logputs("done.\n");
9492 }
9493 if (make_plink2_flags & kfMakePvar) {
9494 uintptr_t* nonref_flags = PgrGetNonrefFlags(simple_pgrp);
9495 uint32_t nonref_flags_storage = 3;
9496 if (!nonref_flags) {
9497 nonref_flags_storage = (PgrGetGflags(simple_pgrp) & kfPgenGlobalAllNonref)? 2 : 1;
9498 }
9499 uint32_t write_info;
9500 uint32_t write_info_pr;
9501 if (unlikely(PvarInfoWriteStatus(variant_include, nonref_flags, raw_variant_ct, info_flags, nonref_flags_storage, pvar_psam_flags, &pvar_info_reload, &write_info, &write_info_pr))) {
9502 logerrputs("Error: Conflicting INFO/PR definitions. Either fix all REF alleles so that the\n\"provisional reference\" flag is no longer needed, or remove/rename the other\nuse of the INFO/PR key.\n");
9503 goto MakePlink2Vsort_ret_INCONSISTENT_INPUT;
9504 }
9505
9506 uint32_t info_has_g_key = 0;
9507 const char* const* info_keys = nullptr;
9508 uint32_t info_key_ct = 0;
9509 uint32_t* info_keys_htable = nullptr;
9510 uint32_t info_keys_htable_size = 0;
9511 if (pvar_info_reload) {
9512 reterr = ParseInfoHeader(xheader, xheader_blen, &info_has_g_key, &info_keys, &info_key_ct, &info_keys_htable, &info_keys_htable_size);
9513 if (reterr) {
9514 goto MakePlink2Vsort_ret_1;
9515 }
9516 if (info_has_g_key && allele_permute) {
9517 logerrputs("Warning: INFO key(s) with Number=G present; " PROG_NAME_STR " does not try to update the\ncorresponding value(s) when alleles are permuted, or variants are split or\njoined. You may want to remove or redo these annotations.\n");
9518 }
9519 }
9520 OutnameZstSet(".pvar", pvar_psam_flags & kfPvarZs, outname_end);
9521 logprintfww5("Writing %s ... ", outname);
9522 fflush(stdout);
9523 reterr = WritePvarResorted(variant_include, &write_chr_info, variant_bps, variant_ids, allele_idx_offsets, allele_storage, allele_presents, allele_permute, pvar_qual_present, pvar_quals, pvar_filter_present, pvar_filter_npass, pvar_filter_storage, PgrGetNonrefFlags(simple_pgrp), pvar_info_reload, variant_cms, new_variant_idx_to_old, info_keys, info_keys_htable, contig_lens, raw_variant_ct, variant_ct, max_allele_ct, max_allele_slen, xheader_blen, info_flags, nonref_flags_storage, max_filter_slen, info_reload_slen, info_keys_htable_size, pvar_psam_flags, output_missing_geno_char, write_info, write_info_pr, max_thread_ct, xheader, outname, outname_end);
9524 if (unlikely(reterr)) {
9525 goto MakePlink2Vsort_ret_1;
9526 }
9527 logputs("done.\n");
9528 }
9529 if (make_plink2_flags & kfMakeFam) {
9530 snprintf(outname_end, kMaxOutfnameExtBlen, ".fam");
9531 logprintfww5("Writing %s ... ", outname);
9532 fflush(stdout);
9533 reterr = WriteFam(outname, sample_include, piip, sex_nm, sex_male, pheno_cols, new_sample_idx_to_old, legacy_output_missing_pheno, sample_ct, pheno_ct, '\t');
9534 if (unlikely(reterr)) {
9535 goto MakePlink2Vsort_ret_1;
9536 }
9537 logputs("done.\n");
9538 }
9539 if (make_plink2_flags & kfMakePsam) {
9540 snprintf(outname_end, kMaxOutfnameExtBlen, ".psam");
9541 logprintfww5("Writing %s ... ", outname);
9542 fflush(stdout);
9543 reterr = WritePsam(outname, sample_include, &(piip->sii), &(piip->parental_id_info), sex_nm, sex_male, pheno_cols, pheno_names, new_sample_idx_to_old, output_missing_pheno, sample_ct, pheno_ct, max_pheno_name_blen, pvar_psam_flags, 0);
9544 if (unlikely(reterr)) {
9545 goto MakePlink2Vsort_ret_1;
9546 }
9547 logputs("done.\n");
9548 }
9549 if (make_plink2_flags & (kfMakeBed | kfMakePgen)) {
9550 // boilerplate from start of MakePlink2NoVsort()
9551 if (make_plink2_flags & kfMakePlink2MMask) {
9552 logerrputs("Error: --make-bed/--make-[b]pgen multiallelics= is currently under development.\n");
9553 reterr = kPglRetNotYetSupported;
9554 goto MakePlink2Vsort_ret_1;
9555 }
9556 MakeCommon mc;
9557 mc.plink2_write_flags = kfPlink2Write0;
9558 mc.raw_sample_ct = raw_sample_ct;
9559 mc.sample_ct = sample_ct;
9560 uintptr_t* sex_male_collapsed = nullptr;
9561 uintptr_t* sex_female_collapsed = nullptr;
9562 if (make_plink2_flags & kfMakePlink2SetInvalidHaploidMissing) {
9563 const uint32_t sample_ctv = BitCtToVecCt(sample_ct);
9564 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
9565 uintptr_t* new_sex_male;
9566 if (unlikely(bigstack_alloc_w(sample_ctv * kWordsPerVec, &new_sex_male) ||
9567 bigstack_alloc_w(sample_ctv * kWordsPerVec, &mc.sex_male_collapsed_interleaved) ||
9568 bigstack_alloc_w(sample_ctv * kWordsPerVec, &sex_female_collapsed) ||
9569 bigstack_alloc_w(sample_ctv * kWordsPerVec, &mc.sex_female_collapsed_interleaved))) {
9570 goto MakePlink2Vsort_ret_NOMEM;
9571 }
9572 CopyBitarrSubset(sex_male, sample_include, sample_ct, new_sex_male);
9573 ZeroTrailingWords(sample_ctl, new_sex_male);
9574 sex_male_collapsed = new_sex_male;
9575 FillInterleavedMaskVec(sex_male_collapsed, sample_ctv, mc.sex_male_collapsed_interleaved);
9576
9577 CopyBitarrSubset(sex_nm, sample_include, sample_ct, sex_female_collapsed);
9578 BitvecInvmask(new_sex_male, sample_ctl, sex_female_collapsed);
9579 ZeroTrailingWords(sample_ctl, sex_female_collapsed);
9580 FillInterleavedMaskVec(sex_female_collapsed, sample_ctv, mc.sex_female_collapsed_interleaved);
9581
9582 mc.plink2_write_flags |= kfPlink2WriteSetInvalidHaploidMissing;
9583 } else {
9584 // defensive
9585 mc.sex_male_collapsed_interleaved = nullptr;
9586 mc.sex_female_collapsed_interleaved = nullptr;
9587 }
9588 if (make_plink2_flags & kfMakePlink2SetMixedMtMissing) {
9589 mc.plink2_write_flags |= kfPlink2WriteSetMixedMtMissing;
9590 }
9591 mc.cip = &write_chr_info;
9592 const uintptr_t* write_allele_idx_offsets = nullptr;
9593 if (allele_idx_offsets && (!(make_plink2_flags & kfMakePlink2EraseAlt2Plus))) {
9594 if ((variant_ct < raw_variant_ct) || new_variant_idx_to_old) {
9595 uintptr_t* new_allele_idx_offsets;
9596 if (unlikely(bigstack_alloc_w(variant_ct + 1, &new_allele_idx_offsets))) {
9597 goto MakePlink2Vsort_ret_NOMEM;
9598 }
9599 const uintptr_t final_offset = InitWriteAlleleIdxOffsets(variant_include, allele_idx_offsets, allele_presents, allele_permute, new_variant_idx_to_old, variant_ct, new_allele_idx_offsets);
9600 if (final_offset != 2 * variant_ct) {
9601 new_allele_idx_offsets[variant_ct] = final_offset;
9602 write_allele_idx_offsets = new_allele_idx_offsets;
9603 } else {
9604 BigstackReset(new_allele_idx_offsets);
9605 }
9606 } else {
9607 write_allele_idx_offsets = allele_idx_offsets;
9608 }
9609 }
9610 mc.write_allele_permute = allele_permute;
9611 if (allele_permute) {
9612 // multiallelic split/join prohibited during command-line parsing
9613 if (new_variant_idx_to_old || (variant_ct < raw_variant_ct)) {
9614 // might want inner loop to map variant uidx -> idx instead
9615 const uintptr_t write_total_allele_ct = write_allele_idx_offsets? write_allele_idx_offsets[variant_ct] : (variant_ct * 2);
9616 AlleleCode* write_allele_permute;
9617 if (unlikely(bigstack_alloc_ac(write_total_allele_ct, &write_allele_permute))) {
9618 goto MakePlink2Vsort_ret_NOMEM;
9619 }
9620 FillAllelePermuteSubset(allele_permute, variant_include, allele_idx_offsets, new_variant_idx_to_old, variant_ct, write_allele_permute);
9621 mc.write_allele_permute = write_allele_permute;
9622 }
9623 }
9624 reterr = MakePgenRobust(sample_include, new_sample_idx_to_old, variant_include, allele_idx_offsets, allele_presents, write_allele_idx_offsets, new_variant_idx_to_old, sex_male_collapsed, sex_female_collapsed, writer_ver, raw_variant_ct, variant_ct, variant_ct, max_allele_ct, hard_call_thresh, dosage_erase_thresh, make_plink2_flags, &mc, simple_pgrp, outname, outname_end);
9625 if (unlikely(reterr)) {
9626 goto MakePlink2Vsort_ret_1;
9627 }
9628 }
9629 }
9630 while (0) {
9631 MakePlink2Vsort_ret_NOMEM:
9632 reterr = kPglRetNomem;
9633 break;
9634 MakePlink2Vsort_ret_INCONSISTENT_INPUT:
9635 reterr = kPglRetInconsistentInput;
9636 break;
9637 }
9638 MakePlink2Vsort_ret_1:
9639 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
9640 return reterr;
9641 }
9642
9643 PglErr SampleSortFileMap(const uintptr_t* sample_include, const SampleIdInfo* siip, const char* sample_sort_fname, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t** new_sample_idx_to_old_ptr) {
9644 // assumes sample_ct >= 2 (enforced by caller)
9645 // return strbox is not collapsed
9646 unsigned char* bigstack_mark = g_bigstack_base;
9647 uintptr_t line_idx = 0;
9648 PglErr reterr = kPglRetSuccess;
9649 TextStream txs;
9650 PreinitTextStream(&txs);
9651 {
9652 char* idbuf;
9653 uintptr_t* already_seen;
9654 if (unlikely(bigstack_alloc_u32(raw_sample_ct, new_sample_idx_to_old_ptr) ||
9655 bigstack_alloc_c(siip->max_sample_id_blen, &idbuf) ||
9656 bigstack_calloc_w(BitCtToWordCt(raw_sample_ct), &already_seen))) {
9657 goto SampleSortFileMap_ret_NOMEM;
9658 }
9659
9660 uint32_t max_line_blen;
9661 if (unlikely(StandardizeMaxLineBlen(bigstack_left() - (bigstack_left() / 4), &max_line_blen))) {
9662 goto SampleSortFileMap_ret_NOMEM;
9663 }
9664 char* line_start;
9665 XidMode xid_mode;
9666 reterr = OpenAndLoadXidHeader(sample_sort_fname, "indiv-sort", (siip->sids || (siip->flags & kfSampleIdStrictSid0))? kfXidHeader0 : kfXidHeaderIgnoreSid, max_line_blen, &txs, &xid_mode, &line_idx, &line_start);
9667 if (unlikely(reterr)) {
9668 if (reterr == kPglRetEof) {
9669 logerrputs("Error: --indiv-sort file is empty.\n");
9670 goto SampleSortFileMap_ret_MALFORMED_INPUT;
9671 }
9672 goto SampleSortFileMap_ret_TSTREAM_XID_FAIL;
9673 }
9674 uint32_t* xid_map;
9675 char* sorted_xidbox;
9676 uintptr_t max_xid_blen;
9677 reterr = SortedXidboxInitAlloc(sample_include, siip, sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen);
9678 if (unlikely(reterr)) {
9679 goto SampleSortFileMap_ret_1;
9680 }
9681 uint32_t* new_sample_idx_to_old_iter = *new_sample_idx_to_old_ptr;
9682 if (*line_start == '#') {
9683 ++line_idx;
9684 line_start = TextGet(&txs);
9685 }
9686 for (; line_start; ++line_idx, line_start = TextGet(&txs)) {
9687 if (unlikely(line_start[0] == '#')) {
9688 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --indiv-sort file starts with a '#'. (This is only permitted before the first nonheader line, and if a #FID/IID header line is present it must denote the end of the header block.)\n", line_idx);
9689 goto SampleSortFileMap_ret_MALFORMED_INPUT_WW;
9690 }
9691 const char* linebuf_iter = line_start;
9692 uint32_t sample_uidx;
9693 if (!SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, sample_ct, 0, xid_mode, &linebuf_iter, &sample_uidx, idbuf)) {
9694 if (unlikely(IsSet(already_seen, sample_uidx))) {
9695 TabsToSpaces(idbuf);
9696 snprintf(g_logbuf, kLogbufSize, "Error: Duplicate sample ID \"%s\" in --indiv-sort file.\n", idbuf);
9697 goto SampleSortFileMap_ret_MALFORMED_INPUT_WW;
9698 }
9699 SetBit(sample_uidx, already_seen);
9700 *new_sample_idx_to_old_iter++ = sample_uidx;
9701 } else if (unlikely(!linebuf_iter)) {
9702 goto SampleSortFileMap_ret_MISSING_TOKENS;
9703 }
9704 }
9705 if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
9706 goto SampleSortFileMap_ret_TSTREAM_FAIL;
9707 }
9708 if (unlikely(S_CAST(uintptr_t, new_sample_idx_to_old_iter - (*new_sample_idx_to_old_ptr)) != sample_ct)) {
9709 logerrputs("Error: --indiv-sort file does not contain all loaded sample IDs.\n");
9710 goto SampleSortFileMap_ret_INCONSISTENT_INPUT;
9711 }
9712 bigstack_mark = R_CAST(unsigned char*, idbuf);
9713 }
9714 while (0) {
9715 SampleSortFileMap_ret_NOMEM:
9716 reterr = kPglRetNomem;
9717 break;
9718 SampleSortFileMap_ret_MALFORMED_INPUT_WW:
9719 WordWrapB(0);
9720 logerrputsb();
9721 SampleSortFileMap_ret_MALFORMED_INPUT:
9722 reterr = kPglRetMalformedInput;
9723 break;
9724 SampleSortFileMap_ret_TSTREAM_XID_FAIL:
9725 if (!TextStreamErrcode(&txs)) {
9726 break;
9727 }
9728 SampleSortFileMap_ret_TSTREAM_FAIL:
9729 TextStreamErrPrint("--indiv-sort file", &txs);
9730 break;
9731 SampleSortFileMap_ret_MISSING_TOKENS:
9732 logerrprintf("Error: Line %" PRIuPTR " of --indiv-sort file has fewer tokens than expected.\n", line_idx);
9733 SampleSortFileMap_ret_INCONSISTENT_INPUT:
9734 reterr = kPglRetInconsistentInput;
9735 break;
9736 }
9737 SampleSortFileMap_ret_1:
9738 CleanupTextStream2("--indiv-sort file", &txs, &reterr);
9739 BigstackReset(bigstack_mark);
9740 return reterr;
9741 }
9742
9743 typedef struct LoadSampleMissingCtsCtxStruct {
9744 const uintptr_t* variant_include;
9745 const ChrInfo* cip;
9746 const uintptr_t* sex_male;
9747 const uintptr_t* y_include;
9748 uint32_t raw_sample_ct;
9749
9750 PgenReader** pgr_ptrs;
9751 uintptr_t** genovecs;
9752 uint32_t* read_variant_uidx_starts;
9753 uint32_t cur_block_size;
9754
9755 uintptr_t** missing_hc_acc1;
9756 uintptr_t** missing_dosage_acc1;
9757 uintptr_t** hethap_acc1;
9758
9759 uint64_t err_info;
9760 } LoadSampleMissingCtsCtx;
9761
9762 THREAD_FUNC_DECL LoadSampleMissingCtsThread(void* raw_arg) {
9763 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
9764 const uintptr_t tidx = arg->tidx;
9765 LoadSampleMissingCtsCtx* ctx = S_CAST(LoadSampleMissingCtsCtx*, arg->sharedp->context);
9766
9767 const uintptr_t* variant_include = ctx->variant_include;
9768 const ChrInfo* cip = ctx->cip;
9769 const uintptr_t* sex_male = ctx->sex_male;
9770 const uintptr_t* y_include = ctx->y_include;
9771 const uint32_t raw_sample_ct = ctx->raw_sample_ct;
9772 const uint32_t raw_sample_ctaw = BitCtToAlignedWordCt(raw_sample_ct);
9773 const uint32_t acc1_vec_ct = BitCtToVecCt(raw_sample_ct);
9774 const uint32_t acc4_vec_ct = acc1_vec_ct * 4;
9775 const uint32_t acc8_vec_ct = acc1_vec_ct * 8;
9776 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
9777 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
9778 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
9779 uintptr_t* genovec_buf = ctx->genovecs[tidx];
9780 uintptr_t* missing_hc_acc1 = ctx->missing_hc_acc1[tidx];
9781 ZeroWArr(acc1_vec_ct * kWordsPerVec * 45, missing_hc_acc1);
9782 VecW* missing_hc_acc4 = &(R_CAST(VecW*, missing_hc_acc1)[acc1_vec_ct]);
9783 VecW* missing_hc_acc8 = &(missing_hc_acc4[acc4_vec_ct]);
9784 VecW* missing_hc_acc32 = &(missing_hc_acc8[acc8_vec_ct]);
9785 uintptr_t* missing_dosage_acc1 = nullptr;
9786 VecW* missing_dosage_acc4 = nullptr;
9787 VecW* missing_dosage_acc8 = nullptr;
9788 VecW* missing_dosage_acc32 = nullptr;
9789 if (ctx->missing_dosage_acc1) {
9790 missing_dosage_acc1 = ctx->missing_dosage_acc1[tidx];
9791 ZeroWArr(acc1_vec_ct * kWordsPerVec * 45, missing_dosage_acc1);
9792 missing_dosage_acc4 = &(R_CAST(VecW*, missing_dosage_acc1)[acc1_vec_ct]);
9793 missing_dosage_acc8 = &(missing_dosage_acc4[acc4_vec_ct]);
9794 missing_dosage_acc32 = &(missing_dosage_acc8[acc8_vec_ct]);
9795 }
9796 // could make this optional
9797 // (could technically make missing_hc optional too...)
9798 uintptr_t* hethap_acc1 = ctx->hethap_acc1[tidx];
9799 ZeroWArr(acc1_vec_ct * kWordsPerVec * 45, hethap_acc1);
9800 VecW* hethap_acc4 = &(R_CAST(VecW*, hethap_acc1)[acc1_vec_ct]);
9801 VecW* hethap_acc8 = &(hethap_acc4[acc4_vec_ct]);
9802 VecW* hethap_acc32 = &(hethap_acc8[acc8_vec_ct]);
9803 uint32_t all_ct_rem15 = 15;
9804 uint32_t all_ct_rem255d15 = 17;
9805 uint32_t hap_ct_rem15 = 15;
9806 uint32_t hap_ct_rem255d15 = 17;
9807 uint64_t new_err_info = 0;
9808 do {
9809 PgenReader* pgrp = ctx->pgr_ptrs[tidx];
9810 PgrSampleSubsetIndex null_pssi;
9811 PgrClearSampleSubsetIndex(pgrp, &null_pssi);
9812 const uint32_t cur_block_size = ctx->cur_block_size;
9813 const uint32_t cur_idx_ct = (((tidx + 1) * cur_block_size) / calc_thread_ct) - ((tidx * cur_block_size) / calc_thread_ct);
9814 uintptr_t variant_uidx_base;
9815 uintptr_t cur_bits;
9816 BitIter1Start(variant_include, ctx->read_variant_uidx_starts[tidx], &variant_uidx_base, &cur_bits);
9817 uint32_t chr_end = 0;
9818 uintptr_t* cur_hets = nullptr;
9819 uint32_t is_diploid_x = 0;
9820 uint32_t is_y = 0;
9821 for (uint32_t cur_idx = 0; cur_idx != cur_idx_ct; ++cur_idx) {
9822 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
9823 if (variant_uidx >= chr_end) {
9824 const uint32_t chr_fo_idx = GetVariantChrFoIdx(cip, variant_uidx);
9825 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
9826 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
9827 cur_hets = hethap_acc1;
9828 is_diploid_x = 0;
9829 is_y = 0;
9830 if (chr_idx == x_code) {
9831 is_diploid_x = !IsSet(cip->haploid_mask, 0);
9832 } else if (chr_idx == y_code) {
9833 is_y = 1;
9834 } else {
9835 if (!IsSet(cip->haploid_mask, chr_idx)) {
9836 cur_hets = nullptr;
9837 }
9838 }
9839 }
9840 // could instead have missing_hc and (missing_hc - missing_dosage); that
9841 // has the advantage of letting you skip one of the two increment
9842 // operations when the variant is all hardcalls.
9843 PglErr reterr = PgrGetMissingnessD(nullptr, null_pssi, raw_sample_ct, variant_uidx, pgrp, missing_hc_acc1, missing_dosage_acc1, cur_hets, genovec_buf);
9844 if (unlikely(reterr)) {
9845 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
9846 goto LoadSampleMissingCtsThread_err;
9847 }
9848 if (is_y) {
9849 BitvecAnd(y_include, raw_sample_ctaw, missing_hc_acc1);
9850 if (missing_dosage_acc1) {
9851 BitvecAnd(y_include, raw_sample_ctaw, missing_dosage_acc1);
9852 }
9853 }
9854 VcountIncr1To4(missing_hc_acc1, acc1_vec_ct, missing_hc_acc4);
9855 if (missing_dosage_acc1) {
9856 VcountIncr1To4(missing_dosage_acc1, acc1_vec_ct, missing_dosage_acc4);
9857 }
9858 if (!(--all_ct_rem15)) {
9859 Vcount0Incr4To8(acc4_vec_ct, missing_hc_acc4, missing_hc_acc8);
9860 if (missing_dosage_acc1) {
9861 Vcount0Incr4To8(acc4_vec_ct, missing_dosage_acc4, missing_dosage_acc8);
9862 }
9863 all_ct_rem15 = 15;
9864 if (!(--all_ct_rem255d15)) {
9865 Vcount0Incr8To32(acc8_vec_ct, missing_hc_acc8, missing_hc_acc32);
9866 if (missing_dosage_acc1) {
9867 Vcount0Incr8To32(acc8_vec_ct, missing_dosage_acc8, missing_dosage_acc32);
9868 }
9869 all_ct_rem255d15 = 17;
9870 }
9871 }
9872 if (cur_hets) {
9873 if (is_diploid_x) {
9874 BitvecAnd(sex_male, raw_sample_ctaw, cur_hets);
9875 }
9876 VcountIncr1To4(cur_hets, acc1_vec_ct, hethap_acc4);
9877 if (!(--hap_ct_rem15)) {
9878 Vcount0Incr4To8(acc4_vec_ct, hethap_acc4, hethap_acc8);
9879 hap_ct_rem15 = 15;
9880 if (!(--hap_ct_rem255d15)) {
9881 Vcount0Incr8To32(acc8_vec_ct, hethap_acc8, hethap_acc32);
9882 hap_ct_rem255d15 = 17;
9883 }
9884 }
9885 }
9886 }
9887 } while (!THREAD_BLOCK_FINISH(arg));
9888 {
9889 VcountIncr4To8(missing_hc_acc4, acc4_vec_ct, missing_hc_acc8);
9890 VcountIncr8To32(missing_hc_acc8, acc8_vec_ct, missing_hc_acc32);
9891 if (missing_dosage_acc1) {
9892 VcountIncr4To8(missing_dosage_acc4, acc4_vec_ct, missing_dosage_acc8);
9893 VcountIncr8To32(missing_dosage_acc8, acc8_vec_ct, missing_dosage_acc32);
9894 }
9895 VcountIncr4To8(hethap_acc4, acc4_vec_ct, hethap_acc8);
9896 VcountIncr8To32(hethap_acc8, acc8_vec_ct, hethap_acc32);
9897 }
9898 while (0) {
9899 LoadSampleMissingCtsThread_err:
9900 UpdateU64IfSmaller(new_err_info, &ctx->err_info);
9901 THREAD_BLOCK_FINISH(arg);
9902 break;
9903 }
9904 THREAD_RETURN;
9905 }
9906
9907 PglErr LoadSampleMissingCts(const uintptr_t* sex_nm, const uintptr_t* sex_male, const uintptr_t* variant_include, const ChrInfo* cip, const char* calc_descrip_str, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t raw_sample_ct, uint32_t y_nosex_missing_stats, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, uint32_t* sample_missing_hc_cts, uint32_t* sample_missing_dosage_cts, uint32_t* sample_hethap_cts) {
9908 assert(sample_missing_hc_cts || sample_missing_dosage_cts);
9909 unsigned char* bigstack_mark = g_bigstack_base;
9910 PglErr reterr = kPglRetSuccess;
9911 ThreadGroup tg;
9912 PreinitThreads(&tg);
9913 LoadSampleMissingCtsCtx ctx;
9914 {
9915 if (!variant_ct) {
9916 ZeroU32Arr(raw_sample_ct, sample_missing_hc_cts);
9917 if (sample_missing_dosage_cts) {
9918 ZeroU32Arr(raw_sample_ct, sample_missing_dosage_cts);
9919 }
9920 ZeroU32Arr(raw_sample_ct, sample_hethap_cts);
9921 goto LoadSampleMissingCts_ret_1;
9922 }
9923 // this doesn't seem to saturate below 35 threads
9924 uint32_t calc_thread_ct = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
9925 const uint32_t acc1_vec_ct = BitCtToVecCt(raw_sample_ct);
9926 const uintptr_t acc1_alloc_cacheline_ct = DivUp(acc1_vec_ct * (45 * k1LU * kBytesPerVec), kCacheline);
9927 ctx.sex_male = sex_male;
9928 uintptr_t thread_alloc_cacheline_ct = 2 * acc1_alloc_cacheline_ct;
9929 ctx.missing_dosage_acc1 = nullptr;
9930 if (sample_missing_dosage_cts) {
9931 if (unlikely(bigstack_alloc_wp(calc_thread_ct, &ctx.missing_dosage_acc1))) {
9932 goto LoadSampleMissingCts_ret_NOMEM;
9933 }
9934 thread_alloc_cacheline_ct += acc1_alloc_cacheline_ct;
9935 }
9936 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
9937 if (unlikely(bigstack_alloc_wp(calc_thread_ct, &ctx.missing_hc_acc1) ||
9938 bigstack_alloc_wp(calc_thread_ct, &ctx.hethap_acc1))) {
9939 goto LoadSampleMissingCts_ret_NOMEM;
9940 }
9941 if (!y_nosex_missing_stats) {
9942 ctx.y_include = sex_male;
9943 } else {
9944 uintptr_t* y_include;
9945 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &y_include))) {
9946 goto LoadSampleMissingCts_ret_NOMEM;
9947 }
9948 AlignedBitarrOrnotCopy(sex_male, sex_nm, raw_sample_ct, y_include);
9949 ctx.y_include = y_include;
9950 }
9951 STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
9952 uint32_t read_block_size;
9953 if (unlikely(PgenMtLoadInit(variant_include, raw_sample_ct, raw_variant_ct, bigstack_left(), pgr_alloc_cacheline_ct, thread_alloc_cacheline_ct, 0, 0, pgfip, &calc_thread_ct, &ctx.genovecs, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &read_block_size, nullptr, main_loadbufs, &ctx.pgr_ptrs, &ctx.read_variant_uidx_starts))) {
9954 goto LoadSampleMissingCts_ret_NOMEM;
9955 }
9956 const uintptr_t acc1_alloc = acc1_alloc_cacheline_ct * kCacheline;
9957 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
9958 ctx.missing_hc_acc1[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(acc1_alloc));
9959 if (ctx.missing_dosage_acc1) {
9960 ctx.missing_dosage_acc1[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(acc1_alloc));
9961 }
9962 ctx.hethap_acc1[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(acc1_alloc));
9963 }
9964 ctx.variant_include = variant_include;
9965 ctx.cip = cip;
9966 ctx.raw_sample_ct = raw_sample_ct;
9967 ctx.err_info = (~0LLU) << 32;
9968 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
9969 goto LoadSampleMissingCts_ret_NOMEM;
9970 }
9971 SetThreadFuncAndData(LoadSampleMissingCtsThread, &ctx, &tg);
9972
9973 // nearly identical to LoadAlleleAndGenoCounts()
9974 logprintf("Calculating %s rates... ", calc_descrip_str);
9975 fputs("0%", stdout);
9976 fflush(stdout);
9977 uint32_t pct = 0;
9978
9979 uint32_t parity = 0;
9980 uint32_t read_block_idx = 0;
9981 uint32_t next_print_variant_idx = variant_ct / 100;
9982 for (uint32_t variant_idx = 0; ; ) {
9983 const uint32_t cur_loaded_variant_ct = MultireadNonempty(variant_include, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr);
9984 if (unlikely(reterr)) {
9985 goto LoadSampleMissingCts_ret_PGR_FAIL;
9986 }
9987 if (variant_idx) {
9988 JoinThreads(&tg);
9989 reterr = S_CAST(PglErr, ctx.err_info);
9990 if (unlikely(reterr)) {
9991 PgenErrPrintNV(reterr, ctx.err_info >> 32);
9992 goto LoadSampleMissingCts_ret_1;
9993 }
9994 }
9995 if (!IsLastBlock(&tg)) {
9996 ctx.cur_block_size = cur_loaded_variant_ct;
9997 ComputeUidxStartPartition(variant_include, cur_loaded_variant_ct, calc_thread_ct, read_block_idx * read_block_size, ctx.read_variant_uidx_starts);
9998 PgrCopyBaseAndOffset(pgfip, calc_thread_ct, ctx.pgr_ptrs);
9999 if (variant_idx + cur_loaded_variant_ct == variant_ct) {
10000 DeclareLastThreadBlock(&tg);
10001 }
10002 if (unlikely(SpawnThreads(&tg))) {
10003 goto LoadSampleMissingCts_ret_THREAD_CREATE_FAIL;
10004 }
10005 }
10006
10007 parity = 1 - parity;
10008 if (variant_idx == variant_ct) {
10009 break;
10010 }
10011 if (variant_idx >= next_print_variant_idx) {
10012 if (pct > 10) {
10013 putc_unlocked('\b', stdout);
10014 }
10015 pct = (variant_idx * 100LLU) / variant_ct;
10016 printf("\b\b%u%%", pct++);
10017 fflush(stdout);
10018 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
10019 }
10020
10021 ++read_block_idx;
10022 variant_idx += cur_loaded_variant_ct;
10023 // crucially, this is independent of the PgenReader block_base
10024 // pointers
10025 pgfip->block_base = main_loadbufs[parity];
10026 }
10027 const uint32_t sample_ctv = acc1_vec_ct * kBitsPerVec;
10028 const uintptr_t acc32_offset = acc1_vec_ct * (13 * k1LU * kWordsPerVec);
10029 uint32_t* scrambled_missing_hc_cts = nullptr;
10030 uint32_t* scrambled_missing_dosage_cts = nullptr;
10031 uint32_t* scrambled_hethap_cts = nullptr;
10032 scrambled_missing_hc_cts = R_CAST(uint32_t*, &(ctx.missing_hc_acc1[0][acc32_offset]));
10033 if (ctx.missing_dosage_acc1) {
10034 scrambled_missing_dosage_cts = R_CAST(uint32_t*, &(ctx.missing_dosage_acc1[0][acc32_offset]));
10035 }
10036 scrambled_hethap_cts = R_CAST(uint32_t*, &(ctx.hethap_acc1[0][acc32_offset]));
10037 for (uint32_t tidx = 1; tidx != calc_thread_ct; ++tidx) {
10038 uint32_t* thread_scrambled_missing_hc_cts = R_CAST(uint32_t*, &(ctx.missing_hc_acc1[tidx][acc32_offset]));
10039 for (uint32_t uii = 0; uii != sample_ctv; ++uii) {
10040 scrambled_missing_hc_cts[uii] += thread_scrambled_missing_hc_cts[uii];
10041 }
10042 if (scrambled_missing_dosage_cts) {
10043 uint32_t* thread_scrambled_missing_dosage_cts = R_CAST(uint32_t*, &(ctx.missing_dosage_acc1[tidx][acc32_offset]));
10044 for (uint32_t uii = 0; uii != sample_ctv; ++uii) {
10045 scrambled_missing_dosage_cts[uii] += thread_scrambled_missing_dosage_cts[uii];
10046 }
10047 }
10048 uint32_t* thread_scrambled_hethap_cts = R_CAST(uint32_t*, &(ctx.hethap_acc1[tidx][acc32_offset]));
10049 for (uint32_t uii = 0; uii != sample_ctv; ++uii) {
10050 scrambled_hethap_cts[uii] += thread_scrambled_hethap_cts[uii];
10051 }
10052 }
10053 for (uint32_t sample_uidx = 0; sample_uidx != raw_sample_ct; ++sample_uidx) {
10054 const uint32_t scrambled_idx = VcountScramble1(sample_uidx);
10055 sample_missing_hc_cts[sample_uidx] = scrambled_missing_hc_cts[scrambled_idx];
10056 if (sample_missing_dosage_cts) {
10057 sample_missing_dosage_cts[sample_uidx] = scrambled_missing_dosage_cts[scrambled_idx];
10058 }
10059 sample_hethap_cts[sample_uidx] = scrambled_hethap_cts[scrambled_idx];
10060 }
10061 if (pct > 10) {
10062 putc_unlocked('\b', stdout);
10063 }
10064 fputs("\b\b", stdout);
10065 logputs("done.\n");
10066 }
10067 while (0) {
10068 LoadSampleMissingCts_ret_NOMEM:
10069 reterr = kPglRetNomem;
10070 break;
10071 LoadSampleMissingCts_ret_PGR_FAIL:
10072 PgenErrPrintN(reterr);
10073 break;
10074 LoadSampleMissingCts_ret_THREAD_CREATE_FAIL:
10075 reterr = kPglRetThreadCreateFail;
10076 break;
10077 }
10078 LoadSampleMissingCts_ret_1:
10079 CleanupThreads(&tg);
10080 pgfip->block_base = nullptr;
10081 BigstackReset(bigstack_mark);
10082 return reterr;
10083 }
10084
10085 #ifdef __cplusplus
10086 } // namespace plink2
10087 #endif