Debian Codegraph @

plink2_export.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 #include "plink2_compress_stream.h"
18 #include "plink2_export.h"
19 #include "plink2_export_legacy.h"
20
21 #ifdef __cplusplus
22 namespace plink2 {
23 #endif
24
25 void InitExportf(ExportfInfo* exportf_info_ptr) {
26 exportf_info_ptr->flags = kfExportf0;
27 exportf_info_ptr->idpaste_flags = kfIdpaste0;
28 exportf_info_ptr->id_delim = '\0';
29 exportf_info_ptr->bgen_bits = 0;
30 exportf_info_ptr->vcf_mode = kVcfExport0;
31 exportf_info_ptr->export_allele_fname = nullptr;
32 }
33
34 void CleanupExportf(ExportfInfo* exportf_info_ptr) {
35 free_cond(exportf_info_ptr->export_allele_fname);
36 }
37
38 PglErr ExportAlleleLoad(const char* fname, const uintptr_t* variant_include, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_variant_id_slen, char input_missing_geno_char, uint32_t max_thread_ct, uint32_t* max_export_allele_slen_ptr, AlleleCode* export_allele, const char*** allele_missing_ptr) {
39 // "Permanent" allocations occur on high end of bigstack.
40 unsigned char* bigstack_mark = g_bigstack_base;
41 PglErr reterr = kPglRetSuccess;
42 TextStream txs;
43 PreinitTextStream(&txs);
44 {
45 uintptr_t* already_seen;
46 if (unlikely(bigstack_calloc_w(BitCtToWordCt(raw_variant_ct), &already_seen))) {
47 goto ExportAlleleLoad_ret_NOMEM;
48 }
49 const uint32_t max_allele_slen = *max_export_allele_slen_ptr;
50 uint32_t max_export_allele_slen = max_allele_slen;
51 const uintptr_t linebuf_min = 64 + kMaxIdSlen + max_export_allele_slen;
52 uint32_t max_line_blen;
53 if (StandardizeMaxLineBlenEx(MAXV(bigstack_left() / 8, linebuf_min), linebuf_min, &max_line_blen)) {
54 goto ExportAlleleLoad_ret_NOMEM;
55 }
56 reterr = InitTextStream(fname, max_line_blen, MAXV(max_thread_ct - 1, 1), &txs);
57 if (unlikely(reterr)) {
58 goto ExportAlleleLoad_ret_TSTREAM_FAIL;
59 }
60
61 // use minimum instead of fast hash table size, since allele_missing could
62 // be very large
63 // (if this path was hotter, we could check if the input file was
64 // uncompressed and small enough)
65 const uint32_t variant_id_htable_size = GetHtableMinSize(variant_ct);
66 uint32_t* variant_id_htable;
67 if (unlikely(bigstack_alloc_u32(variant_id_htable_size * sizeof(int32_t), &variant_id_htable))) {
68 goto ExportAlleleLoad_ret_NOMEM;
69 }
70 reterr = PopulateIdHtableMt(g_bigstack_end, variant_include, variant_ids, variant_ct, 0, variant_id_htable_size, max_thread_ct, &g_bigstack_base, variant_id_htable, nullptr);
71 if (unlikely(reterr)) {
72 goto ExportAlleleLoad_ret_1;
73 }
74
75 unsigned char* tmp_alloc_base = g_bigstack_base;
76 unsigned char* tmp_alloc_end = g_bigstack_end;
77 const char** allele_missing = nullptr;
78 uintptr_t duplicate_ct = 0;
79 uintptr_t miss_ct = 0;
80 uintptr_t line_idx = 0;
81 uint32_t hit_ct = 0;
82 uint32_t cur_allele_ct = 2;
83 while (1) {
84 ++line_idx;
85 char* line_start = TextGet(&txs);
86 if (!line_start) {
87 if (likely(!TextStreamErrcode2(&txs, &reterr))) {
88 break;
89 }
90 goto ExportAlleleLoad_ret_TSTREAM_FAIL;
91 }
92 char* token_end = CurTokenEnd(line_start);
93 const uint32_t variant_uidx = VariantIdDupflagHtableFind(line_start, variant_ids, variant_id_htable, token_end - line_start, variant_id_htable_size, max_variant_id_slen);
94 if (variant_uidx & 0x80000000U) {
95 if (likely(variant_uidx == UINT32_MAX)) {
96 ++miss_ct;
97 continue;
98 }
99 *token_end = '\0';
100 snprintf(g_logbuf, kLogbufSize, "Error: --export-allele variant ID '%s' appears multiple times in dataset.\n", line_start);
101 goto ExportAlleleLoad_ret_INCONSISTENT_INPUT_WW;
102 }
103 char* allele_start = FirstNonTspace(token_end);
104 char* allele_end = FirstSpaceOrEoln(allele_start);
105 const uint32_t allele_slen = allele_end - allele_start;
106 if (!allele_slen) {
107 logerrprintfww("Error: Line %" PRIuPTR " of --export-allele file has fewer tokens than expected.\n", line_idx);
108 goto ExportAlleleLoad_ret_MALFORMED_INPUT;
109 }
110 uintptr_t allele_idx_offset_base = variant_uidx * 2;
111 if (allele_idx_offsets) {
112 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
113 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
114 }
115 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
116 int32_t cur_allele_idx = -1;
117 if (allele_slen <= max_allele_slen) {
118 for (uint32_t allele_idx = 0; allele_idx != cur_allele_ct; ++allele_idx) {
119 if (strequal_unsafe(cur_alleles[allele_idx], allele_start, allele_slen)) {
120 cur_allele_idx = allele_idx;
121 break;
122 }
123 }
124 }
125 if (IsSet(already_seen, variant_uidx)) {
126 // Only ok if allele is the same as before.
127 ++duplicate_ct;
128 if (cur_allele_idx == -1) {
129 if (likely(allele_missing && allele_missing[variant_uidx] && strequal_unsafe(allele_missing[variant_uidx], allele_start, allele_slen))) {
130 continue;
131 }
132 } else {
133 if (likely(((!allele_missing) || (!allele_missing[variant_uidx])) && (S_CAST(uint32_t, cur_allele_idx) == export_allele[variant_uidx]))) {
134 continue;
135 }
136 }
137 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --export-allele file has a variant ID duplicating an earlier line, and with a different allele code.\n", line_idx);
138 goto ExportAlleleLoad_ret_INCONSISTENT_INPUT_WW;
139 }
140 SetBit(variant_uidx, already_seen);
141 ++hit_ct;
142 if (cur_allele_idx != -1) {
143 export_allele[variant_uidx] = S_CAST(uint32_t, cur_allele_idx);
144 continue;
145 }
146 if (!allele_missing) {
147 if (unlikely(bigstack_end_calloc_kcp(raw_variant_ct, &allele_missing))) {
148 goto ExportAlleleLoad_ret_NOMEM;
149 }
150 tmp_alloc_end = g_bigstack_end;
151 }
152 if (allele_slen == 1) {
153 char allele_char = *allele_start;
154 if (allele_char == input_missing_geno_char) {
155 allele_char = '.';
156 }
157 allele_missing[variant_uidx] = &(g_one_char_strs[2 * ctou32(allele_char)]);
158 continue;
159 }
160 if (StoreStringAtEndK(tmp_alloc_base, allele_start, allele_slen, &tmp_alloc_end, &(allele_missing[variant_uidx]))) {
161 goto ExportAlleleLoad_ret_NOMEM;
162 }
163 }
164 if (duplicate_ct) {
165 logerrprintfww("Warning: %" PRIuPTR " duplicate variant ID%s in --export-allele file (not an error since allele%s consistent).\n", duplicate_ct, (duplicate_ct == 1)? "" : "s", (duplicate_ct == 1)? " was" : "s were");
166 }
167 if (miss_ct) {
168 snprintf(g_logbuf, kLogbufSize, "--export-allele: %u variant%s updated, %" PRIuPTR " variant ID%s not present.\n", hit_ct, (hit_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s");
169 WordWrapB(0);
170 } else {
171 snprintf(g_logbuf, kLogbufSize, "--export-allele: %u variant%s updated.\n", hit_ct, (hit_ct == 1)? "" : "s");
172 }
173 logputsb();
174 *max_export_allele_slen_ptr = max_export_allele_slen;
175 *allele_missing_ptr = allele_missing;
176 BigstackEndSet(tmp_alloc_end);
177 }
178 while (0) {
179 ExportAlleleLoad_ret_TSTREAM_FAIL:
180 TextStreamErrPrint("--export-allele file", &txs);
181 break;
182 ExportAlleleLoad_ret_NOMEM:
183 reterr = kPglRetNomem;
184 break;
185 ExportAlleleLoad_ret_MALFORMED_INPUT:
186 reterr = kPglRetMalformedInput;
187 break;
188 ExportAlleleLoad_ret_INCONSISTENT_INPUT_WW:
189 WordWrapB(0);
190 logerrputsb();
191 reterr = kPglRetInconsistentInput;
192 break;
193 }
194 ExportAlleleLoad_ret_1:
195 CleanupTextStream2("--export-allele file", &txs, &reterr);
196 BigstackReset(bigstack_mark);
197 return reterr;
198 }
199
200 PglErr Export012Vmaj(const char* outname, const uintptr_t* sample_include, const uint32_t* sample_include_cumulative_popcounts, const char* sample_ids, 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 AlleleCode* export_allele, const char* const* export_allele_missing, const double* variant_cms, uint32_t sample_ct, uintptr_t max_sample_id_blen, uint32_t variant_ct, uint32_t max_allele_slen, char exportf_delim, PgenReader* simple_pgrp) {
201 // todo: --recode-allele
202 unsigned char* bigstack_mark = g_bigstack_base;
203 FILE* outfile = nullptr;
204 PglErr reterr = kPglRetSuccess;
205 {
206 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
207 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
208 const uint32_t max_chr_blen = 1 + GetMaxChrSlen(cip);
209 char* chr_buf; // includes trailing tab
210 char* writebuf;
211 uintptr_t* genovec;
212 // dosages are limited to 7 characters (x.yyyyy)
213 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf) ||
214 bigstack_alloc_c(kMaxMediumLine + max_chr_blen + 2 * kMaxIdSlen + 48 + 2 * max_allele_slen + (8 * k1LU) * sample_ct, &writebuf) ||
215 bigstack_alloc_w(sample_ctl2, &genovec))) {
216 goto Export012Vmaj_ret_NOMEM;
217 }
218 char* writebuf_flush = &(writebuf[kMaxMediumLine]);
219 const uint32_t dosage_is_present = PgrGetGflags(simple_pgrp) & kfPgenGlobalDosagePresent;
220 uintptr_t* dosage_present = nullptr;
221 Dosage* dosage_main = nullptr;
222 if (dosage_is_present) {
223 if (unlikely(bigstack_alloc_w(sample_ctl, &dosage_present) ||
224 bigstack_alloc_dosage(sample_ct, &dosage_main))) {
225 goto Export012Vmaj_ret_NOMEM;
226 }
227 }
228 uintptr_t* missingness_dosage = nullptr;
229 if (export_allele_missing) {
230 if (unlikely(bigstack_alloc_w(sample_ctl, &missingness_dosage))) {
231 goto Export012Vmaj_ret_NOMEM;
232 }
233 }
234 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
235 goto Export012Vmaj_ret_OPEN_FAIL;
236 }
237 char* write_iter;
238 if (exportf_delim == '\t') {
239 write_iter = strcpya_k(writebuf, "CHR\tSNP\t(C)M\tPOS\tCOUNTED\tALT");
240 } else {
241 write_iter = strcpya_k(writebuf, "CHR SNP (C)M POS COUNTED ALT");
242 }
243 uintptr_t sample_uidx_base = 0;
244 uintptr_t sample_include_bits = sample_include[0];
245 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
246 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &sample_include_bits);
247 *write_iter++ = exportf_delim;
248 const char* fid_start = &(sample_ids[sample_uidx * max_sample_id_blen]);
249 const char* fid_end = AdvToDelim(fid_start, exportf_delim);
250 write_iter = memcpyax(write_iter, fid_start, fid_end - fid_start, '_');
251 write_iter = strcpya(write_iter, &(fid_end[1]));
252 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
253 goto Export012Vmaj_ret_WRITE_FAIL;
254 }
255 }
256 AppendBinaryEoln(&write_iter);
257 PgrSampleSubsetIndex pssi;
258 PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi);
259 logprintfww5("--export Av to %s ... ", outname);
260 fputs("0%", stdout);
261 fflush(stdout);
262 uint32_t chr_fo_idx = UINT32_MAX;
263 uint32_t chr_end = 0;
264 uint32_t chr_blen = 0;
265 uint32_t exported_allele_idx = 0;
266 uint32_t cur_allele_ct = 2;
267 const uint32_t sample_ctl2_m1 = sample_ctl2 - 1;
268
269 uint32_t pct = 0;
270 uint32_t next_print_variant_idx = variant_ct / 100;
271 uintptr_t variant_uidx_base = 0;
272 uintptr_t variant_include_bits = variant_include[0];
273 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
274 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
275 if (variant_uidx >= chr_end) {
276 do {
277 ++chr_fo_idx;
278 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
279 } while (variant_uidx >= chr_end);
280 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
281 char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
282 *chr_name_end++ = exportf_delim;
283 chr_blen = chr_name_end - chr_buf;
284 }
285 write_iter = memcpya(write_iter, chr_buf, chr_blen);
286 write_iter = strcpyax(write_iter, variant_ids[variant_uidx], exportf_delim);
287 if (variant_cms) {
288 write_iter = dtoa_g_p8(variant_cms[variant_uidx], write_iter);
289 } else {
290 *write_iter++ = '0';
291 }
292 *write_iter++ = exportf_delim;
293 write_iter = u32toa_x(variant_bps[variant_uidx], exportf_delim, write_iter);
294
295 if (export_allele) {
296 exported_allele_idx = export_allele[variant_uidx];
297 }
298 uintptr_t allele_idx_offset_base = variant_uidx * 2;
299 if (allele_idx_offsets) {
300 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
301 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
302 }
303 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
304 if (export_allele_missing && export_allele_missing[variant_uidx]) {
305 reterr = PgrGetMissingnessD(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, nullptr, missingness_dosage, nullptr, genovec);
306 if (unlikely(reterr)) {
307 PgenErrPrintNV(reterr, variant_uidx);
308 goto Export012Vmaj_ret_1;
309 }
310 write_iter = strcpyax(write_iter, export_allele_missing[variant_uidx], exportf_delim);
311 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
312 goto Export012Vmaj_ret_WRITE_FAIL;
313 }
314 // in this case, exported_allele_idx corresponds to the REF allele.
315 // May as well put it first.
316 write_iter = strcpya(write_iter, cur_alleles[exported_allele_idx]);
317 for (uint32_t allele_idx = 0; allele_idx != cur_allele_ct; ++allele_idx) {
318 if (allele_idx == exported_allele_idx) {
319 continue;
320 }
321 *write_iter++ = ',';
322 write_iter = strcpya(write_iter, cur_alleles[allele_idx]);
323 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
324 goto Export012Vmaj_ret_WRITE_FAIL;
325 }
326 }
327 // We only care about missingness here.
328 const uint32_t sample_ctl_m1 = sample_ctl - 1;
329 uint32_t loop_len = kBitsPerWord;
330 for (uint32_t widx = 0; ; ++widx) {
331 if (widx >= sample_ctl_m1) {
332 if (widx > sample_ctl_m1) {
333 break;
334 }
335 loop_len = ModNz(sample_ct, kBitsPerWord);
336 }
337 uintptr_t missingness_word = missingness_dosage[widx];
338 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
339 *write_iter++ = exportf_delim;
340 if (missingness_word & 1) {
341 write_iter = strcpya_k(write_iter, "NA");
342 } else {
343 *write_iter++ = '0';
344 }
345 missingness_word >>= 1;
346 }
347 }
348 } else {
349 uint32_t dosage_ct;
350 reterr = PgrGet1D(sample_include, pssi, sample_ct, variant_uidx, exported_allele_idx, simple_pgrp, genovec, dosage_present, dosage_main, &dosage_ct);
351 if (unlikely(reterr)) {
352 PgenErrPrintNV(reterr, variant_uidx);
353 goto Export012Vmaj_ret_1;
354 }
355 write_iter = strcpyax(write_iter, cur_alleles[exported_allele_idx], exportf_delim);
356 const uint32_t first_alt_idx = (exported_allele_idx == 0);
357 write_iter = strcpya(write_iter, cur_alleles[first_alt_idx]);
358 if (cur_allele_ct > 2) {
359 for (uint32_t allele_idx = first_alt_idx + 1; allele_idx != cur_allele_ct; ++allele_idx) {
360 if (allele_idx == exported_allele_idx) {
361 continue;
362 }
363 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
364 goto Export012Vmaj_ret_WRITE_FAIL;
365 }
366 *write_iter++ = ',';
367 write_iter = strcpya(write_iter, cur_alleles[allele_idx]);
368 }
369 }
370 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
371 goto Export012Vmaj_ret_WRITE_FAIL;
372 }
373 uint32_t loop_len = kBitsPerWordD2;
374 if (!dosage_ct) {
375 for (uint32_t widx = 0; ; ++widx) {
376 if (widx >= sample_ctl2_m1) {
377 if (widx > sample_ctl2_m1) {
378 break;
379 }
380 loop_len = ModNz(sample_ct, kBitsPerWordD2);
381 }
382 uintptr_t geno_word = genovec[widx];
383 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
384 *write_iter++ = exportf_delim;
385 uintptr_t cur_geno = geno_word & 3;
386 if (cur_geno != 3) {
387 *write_iter++ = '0' + cur_geno;
388 } else {
389 write_iter = strcpya_k(write_iter, "NA");
390 }
391 geno_word >>= 2;
392 }
393 }
394 } else {
395 Dosage* dosage_main_iter = dosage_main;
396 for (uint32_t widx = 0; ; ++widx) {
397 if (widx >= sample_ctl2_m1) {
398 if (widx > sample_ctl2_m1) {
399 break;
400 }
401 loop_len = ModNz(sample_ct, kBitsPerWordD2);
402 }
403 uintptr_t geno_word = genovec[widx];
404 uint32_t dosage_present_hw = DowncastWToHW(dosage_present)[widx];
405 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
406 *write_iter++ = exportf_delim;
407 if (dosage_present_hw & 1) {
408 write_iter = PrintSmallDosage(*dosage_main_iter++, write_iter);
409 } else {
410 uintptr_t cur_geno = geno_word & 3;
411 if (cur_geno != 3) {
412 *write_iter++ = '0' + cur_geno;
413 } else {
414 write_iter = strcpya_k(write_iter, "NA");
415 }
416 }
417 geno_word >>= 2;
418 dosage_present_hw >>= 1;
419 }
420 }
421 }
422 }
423 AppendBinaryEoln(&write_iter);
424 if (variant_idx >= next_print_variant_idx) {
425 if (pct > 10) {
426 putc_unlocked('\b', stdout);
427 }
428 pct = (variant_idx * 100LLU) / variant_ct;
429 printf("\b\b%u%%", pct++);
430 fflush(stdout);
431 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
432 }
433 }
434 if (unlikely(fclose_flush_null(writebuf_flush, write_iter, &outfile))) {
435 goto Export012Vmaj_ret_WRITE_FAIL;
436 }
437 if (pct > 10) {
438 putc_unlocked('\b', stdout);
439 }
440 fputs("\b\b", stdout);
441 logputs("done.\n");
442 }
443 while (0) {
444 Export012Vmaj_ret_NOMEM:
445 reterr = kPglRetNomem;
446 break;
447 Export012Vmaj_ret_OPEN_FAIL:
448 reterr = kPglRetOpenFail;
449 break;
450 Export012Vmaj_ret_WRITE_FAIL:
451 reterr = kPglRetWriteFail;
452 break;
453 }
454 Export012Vmaj_ret_1:
455 fclose_cond(outfile);
456 BigstackReset(bigstack_mark);
457 return reterr;
458 }
459
460 static_assert(kDosageMid == 16384, "PrintGenDosage() needs to be updated.");
461 char* PrintGenDosage(uint32_t rawval, char* start) {
462 // Similar to PrintSmallDosage(), but it's complicated by .gen import's
463 // quantization step (instead of rounding the numbers directly, they're first
464 // converted to bgen-1.1 equivalents). We check
465 // ((n - 0.75)/16384, (n + 0.75)/16384) for even n
466 // ((n - 0.25)/16384, (n + 0.25)/16384) for odd n
467 // due to banker's rounding.
468 *start++ = '0' + (rawval / 16384);
469 rawval = rawval % 16384;
470 if (!rawval) {
471 return start;
472 }
473 *start++ = '.';
474 const uint32_t halfwidth_65536ths = 3 - (2 * (rawval % 2));
475 // (rawval * 4) is in 65536ths
476 // 65536 * 625 = 40960k
477
478 const uint32_t range_top_40960k = (rawval * 4 + halfwidth_65536ths) * 625;
479 // this is technically checking a half-open rather than a fully-open
480 // interval, but that's fine since we never hit the boundary points
481 if ((range_top_40960k % 4096) < 1250 * halfwidth_65536ths) {
482 // when this is true, the four-decimal-place approximation is in the range
483 // which round-trips back to our original number.
484 const uint32_t four_decimal_places = range_top_40960k / 4096;
485 return u32toa_trunc4(four_decimal_places, start);
486 }
487
488 // we wish to print (100000 * remainder + 8192) / 16384, left-0-padded. and
489 // may as well banker's round too.
490 //
491 // banker's rounding yields a different result than regular rounding for n/64
492 // when n is congruent to 1 mod 4:
493 // 1/64 = .015625 -> print 0.01562
494 // 3/64 = .046875 -> print 0.04688
495 // 5/64 = .078125 -> print 0.07812
496 const uint32_t five_decimal_places = ((3125 * rawval + 256) / 512) - ((rawval % 1024) == 256);
497 const uint32_t first_decimal_place = five_decimal_places / 10000;
498 *start++ = '0' + first_decimal_place;
499 const uint32_t last_four_digits = five_decimal_places - first_decimal_place * 10000;
500 if (last_four_digits) {
501 return u32toa_trunc4(last_four_digits, start);
502 }
503 return start;
504 }
505
506 static inline BoolErr bgzfwrite_ck(char* buf_flush, BgzfCompressStream* bgzfp, char** write_iter_ptr) {
507 if ((*write_iter_ptr) < buf_flush) {
508 return 0;
509 }
510 char* buf = &(buf_flush[-kMaxMediumLine]);
511 char* buf_end = *write_iter_ptr;
512 *write_iter_ptr = buf;
513 return BgzfWrite(buf, buf_end - buf, bgzfp);
514 }
515
516 BoolErr bgzfclose_flush(char* buf_flush, char* write_iter, BgzfCompressStream* bgzfp, PglErr* reterrp) {
517 char* buf = &(buf_flush[-kMaxMediumLine]);
518
519 // safe to ignore this error-return since CleanupBgzfCompressStream will also
520 // error-return
521 BgzfWrite(buf, write_iter - buf, bgzfp);
522
523 return CleanupBgzfCompressStream(bgzfp, reterrp);
524 }
525
526 PglErr ExportOxGen(const uintptr_t* sample_include, const uint32_t* sample_include_cumulative_popcounts, const uintptr_t* sex_nonfemale_collapsed, 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 AlleleCode* allele_permute, uint32_t sample_ct, uint32_t variant_ct, uint32_t max_allele_slen, __maybe_unused uint32_t max_thread_ct, ExportfFlags exportf_flags, PgenReader* simple_pgrp, char* outname, char* outname_end, uint32_t* sample_missing_geno_cts) {
527 unsigned char* bigstack_mark = g_bigstack_base;
528 PglErr reterr = kPglRetSuccess;
529 BgzfCompressStream bgzf;
530 PreinitBgzfCompressStream(&bgzf);
531 {
532 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
533 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
534 uintptr_t* genovec;
535 // if we weren't using bigstack_alloc, this would need to be sample_ctaw2
536 if (unlikely(bigstack_alloc_w(sample_ctl2, &genovec))) {
537 goto ExportOxGen_ret_NOMEM;
538 }
539
540 // See LoadSampleMissingCtsThread() in plink2_filter.cc.
541 // Yes, this is overkill, but the obvious alternative of incrementing
542 // sample_missing_geno_cts[] when writing a missing call requires a bit of
543 // custom chrY logic anyway.
544 const uint32_t acc1_vec_ct = BitCtToVecCt(sample_ct);
545 uintptr_t* missing_acc1;
546 if (unlikely(bigstack_calloc_w(acc1_vec_ct * kWordsPerVec * 45, &missing_acc1))) {
547 goto ExportOxGen_ret_NOMEM;
548 }
549 const uint32_t acc4_vec_ct = acc1_vec_ct * 4;
550 const uint32_t acc8_vec_ct = acc1_vec_ct * 8;
551 VecW* missing_acc4 = &(R_CAST(VecW*, missing_acc1)[acc1_vec_ct]);
552 VecW* missing_acc8 = &(missing_acc4[acc4_vec_ct]);
553 VecW* missing_acc32 = &(missing_acc8[acc8_vec_ct]);
554
555 uintptr_t* dosage_present = nullptr;
556 Dosage* dosage_main = nullptr;
557 if (PgrGetGflags(simple_pgrp) & kfPgenGlobalDosagePresent) {
558 const uint32_t multiallelic_present = (allele_idx_offsets != nullptr);
559 if (unlikely(bigstack_alloc_dosage(sample_ct * (1 + multiallelic_present), &dosage_main) ||
560 bigstack_alloc_w(sample_ctl, &dosage_present))) {
561 goto ExportOxGen_ret_NOMEM;
562 }
563 }
564 const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
565 const uint32_t is_v2 = (exportf_flags / kfExportfOxGenV2) & 1;
566 // if no dosages, all genotypes are 6 bytes (missing = " 0 0 0")
567 // with dosages, we print up to 5 digits past the decimal point, so 7 bytes
568 // + space for each number, 24 bytes max
569 const uintptr_t max_geno_slen = 6 + (dosage_present != nullptr) * 18;
570 char* chr_buf; // includes trailing space
571 char* writebuf;
572 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf) ||
573 bigstack_alloc_c(kMaxMediumLine + max_chr_blen + (kMaxIdSlen << is_v2) + 16 + 2 * max_allele_slen + max_geno_slen * sample_ct, &writebuf))) {
574 goto ExportOxGen_ret_NOMEM;
575 }
576 {
577 uint32_t clvl = 0;
578 if (!(exportf_flags & kfExportfBgz)) {
579 snprintf(outname_end, kMaxOutfnameExtBlen, ".gen");
580 } else {
581 snprintf(outname_end, kMaxOutfnameExtBlen, ".gen.gz");
582 clvl = kBgzfDefaultClvl;
583 }
584 reterr = InitBgzfCompressStreamEx(outname, 0, clvl, max_thread_ct, &bgzf);
585 if (unlikely(reterr)) {
586 if (reterr == kPglRetOpenFail) {
587 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
588 }
589 goto ExportOxGen_ret_1;
590 }
591 }
592 char* writebuf_flush = &(writebuf[kMaxMediumLine]);
593 char* write_iter = writebuf;
594 uint32_t chr_blen = 0;
595
596 // although we don't support --set-hh-missing, etc. here, we do still want
597 // to be aware of chrY so we can exclude nonmales from the
598 // sample_missing_geno_cts update there.
599 uint32_t is_y = 0;
600
601 PgrSampleSubsetIndex pssi;
602 PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi);
603 uint32_t chr_fo_idx = UINT32_MAX;
604 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
605 uint32_t chr_end = 0;
606 uint32_t vidx_rem15 = 15;
607 uint32_t vidx_rem255d15 = 17;
608 const uint32_t sample_ctl2_m1 = sample_ctl2 - 1;
609 // " 1 0 0", " 0 1 0", " 0 0 1", " 0 0 0"
610 const uint64_t hardcall_strs[4] = {0x302030203120LLU, 0x302031203020LLU, 0x312030203020LLU, 0x302030203020LLU};
611 const uint32_t ref_allele_last = !(exportf_flags & kfExportfRefFirst);
612 logprintfww5("Writing %s ... ", outname);
613 fputs("0%", stdout);
614 fflush(stdout);
615 uintptr_t variant_uidx_base = 0;
616 uintptr_t cur_bits = variant_include[0];
617 uint32_t pct = 0;
618 uint32_t next_print_variant_idx = variant_ct / 100;
619 uint32_t ref_allele_idx = 0;
620 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
621 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
622 if (variant_uidx >= chr_end) {
623 do {
624 ++chr_fo_idx;
625 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
626 } while (variant_uidx >= chr_end);
627 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
628 char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
629 // Oxford spec doesn't seem to require spaces for .gen (only .sample),
630 // but in practice spaces always seem to be used, and plink 1.9 doesn't
631 // let you toggle this, so let's not worry about supporting tabs here
632 *chr_name_end++ = ' ';
633 chr_blen = chr_name_end - chr_buf;
634 is_y = (chr_idx == y_code);
635 }
636 write_iter = memcpya(write_iter, chr_buf, chr_blen);
637 const char* variant_id = variant_ids[variant_uidx];
638 const uint32_t variant_id_slen = strlen(variant_id);
639 write_iter = memcpyax(write_iter, variant_id, variant_id_slen, ' ');
640 if (is_v2) {
641 write_iter = memcpyax(write_iter, variant_id, variant_id_slen, ' ');
642 }
643 write_iter = u32toa_x(variant_bps[variant_uidx], ' ', write_iter);
644 uintptr_t allele_idx_offset_base = variant_uidx * 2;
645 if (allele_idx_offsets) {
646 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
647 if (allele_idx_offsets[variant_uidx + 1] != allele_idx_offset_base + 2) {
648 logputs("\n");
649 logerrprintfww("Error: %s cannot contain multiallelic variants.\n", outname);
650 goto ExportOxGen_ret_INCONSISTENT_INPUT;
651 }
652 }
653 if (allele_permute) {
654 ref_allele_idx = allele_permute[allele_idx_offset_base];
655 }
656 // No dosage rescaling here, too messy to put that in more than one
657 // place.
658 uint32_t dosage_ct;
659 reterr = PgrGetD(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, genovec, dosage_present, dosage_main, &dosage_ct);
660 if (unlikely(reterr)) {
661 PgenErrPrintNV(reterr, variant_uidx);
662 goto ExportOxGen_ret_1;
663 }
664 if (ref_allele_idx != ref_allele_last) {
665 GenovecInvertUnsafe(sample_ct, genovec);
666 BiallelicDosage16Invert(dosage_ct, dosage_main);
667 }
668
669 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
670 if (ref_allele_last) {
671 write_iter = strcpyax(write_iter, cur_alleles[1 - ref_allele_idx], ' ');
672 write_iter = strcpya(write_iter, cur_alleles[ref_allele_idx]);
673 } else {
674 write_iter = strcpyax(write_iter, cur_alleles[ref_allele_idx], ' ');
675 write_iter = strcpya(write_iter, cur_alleles[1 - ref_allele_idx]);
676 }
677 uint32_t inner_loop_last = kBitsPerWordD2 - 1;
678 if (!dosage_ct) {
679 for (uint32_t widx = 0; ; ++widx) {
680 if (widx >= sample_ctl2_m1) {
681 if (widx > sample_ctl2_m1) {
682 break;
683 }
684 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
685 }
686 uintptr_t geno_word = genovec[widx];
687 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
688 // could process 2 genotypes at a time and do 8 byte + 4 byte copy
689 // for higher speed (may need to back up write_iter by 6 bytes at
690 // end). but this is not a bottleneck.
691 memcpy(write_iter, &(hardcall_strs[geno_word & 3]), 8);
692 write_iter = &(write_iter[6]);
693 geno_word >>= 2;
694 }
695 }
696 } else {
697 const Halfword* dosage_present_alias = DowncastWToHW(dosage_present);
698 const Dosage* dosage_main_iter = dosage_main;
699 for (uint32_t widx = 0; ; ++widx) {
700 if (widx >= sample_ctl2_m1) {
701 if (widx > sample_ctl2_m1) {
702 break;
703 }
704 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
705 }
706 uintptr_t geno_word = genovec[widx];
707 uint32_t dosage_present_hw = dosage_present_alias[widx];
708 if (!dosage_present_hw) {
709 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
710 memcpy(write_iter, &(hardcall_strs[geno_word & 3]), 8);
711 write_iter = &(write_iter[6]);
712 geno_word >>= 2;
713 }
714 } else {
715 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
716 if (dosage_present_hw & 1) {
717 const uint32_t dosage_int = *dosage_main_iter++;
718 if (dosage_int <= kDosageMid) {
719 *write_iter++ = ' ';
720 write_iter = PrintGenDosage(kDosageMid - dosage_int, write_iter);
721 *write_iter++ = ' ';
722 write_iter = PrintGenDosage(dosage_int, write_iter);
723 write_iter = strcpya_k(write_iter, " 0");
724 } else {
725 assert(dosage_int <= kDosageMax);
726 write_iter = strcpya_k(write_iter, " 0 ");
727 write_iter = PrintGenDosage(kDosageMax - dosage_int, write_iter);
728 *write_iter++ = ' ';
729 write_iter = PrintGenDosage(dosage_int - kDosageMid, write_iter);
730 }
731 } else {
732 memcpy(write_iter, &(hardcall_strs[geno_word & 3]), 8);
733 write_iter = &(write_iter[6]);
734 }
735 geno_word >>= 2;
736 dosage_present_hw >>= 1;
737 }
738 }
739 }
740 }
741 AppendBinaryEoln(&write_iter);
742 if (unlikely(bgzfwrite_ck(writebuf_flush, &bgzf, &write_iter))) {
743 goto ExportOxGen_ret_WRITE_FAIL;
744 }
745 // bugfix (13 Apr 2018): this missingness calculation was only taking
746 // hardcalls into account, which is inappropriate for .gen/.bgen
747 GenoarrToMissingnessUnsafe(genovec, sample_ct, missing_acc1);
748 if (dosage_ct) {
749 BitvecInvmask(dosage_present, sample_ctl, missing_acc1);
750 }
751 if (is_y) {
752 BitvecAnd(sex_nonfemale_collapsed, sample_ctl, missing_acc1);
753 }
754 VcountIncr1To4(missing_acc1, acc1_vec_ct, missing_acc4);
755 if (!(--vidx_rem15)) {
756 Vcount0Incr4To8(acc4_vec_ct, missing_acc4, missing_acc8);
757 vidx_rem15 = 15;
758 if (!(--vidx_rem255d15)) {
759 Vcount0Incr8To32(acc8_vec_ct, missing_acc8, missing_acc32);
760 vidx_rem255d15 = 17;
761 }
762 }
763 if (variant_idx >= next_print_variant_idx) {
764 if (pct > 10) {
765 putc_unlocked('\b', stdout);
766 }
767 pct = (variant_idx * 100LLU) / variant_ct;
768 printf("\b\b%u%%", pct++);
769 fflush(stdout);
770 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
771 }
772 }
773 if (unlikely(bgzfclose_flush(writebuf_flush, write_iter, &bgzf, &reterr))) {
774 goto ExportOxGen_ret_1;
775 }
776 if (pct > 10) {
777 putc_unlocked('\b', stdout);
778 }
779 fputs("\b\b", stdout);
780 logputs("done.\n");
781 VcountIncr4To8(missing_acc4, acc4_vec_ct, missing_acc8);
782 VcountIncr8To32(missing_acc8, acc8_vec_ct, missing_acc32);
783 uint32_t* scrambled_missing_cts = DowncastVecWToU32(missing_acc32);
784 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
785 const uint32_t scrambled_idx = VcountScramble1(sample_idx);
786 sample_missing_geno_cts[sample_idx] = scrambled_missing_cts[scrambled_idx];
787 }
788 }
789 while (0) {
790 ExportOxGen_ret_NOMEM:
791 reterr = kPglRetNomem;
792 break;
793 ExportOxGen_ret_WRITE_FAIL:
794 reterr = kPglRetWriteFail;
795 break;
796 ExportOxGen_ret_INCONSISTENT_INPUT:
797 reterr = kPglRetInconsistentInput;
798 break;
799 }
800 ExportOxGen_ret_1:
801 CleanupBgzfCompressStream(&bgzf, &reterr);
802 BigstackReset(bigstack_mark);
803 return reterr;
804 }
805
806 PglErr ExportOxHapslegend(const uintptr_t* sample_include, const uint32_t* sample_include_cumulative_popcounts, const uintptr_t* sex_male_collapsed, 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 AlleleCode* allele_permute, uint32_t sample_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_slen, __maybe_unused uint32_t max_thread_ct, ExportfFlags exportf_flags, PgenReader* simple_pgrp, char* outname, char* outname_end) {
807 assert(sample_ct);
808 assert(variant_ct);
809 unsigned char* bigstack_mark = g_bigstack_base;
810 FILE* outfile = nullptr;
811 PglErr reterr = kPglRetSuccess;
812 BgzfCompressStream bgzf;
813 PreinitBgzfCompressStream(&bgzf);
814 {
815 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
816 const uint32_t just_haps = (exportf_flags / kfExportfHaps) & 1;
817 const uint32_t male_ct = PopcountWords(sex_male_collapsed, sample_ctl);
818 if (unlikely(XymtIsNonempty(variant_include, cip, kChrOffsetY) && (male_ct != sample_ct))) {
819 logerrprintf("Error: '--export haps%s' must exclude chrY unless the dataset is all-male.\n", just_haps? "" : "legend");
820 goto ExportOxHapslegend_ret_INCONSISTENT_INPUT;
821 }
822 const uint32_t ref_allele_last = !(exportf_flags & kfExportfRefFirst);
823 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
824 char* chr_buf = nullptr;
825 uint32_t is_x = 0;
826 uint32_t is_haploid = 0;
827 const uint32_t variant_uidx_start = AdvTo1Bit(variant_include, 0);
828 uint32_t chr_fo_idx = UINT32_MAX;
829 uint32_t chr_end = 0;
830 uint32_t allele_idx0 = ref_allele_last;
831 uint32_t allele_idx1 = 1 - ref_allele_last;
832 uintptr_t writebuf_alloc = 0;
833 if (!just_haps) {
834 // .legend doesn't have a chromosome column, so verify we only need to
835 // export a single chromosome
836 chr_fo_idx = GetVariantChrFoIdx(cip, variant_uidx_start);
837 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
838 if (unlikely((chr_end != raw_variant_ct) && (PopcountBitRange(variant_include, variant_uidx_start, chr_end) != variant_ct))) {
839 logerrputs("Error: '--export hapslegend' does not support multiple chromosomes.\n");
840 goto ExportOxHapslegend_ret_INCONSISTENT_INPUT;
841 }
842 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
843 is_x = (chr_idx == x_code);
844 is_haploid = IsSet(cip->haploid_mask, chr_idx);
845 snprintf(outname_end, kMaxOutfnameExtBlen, ".legend");
846 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
847 goto ExportOxHapslegend_ret_OPEN_FAIL;
848 }
849 char* writebuf;
850 if (unlikely(bigstack_alloc_c(kMaxMediumLine + kMaxIdSlen + 32 + 2 * max_allele_slen, &writebuf))) {
851 goto ExportOxHapslegend_ret_NOMEM;
852 }
853 char* writebuf_flush = &(writebuf[kMaxMediumLine]);
854 char* write_iter = strcpya_k(writebuf, "id position a0 a1" EOLN_STR);
855 logprintfww5("Writing %s ... ", outname);
856 fflush(stdout);
857 uintptr_t variant_uidx_base;
858 uintptr_t cur_bits;
859 BitIter1Start(variant_include, variant_uidx_start, &variant_uidx_base, &cur_bits);
860 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
861 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
862 write_iter = strcpyax(write_iter, variant_ids[variant_uidx], ' ');
863 write_iter = u32toa_x(variant_bps[variant_uidx], ' ', write_iter);
864 uintptr_t allele_idx_offset_base = variant_uidx * 2;
865 if (allele_idx_offsets) {
866 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
867 // Multiallelic variants currently tolerated if allele_permute
868 // specified, and only its top two alleles are ever present.
869 if (unlikely((!allele_permute) && (allele_idx_offsets[variant_uidx + 1] != allele_idx_offset_base + 2))) {
870 logputs("\n");
871 logerrprintfww("Error: %s cannot contain multiallelic variants.\n", outname);
872 goto ExportOxHapslegend_ret_INCONSISTENT_INPUT;
873 }
874 }
875 if (allele_permute) {
876 allele_idx0 = allele_permute[allele_idx_offset_base + ref_allele_last];
877 allele_idx1 = allele_permute[allele_idx_offset_base + 1 - ref_allele_last];
878 }
879 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
880 write_iter = strcpyax(write_iter, cur_alleles[allele_idx0], ' ');
881 write_iter = strcpya(write_iter, cur_alleles[allele_idx1]);
882 AppendBinaryEoln(&write_iter);
883 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
884 goto ExportOxHapslegend_ret_WRITE_FAIL;
885 }
886 }
887 if (unlikely(fclose_flush_null(writebuf_flush, write_iter, &outfile))) {
888 goto ExportOxHapslegend_ret_WRITE_FAIL;
889 }
890 logputs("done.\n");
891 BigstackReset(writebuf);
892 } else {
893 const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
894 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
895 goto ExportOxHapslegend_ret_NOMEM;
896 }
897 writebuf_alloc = max_chr_blen + kMaxIdSlen + 32 + 2 * max_allele_slen;
898 }
899 writebuf_alloc += kMaxMediumLine + (4 * k1LU) * sample_ct + kCacheline;
900 const uint32_t sample_ctv = BitCtToVecCt(sample_ct);
901 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
902 char* writebuf;
903 uintptr_t* sex_male_collapsed_interleaved;
904 uintptr_t* genovec;
905 uintptr_t* phasepresent;
906 uintptr_t* phaseinfo;
907 if (unlikely(bigstack_alloc_w(sample_ctv * kWordsPerVec, &sex_male_collapsed_interleaved) ||
908 bigstack_alloc_c(writebuf_alloc, &writebuf) ||
909 bigstack_alloc_w(sample_ctl2, &genovec) ||
910 bigstack_alloc_w(sample_ctl, &phasepresent) ||
911 bigstack_alloc_w(sample_ctl, &phaseinfo))) {
912 goto ExportOxHapslegend_ret_NOMEM;
913 }
914 // sex_male_collapsed had trailing words zeroed out
915 FillInterleavedMaskVec(sex_male_collapsed, sample_ctv, sex_male_collapsed_interleaved);
916 // these could also be compile-time constants
917 uint32_t genotext_haploid[32];
918 // this can be more efficient, but don't worry about it for now
919 genotext_haploid[0] = 0x202d2030; // "0 - "
920 genotext_haploid[2] = 0x21475542; // "BUG!"
921 genotext_haploid[4] = 0x202d2031;
922 genotext_haploid[6] = 0x21475542;
923 InitLookup16x4bx2(genotext_haploid);
924 uint32_t genotext_diploid[112];
925 genotext_diploid[0] = 0x20302030;
926 genotext_diploid[2] = 0x21475542;
927 genotext_diploid[4] = 0x20312031;
928 genotext_diploid[6] = 0x21475542;
929 genotext_diploid[34] = 0x20312030;
930 genotext_diploid[38] = 0x20302031;
931 InitPhaseLookup4b(genotext_diploid);
932 uint32_t genotext_x[128];
933 genotext_x[0] = 0x20302030;
934 genotext_x[2] = 0x21475542;
935 genotext_x[4] = 0x20312031;
936 genotext_x[6] = 0x21475542;
937 genotext_x[32] = 0x202d2030;
938 genotext_x[34] = 0x20312030;
939 genotext_x[36] = 0x202d2031;
940 genotext_x[38] = 0x20302031;
941 InitPhaseXNohhLookup4b(genotext_x);
942
943 char* writebuf_flush = &(writebuf[kMaxMediumLine]);
944 char* write_iter = writebuf;
945 {
946 uint32_t clvl = 0;
947 if (!(exportf_flags & kfExportfBgz)) {
948 snprintf(outname_end, kMaxOutfnameExtBlen, ".haps");
949 } else {
950 snprintf(outname_end, kMaxOutfnameExtBlen, ".haps.gz");
951 clvl = kBgzfDefaultClvl;
952 }
953 reterr = InitBgzfCompressStreamEx(outname, 0, clvl, max_thread_ct, &bgzf);
954 if (unlikely(reterr)) {
955 if (reterr == kPglRetOpenFail) {
956 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
957 }
958 goto ExportOxHapslegend_ret_1;
959 }
960 }
961 logprintfww5("Writing %s ... ", outname);
962 fputs("0%", stdout);
963 fflush(stdout);
964 uintptr_t variant_uidx_base;
965 uintptr_t cur_bits;
966 BitIter1Start(variant_include, variant_uidx_start, &variant_uidx_base, &cur_bits);
967 PgrSampleSubsetIndex pssi;
968 PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi);
969 uint32_t chr_blen = 0;
970 uint32_t pct = 0;
971 uint32_t next_print_variant_idx = variant_ct / 100;
972 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
973 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
974 if (variant_uidx >= chr_end) {
975 do {
976 ++chr_fo_idx;
977 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
978 } while (variant_uidx >= chr_end);
979 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
980 char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
981 *chr_name_end++ = ' ';
982 chr_blen = chr_name_end - chr_buf;
983 is_x = (chr_idx == x_code);
984 is_haploid = IsSet(cip->haploid_mask, chr_idx);
985 }
986 uintptr_t allele_idx_offset_base = variant_uidx * 2;
987 if (allele_idx_offsets) {
988 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
989 if (unlikely((!allele_permute) && (allele_idx_offsets[variant_uidx + 1] != allele_idx_offset_base + 2))) {
990 logputs("\n");
991 logerrprintfww("Error: %s cannot contain multiallelic variants.\n", outname);
992 goto ExportOxHapslegend_ret_INCONSISTENT_INPUT;
993 }
994 }
995 if (allele_permute) {
996 allele_idx0 = allele_permute[allele_idx_offset_base + ref_allele_last];
997 allele_idx1 = allele_permute[allele_idx_offset_base + 1 - ref_allele_last];
998 }
999 uint32_t phasepresent_ct;
1000 reterr = PgrGet2P(sample_include, pssi, sample_ct, variant_uidx, allele_idx0, allele_idx1, simple_pgrp, genovec, phasepresent, phaseinfo, &phasepresent_ct);
1001 if (unlikely(reterr)) {
1002 PgenErrPrintNV(reterr, variant_uidx);
1003 goto ExportOxHapslegend_ret_1;
1004 }
1005 ZeroTrailingNyps(sample_ct, genovec);
1006 STD_ARRAY_DECL(uint32_t, 4, genocounts);
1007 GenoarrCountFreqsUnsafe(genovec, sample_ct, genocounts);
1008 if (unlikely(phasepresent_ct != genocounts[1])) {
1009 logputs("\n");
1010 logerrprintf("Error: '--export haps%s' must be used with a fully phased dataset.\n", just_haps? "" : "legend");
1011 goto ExportOxHapslegend_ret_INCONSISTENT_INPUT;
1012 } else if (unlikely(genocounts[3])) {
1013 logputs("\n");
1014 logerrprintf("Error: '--export haps%s' cannot be used with missing genotype calls.\n", just_haps? "" : "legend");
1015 goto ExportOxHapslegend_ret_INCONSISTENT_INPUT;
1016 }
1017 if (is_haploid) {
1018 // verify that there are no het haploids/mixed MTs
1019 if (is_x) {
1020 GenoarrCountSubsetFreqs(genovec, sex_male_collapsed_interleaved, sample_ct, male_ct, genocounts);
1021 }
1022 if (unlikely(genocounts[1])) {
1023 logputs("\n");
1024 logerrprintfww("Error: '--export haps%s' cannot be used when heterozygous haploid or mixed MT calls are present.%s\n", just_haps? "" : "legend", (is_x && (variant_bps[variant_uidx] <= 2781479))? " (Did you forget --split-par?)" : "");
1025 goto ExportOxHapslegend_ret_INCONSISTENT_INPUT;
1026 }
1027 }
1028 if (just_haps) {
1029 write_iter = memcpya(write_iter, chr_buf, chr_blen);
1030 write_iter = strcpyax(write_iter, variant_ids[variant_uidx], ' ');
1031 write_iter = u32toa_x(variant_bps[variant_uidx], ' ', write_iter);
1032 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
1033 write_iter = strcpyax(write_iter, cur_alleles[allele_idx0], ' ');
1034 write_iter = strcpyax(write_iter, cur_alleles[allele_idx1], ' ');
1035 }
1036 if (!is_x) {
1037 if (!phasepresent_ct) {
1038 GenoarrLookup16x4bx2(genovec, is_haploid? genotext_haploid : genotext_diploid, sample_ct, write_iter);
1039 } else {
1040 BitvecAnd(phasepresent, sample_ctl, phaseinfo);
1041 PhaseLookup4b(genovec, phasepresent, phaseinfo, genotext_diploid, sample_ct, write_iter);
1042 }
1043 } else {
1044 if (!phasepresent_ct) {
1045 GenoarrSexLookup4b(genovec, sex_male_collapsed, genotext_x, sample_ct, write_iter);
1046 } else {
1047 BitvecAnd(phasepresent, sample_ctl, phaseinfo);
1048 PhaseXNohhLookup4b(genovec, phasepresent, phaseinfo, sex_male_collapsed, genotext_x, sample_ct, write_iter);
1049 }
1050 }
1051 write_iter = &(write_iter[sample_ct * 4]);
1052 DecrAppendBinaryEoln(&write_iter);
1053 if (unlikely(bgzfwrite_ck(writebuf_flush, &bgzf, &write_iter))) {
1054 goto ExportOxHapslegend_ret_WRITE_FAIL;
1055 }
1056 if (variant_idx >= next_print_variant_idx) {
1057 if (pct > 10) {
1058 putc_unlocked('\b', stdout);
1059 }
1060 pct = (variant_idx * 100LLU) / variant_ct;
1061 printf("\b\b%u%%", pct++);
1062 fflush(stdout);
1063 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
1064 }
1065 }
1066 if (unlikely(bgzfclose_flush(writebuf_flush, write_iter, &bgzf, &reterr))) {
1067 goto ExportOxHapslegend_ret_1;
1068 }
1069 if (pct > 10) {
1070 putc_unlocked('\b', stdout);
1071 }
1072 fputs("\b\b", stdout);
1073 logputs("done.\n");
1074 }
1075 while (0) {
1076 ExportOxHapslegend_ret_NOMEM:
1077 reterr = kPglRetNomem;
1078 break;
1079 ExportOxHapslegend_ret_OPEN_FAIL:
1080 reterr = kPglRetOpenFail;
1081 break;
1082 ExportOxHapslegend_ret_WRITE_FAIL:
1083 reterr = kPglRetWriteFail;
1084 break;
1085 ExportOxHapslegend_ret_INCONSISTENT_INPUT:
1086 reterr = kPglRetInconsistentInput;
1087 break;
1088 }
1089 ExportOxHapslegend_ret_1:
1090 fclose_cond(outfile);
1091 CleanupBgzfCompressStream(&bgzf, &reterr);
1092 BigstackReset(bigstack_mark);
1093 return reterr;
1094 }
1095
1096 static const uint16_t kBgen11HardcallUsis[16] = {
1097 32768, 0, 0, 0,
1098 0, 32768, 0, 0,
1099 0, 0, 32768, 0,
1100 0, 0, 0, 0};
1101
1102 typedef struct ExportBgen11CtxStruct {
1103 const uintptr_t* variant_include;
1104 const uintptr_t* allele_idx_offsets;
1105 const uintptr_t* sample_include;
1106 const uint32_t* sample_include_cumulative_popcounts;
1107 const AlleleCode* allele_permute;
1108 const uintptr_t* sex_nonfemale_collapsed;
1109 uint32_t sample_ct;
1110 uint32_t y_start;
1111 uint32_t y_end;
1112 uint32_t ref_allele_last;
1113
1114 PgenReader** pgr_ptrs;
1115 uintptr_t** genovecs;
1116 uintptr_t** dosage_presents;
1117 Dosage** dosage_mains;
1118 uint32_t* read_variant_uidx_starts;
1119
1120 uint32_t cur_block_write_ct;
1121
1122 struct libdeflate_compressor** libdeflate_compressors;
1123 uintptr_t** missing_acc1;
1124 uint16_t** bgen_geno_bufs;
1125 uint32_t bgen_compressed_buf_max;
1126
1127 unsigned char* writebufs[2];
1128 uint32_t* variant_bytects[2];
1129
1130 // high 32 bits = variant_uidx, earlier one takes precedence
1131 // low 32 bits = uint32_t(PglErr)
1132 uint64_t err_info;
1133 } ExportBgen11Ctx;
1134
1135 THREAD_FUNC_DECL ExportBgen11Thread(void* raw_arg) {
1136 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
1137 const uintptr_t tidx = arg->tidx;
1138 ExportBgen11Ctx* ctx = S_CAST(ExportBgen11Ctx*, arg->sharedp->context);
1139
1140 PgenReader* pgrp = ctx->pgr_ptrs[tidx];
1141 uintptr_t* genovec = ctx->genovecs[tidx];
1142 const uint32_t sample_ct = ctx->sample_ct;
1143 const uint32_t acc1_vec_ct = BitCtToVecCt(sample_ct);
1144 const uint32_t acc4_vec_ct = acc1_vec_ct * 4;
1145 const uint32_t acc8_vec_ct = acc1_vec_ct * 8;
1146 uintptr_t* missing_acc1 = ctx->missing_acc1[tidx];
1147 VecW* missing_acc4 = &(R_CAST(VecW*, missing_acc1)[acc1_vec_ct]);
1148 VecW* missing_acc8 = &(missing_acc4[acc4_vec_ct]);
1149 VecW* missing_acc32 = &(missing_acc8[acc8_vec_ct]);
1150 uintptr_t* dosage_present = ctx->dosage_presents? ctx->dosage_presents[tidx] : nullptr;
1151 Dosage* dosage_main = dosage_present? ctx->dosage_mains[tidx] : nullptr;
1152 uint16_t* bgen_geno_buf = ctx->bgen_geno_bufs[tidx];
1153 struct libdeflate_compressor* compressor = ctx->libdeflate_compressors[tidx];
1154 const uintptr_t* variant_include = ctx->variant_include;
1155 const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
1156 const uintptr_t* sample_include = ctx->sample_include;
1157 PgrSampleSubsetIndex pssi;
1158 PgrSetSampleSubsetIndex(ctx->sample_include_cumulative_popcounts, pgrp, &pssi);
1159 const uintptr_t* sex_nonfemale_collapsed = ctx->sex_nonfemale_collapsed;
1160 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
1161 const uint32_t sample_ctl2_m1 = NypCtToWordCt(sample_ct) - 1;
1162 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
1163 const uint32_t bgen_geno_buf_blen = 6 * sample_ct;
1164 const uint32_t bgen_compressed_buf_max = ctx->bgen_compressed_buf_max;
1165 const AlleleCode* allele_permute = ctx->allele_permute;
1166 uint32_t is_y = 0;
1167 uint32_t y_thresh = ctx->y_start;
1168 const uint32_t y_end = ctx->y_end;
1169 const uint32_t ref_allele_last = ctx->ref_allele_last;
1170 uint32_t vidx_rem15 = 15;
1171 uint32_t vidx_rem255d15 = 17;
1172 uint32_t ref_allele_idx = 0;
1173 uint32_t parity = 0;
1174 ZeroWArr(acc1_vec_ct * kWordsPerVec * 45, missing_acc1);
1175 uint64_t new_err_info = 0;
1176 do {
1177 const uintptr_t cur_block_write_ct = ctx->cur_block_write_ct;
1178 uint32_t write_idx = (tidx * cur_block_write_ct) / calc_thread_ct;
1179 const uint32_t write_idx_end = ((tidx + 1) * cur_block_write_ct) / calc_thread_ct;
1180 unsigned char* writebuf_iter = &(ctx->writebufs[parity][write_idx * S_CAST(uintptr_t, bgen_compressed_buf_max)]);
1181 uint32_t* variant_bytect_iter = &(ctx->variant_bytects[parity][write_idx]);
1182 uintptr_t variant_uidx_base;
1183 uintptr_t cur_bits;
1184 BitIter1Start(variant_include, ctx->read_variant_uidx_starts[tidx], &variant_uidx_base, &cur_bits);
1185 for (; write_idx != write_idx_end; ++write_idx) {
1186 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
1187 if (variant_uidx >= y_thresh) {
1188 if (variant_uidx < y_end) {
1189 y_thresh = y_end;
1190 is_y = 1;
1191 } else {
1192 y_thresh = UINT32_MAX;
1193 is_y = 0;
1194 }
1195 }
1196 uintptr_t allele_idx_offset_base = variant_uidx * 2;
1197 if (allele_idx_offsets) {
1198 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
1199 if (allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base != 2) {
1200 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, kPglRetInconsistentInput);
1201 goto ExportBgen11Thread_err;
1202 }
1203 }
1204 if (allele_permute) {
1205 ref_allele_idx = allele_permute[allele_idx_offset_base];
1206 }
1207 uint32_t dosage_ct;
1208 PglErr reterr = PgrGetD(sample_include, pssi, sample_ct, variant_uidx, pgrp, genovec, dosage_present, dosage_main, &dosage_ct);
1209 if (unlikely(reterr)) {
1210 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
1211 goto ExportBgen11Thread_err;
1212 }
1213 if (ref_allele_idx + ref_allele_last == 1) {
1214 GenovecInvertUnsafe(sample_ct, genovec);
1215 BiallelicDosage16Invert(dosage_ct, dosage_main);
1216 }
1217 uint32_t inner_loop_last = kBitsPerWordD2 - 1;
1218 uint16_t* bgen_geno_buf_iter = bgen_geno_buf;
1219 if (!dosage_ct) {
1220 for (uint32_t widx = 0; ; ++widx) {
1221 if (widx >= sample_ctl2_m1) {
1222 if (widx > sample_ctl2_m1) {
1223 break;
1224 }
1225 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
1226 }
1227 uintptr_t geno_word = genovec[widx];
1228 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
1229 // possible todo: change this to 16x6bx2 lookup table
1230 memcpy_k(bgen_geno_buf_iter, &(kBgen11HardcallUsis[(geno_word & 3) * 4]), 6);
1231 bgen_geno_buf_iter = &(bgen_geno_buf_iter[3]);
1232 geno_word >>= 2;
1233 }
1234 }
1235 } else {
1236 const Halfword* dosage_present_alias = DowncastWToHW(dosage_present);
1237 const Dosage* dosage_main_iter = dosage_main;
1238 for (uint32_t widx = 0; ; ++widx) {
1239 if (widx >= sample_ctl2_m1) {
1240 if (widx > sample_ctl2_m1) {
1241 break;
1242 }
1243 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
1244 }
1245 uintptr_t geno_word = genovec[widx];
1246 uint32_t dosage_present_hw = dosage_present_alias[widx];
1247 if (!dosage_present_hw) {
1248 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
1249 memcpy_k(bgen_geno_buf_iter, &(kBgen11HardcallUsis[(geno_word & 3) * 4]), 6);
1250 bgen_geno_buf_iter = &(bgen_geno_buf_iter[3]);
1251 geno_word >>= 2;
1252 }
1253 } else {
1254 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
1255 if (dosage_present_hw & 1) {
1256 uint32_t dosage_int = *dosage_main_iter++;
1257 dosage_int *= 2;
1258 if (dosage_int <= kDosageMax) {
1259 *bgen_geno_buf_iter++ = kDosageMax - dosage_int;
1260 *bgen_geno_buf_iter++ = dosage_int;
1261 *bgen_geno_buf_iter++ = 0;
1262 } else {
1263 dosage_int -= kDosageMax;
1264 *bgen_geno_buf_iter++ = 0;
1265 *bgen_geno_buf_iter++ = kDosageMax - dosage_int;
1266 *bgen_geno_buf_iter++ = dosage_int;
1267 }
1268 } else {
1269 memcpy_k(bgen_geno_buf_iter, &(kBgen11HardcallUsis[(geno_word & 3) * 4]), 6);
1270 bgen_geno_buf_iter = &(bgen_geno_buf_iter[3]);
1271 }
1272 geno_word >>= 2;
1273 dosage_present_hw >>= 1;
1274 }
1275 }
1276 }
1277 }
1278 uintptr_t compressed_blen = libdeflate_zlib_compress(compressor, bgen_geno_buf, bgen_geno_buf_blen, writebuf_iter, bgen_compressed_buf_max);
1279 assert(compressed_blen);
1280 *variant_bytect_iter++ = compressed_blen;
1281 writebuf_iter = &(writebuf_iter[bgen_compressed_buf_max]);
1282 // bugfix (13 Apr 2018): this missingness calculation was only taking
1283 // hardcalls into account, which is inappropriate for .gen/.bgen
1284 GenoarrToMissingnessUnsafe(genovec, sample_ct, missing_acc1);
1285 if (dosage_ct) {
1286 BitvecInvmask(dosage_present, sample_ctl, missing_acc1);
1287 }
1288 if (is_y) {
1289 BitvecAnd(sex_nonfemale_collapsed, sample_ctl, missing_acc1);
1290 }
1291 VcountIncr1To4(missing_acc1, acc1_vec_ct, missing_acc4);
1292 if (!(--vidx_rem15)) {
1293 Vcount0Incr4To8(acc4_vec_ct, missing_acc4, missing_acc8);
1294 vidx_rem15 = 15;
1295 if (!(--vidx_rem255d15)) {
1296 Vcount0Incr8To32(acc8_vec_ct, missing_acc8, missing_acc32);
1297 vidx_rem255d15 = 17;
1298 }
1299 }
1300 }
1301 parity = 1 - parity;
1302 } while (!THREAD_BLOCK_FINISH(arg));
1303 {
1304 VcountIncr4To8(missing_acc4, acc4_vec_ct, missing_acc8);
1305 VcountIncr8To32(missing_acc8, acc8_vec_ct, missing_acc32);
1306 }
1307 while (0) {
1308 ExportBgen11Thread_err:
1309 UpdateU64IfSmaller(new_err_info, &ctx->err_info);
1310 THREAD_BLOCK_FINISH(arg);
1311 break;
1312 }
1313 THREAD_RETURN;
1314 }
1315
1316 PglErr ExportBgen11(const char* outname, const uintptr_t* sample_include, uint32_t* sample_include_cumulative_popcounts, const uintptr_t* sex_nonfemale_collapsed, 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 AlleleCode* allele_permute, uint32_t sample_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_slen, uint32_t max_thread_ct, ExportfFlags exportf_flags, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, uint32_t* sample_missing_geno_cts) {
1317 // isomorphic to ExportOxGen().
1318 assert(sample_ct);
1319 unsigned char* bigstack_mark = g_bigstack_base;
1320 FILE* outfile = nullptr;
1321 PglErr reterr = kPglRetSuccess;
1322 ThreadGroup tg;
1323 PreinitThreads(&tg);
1324 ExportBgen11Ctx ctx;
1325 {
1326 const uint32_t max_chr_slen = GetMaxChrSlen(cip);
1327 if (unlikely(BIGSTACK_ALLOC_X(struct libdeflate_compressor*, max_thread_ct, &ctx.libdeflate_compressors))) {
1328 goto ExportBgen11_ret_NOMEM;
1329 }
1330 ZeroPtrArr(max_thread_ct, ctx.libdeflate_compressors);
1331 // allocate the first compressor so we can call
1332 // libdeflate_zlib_compress_bound().
1333 // could add a --bgz-level flag analogous to --zst-level, of course.
1334 ctx.libdeflate_compressors[0] = libdeflate_alloc_compressor(6);
1335 if (unlikely(!ctx.libdeflate_compressors[0])) {
1336 goto ExportBgen11_ret_NOMEM;
1337 }
1338 const uintptr_t bgen_compressed_buf_max = libdeflate_zlib_compress_bound(ctx.libdeflate_compressors[0], 6LU * sample_ct);
1339 #ifdef __LP64__
1340 if (unlikely(bgen_compressed_buf_max > UINT32_MAX)) {
1341 logerrputs("Error: Too many samples for .bgen format.\n");
1342 goto ExportBgen11_ret_INCONSISTENT_INPUT;
1343 }
1344 #endif
1345 ctx.bgen_compressed_buf_max = bgen_compressed_buf_max;
1346 const uintptr_t writebuf_len = bgen_compressed_buf_max + 2 * max_allele_slen + 2 * kMaxIdSlen + 32;
1347 char* chr_buf;
1348 unsigned char* writebuf;
1349 if (unlikely(bigstack_alloc_c(max_chr_slen, &chr_buf) ||
1350 bigstack_alloc_uc(writebuf_len, &writebuf))) {
1351 goto ExportBgen11_ret_NOMEM;
1352 }
1353 ctx.sex_nonfemale_collapsed = sex_nonfemale_collapsed;
1354
1355 const uintptr_t max_write_block_byte_ct = bigstack_left() / 4;
1356 uint32_t max_write_block_size = kPglVblockSize;
1357 for (; ; max_write_block_size /= 2) {
1358 // limit each write buffer to 1/4 of remaining workspace
1359 if (S_CAST(uint64_t, bgen_compressed_buf_max + sizeof(int32_t)) * max_write_block_size <= max_write_block_byte_ct) {
1360 break;
1361 }
1362 if (unlikely(max_write_block_size <= kBitsPerVec)) {
1363 goto ExportBgen11_ret_NOMEM;
1364 }
1365 }
1366 uint32_t calc_thread_ct = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
1367 // seems to saturate around this point
1368 // todo: retest with libdeflate
1369 if (calc_thread_ct > 15) {
1370 calc_thread_ct = 15;
1371 }
1372 if (unlikely(bigstack_alloc_uc(bgen_compressed_buf_max * max_write_block_size, &(ctx.writebufs[0])) ||
1373 bigstack_alloc_uc(bgen_compressed_buf_max * max_write_block_size, &(ctx.writebufs[1])) ||
1374 bigstack_alloc_u32(max_write_block_size, &(ctx.variant_bytects[0])) ||
1375 bigstack_alloc_u32(max_write_block_size, &(ctx.variant_bytects[1])) ||
1376 bigstack_alloc_wp(calc_thread_ct, &ctx.missing_acc1) ||
1377 bigstack_alloc_u16p(calc_thread_ct, &ctx.bgen_geno_bufs))) {
1378 goto ExportBgen11_ret_NOMEM;
1379 }
1380 // we allocated [0] earlier
1381 for (uint32_t tidx = 1; tidx != calc_thread_ct; ++tidx) {
1382 ctx.libdeflate_compressors[tidx] = libdeflate_alloc_compressor(6);
1383 if (unlikely(!ctx.libdeflate_compressors[tidx])) {
1384 goto ExportBgen11_ret_NOMEM;
1385 }
1386 }
1387
1388 const uint32_t acc1_vec_ct = BitCtToVecCt(sample_ct);
1389 const uint32_t dosage_is_present = pgfip->gflags & kfPgenGlobalDosagePresent;
1390 const uintptr_t track_missing_cacheline_ct = VecCtToCachelineCt(acc1_vec_ct * 45);
1391 // no overflow risk here, thanks to compress_bound() check above
1392 const uintptr_t bgen_geno_cacheline_ct = DivUp(6 * sample_ct, kCacheline);
1393 const uintptr_t thread_xalloc_cacheline_ct = track_missing_cacheline_ct + bgen_geno_cacheline_ct;
1394 STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
1395 // defensive
1396 ctx.dosage_presents = nullptr;
1397 ctx.dosage_mains = nullptr;
1398 uint32_t read_block_size;
1399 if (unlikely(PgenMtLoadInit(variant_include, sample_ct, variant_ct, bigstack_left(), pgr_alloc_cacheline_ct, thread_xalloc_cacheline_ct, 0, 0, pgfip, &calc_thread_ct, &ctx.genovecs, nullptr, nullptr, nullptr, dosage_is_present? (&ctx.dosage_presents) : nullptr, dosage_is_present? (&ctx.dosage_mains) : nullptr, nullptr, nullptr, &read_block_size, nullptr, main_loadbufs, &ctx.pgr_ptrs, &ctx.read_variant_uidx_starts))) {
1400 goto ExportBgen11_ret_NOMEM;
1401 }
1402 if (read_block_size > max_write_block_size) {
1403 read_block_size = max_write_block_size;
1404 }
1405
1406 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
1407 goto ExportBgen11_ret_OPEN_FAIL;
1408 }
1409 // bgen 1.1 header
1410 // note that \xxx character constants are interpreted in octal, so \24 is
1411 // decimal 20, etc.
1412 memcpy(writebuf, "\24\0\0\0\24\0\0", 8);
1413 memcpy(&(writebuf[8]), &variant_ct, 4);
1414 memcpy(&(writebuf[12]), &sample_ct, 4);
1415 memcpy(&(writebuf[16]), "bgen\5\0\0", 8);
1416 if (unlikely(fwrite_checked(writebuf, 24, outfile))) {
1417 goto ExportBgen11_ret_WRITE_FAIL;
1418 }
1419
1420 const uint32_t ref_allele_last = !(exportf_flags & kfExportfRefFirst);
1421 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
1422 ctx.missing_acc1[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(track_missing_cacheline_ct * kCacheline));
1423 ctx.bgen_geno_bufs[tidx] = S_CAST(uint16_t*, bigstack_alloc_raw(bgen_geno_cacheline_ct * kCacheline));
1424 }
1425 ctx.sample_ct = sample_ct;
1426 ctx.variant_include = variant_include;
1427 ctx.allele_idx_offsets = allele_idx_offsets;
1428 ctx.sample_include = sample_include;
1429 ctx.sample_include_cumulative_popcounts = sample_include_cumulative_popcounts;
1430 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
1431 goto ExportBgen11_ret_NOMEM;
1432 }
1433 ctx.allele_permute = allele_permute;
1434 GetXymtStartAndEnd(cip, kChrOffsetY, &ctx.y_start, &ctx.y_end);
1435 ctx.ref_allele_last = ref_allele_last;
1436 ctx.err_info = (~0LLU) << 32;
1437 SetThreadFuncAndData(ExportBgen11Thread, &ctx, &tg);
1438
1439 // 6 bytes present at start of every bgen-1.1 variant record
1440 memcpy(writebuf, &sample_ct, 4);
1441 memcpy(&(writebuf[4]), "\0", 2);
1442
1443 // Main workflow:
1444 // 1. Set n=0, load/skip block 0
1445 //
1446 // 2. Spawn threads processing block n
1447 // 3. If n>0, write results for block (n-1)
1448 // 4. Increment n by 1
1449 // 5. Load/skip block n unless eof
1450 // 6. Join threads
1451 // 7. Goto step 2 unless eof
1452 //
1453 // 8. Write results for last block
1454 uintptr_t write_variant_uidx_base = 0;
1455 uintptr_t cur_bits = variant_include[0];
1456 uint32_t parity = 0;
1457 uint32_t read_block_idx = 0;
1458 uint32_t chr_fo_idx = UINT32_MAX;
1459 uint32_t chr_end = 0;
1460 uint32_t chr_slen = 0;
1461
1462 uint32_t prev_block_write_ct = 0;
1463 uint32_t pct = 0;
1464 uint32_t next_print_variant_idx = variant_ct / 100;
1465 logprintfww5("Writing %s ... ", outname);
1466 fputs("0%", stdout);
1467 fflush(stdout);
1468 uint32_t ref_allele_idx = 0;
1469 uint32_t alt1_allele_idx = 1;
1470 for (uint32_t variant_idx = 0; ; ) {
1471 const uint32_t cur_block_write_ct = MultireadNonempty(variant_include, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr);
1472 if (unlikely(reterr)) {
1473 goto ExportBgen11_ret_PGR_FAIL;
1474 }
1475 if (variant_idx) {
1476 JoinThreads(&tg);
1477 reterr = S_CAST(PglErr, ctx.err_info);
1478 if (unlikely(reterr)) {
1479 if (reterr == kPglRetInconsistentInput) {
1480 logputs("\n");
1481 logerrprintfww("Error: %s cannot contain multiallelic variants.\n", outname);
1482 } else {
1483 PgenErrPrintNV(reterr, ctx.err_info >> 32);
1484 }
1485 goto ExportBgen11_ret_1;
1486 }
1487 }
1488 if (!IsLastBlock(&tg)) {
1489 ctx.cur_block_write_ct = cur_block_write_ct;
1490 ComputeUidxStartPartition(variant_include, cur_block_write_ct, calc_thread_ct, read_block_idx * read_block_size, ctx.read_variant_uidx_starts);
1491 PgrCopyBaseAndOffset(pgfip, calc_thread_ct, ctx.pgr_ptrs);
1492 if (variant_idx + cur_block_write_ct == variant_ct) {
1493 DeclareLastThreadBlock(&tg);
1494 }
1495 if (unlikely(SpawnThreads(&tg))) {
1496 goto ExportBgen11_ret_THREAD_CREATE_FAIL;
1497 }
1498 }
1499 parity = 1 - parity;
1500 if (variant_idx) {
1501 // write *previous* block results
1502 const unsigned char* compressed_data_iter = ctx.writebufs[parity];
1503 const uint32_t* variant_bytect_iter = ctx.variant_bytects[parity];
1504 for (uint32_t variant_bidx = 0; variant_bidx != prev_block_write_ct; ++variant_bidx) {
1505 const uint32_t write_variant_uidx = BitIter1(variant_include, &write_variant_uidx_base, &cur_bits);
1506 if (write_variant_uidx >= chr_end) {
1507 do {
1508 ++chr_fo_idx;
1509 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
1510 } while (write_variant_uidx >= chr_end);
1511 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
1512 const char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
1513 chr_slen = chr_name_end - chr_buf;
1514 }
1515 const char* cur_variant_id = variant_ids[write_variant_uidx];
1516 const uint32_t id_slen = strlen(cur_variant_id);
1517 unsigned char* writebuf_iter = memcpyua(&(writebuf[6]), &id_slen, 2);
1518 writebuf_iter = memcpyua(writebuf_iter, cur_variant_id, id_slen);
1519 AppendU16(chr_slen, &writebuf_iter);
1520 writebuf_iter = memcpyua(writebuf_iter, chr_buf, chr_slen);
1521 AppendU32(variant_bps[write_variant_uidx], &writebuf_iter);
1522 uintptr_t allele_idx_offset_base = write_variant_uidx * 2;
1523 if (allele_idx_offsets) {
1524 allele_idx_offset_base = allele_idx_offsets[write_variant_uidx];
1525 if (unlikely((!allele_permute) && (allele_idx_offsets[write_variant_uidx + 1] != allele_idx_offset_base + 2))) {
1526 logputs("\n");
1527 logerrprintfww("Error: %s cannot contain multiallelic variants.\n", outname);
1528 goto ExportBgen11_ret_INCONSISTENT_INPUT;
1529 }
1530 }
1531 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
1532 if (allele_permute) {
1533 ref_allele_idx = allele_permute[allele_idx_offset_base];
1534 alt1_allele_idx = allele_permute[allele_idx_offset_base + 1];
1535 }
1536 const char* first_allele;
1537 const char* second_allele;
1538 if (ref_allele_last) {
1539 first_allele = cur_alleles[alt1_allele_idx];
1540 second_allele = cur_alleles[ref_allele_idx];
1541 } else {
1542 first_allele = cur_alleles[ref_allele_idx];
1543 second_allele = cur_alleles[alt1_allele_idx];
1544 }
1545 uint32_t allele_slen = strlen(first_allele);
1546 AppendU32(allele_slen, &writebuf_iter);
1547 writebuf_iter = memcpyua(writebuf_iter, first_allele, allele_slen);
1548 allele_slen = strlen(second_allele);
1549 AppendU32(allele_slen, &writebuf_iter);
1550 writebuf_iter = memcpyua(writebuf_iter, second_allele, allele_slen);
1551 const uint32_t cur_variant_bytect = *variant_bytect_iter++;
1552 AppendU32(cur_variant_bytect, &writebuf_iter);
1553 writebuf_iter = memcpyua(writebuf_iter, compressed_data_iter, cur_variant_bytect);
1554 compressed_data_iter = &(compressed_data_iter[bgen_compressed_buf_max]);
1555 if (unlikely(fwrite_checked(writebuf, writebuf_iter - writebuf, outfile))) {
1556 goto ExportBgen11_ret_WRITE_FAIL;
1557 }
1558 }
1559 }
1560 if (variant_idx == variant_ct) {
1561 break;
1562 }
1563 if (variant_idx >= next_print_variant_idx) {
1564 if (pct > 10) {
1565 putc_unlocked('\b', stdout);
1566 }
1567 pct = (variant_idx * 100LLU) / variant_ct;
1568 printf("\b\b%u%%", pct++);
1569 fflush(stdout);
1570 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
1571 }
1572 ++read_block_idx;
1573 prev_block_write_ct = cur_block_write_ct;
1574 variant_idx += cur_block_write_ct;
1575 pgfip->block_base = main_loadbufs[parity];
1576 }
1577 if (unlikely(fclose_null(&outfile))) {
1578 goto ExportBgen11_ret_WRITE_FAIL;
1579 }
1580 if (pct > 10) {
1581 putc_unlocked('\b', stdout);
1582 }
1583 fputs("\b\b", stdout);
1584 logputs("done.\n");
1585 const uint32_t sample_ctav = acc1_vec_ct * kBitsPerVec;
1586 const uintptr_t acc32_offset = acc1_vec_ct * (13 * k1LU * kWordsPerVec);
1587 uint32_t* scrambled_missing_cts = DowncastWToU32(&(ctx.missing_acc1[0][acc32_offset]));
1588 for (uint32_t tidx = 1; tidx != calc_thread_ct; ++tidx) {
1589 const uint32_t* thread_scrambled_missing_cts = DowncastWToU32(&(ctx.missing_acc1[tidx][acc32_offset]));
1590 for (uint32_t uii = 0; uii != sample_ctav; ++uii) {
1591 scrambled_missing_cts[uii] += thread_scrambled_missing_cts[uii];
1592 }
1593 }
1594 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1595 const uint32_t scrambled_idx = VcountScramble1(sample_idx);
1596 sample_missing_geno_cts[sample_idx] = scrambled_missing_cts[scrambled_idx];
1597 }
1598 }
1599 while (0) {
1600 ExportBgen11_ret_NOMEM:
1601 reterr = kPglRetNomem;
1602 break;
1603 ExportBgen11_ret_OPEN_FAIL:
1604 reterr = kPglRetOpenFail;
1605 break;
1606 ExportBgen11_ret_PGR_FAIL:
1607 PgenErrPrintN(reterr);
1608 break;
1609 ExportBgen11_ret_WRITE_FAIL:
1610 reterr = kPglRetWriteFail;
1611 break;
1612 ExportBgen11_ret_INCONSISTENT_INPUT:
1613 reterr = kPglRetInconsistentInput;
1614 break;
1615 ExportBgen11_ret_THREAD_CREATE_FAIL:
1616 reterr = kPglRetThreadCreateFail;
1617 break;
1618 }
1619 ExportBgen11_ret_1:
1620 CleanupThreads(&tg);
1621 if (ctx.libdeflate_compressors) {
1622 for (uint32_t tidx = 0; tidx != max_thread_ct; ++tidx) {
1623 if (!ctx.libdeflate_compressors[tidx]) {
1624 break;
1625 }
1626 libdeflate_free_compressor(ctx.libdeflate_compressors[tidx]);
1627 }
1628 }
1629 fclose_cond(outfile);
1630 BigstackReset(bigstack_mark);
1631 pgfip->block_base = nullptr;
1632 return reterr;
1633 }
1634
1635 // For constant-ploidy cases. Writes up to 7 bytes past the end.
1636 // For what it's worth, bgen_geno_buf_iter is always word-aligned on entry (8
1637 // bytes after beginning of buffer, which is at the start of a cacheline), and
1638 // it's easy to force vector-alignment if it would be useful.
1639 unsigned char* FillBgen13PloidyAndMissingness(const uintptr_t* genovec, const uintptr_t* dosage_present, uintptr_t ploidy, uint32_t sample_ct, uint32_t dosage_ct, unsigned char* bgen_geno_buf_iter) {
1640 // bugfix (30 Aug 2018): need to spell out mask in 32-bit case
1641 const uint64_t ploidy_u64 = ploidy * 0x101010101010101LLU;
1642 const uint32_t sample_ct8 = DivUp(sample_ct, 8);
1643 const uint16_t* genovec_alias = DowncastKWToU16(genovec);
1644 if (!dosage_ct) {
1645 for (uint32_t write_widx = 0; write_widx != sample_ct8; ++write_widx) {
1646 const uint64_t cur_geno8 = genovec_alias[write_widx];
1647 uint64_t cur_missing8 = cur_geno8 & (cur_geno8 >> 1);
1648 #ifdef USE_AVX2
1649 // 0,2,4,6...14 -> 7,15,23,...,63
1650 // todo: try inverse-movespreadmask
1651 cur_missing8 = _pdep_u64(cur_missing8 & 0x5555, 0x80 * kMask1111);
1652 #else
1653 // 0,2,4,6,8,10,12,14 -> 0,2,4,6,32,34,36,38
1654 cur_missing8 = (cur_missing8 | (cur_missing8 << 24)) & 0x5500000055LLU;
1655 // Multiply by number with bits 7,13,19,25 set, then mask out all but the
1656 // bits we want. There are potential carries at bits 13, 19, 25, 45, 51,
1657 // and 57, but none of them hurt us.
1658 cur_missing8 = (cur_missing8 * 0x2082080) & (0x8080808080808080LLU);
1659 #endif
1660 const uint64_t write_u64 = cur_missing8 + ploidy_u64;
1661 CopyToUnalignedOffsetU64(bgen_geno_buf_iter, &write_u64, write_widx);
1662 }
1663 } else {
1664 // don't bother with word-based 32-bit code because this case becomes
1665 // more annoying
1666 const unsigned char* dosage_present_alias = DowncastKToUc(dosage_present);
1667 for (uint32_t write_widx = 0; write_widx != sample_ct8; ++write_widx) {
1668 const uint64_t cur_geno8 = genovec_alias[write_widx];
1669 uint64_t cur_dosage_missing8 = ~dosage_present_alias[write_widx];
1670 uint64_t cur_hardcall_missing8 = cur_geno8 & (cur_geno8 >> 1);
1671 #ifdef USE_AVX2
1672 // 0,2,4,6...14 -> 7,15,23,...,63
1673 cur_hardcall_missing8 = _pdep_u64(cur_hardcall_missing8 & 0x5555, 0x80 * kMask1111);
1674 cur_dosage_missing8 = _pdep_u64(cur_dosage_missing8, 0x80 * kMask0101);
1675 const uint64_t cur_missing8 = cur_hardcall_missing8 & cur_dosage_missing8;
1676 #else
1677 // 0,2,4,6,8,10,12,14 -> 0,2,4,6,32,34,36,38
1678 cur_hardcall_missing8 = (cur_hardcall_missing8 | (cur_hardcall_missing8 << 24)) & 0x5500000055LLU;
1679 // -> 0,8,16,24,32,40,48,56, with extraneous bits set
1680 cur_hardcall_missing8 = cur_hardcall_missing8 * 0x41041;
1681 // 0,1,2,3,4,5,6,7 -> 0,8,16,24,32,40,48,56, with extraneous bits set
1682 // this operation also appears in GflagsVfilter(), may want to wrap it
1683 cur_dosage_missing8 = ((cur_dosage_missing8 & 0xfe) * 0x2040810204080LLU) | (cur_dosage_missing8 & 1);
1684 const uint64_t cur_missing8 = ((cur_hardcall_missing8 & cur_dosage_missing8) & 0x101010101010101LLU) << 7;
1685 #endif
1686 const uint64_t write_u64 = cur_missing8 + ploidy_u64;
1687 CopyToUnalignedOffsetU64(bgen_geno_buf_iter, &write_u64, write_widx);
1688 }
1689 }
1690 return &(bgen_geno_buf_iter[sample_ct]);
1691 }
1692
1693 uint32_t NoFemaleMissing(const uintptr_t* genovec, const uintptr_t* dosage_present, const uintptr_t* sex_female, uint32_t sample_ctl2, uint32_t dosage_ct) {
1694 if (dosage_ct) {
1695 const uint32_t sample_ctl = DivUp(sample_ctl2, 2);
1696 if (!IntersectionIsEmpty(sex_female, dosage_present, sample_ctl)) {
1697 return 0;
1698 }
1699 }
1700 const Halfword* sex_female_alias = DowncastKWToHW(sex_female);
1701 // todo: try vectorizing this loop
1702 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
1703 const uintptr_t geno_word = genovec[widx];
1704 const uintptr_t cur_female_01 = UnpackHalfwordToWord(sex_female_alias[widx]);
1705 if (geno_word & (geno_word >> 1) & cur_female_01) {
1706 return 0;
1707 }
1708 }
1709 return 1;
1710 }
1711
1712 // These may belong in plink2_base or plink2_common.
1713 // cur_write_bit_idx stays in [0, kBitsPerWord - 1]
1714 static inline void AppendBits(uint32_t bit_ct, uintptr_t payload, uintptr_t* cur_write_bits_ptr, uint32_t* cur_write_bit_idx_ptr, unsigned char** probs_write_iter_ptr) {
1715 uint32_t cur_write_bit_idx = *cur_write_bit_idx_ptr;
1716 *cur_write_bits_ptr |= payload << cur_write_bit_idx;
1717 cur_write_bit_idx += bit_ct;
1718 if (cur_write_bit_idx >= kBitsPerWord) {
1719 AppendW(*cur_write_bits_ptr, probs_write_iter_ptr);
1720 cur_write_bit_idx -= kBitsPerWord;
1721 *cur_write_bits_ptr = payload >> (bit_ct - cur_write_bit_idx);
1722 }
1723 *cur_write_bit_idx_ptr = cur_write_bit_idx;
1724 }
1725
1726 static inline void Append0Bits(uint32_t bit_ct, uintptr_t* cur_write_bits_ptr, uint32_t* cur_write_bit_idx_ptr, unsigned char** probs_write_iter_ptr) {
1727 uint32_t cur_write_bit_idx = *cur_write_bit_idx_ptr;
1728 cur_write_bit_idx += bit_ct;
1729 if (cur_write_bit_idx >= kBitsPerWord) {
1730 AppendW(*cur_write_bits_ptr, probs_write_iter_ptr);
1731 cur_write_bit_idx -= kBitsPerWord;
1732 *cur_write_bits_ptr = 0;
1733 }
1734 *cur_write_bit_idx_ptr = cur_write_bit_idx;
1735 }
1736
1737 typedef struct Bgen13TablesStruct {
1738 // Precomputed 1-genotype-at-a-time tables (4 entries)
1739 uint32_t* diploid_basic_table;
1740 uint16_t* haploid_basic_table;
1741
1742 // Precomputed 4-genotype-at-a-time tables (256 entries; multiply index by
1743 // two and copy two values at a time for table16).
1744 uint64_t* diploid_hardcall_table8;
1745 uint64_t* diploid_hardcall_table16;
1746
1747 // Precomputed 1-genotype-at-a-time table (16 entries: phasepresent = bit 2,
1748 // phaseinfo = bit 3)
1749 uint32_t* diploid_phased_hardcall_table;
1750
1751 // 4-genotype-at-a-time tables.
1752 uint32_t* haploid_hardcall_table8;
1753 uint64_t* haploid_hardcall_table16;
1754
1755 uint32_t bit_precision;
1756 } Bgen13Tables;
1757
1758 BoolErr ConstructBgen13LookupTables(uint32_t exportf_bits, Bgen13Tables* tablesp) {
1759 const uint32_t max_val = (1U << exportf_bits) - 1;
1760 const uint32_t half_val_roundeven = ((max_val + 1) / 2) & (~1);
1761 if (bigstack_alloc_u32(4, &tablesp->diploid_basic_table) ||
1762 bigstack_alloc_u32(16, &tablesp->diploid_phased_hardcall_table) ||
1763 bigstack_alloc_u16(4, &tablesp->haploid_basic_table)) {
1764 return 1;
1765 }
1766 // reference allele is exported as second allele so default import and
1767 // export settings work together
1768 // (yeah, this will make multiallelic case annoying)
1769 // unphased diploid:
1770 // [0] = 0, 0
1771 // [1] = 0, max
1772 // [2] = max, 0
1773 // [3] = 0, 0
1774 tablesp->diploid_basic_table[0] = 0;
1775 tablesp->diploid_basic_table[1] = max_val << exportf_bits;
1776 tablesp->diploid_basic_table[2] = max_val;
1777 tablesp->diploid_basic_table[3] = 0;
1778
1779 // phased diploid:
1780 // [0] = 0, 0
1781 // [1] unphased = half, half
1782 // [1] phased, phaseinfo clear = 0, max
1783 // [1] phased, phaseinfo set = max, 0
1784 // [2] = max, max
1785 // [3] = 0, 0
1786 tablesp->diploid_phased_hardcall_table[0] = 0;
1787 tablesp->diploid_phased_hardcall_table[1] = half_val_roundeven * ((1U << exportf_bits) + 1);
1788 tablesp->diploid_phased_hardcall_table[2] = max_val * ((1U << exportf_bits) + 1);
1789 tablesp->diploid_phased_hardcall_table[3] = 0;
1790 // might need to defend against garbage phaseinfo
1791 // cheap to defend against garbage phasepresent
1792 memcpy(&(tablesp->diploid_phased_hardcall_table[4]), tablesp->diploid_phased_hardcall_table, 4 * sizeof(int32_t));
1793 memcpy(&(tablesp->diploid_phased_hardcall_table[8]), tablesp->diploid_phased_hardcall_table, 8 * sizeof(int32_t));
1794 tablesp->diploid_phased_hardcall_table[5] = max_val << exportf_bits;
1795 tablesp->diploid_phased_hardcall_table[13] = max_val;
1796
1797 // haploid:
1798 // [0] = 0
1799 // [1] = half, may as well round-to-even
1800 // [2] = max
1801 // [3] = 0
1802 tablesp->haploid_basic_table[0] = 0;
1803 tablesp->haploid_basic_table[1] = half_val_roundeven;
1804 tablesp->haploid_basic_table[2] = max_val;
1805 tablesp->haploid_basic_table[3] = 0;
1806
1807 if (exportf_bits <= 8) {
1808 // can conditionally skip some of these tables, but whatever
1809 if (unlikely(bigstack_alloc_u64(256, &tablesp->diploid_hardcall_table8) ||
1810 bigstack_alloc_u32(256, &tablesp->haploid_hardcall_table8))) {
1811 return 1;
1812 }
1813 tablesp->diploid_hardcall_table16 = nullptr;
1814 tablesp->haploid_hardcall_table16 = nullptr;
1815 uint64_t* write64_iter = tablesp->diploid_hardcall_table8;
1816 for (uint32_t uii = 0; uii != 4; ++uii) {
1817 const uint64_t entry3 = S_CAST(uint64_t, tablesp->diploid_basic_table[uii]) << (exportf_bits * 6);
1818 for (uint32_t ujj = 0; ujj != 4; ++ujj) {
1819 const uint64_t entry23 = entry3 | (S_CAST(uint64_t, tablesp->diploid_basic_table[ujj]) << (exportf_bits * 4));
1820 for (uint32_t ukk = 0; ukk != 4; ++ukk) {
1821 const uint64_t entry123 = entry23 | (S_CAST(uint64_t, tablesp->diploid_basic_table[ukk]) << (exportf_bits * 2));
1822 for (uint32_t umm = 0; umm != 4; ++umm) {
1823 *write64_iter++ = entry123 | tablesp->diploid_basic_table[umm];
1824 }
1825 }
1826 }
1827 }
1828
1829 uint32_t* write32_iter = tablesp->haploid_hardcall_table8;
1830 for (uint32_t uii = 0; uii != 4; ++uii) {
1831 const uint32_t entry3 = S_CAST(uint32_t, tablesp->haploid_basic_table[uii]) << (exportf_bits * 3);
1832 for (uint32_t ujj = 0; ujj != 4; ++ujj) {
1833 const uint32_t entry23 = entry3 | (S_CAST(uint32_t, tablesp->haploid_basic_table[ujj]) << (exportf_bits * 2));
1834 for (uint32_t ukk = 0; ukk != 4; ++ukk) {
1835 const uint32_t entry123 = entry23 | (S_CAST(uint32_t, tablesp->haploid_basic_table[ukk]) << exportf_bits);
1836 for (uint32_t umm = 0; umm != 4; ++umm) {
1837 *write32_iter++ = entry123 | tablesp->haploid_basic_table[umm];
1838 }
1839 }
1840 }
1841 }
1842 } else {
1843 if (unlikely(bigstack_alloc_u64(512, &tablesp->diploid_hardcall_table16) ||
1844 bigstack_alloc_u64(256, &tablesp->haploid_hardcall_table16))) {
1845 return 1;
1846 }
1847 tablesp->diploid_hardcall_table8 = nullptr;
1848 tablesp->haploid_hardcall_table8 = nullptr;
1849 uint64_t* write64_iter = tablesp->diploid_hardcall_table16;
1850 uint64_t entry23_low = 0;
1851 for (uint32_t uii = 0; uii != 4; ++uii) {
1852 const uint64_t entry3 = S_CAST(uint64_t, tablesp->diploid_basic_table[uii]) << (exportf_bits * 2);
1853 for (uint32_t ujj = 0; ujj != 4; ++ujj) {
1854 uint64_t entry23_high = entry3 | tablesp->diploid_basic_table[ujj];
1855 if (exportf_bits < 16) {
1856 entry23_low = entry23_high << (4 * exportf_bits);
1857 entry23_high = entry23_high >> (64 - 4 * exportf_bits);
1858 }
1859 for (uint32_t ukk = 0; ukk != 4; ++ukk) {
1860 const uint64_t entry123_low = entry23_low | (S_CAST(uint64_t, tablesp->diploid_basic_table[ukk]) << (exportf_bits * 2));
1861 for (uint32_t umm = 0; umm != 4; ++umm) {
1862 *write64_iter++ = entry123_low | tablesp->diploid_basic_table[umm];
1863 *write64_iter++ = entry23_high;
1864 }
1865 }
1866 }
1867 }
1868
1869 write64_iter = tablesp->haploid_hardcall_table16;
1870 for (uint32_t uii = 0; uii != 4; ++uii) {
1871 const uint64_t entry3 = S_CAST(uint64_t, tablesp->haploid_basic_table[uii]) << (exportf_bits * 3);
1872 for (uint32_t ujj = 0; ujj != 4; ++ujj) {
1873 const uint64_t entry23 = entry3 | (S_CAST(uint64_t, tablesp->haploid_basic_table[ujj]) << (exportf_bits * 2));
1874 for (uint32_t ukk = 0; ukk != 4; ++ukk) {
1875 const uint64_t entry123 = entry23 | (S_CAST(uint64_t, tablesp->haploid_basic_table[ukk]) << exportf_bits);
1876 for (uint32_t umm = 0; umm != 4; ++umm) {
1877 *write64_iter++ = entry123 | tablesp->haploid_basic_table[umm];
1878 }
1879 }
1880 }
1881 }
1882 }
1883 tablesp->bit_precision = exportf_bits;
1884 return 0;
1885 }
1886
1887 typedef struct ExportBgen13CtxStruct {
1888 const uintptr_t* variant_include;
1889 const ChrInfo* cip;
1890 const uintptr_t* allele_idx_offsets;
1891 const uintptr_t* sample_include;
1892 const uint32_t* sample_include_cumulative_popcounts;
1893 const AlleleCode* allele_permute;
1894 const uintptr_t* sex_male_collapsed;
1895 const uintptr_t* sex_female_collapsed;
1896 Bgen13Tables tables;
1897 uint32_t sample_ct;
1898 uint32_t ref_allele_last;
1899
1900 PgenReader** pgr_ptrs;
1901 uintptr_t** genovecs;
1902 uintptr_t** phasepresents;
1903 uintptr_t** phaseinfos;
1904 uintptr_t** dosage_presents;
1905 Dosage** dosage_mains;
1906 uintptr_t** dphase_presents;
1907 SDosage** dphase_deltas;
1908 uint32_t* read_variant_uidx_starts;
1909
1910 uint32_t cur_block_write_ct;
1911
1912 struct libdeflate_compressor** libdeflate_compressors;
1913 uintptr_t** missing_acc1;
1914 unsigned char** uncompressed_bgen_geno_bufs;
1915 uint32_t bgen_compressed_buf_max;
1916
1917 unsigned char* writebufs[2];
1918 uint32_t* variant_bytects[2];
1919
1920 // high 32 bits = variant_uidx, earlier one takes precedence
1921 // low 32 bits = uint32_t(PglErr)
1922 uint64_t err_info;
1923 } ExportBgen13Ctx;
1924
1925 THREAD_FUNC_DECL ExportBgen13Thread(void* raw_arg) {
1926 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
1927 const uintptr_t tidx = arg->tidx;
1928 ExportBgen13Ctx* ctx = S_CAST(ExportBgen13Ctx*, arg->sharedp->context);
1929
1930 PgenReader* pgrp = ctx->pgr_ptrs[tidx];
1931 PgenVariant pgv;
1932 pgv.genovec = ctx->genovecs[tidx];
1933 const uint32_t sample_ct = ctx->sample_ct;
1934 const uint32_t acc1_vec_ct = BitCtToVecCt(sample_ct);
1935 const uint32_t acc4_vec_ct = acc1_vec_ct * 4;
1936 const uint32_t acc8_vec_ct = acc1_vec_ct * 8;
1937 uintptr_t* missing_acc1 = ctx->missing_acc1[tidx];
1938 VecW* missing_acc4 = &(R_CAST(VecW*, missing_acc1)[acc1_vec_ct]);
1939 VecW* missing_acc8 = &(missing_acc4[acc4_vec_ct]);
1940 VecW* missing_acc32 = &(missing_acc8[acc8_vec_ct]);
1941 // todo: multiallelic support
1942 pgv.phasepresent = nullptr;
1943 pgv.phaseinfo = nullptr;
1944 if (ctx->phasepresents) {
1945 pgv.phasepresent = ctx->phasepresents[tidx];
1946 pgv.phaseinfo = ctx->phaseinfos[tidx];
1947 }
1948 pgv.dosage_present = ctx->dosage_presents? ctx->dosage_presents[tidx] : nullptr;
1949 pgv.dosage_main = pgv.dosage_present? ctx->dosage_mains[tidx] : nullptr;
1950 pgv.dphase_present = ctx->dphase_presents? ctx->dphase_presents[tidx] : nullptr;
1951 pgv.dphase_delta = pgv.dphase_present? ctx->dphase_deltas[tidx] : nullptr;
1952 // Note that we may write up to 12 bytes past the end
1953 unsigned char* uncompressed_bgen_geno_buf = ctx->uncompressed_bgen_geno_bufs[tidx];
1954 struct libdeflate_compressor* compressor = ctx->libdeflate_compressors? ctx->libdeflate_compressors[tidx] : nullptr;
1955 const uint32_t zst_level = g_zst_level;
1956 const uintptr_t* variant_include = ctx->variant_include;
1957 const ChrInfo* cip = ctx->cip;
1958 const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
1959 const uintptr_t* sample_include = ctx->sample_include;
1960 PgrSampleSubsetIndex pssi;
1961 PgrSetSampleSubsetIndex(ctx->sample_include_cumulative_popcounts, pgrp, &pssi);
1962 const uintptr_t* sex_male_collapsed = ctx->sex_male_collapsed;
1963 const uintptr_t* sex_female_collapsed = ctx->sex_female_collapsed;
1964 const uint16_t* bgen_haploid_basic_table = ctx->tables.haploid_basic_table;
1965 const uint32_t* bgen_diploid_basic_table = ctx->tables.diploid_basic_table;
1966 const uint64_t* bgen_diploid_hardcall_table8 = ctx->tables.diploid_hardcall_table8;
1967 const uint64_t* bgen_diploid_hardcall_table16 = ctx->tables.diploid_hardcall_table16;
1968 const uint32_t* bgen_diploid_phased_hardcall_table = ctx->tables.diploid_phased_hardcall_table;
1969 const uint32_t* bgen_haploid_hardcall_table8 = ctx->tables.haploid_hardcall_table8;
1970 const uint64_t* bgen_haploid_hardcall_table16 = ctx->tables.haploid_hardcall_table16;
1971 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
1972 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
1973 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
1974 const uint32_t sample_ctl2_m1 = sample_ctl2 - 1;
1975 const uint32_t sample_ct4 = DivUp(sample_ct, 4);
1976 const uint32_t bit_precision = ctx->tables.bit_precision;
1977 // note that this assumes bit_precision <= 16
1978 const uint32_t two_byte_probs = (bit_precision > 8);
1979 const uint32_t max_output_val = (1U << bit_precision) - 1;
1980 const uint32_t bgen_compressed_buf_max = ctx->bgen_compressed_buf_max;
1981 const AlleleCode* allele_permute = ctx->allele_permute;
1982 uint32_t chr_fo_idx = UINT32_MAX; // deliberate overflow
1983 uint32_t chr_end = 0;
1984 uint32_t is_x = 0;
1985 uint32_t is_y = 0;
1986 uint32_t cur_y = 0;
1987
1988 uint32_t is_haploid = 0; // includes chrX
1989 // Unlike the VCF/BCF export case, we do not save heterozygous haploid calls
1990 // as ploidy=2 unless there is also phase information.
1991 // Unlike VCF, chrY female (but not unknown-sex) ploidy is 0 when genotype is
1992 // missing.
1993 const uint32_t male_ct = PopcountWords(sex_male_collapsed, sample_ctl);
1994 const uint32_t female_ct = PopcountWords(sex_female_collapsed, sample_ctl);
1995 const uint32_t x_code = (male_ct != sample_ct)? cip->xymt_codes[kChrOffsetX] : UINT32_MAXM1;
1996 const uint32_t y_code = female_ct? cip->xymt_codes[kChrOffsetY] : UINT32_MAXM1;
1997 const uint32_t ref_allele_last = ctx->ref_allele_last;
1998 uint32_t vidx_rem15 = 15;
1999 uint32_t vidx_rem255d15 = 17;
2000 uint32_t ref_allele_idx = 0;
2001 uint32_t parity = 0;
2002 ZeroWArr(acc1_vec_ct * kWordsPerVec * 45, missing_acc1);
2003 uint64_t new_err_info = 0;
2004 do {
2005 const uintptr_t cur_block_write_ct = ctx->cur_block_write_ct;
2006 uint32_t write_idx = (tidx * cur_block_write_ct) / calc_thread_ct;
2007 const uint32_t write_idx_end = ((tidx + 1) * cur_block_write_ct) / calc_thread_ct;
2008 unsigned char* writebuf_iter = &(ctx->writebufs[parity][write_idx * S_CAST(uintptr_t, bgen_compressed_buf_max)]);
2009 // [2n] = 4 + compressed_len, [2n + 1] = uncompressed_len
2010 uint32_t* variant_bytect_iter = &(ctx->variant_bytects[parity][2 * write_idx]);
2011 uintptr_t variant_uidx_base;
2012 uintptr_t variant_include_bits;
2013 BitIter1Start(variant_include, ctx->read_variant_uidx_starts[tidx], &variant_uidx_base, &variant_include_bits);
2014 for (; write_idx != write_idx_end; ++write_idx) {
2015 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
2016 if (variant_uidx >= chr_end) {
2017 do {
2018 ++chr_fo_idx;
2019 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
2020 } while (variant_uidx >= chr_end);
2021 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
2022 is_y = (chr_idx == y_code);
2023 is_haploid = IsSet(cip->haploid_mask, chr_idx);
2024 is_x = 0;
2025 if (chr_idx == x_code) {
2026 if (male_ct) {
2027 is_x = 1;
2028 } else {
2029 is_haploid = 0;
2030 }
2031 }
2032 cur_y = 0;
2033 }
2034 uintptr_t allele_idx_offset_base = variant_uidx * 2;
2035 if (allele_idx_offsets) {
2036 // todo: multiallelic cases
2037 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
2038 if (allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base != 2) {
2039 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, kPglRetInconsistentInput);
2040 goto ExportBgen13Thread_err;
2041 }
2042 }
2043 if (allele_permute) {
2044 ref_allele_idx = allele_permute[allele_idx_offset_base];
2045 }
2046 // (note that multiallelic variants should always be stored using the
2047 // phased format; just set both sides equal when the call is actually
2048 // unphased. this way there's no O([allele count]^2) bloat problem.)
2049 PglErr reterr = PgrGetDp(sample_include, pssi, sample_ct, variant_uidx, pgrp, &pgv);
2050 if (unlikely(reterr)) {
2051 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
2052 goto ExportBgen13Thread_err;
2053 }
2054 // note that this is inverted from bgen-1.1
2055 // todo: switch to allele-rotation function call
2056 if (ref_allele_idx + ref_allele_last != 1) {
2057 GenovecInvertUnsafe(sample_ct, pgv.genovec);
2058 if (pgv.phasepresent_ct) {
2059 BitvecInvert(sample_ctl, pgv.phaseinfo);
2060 }
2061 if (pgv.dosage_ct) {
2062 BiallelicDosage16Invert(pgv.dosage_ct, pgv.dosage_main);
2063 if (pgv.dphase_ct) {
2064 BiallelicDphase16Invert(pgv.dphase_ct, pgv.dphase_delta);
2065 }
2066 }
2067 }
2068 unsigned char* bgen_geno_buf_iter = uncompressed_bgen_geno_buf;
2069 // 4 bytes: # of samples
2070 // 2 bytes: # of alleles
2071 // 1 byte: minimum ploidy
2072 // 1 byte: maximum ploidy
2073 // sample_ct bytes: high bit = missing, low bits = ploidy
2074 // 1 byte: is_phased
2075 // 1 byte: bit_precision
2076
2077 AppendU32(sample_ct, &bgen_geno_buf_iter);
2078 if (is_y) {
2079 // All-nonfemales case treated as haploid general case.
2080 // The difference here is that missing female calls are saved as
2081 // ploidy 0; this basically forces us to write a single value at
2082 // a time.
2083 cur_y = !NoFemaleMissing(pgv.genovec, pgv.dosage_present, sex_female_collapsed, sample_ctl2, pgv.dosage_ct);
2084 }
2085 if (pgv.dphase_ct && (bit_precision < 15)) {
2086 // Theoretically possible for all dphase_delta values to be too small
2087 // to ever make left dosage != right dosage. If so, allow unphased
2088 // output.
2089 uintptr_t sample_widx = 0;
2090 uintptr_t dosage_present_bits = pgv.dosage_present[0];
2091 uint32_t dphase_idx = 0;
2092 uint32_t dosage_idx = 0;
2093 for (; dosage_idx != pgv.dosage_ct; ++dosage_idx) {
2094 const uintptr_t lowbit = BitIter1y(pgv.dosage_present, &sample_widx, &dosage_present_bits);
2095 if (pgv.dphase_present[sample_widx] & lowbit) {
2096 const uint32_t cur_dosage = pgv.dosage_main[dosage_idx];
2097 const int32_t cur_dphase_delta_val = pgv.dphase_delta[dphase_idx++];
2098 const uint32_t left_raw = (cur_dosage + cur_dphase_delta_val) >> 1;
2099 const uint32_t right_raw = (cur_dosage - cur_dphase_delta_val) >> 1;
2100 const uint32_t left_output_preshift = left_raw * max_output_val + kDosage4th;
2101 const uint32_t right_output_preshift = right_raw * max_output_val + kDosage4th;
2102 if ((left_output_preshift ^ right_output_preshift) / kDosageMid) {
2103 break;
2104 }
2105 }
2106 }
2107 if (dosage_idx >= pgv.dosage_ct) {
2108 pgv.dphase_ct = 0;
2109 }
2110 }
2111 const uint32_t use_phased_format = pgv.phasepresent_ct || pgv.dphase_ct;
2112 if (use_phased_format && pgv.dosage_ct) {
2113 if (!pgv.phasepresent_ct) {
2114 ZeroWArr(sample_ctl, pgv.phasepresent);
2115 } else if (!pgv.dphase_ct) {
2116 ZeroWArr(sample_ctl, pgv.dphase_present);
2117 }
2118 }
2119 if ((!is_haploid) || (pgv.phasepresent_ct == sample_ct) || (pgv.dphase_ct && UnionIsFull(pgv.phasepresent, pgv.dphase_present, sample_ct))) {
2120 // 2 alleles, min ploidy == max ploidy == 2
2121 // (this includes the chrX no-sex-info case)
2122 // dosages can be patched in after the fact
2123 AppendU32(0x2020002, &bgen_geno_buf_iter);
2124 bgen_geno_buf_iter = FillBgen13PloidyAndMissingness(pgv.genovec, pgv.dosage_present, 2, sample_ct, pgv.dosage_ct, bgen_geno_buf_iter);
2125 *bgen_geno_buf_iter++ = use_phased_format;
2126 *bgen_geno_buf_iter++ = bit_precision;
2127 const unsigned char* genovec_alias = DowncastKToUc(pgv.genovec);
2128 unsigned char* probs_write_citer = bgen_geno_buf_iter;
2129 if (!use_phased_format) {
2130 if (!two_byte_probs) {
2131 for (uint32_t geno_byte_idx = 0; geno_byte_idx != sample_ct4; ++geno_byte_idx) {
2132 const unsigned char cur_geno4 = genovec_alias[geno_byte_idx];
2133 memcpy(probs_write_citer, &(bgen_diploid_hardcall_table8[cur_geno4]), sizeof(int64_t));
2134 probs_write_citer = &(probs_write_citer[bit_precision]);
2135 }
2136 } else {
2137 // 9..16
2138 for (uint32_t geno_byte_idx = 0; geno_byte_idx != sample_ct4; ++geno_byte_idx) {
2139 const unsigned char cur_geno4 = genovec_alias[geno_byte_idx];
2140 memcpy(probs_write_citer, &(bgen_diploid_hardcall_table16[2 * cur_geno4]), 2 * sizeof(int64_t));
2141 probs_write_citer = &(probs_write_citer[bit_precision]);
2142 }
2143 }
2144 } else {
2145 // use_phased_format
2146 const unsigned char* phasepresent_alias = DowncastKToUc(pgv.phasepresent);
2147 const unsigned char* phaseinfo_alias = DowncastKToUc(pgv.phaseinfo);
2148 const uint32_t bit_precision_x2 = bit_precision * 2;
2149
2150 uintptr_t cur_write_bits = 0;
2151 uint32_t cur_write_bit_idx = 0;
2152 // possible todo: iterate over genovec halfwords instead, and convert
2153 // diploid_phased_hardcall_table to support two-at-a-time lookup.
2154 for (uint32_t geno_byte_idx = 0; geno_byte_idx != sample_ct4; ++geno_byte_idx) {
2155 const uint32_t geno_byte_idx_d2 = geno_byte_idx / 2;
2156 uint32_t cur_geno4 = genovec_alias[geno_byte_idx];
2157 uint32_t cur_phasepresent4 = phasepresent_alias[geno_byte_idx_d2];
2158 uint32_t cur_phaseinfo4 = phaseinfo_alias[geno_byte_idx_d2];
2159 if (geno_byte_idx % 2) {
2160 cur_phasepresent4 >>= 4;
2161 cur_phaseinfo4 >>= 4;
2162 }
2163 for (uint32_t uii = 0; uii != 4; ++uii) {
2164 const uint32_t cur_index = (cur_geno4 & 3) | ((cur_phasepresent4 & 1) * 4) | ((cur_phaseinfo4 & 1) * 8);
2165 const uintptr_t payload = bgen_diploid_phased_hardcall_table[cur_index];
2166 AppendBits(bit_precision_x2, payload, &cur_write_bits, &cur_write_bit_idx, &probs_write_citer);
2167 cur_geno4 >>= 2;
2168 cur_phasepresent4 >>= 1;
2169 cur_phaseinfo4 >>= 1;
2170 }
2171 }
2172 CopyToUnalignedW(probs_write_citer, &cur_write_bits);
2173 }
2174 if (pgv.dosage_ct) {
2175 const uintptr_t bit_precision_x2 = bit_precision * 2;
2176 uintptr_t sample_uidx_base = 0;
2177 uintptr_t dosage_present_bits = pgv.dosage_present[0];
2178 if (!use_phased_format) {
2179 // first value is P(geno=2), second value is P(geno=1)
2180 for (uint32_t dosage_idx = 0; dosage_idx != pgv.dosage_ct; ++dosage_idx) {
2181 // multiply by e.g. 255/16384 and round
2182 // there are multiple ways to interpret "round to even" here,
2183 // so I give up and just round 0.5 up (especially since it
2184 // should be very rare).
2185 const uintptr_t sample_uidx = BitIter1(pgv.dosage_present, &sample_uidx_base, &dosage_present_bits);
2186 // note that this needs to be changed to uint64_t if internal
2187 // dosage representation is no longer 16-bit
2188 const uint32_t cur_dosage = pgv.dosage_main[dosage_idx];
2189 uint32_t output_prob2 = 0;
2190 uint32_t output_prob1;
2191 if (cur_dosage > kDosageMid) {
2192 output_prob2 = ((cur_dosage - kDosageMid) * max_output_val + kDosage4th) / kDosageMid;
2193 output_prob1 = max_output_val - output_prob2;
2194 } else {
2195 output_prob1 = (cur_dosage * max_output_val + kDosage4th) / kDosageMid;
2196 }
2197 CopyBits(output_prob2 | (output_prob1 << bit_precision), sample_uidx * S_CAST(uint64_t, bit_precision_x2), bit_precision_x2, bgen_geno_buf_iter);
2198 }
2199 } else {
2200 // phased format, need to take hphase and/or dphase into account
2201 uint32_t dphase_idx = 0;
2202 for (uint32_t dosage_idx = 0; dosage_idx != pgv.dosage_ct; ++dosage_idx) {
2203 const uintptr_t sample_uidx = BitIter1(pgv.dosage_present, &sample_uidx_base, &dosage_present_bits);
2204 const uint32_t cur_dosage = pgv.dosage_main[dosage_idx];
2205 uint32_t output_prob1;
2206 uint32_t output_prob2;
2207 if (IsSet(pgv.dphase_present, sample_uidx)) {
2208 const int32_t cur_dphase_delta_val = pgv.dphase_delta[dphase_idx++];
2209 const uint32_t left_raw = (cur_dosage + cur_dphase_delta_val) >> 1;
2210 const uint32_t right_raw = (cur_dosage - cur_dphase_delta_val) >> 1;
2211 output_prob1 = (left_raw * max_output_val + kDosage4th) / kDosageMid;
2212 output_prob2 = (right_raw * max_output_val + kDosage4th) / kDosageMid;
2213 } else if (IsSet(pgv.phasepresent, sample_uidx)) {
2214 if (cur_dosage > kDosageMid) {
2215 output_prob1 = ((cur_dosage - kDosageMid) * max_output_val + kDosage4th) / kDosageMid;
2216 output_prob2 = max_output_val;
2217 } else {
2218 output_prob1 = 0;
2219 output_prob2 = (cur_dosage * max_output_val + kDosage4th) / kDosageMid;
2220 }
2221 if (IsSet(pgv.phaseinfo, sample_uidx)) {
2222 const uint32_t tmpval = output_prob1;
2223 output_prob1 = output_prob2;
2224 output_prob2 = tmpval;
2225 }
2226 } else {
2227 // unphased
2228 output_prob1 = (cur_dosage * max_output_val + kDosageMid) / kDosageMax;
2229 output_prob2 = output_prob1;
2230 }
2231 CopyBits(output_prob1 | (output_prob2 << bit_precision), sample_uidx * S_CAST(uint64_t, bit_precision_x2), bit_precision_x2, bgen_geno_buf_iter);
2232 }
2233 }
2234 }
2235 const uint64_t tot_prob_bit_ct = sample_ct * 2 * S_CAST(uint64_t, bit_precision);
2236 bgen_geno_buf_iter = &(bgen_geno_buf_iter[tot_prob_bit_ct / CHAR_BIT]);
2237 const uint32_t remainder = tot_prob_bit_ct % 8;
2238 if (remainder) {
2239 *bgen_geno_buf_iter &= (1 << remainder) - 1;
2240 ++bgen_geno_buf_iter;
2241 }
2242 } else if ((!use_phased_format) && (!is_x) && (!cur_y)) {
2243 // 2 alleles, min ploidy == max ploidy == 1
2244 // dosages can be patched in after the fact
2245 AppendU32(0x1010002, &bgen_geno_buf_iter);
2246 bgen_geno_buf_iter = FillBgen13PloidyAndMissingness(pgv.genovec, pgv.dosage_present, 1, sample_ct, pgv.dosage_ct, bgen_geno_buf_iter);
2247 *bgen_geno_buf_iter++ = 0;
2248 *bgen_geno_buf_iter++ = bit_precision;
2249 unsigned char* probs_write_citer = bgen_geno_buf_iter;
2250 const uint16_t* genovec_u16 = DowncastKWToU16(pgv.genovec);
2251 const uint32_t sample_ct8 = DivUp(sample_ct, 8);
2252 const uint32_t bit_precision_x4 = bit_precision * 4;
2253 if (!two_byte_probs) {
2254 for (uint32_t geno_u16_idx = 0; geno_u16_idx != sample_ct8; ++geno_u16_idx) {
2255 const uint32_t cur_geno8 = genovec_u16[geno_u16_idx];
2256 const uint64_t new_bytes = bgen_haploid_hardcall_table8[cur_geno8 & 255] | (S_CAST(uint64_t, bgen_haploid_hardcall_table8[cur_geno8 >> 8]) << bit_precision_x4);
2257 memcpy(probs_write_citer, &new_bytes, sizeof(int64_t));
2258 probs_write_citer = &(probs_write_citer[bit_precision]);
2259 }
2260 } else {
2261 const uint32_t backfill = 64 - bit_precision_x4;
2262 for (uint32_t geno_u16_idx = 0; geno_u16_idx != sample_ct8; ++geno_u16_idx) {
2263 // this may write 14 bytes past the end
2264 const uint32_t cur_geno8 = genovec_u16[geno_u16_idx];
2265 uint64_t low_bits = bgen_haploid_hardcall_table16[cur_geno8 & 255];
2266 uint64_t high_bits = bgen_haploid_hardcall_table16[cur_geno8 >> 8];
2267 if (backfill) {
2268 low_bits |= high_bits << bit_precision_x4;
2269 high_bits = high_bits >> backfill;
2270 }
2271 memcpy(probs_write_citer, &low_bits, sizeof(int64_t));
2272 memcpy(&(probs_write_citer[8]), &high_bits, sizeof(int64_t));
2273 probs_write_citer = &(probs_write_citer[bit_precision]);
2274 }
2275 }
2276 if (pgv.dosage_ct) {
2277 uintptr_t sample_uidx_base = 0;
2278 uintptr_t dosage_present_bits = pgv.dosage_present[0];
2279 const uint32_t half_int = kDosageMid - (bit_precision == 1);
2280 for (uint32_t dosage_idx = 0; dosage_idx != pgv.dosage_ct; ++dosage_idx) {
2281 // multiply by e.g. 255/32768 and round-to-even
2282 const uintptr_t sample_uidx = BitIter1(pgv.dosage_present, &sample_uidx_base, &dosage_present_bits);
2283 // note that this needs to be changed to uint64_t if internal
2284 // dosage representation is no longer 16-bit
2285 const uint32_t cur_dosage = pgv.dosage_main[dosage_idx];
2286 const uint32_t output_prob = (cur_dosage * max_output_val + half_int) / kDosageMax;
2287 CopyBits(output_prob, sample_uidx * S_CAST(uint64_t, bit_precision), bit_precision, bgen_geno_buf_iter);
2288 }
2289 }
2290 const uint64_t tot_prob_bit_ct = sample_ct * S_CAST(uint64_t, bit_precision);
2291 bgen_geno_buf_iter = &(bgen_geno_buf_iter[tot_prob_bit_ct / CHAR_BIT]);
2292 const uint32_t remainder = tot_prob_bit_ct % 8;
2293 if (remainder) {
2294 *bgen_geno_buf_iter &= (1 << remainder) - 1;
2295 ++bgen_geno_buf_iter;
2296 }
2297 } else {
2298 uintptr_t cur_write_bits = 0;
2299 uint32_t cur_write_bit_idx = 0;
2300 uint32_t loop_len = kBitsPerWordD2;
2301 if (!pgv.dosage_ct) {
2302 if (!pgv.phasepresent_ct) {
2303 if (is_x) {
2304 // if male_ct == 0, we used the all-diploid code path instead
2305 // if male_ct == sample_ct, we treat as haploid general case
2306 AppendU32(0x2010002, &bgen_geno_buf_iter);
2307 unsigned char* ploidy_and_missingness_iter = bgen_geno_buf_iter;
2308 bgen_geno_buf_iter = &(bgen_geno_buf_iter[sample_ct]);
2309 *bgen_geno_buf_iter++ = 0;
2310 *bgen_geno_buf_iter++ = bit_precision;
2311 for (uint32_t widx = 0; ; ++widx) {
2312 if (widx >= sample_ctl2_m1) {
2313 if (widx > sample_ctl2_m1) {
2314 break;
2315 }
2316 loop_len = ModNz(sample_ct, kBitsPerWordD2);
2317 }
2318 uintptr_t geno_word = pgv.genovec[widx];
2319 uint32_t male_hw = DowncastKWToHW(sex_male_collapsed)[widx];
2320 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
2321 const uintptr_t cur_geno = geno_word & 3;
2322 const uint32_t cur_male = male_hw & 1;
2323 *ploidy_and_missingness_iter++ = (cur_geno == 3) * 128 + 2 - cur_male;
2324 if (cur_male) {
2325 AppendBits(bit_precision, bgen_haploid_basic_table[cur_geno], &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2326 } else {
2327 AppendBits(2 * bit_precision, bgen_diploid_basic_table[cur_geno], &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2328 }
2329 geno_word >>= 2;
2330 male_hw >>= 1;
2331 }
2332 }
2333 } else {
2334 assert(cur_y);
2335 if ((female_ct == sample_ct) && AllBitsAreOne(pgv.genovec, sample_ct * 2)) {
2336 // chrY, all females, all missing = max ploidy 0
2337 AppendU32(0x0000002, &bgen_geno_buf_iter);
2338 bgen_geno_buf_iter = memsetua(bgen_geno_buf_iter, 128, sample_ct);
2339 *bgen_geno_buf_iter++ = 0;
2340 *bgen_geno_buf_iter++ = bit_precision;
2341 } else {
2342 AppendU32(0x1000002, &bgen_geno_buf_iter);
2343 unsigned char* ploidy_and_missingness_iter = bgen_geno_buf_iter;
2344 bgen_geno_buf_iter = &(bgen_geno_buf_iter[sample_ct]);
2345 *bgen_geno_buf_iter++ = 0;
2346 *bgen_geno_buf_iter++ = bit_precision;
2347 for (uint32_t widx = 0; ; ++widx) {
2348 if (widx >= sample_ctl2_m1) {
2349 if (widx > sample_ctl2_m1) {
2350 break;
2351 }
2352 loop_len = ModNz(sample_ct, kBitsPerWordD2);
2353 }
2354 uintptr_t geno_word = pgv.genovec[widx];
2355 uint32_t female_hw = DowncastKWToHW(sex_female_collapsed)[widx];
2356 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
2357 const uintptr_t cur_geno = geno_word & 3;
2358 const uint32_t cur_female = female_hw & 1;
2359 const uint32_t ploidy_and_missingness = (cur_geno == 3) * (128 - cur_female) + 1;
2360 *ploidy_and_missingness_iter++ = ploidy_and_missingness;
2361 if (ploidy_and_missingness != 128) {
2362 AppendBits(bit_precision, bgen_haploid_basic_table[cur_geno], &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2363 }
2364 geno_word >>= 2;
2365 female_hw >>= 1;
2366 }
2367 }
2368 }
2369 }
2370 } else {
2371 // phase present, no dosages present, variable ploidy
2372 // lookup tables still usable
2373 if (is_x) {
2374 AppendU32(0x2010002, &bgen_geno_buf_iter);
2375 unsigned char* ploidy_and_missingness_iter = bgen_geno_buf_iter;
2376 bgen_geno_buf_iter = &(bgen_geno_buf_iter[sample_ct]);
2377 *bgen_geno_buf_iter++ = 1;
2378 *bgen_geno_buf_iter++ = bit_precision;
2379 for (uint32_t widx = 0; ; ++widx) {
2380 if (widx >= sample_ctl2_m1) {
2381 if (widx > sample_ctl2_m1) {
2382 break;
2383 }
2384 loop_len = ModNz(sample_ct, kBitsPerWordD2);
2385 }
2386 uintptr_t geno_word = pgv.genovec[widx];
2387 uint32_t nonmale_hw = ~DowncastKWToHW(sex_male_collapsed)[widx];
2388 uint32_t phasepresent_hw = DowncastKWToHW(pgv.phasepresent)[widx];
2389 uint32_t phaseinfo_hw = DowncastKWToHW(pgv.phaseinfo)[widx];
2390 // todo: pretty sure this can be sped up by pre-shifting
2391 // phaseinfo_hw by 3. not sure what else can be done,
2392 // though...
2393 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits, geno_word >>= 2, nonmale_hw >>= 1, phasepresent_hw >>= 1, phaseinfo_hw >>= 1) {
2394 const uintptr_t cur_geno = geno_word & 3;
2395 const uint32_t cur_nonmale = nonmale_hw & 1;
2396 if (cur_geno == 3) {
2397 *ploidy_and_missingness_iter++ = 129 + cur_nonmale;
2398 Append0Bits(bit_precision << cur_nonmale, &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2399 continue;
2400 }
2401 const uint32_t cur_phasepresent = phasepresent_hw & 1;
2402 if (cur_phasepresent | cur_nonmale) {
2403 *ploidy_and_missingness_iter++ = 2;
2404 const uint32_t cur_index = cur_geno | (cur_phasepresent * 4) | ((phaseinfo_hw & 1) * 8);
2405 AppendBits(bit_precision * 2, bgen_diploid_phased_hardcall_table[cur_index], &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2406 continue;
2407 }
2408 *ploidy_and_missingness_iter++ = 1;
2409 AppendBits(bit_precision, bgen_haploid_basic_table[cur_geno], &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2410 }
2411 }
2412 } else {
2413 // can't be all-female all-missing since phasepresent_ct > 0
2414 AppendU32(0x2010002 - cur_y * 0x10000, &bgen_geno_buf_iter);
2415 unsigned char* ploidy_and_missingness_iter = bgen_geno_buf_iter;
2416 bgen_geno_buf_iter = &(bgen_geno_buf_iter[sample_ct]);
2417 *bgen_geno_buf_iter++ = 1;
2418 *bgen_geno_buf_iter++ = bit_precision;
2419 uint32_t female_hw = 0;
2420 for (uint32_t widx = 0; ; ++widx) {
2421 if (widx >= sample_ctl2_m1) {
2422 if (widx > sample_ctl2_m1) {
2423 break;
2424 }
2425 loop_len = ModNz(sample_ct, kBitsPerWordD2);
2426 }
2427 uintptr_t geno_word = pgv.genovec[widx];
2428 if (cur_y) {
2429 female_hw = DowncastKWToHW(sex_female_collapsed)[widx];
2430 }
2431 uint32_t phasepresent_hw = DowncastKWToHW(pgv.phasepresent)[widx];
2432 uint32_t phaseinfo_hw = DowncastKWToHW(pgv.phaseinfo)[widx];
2433 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits, geno_word >>= 2, phasepresent_hw >>= 1, phaseinfo_hw >>= 1) {
2434 const uintptr_t cur_geno = geno_word & 3;
2435 if (cur_geno == 3) {
2436 // female_hw not incrementally shifted for now
2437 if (!(female_hw & (1U << sample_idx_lowbits))) {
2438 *ploidy_and_missingness_iter++ = 129;
2439 Append0Bits(bit_precision, &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2440 } else {
2441 *ploidy_and_missingness_iter++ = 128;
2442 }
2443 continue;
2444 }
2445 const uint32_t cur_phasepresent = phasepresent_hw & 1;
2446 if (cur_phasepresent) {
2447 *ploidy_and_missingness_iter++ = 2;
2448 const uint32_t cur_index = cur_geno | (cur_phasepresent * 4) | ((phaseinfo_hw & 1) * 8);
2449 AppendBits(bit_precision * 2, bgen_diploid_phased_hardcall_table[cur_index], &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2450 continue;
2451 }
2452 *ploidy_and_missingness_iter++ = 1;
2453 AppendBits(bit_precision, bgen_haploid_basic_table[cur_geno], &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2454 }
2455 }
2456 }
2457 }
2458 } else {
2459 // dosages present, variable ploidy
2460 // don't bother with lookup tables here
2461 const Dosage* dosage_main_iter = pgv.dosage_main;
2462 if (!use_phased_format) {
2463 if (is_x) {
2464 AppendU32(0x2010002, &bgen_geno_buf_iter);
2465 unsigned char* ploidy_and_missingness_iter = bgen_geno_buf_iter;
2466 bgen_geno_buf_iter = &(bgen_geno_buf_iter[sample_ct]);
2467 *bgen_geno_buf_iter++ = 0;
2468 *bgen_geno_buf_iter++ = bit_precision;
2469 for (uint32_t widx = 0; ; ++widx) {
2470 if (widx >= sample_ctl2_m1) {
2471 if (widx > sample_ctl2_m1) {
2472 break;
2473 }
2474 loop_len = ModNz(sample_ct, kBitsPerWordD2);
2475 }
2476 uintptr_t geno_word = pgv.genovec[widx];
2477 const uint32_t male_hw = DowncastKWToHW(sex_male_collapsed)[widx];
2478 const uint32_t dosage_present_hw = DowncastKWToHW(pgv.dosage_present)[widx];
2479 uint32_t shifted_bit = 1;
2480 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits, shifted_bit *= 2, geno_word >>= 2) {
2481 const uint32_t cur_male = male_hw & shifted_bit;
2482 uint32_t cur_dosage;
2483 if (dosage_present_hw & shifted_bit) {
2484 cur_dosage = *dosage_main_iter++;
2485 } else {
2486 const uintptr_t cur_geno = geno_word & 3;
2487 if (cur_geno == 3) {
2488 const uint32_t cur_nonmale = !cur_male;
2489 *ploidy_and_missingness_iter++ = 129 + cur_nonmale;
2490 Append0Bits(bit_precision << cur_nonmale, &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2491 continue;
2492 }
2493 cur_dosage = cur_geno * kDosageMid;
2494 }
2495 if (cur_male) {
2496 *ploidy_and_missingness_iter++ = 1;
2497 uint32_t output_prob = (cur_dosage * max_output_val + kDosageMid) / kDosageMax;
2498 AppendBits(bit_precision, output_prob, &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2499 continue;
2500 }
2501 *ploidy_and_missingness_iter++ = 2;
2502 uint32_t output_prob2 = 0;
2503 uint32_t output_prob1;
2504 if (cur_dosage > kDosageMid) {
2505 output_prob2 = ((cur_dosage - kDosageMid) * max_output_val + kDosage4th) / kDosageMid;
2506 output_prob1 = max_output_val - output_prob2;
2507 } else {
2508 output_prob1 = (cur_dosage * max_output_val + kDosage4th) / kDosageMid;
2509 }
2510 AppendBits(bit_precision * 2, output_prob2 | (output_prob1 << bit_precision), &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2511 }
2512 }
2513 } else {
2514 assert(cur_y);
2515 // can't be all-female all-missing since dosage_ct > 0
2516 AppendU32(0x1000002, &bgen_geno_buf_iter);
2517 unsigned char* ploidy_and_missingness_iter = bgen_geno_buf_iter;
2518 bgen_geno_buf_iter = &(bgen_geno_buf_iter[sample_ct]);
2519 *bgen_geno_buf_iter++ = 0;
2520 *bgen_geno_buf_iter++ = bit_precision;
2521 for (uint32_t widx = 0; ; ++widx) {
2522 if (widx >= sample_ctl2_m1) {
2523 if (widx > sample_ctl2_m1) {
2524 break;
2525 }
2526 loop_len = ModNz(sample_ct, kBitsPerWordD2);
2527 }
2528 uintptr_t geno_word = pgv.genovec[widx];
2529 const uint32_t female_hw = DowncastKWToHW(sex_female_collapsed)[widx];
2530 const uint32_t dosage_present_hw = DowncastKWToHW(pgv.dosage_present)[widx];
2531 uint32_t shifted_bit = 1;
2532 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits, shifted_bit *= 2, geno_word >>= 2) {
2533 uint32_t cur_dosage;
2534 if (dosage_present_hw & shifted_bit) {
2535 cur_dosage = *dosage_main_iter++;
2536 } else {
2537 const uintptr_t cur_geno = geno_word & 3;
2538 if (cur_geno == 3) {
2539 if (!(female_hw & shifted_bit)) {
2540 *ploidy_and_missingness_iter++ = 129;
2541 Append0Bits(bit_precision, &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2542 } else {
2543 *ploidy_and_missingness_iter++ = 128;
2544 }
2545 continue;
2546 }
2547 cur_dosage = cur_geno * kDosageMid;
2548 }
2549 *ploidy_and_missingness_iter++ = 1;
2550 uint32_t output_prob = (cur_dosage * max_output_val + kDosageMid) / kDosageMax;
2551 AppendBits(bit_precision, output_prob, &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2552 }
2553 }
2554 }
2555 } else {
2556 const SDosage* dphase_delta_iter = pgv.dphase_delta;
2557 if (is_x) {
2558 AppendU32(0x2010002, &bgen_geno_buf_iter);
2559 unsigned char* ploidy_and_missingness_iter = bgen_geno_buf_iter;
2560 bgen_geno_buf_iter = &(bgen_geno_buf_iter[sample_ct]);
2561 *bgen_geno_buf_iter++ = 1;
2562 *bgen_geno_buf_iter++ = bit_precision;
2563 for (uint32_t widx = 0; ; ++widx) {
2564 if (widx >= sample_ctl2_m1) {
2565 if (widx > sample_ctl2_m1) {
2566 break;
2567 }
2568 loop_len = ModNz(sample_ct, kBitsPerWordD2);
2569 }
2570 uintptr_t geno_word = pgv.genovec[widx];
2571 const uint32_t male_hw = DowncastKWToHW(sex_male_collapsed)[widx];
2572 const uint32_t phaseinfo_hw = DowncastKWToHW(pgv.phaseinfo)[widx];
2573 const uint32_t dosage_present_hw = DowncastKWToHW(pgv.dosage_present)[widx];
2574 const uint32_t dphase_present_hw = DowncastKWToHW(pgv.dphase_present)[widx];
2575 const uint32_t either_phase_present_hw = dphase_present_hw | (DowncastKWToHW(pgv.phasepresent)[widx]);
2576 uint32_t shifted_bit = 1;
2577 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits, shifted_bit *= 2, geno_word >>= 2) {
2578 const uint32_t cur_male = male_hw & shifted_bit;
2579 uint32_t cur_dosage;
2580 if (dosage_present_hw & shifted_bit) {
2581 cur_dosage = *dosage_main_iter++;
2582 } else {
2583 const uintptr_t cur_geno = geno_word & 3;
2584 if (cur_geno == 3) {
2585 const uint32_t cur_nonmale = !cur_male;
2586 *ploidy_and_missingness_iter++ = 129 + cur_nonmale;
2587 Append0Bits(bit_precision << cur_nonmale, &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2588 continue;
2589 }
2590 cur_dosage = cur_geno * kDosageMid;
2591 }
2592 uint32_t output_prob1;
2593 uint32_t output_prob2;
2594 if (either_phase_present_hw & shifted_bit) {
2595 if (dphase_present_hw & shifted_bit) {
2596 const int32_t cur_dphase_delta_val = *dphase_delta_iter++;
2597 const uint32_t left_raw = (cur_dosage + cur_dphase_delta_val) >> 1;
2598 const uint32_t right_raw = (cur_dosage - cur_dphase_delta_val) >> 1;
2599 output_prob1 = (left_raw * max_output_val + kDosage4th) / kDosageMid;
2600 output_prob2 = (right_raw * max_output_val + kDosage4th) / kDosageMid;
2601 } else {
2602 if (cur_dosage > kDosageMid) {
2603 output_prob1 = ((cur_dosage - kDosageMid) * max_output_val + kDosage4th) / kDosageMid;
2604 output_prob2 = max_output_val;
2605 } else {
2606 output_prob1 = 0;
2607 output_prob2 = (cur_dosage * max_output_val + kDosage4th) / kDosageMid;
2608 }
2609 if (phaseinfo_hw & shifted_bit) {
2610 const uint32_t tmpval = output_prob1;
2611 output_prob1 = output_prob2;
2612 output_prob2 = tmpval;
2613 }
2614 }
2615 } else {
2616 // unphased, nonmissing
2617 output_prob1 = (cur_dosage * max_output_val + kDosageMid) / kDosageMax;
2618 if (cur_male) {
2619 *ploidy_and_missingness_iter++ = 1;
2620 AppendBits(bit_precision, output_prob1, &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2621 continue;
2622 }
2623 output_prob2 = output_prob1;
2624 }
2625 *ploidy_and_missingness_iter++ = 2;
2626 AppendBits(bit_precision * 2, output_prob1 | (output_prob2 << bit_precision), &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2627 }
2628 }
2629 } else {
2630 // can't be all-female all-missing since dosage_ct > 0
2631 AppendU32(0x2010002 - cur_y * 0x10000, &bgen_geno_buf_iter);
2632 unsigned char* ploidy_and_missingness_iter = bgen_geno_buf_iter;
2633 bgen_geno_buf_iter = &(bgen_geno_buf_iter[sample_ct]);
2634 *bgen_geno_buf_iter++ = 1;
2635 *bgen_geno_buf_iter++ = bit_precision;
2636 uint32_t female_hw = 0;
2637 for (uint32_t widx = 0; ; ++widx) {
2638 if (widx >= sample_ctl2_m1) {
2639 if (widx > sample_ctl2_m1) {
2640 break;
2641 }
2642 loop_len = ModNz(sample_ct, kBitsPerWordD2);
2643 }
2644 uintptr_t geno_word = pgv.genovec[widx];
2645 if (cur_y) {
2646 female_hw = DowncastKWToHW(sex_female_collapsed)[widx];
2647 }
2648 const uint32_t phaseinfo_hw = DowncastKWToHW(pgv.phaseinfo)[widx];
2649 const uint32_t dosage_present_hw = DowncastKWToHW(pgv.dosage_present)[widx];
2650 const uint32_t dphase_present_hw = DowncastKWToHW(pgv.dphase_present)[widx];
2651 const uint32_t either_phase_present_hw = dphase_present_hw | (DowncastKWToHW(pgv.phasepresent)[widx]);
2652 uint32_t shifted_bit = 1;
2653 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits, shifted_bit *= 2, geno_word >>= 2) {
2654 uint32_t cur_dosage;
2655 if (dosage_present_hw & shifted_bit) {
2656 cur_dosage = *dosage_main_iter++;
2657 } else {
2658 const uintptr_t cur_geno = geno_word & 3;
2659 if (cur_geno == 3) {
2660 if (!(female_hw & shifted_bit)) {
2661 *ploidy_and_missingness_iter++ = 129;
2662 Append0Bits(bit_precision, &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2663 } else {
2664 *ploidy_and_missingness_iter++ = 128;
2665 }
2666 continue;
2667 }
2668 cur_dosage = cur_geno * kDosageMid;
2669 }
2670 if (either_phase_present_hw & shifted_bit) {
2671 *ploidy_and_missingness_iter++ = 2;
2672 uint32_t output_prob1;
2673 uint32_t output_prob2;
2674 if (dphase_present_hw & shifted_bit) {
2675 const int32_t cur_dphase_delta_val = *dphase_delta_iter++;
2676 const uint32_t left_raw = (cur_dosage + cur_dphase_delta_val) >> 1;
2677 const uint32_t right_raw = (cur_dosage - cur_dphase_delta_val) >> 1;
2678 output_prob1 = (left_raw * max_output_val + kDosage4th) / kDosageMid;
2679 output_prob2 = (right_raw * max_output_val + kDosage4th) / kDosageMid;
2680 } else {
2681 if (cur_dosage > kDosageMid) {
2682 output_prob1 = ((cur_dosage - kDosageMid) * max_output_val + kDosage4th) / kDosageMid;
2683 output_prob2 = max_output_val;
2684 } else {
2685 output_prob1 = 0;
2686 output_prob2 = (cur_dosage * max_output_val + kDosage4th) / kDosageMid;
2687 }
2688 if (phaseinfo_hw & shifted_bit) {
2689 const uint32_t tmpval = output_prob1;
2690 output_prob1 = output_prob2;
2691 output_prob2 = tmpval;
2692 }
2693 }
2694 AppendBits(bit_precision * 2, output_prob1 | (output_prob2 << bit_precision), &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2695 continue;
2696 }
2697 *ploidy_and_missingness_iter++ = 1;
2698 uint32_t output_prob = (cur_dosage * max_output_val + kDosageMid) / kDosageMax;
2699 AppendBits(bit_precision, output_prob, &cur_write_bits, &cur_write_bit_idx, &bgen_geno_buf_iter);
2700 }
2701 }
2702 }
2703 }
2704 }
2705 // bugfix (7 Oct 2024)
2706 CopyToUnalignedW(bgen_geno_buf_iter, &cur_write_bits);
2707 bgen_geno_buf_iter = &(bgen_geno_buf_iter[DivUp(cur_write_bit_idx, CHAR_BIT)]);
2708 }
2709 const uint32_t uncompressed_bytect = bgen_geno_buf_iter - uncompressed_bgen_geno_buf;
2710 uintptr_t compressed_bytect;
2711 if (compressor) {
2712 compressed_bytect = libdeflate_zlib_compress(compressor, uncompressed_bgen_geno_buf, uncompressed_bytect, writebuf_iter, bgen_compressed_buf_max);
2713 } else {
2714 compressed_bytect = ZSTD_compress(writebuf_iter, bgen_compressed_buf_max, uncompressed_bgen_geno_buf, uncompressed_bytect, zst_level);
2715 }
2716 assert(compressed_bytect);
2717 *variant_bytect_iter++ = 4 + compressed_bytect;
2718 *variant_bytect_iter++ = uncompressed_bytect;
2719 writebuf_iter = &(writebuf_iter[bgen_compressed_buf_max]);
2720 GenoarrToMissingnessUnsafe(pgv.genovec, sample_ct, missing_acc1);
2721 if (pgv.dosage_ct) {
2722 BitvecInvmask(pgv.dosage_present, sample_ctl, missing_acc1);
2723 }
2724 if (is_y) {
2725 BitvecInvmask(sex_female_collapsed, sample_ctl, missing_acc1);
2726 }
2727 VcountIncr1To4(missing_acc1, acc1_vec_ct, missing_acc4);
2728 if (!(--vidx_rem15)) {
2729 Vcount0Incr4To8(acc4_vec_ct, missing_acc4, missing_acc8);
2730 vidx_rem15 = 15;
2731 if (!(--vidx_rem255d15)) {
2732 Vcount0Incr8To32(acc8_vec_ct, missing_acc8, missing_acc32);
2733 vidx_rem255d15 = 17;
2734 }
2735 }
2736 }
2737 parity = 1 - parity;
2738 } while (!THREAD_BLOCK_FINISH(arg));
2739 {
2740 VcountIncr4To8(missing_acc4, acc4_vec_ct, missing_acc8);
2741 VcountIncr8To32(missing_acc8, acc8_vec_ct, missing_acc32);
2742 }
2743 while (0) {
2744 ExportBgen13Thread_err:
2745 UpdateU64IfSmaller(new_err_info, &ctx->err_info);
2746 THREAD_BLOCK_FINISH(arg);
2747 break;
2748 }
2749 THREAD_RETURN;
2750 }
2751
2752 // This allocates exported_sample_ids on top. It can easily be modified to
2753 // export an ID hash table as well (since such a hash table is always
2754 // constructed for the sake of detecting and warning about duplicate
2755 // post-id-paste IDs).
2756 BoolErr ExportIdpaste(const uintptr_t* sample_include, const SampleIdInfo* siip, const char* ftypename, const char* reimport_flagname, uint32_t sample_ct, IdpasteFlags exportf_id_paste, char exportf_id_delim, uintptr_t* max_exported_sample_id_blen_ptr, char** exported_sample_ids_ptr) {
2757 const uint32_t write_fid = DataFidColIsRequired(sample_include, siip, sample_ct, exportf_id_paste / kfIdpasteMaybefid);
2758 const char* sample_ids = siip->sample_ids;
2759 const char* sids = siip->sids;
2760 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
2761 uintptr_t max_sid_blen = siip->max_sid_blen;
2762 const uint32_t write_iid = (exportf_id_paste / kfIdpasteIid) & 1;
2763 const uint32_t write_sid = DataSidColIsRequired(sample_include, sids, sample_ct, max_sid_blen, exportf_id_paste / kfIdpasteMaybesid);
2764 if (write_sid && (!sids)) {
2765 max_sid_blen = 2;
2766 }
2767 uint32_t id_delim_warning = 0;
2768 char id_delim = exportf_id_delim? exportf_id_delim : '_';
2769 const uintptr_t max_exported_sample_id_blen = max_sample_id_blen + write_sid * max_sid_blen;
2770 const uint32_t exported_id_htable_size = GetHtableMinSize(sample_ct);
2771 uint32_t* new_id_htable;
2772 // check for duplicates
2773 if (unlikely(bigstack_alloc_c(sample_ct * max_exported_sample_id_blen, exported_sample_ids_ptr) ||
2774 bigstack_alloc_u32(exported_id_htable_size, &new_id_htable))) {
2775 return 1;
2776 }
2777 *max_exported_sample_id_blen_ptr = max_exported_sample_id_blen;
2778 char* exported_sample_ids = *exported_sample_ids_ptr;
2779 uintptr_t sample_uidx_base = 0;
2780 uintptr_t cur_bits = sample_include[0];
2781 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
2782 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
2783 const char* orig_sample_id = &(sample_ids[sample_uidx * max_sample_id_blen]);
2784 const char* orig_fid_end = AdvToDelim(orig_sample_id, '\t');
2785 char* exported_sample_ids_iter = &(exported_sample_ids[sample_idx * max_exported_sample_id_blen]);
2786 if (write_fid) {
2787 const uint32_t fid_slen = orig_fid_end - orig_sample_id;
2788 if ((!id_delim_warning) && memchr(orig_sample_id, id_delim, fid_slen)) {
2789 id_delim_warning = 1;
2790 }
2791 exported_sample_ids_iter = memcpyax(exported_sample_ids_iter, orig_sample_id, fid_slen, id_delim);
2792 }
2793 if (write_iid) {
2794 const char* orig_iid = &(orig_fid_end[1]);
2795 const uint32_t iid_slen = strlen(orig_iid);
2796 if ((!id_delim_warning) && memchr(orig_iid, id_delim, iid_slen)) {
2797 id_delim_warning = 1;
2798 }
2799 exported_sample_ids_iter = memcpyax(exported_sample_ids_iter, orig_iid, iid_slen, id_delim);
2800 }
2801 if (write_sid) {
2802 if (sids) {
2803 const char* orig_sid = &(sids[sample_uidx * max_sid_blen]);
2804 const uint32_t sid_slen = strlen(orig_sid);
2805 if ((!id_delim_warning) && memchr(orig_sid, id_delim, sid_slen)) {
2806 id_delim_warning = 1;
2807 }
2808 exported_sample_ids_iter = memcpya(exported_sample_ids_iter, orig_sid, sid_slen);
2809 } else {
2810 *exported_sample_ids_iter++ = '0';
2811 }
2812 ++exported_sample_ids_iter;
2813 }
2814 exported_sample_ids_iter[-1] = '\0';
2815 }
2816 if (id_delim_warning && (write_fid + write_iid + write_sid >= 2)) {
2817 if (reimport_flagname) {
2818 if (exportf_id_delim) {
2819 logerrprintfww("Warning: '%c' present in original sample IDs; --%s will not be able to reconstruct them. Consider rerunning with a different --export id-delim= value.\n", exportf_id_delim, reimport_flagname);
2820 } else {
2821 logerrprintfww("Warning: '_' present in original sample IDs; --%s will not be able to reconstruct them. Consider rerunning with a suitable --export id-delim= value.\n", reimport_flagname);
2822 }
2823 } else {
2824 if (exportf_id_delim) {
2825 logerrprintfww("Warning: '%c' present in original sample IDs; this may prevent them from being reconstructed. Consider rerunning with a different --export id-delim= value.\n", exportf_id_delim);
2826 } else {
2827 logerrputs("Warning: '_' present in original sample IDs; this may prevent them from being\nreconstructed. Consider rerunning with a suitable --export id-delim= value.\n");
2828 }
2829 }
2830 }
2831 if (PopulateStrboxHtable(exported_sample_ids, sample_ct, max_exported_sample_id_blen, exported_id_htable_size, new_id_htable)) {
2832 logerrprintfww("Warning: Duplicate sample ID(s) are being written to --export %s file.\n", ftypename);
2833 }
2834 BigstackReset(new_id_htable);
2835 return 0;
2836 }
2837
2838 PglErr ExportBgen13(const char* outname, const uintptr_t* sample_include, uint32_t* sample_include_cumulative_popcounts, const SampleIdInfo* siip, const uintptr_t* sex_male_collapsed, const uintptr_t* sex_female_collapsed, 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 AlleleCode* allele_permute, uint32_t sample_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_slen, uint32_t max_thread_ct, ExportfFlags exportf_flags, uint32_t exportf_bits, IdpasteFlags exportf_id_paste, char exportf_id_delim, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, uint32_t* sample_missing_geno_cts) {
2839 unsigned char* bigstack_mark = g_bigstack_base;
2840 FILE* outfile = nullptr;
2841 PglErr reterr = kPglRetSuccess;
2842 ThreadGroup tg;
2843 PreinitThreads(&tg);
2844 ExportBgen13Ctx ctx;
2845 {
2846 const uint32_t use_zstd_compression = !(exportf_flags & kfExportfBgen12);
2847 if (use_zstd_compression) {
2848 ctx.libdeflate_compressors = nullptr;
2849 } else {
2850 if (unlikely(BIGSTACK_ALLOC_X(struct libdeflate_compressor*, max_thread_ct, &ctx.libdeflate_compressors))) {
2851 goto ExportBgen13_ret_NOMEM;
2852 }
2853 ZeroPtrArr(max_thread_ct, ctx.libdeflate_compressors);
2854 }
2855 const uint32_t phase_is_present = pgfip->gflags & (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePhasePresent);
2856 if (!exportf_bits) {
2857 // default
2858 exportf_bits = 16;
2859 } else if (phase_is_present) {
2860 if (exportf_bits < 15) {
2861 if (exportf_bits == 1) {
2862 logerrputs("Warning: Unphased heterozygous calls in partially-phased variants cannot be\nexported with bits=1.\n");
2863 } else {
2864 logerrprintf("Warning: Unphased heterozygous hardcalls in partially-phased variants are\npoorly represented with bits=%u.\n", exportf_bits);
2865 const double suggested_thresh = 0.00009375 * (16384 >> exportf_bits);
2866 if (exportf_bits < 4) {
2867 logerrprintfww("It is necessary to use e.g. --hard-call-threshold %g + --dosage-erase-threshold %g to re-import them cleanly.\n", suggested_thresh, suggested_thresh);
2868 } else {
2869 logerrprintfww("It is necessary to use e.g. --dosage-erase-threshold %g to re-import them cleanly.\n", suggested_thresh);
2870 }
2871 }
2872 }
2873 }
2874 if (unlikely(ConstructBgen13LookupTables(exportf_bits, &ctx.tables))) {
2875 goto ExportBgen13_ret_NOMEM;
2876 }
2877 const uint32_t max_chr_slen = GetMaxChrSlen(cip);
2878 uintptr_t bgen_geno_cacheline_ct;
2879 uintptr_t bgen_compressed_buf_max;
2880 {
2881 const uint64_t tot_prob_bit_ct = S_CAST(uint64_t, sample_ct) * 2 * exportf_bits;
2882 uint64_t bgen_geno_buf_size = 10 + sample_ct + DivUp(tot_prob_bit_ct, 8);
2883 if (unlikely(bgen_geno_buf_size > 0xffffffffU - 4)) {
2884 // could return VarRecordTooLarge error instead
2885 logerrputs("Error: Too many samples for .bgen format.\n");
2886 goto ExportBgen13_ret_INCONSISTENT_INPUT;
2887 }
2888 if (!use_zstd_compression) {
2889 bgen_compressed_buf_max = libdeflate_deflate_compress_bound(nullptr, bgen_geno_buf_size);
2890 } else {
2891 bgen_compressed_buf_max = ZSTD_compressBound(bgen_geno_buf_size);
2892 }
2893 // +14 since we may write that far past the end
2894 bgen_geno_buf_size += 14;
2895 bgen_geno_cacheline_ct = DivUp(bgen_geno_buf_size, kCacheline);
2896 }
2897 ctx.bgen_compressed_buf_max = bgen_compressed_buf_max;
2898 // When writing sample ID block, we flush-check after each sample ID.
2899 // When writing variant data blocks, we flush-check at the beginning of
2900 // each allele, and at the beginning and end of each genotype data block.
2901 uintptr_t writebuf_len = 16 + kMaxIdSlen + max_chr_slen;
2902 if (writebuf_len < max_allele_slen + 4) {
2903 writebuf_len = max_allele_slen + 4;
2904 }
2905 if (writebuf_len < bgen_compressed_buf_max) {
2906 writebuf_len = bgen_compressed_buf_max;
2907 }
2908 writebuf_len += kMaxMediumLine;
2909 char* chr_buf;
2910 unsigned char* writebuf;
2911 if (unlikely(bigstack_alloc_c(max_chr_slen, &chr_buf) ||
2912 bigstack_alloc_uc(writebuf_len, &writebuf))) {
2913 goto ExportBgen13_ret_NOMEM;
2914 }
2915 ctx.sex_male_collapsed = sex_male_collapsed;
2916 ctx.sex_female_collapsed = sex_female_collapsed;
2917
2918 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
2919 goto ExportBgen13_ret_OPEN_FAIL;
2920 }
2921 // bgen 1.2-1.3 header
2922 // note that \xxx character constants are interpreted in octal, so \200 is
2923 // decimal 128, etc.
2924 unsigned char* write_iter = &(writebuf[4]);
2925 AppendU32(20, &write_iter);
2926 AppendU32(variant_ct, &write_iter);
2927 AppendU32(sample_ct, &write_iter);
2928 write_iter = memcpyua(write_iter, "bgen\0\0\0\200", 8);
2929 // compression mode (1 + use_zstd_compression), layout=2
2930 writebuf[20] = 9 + use_zstd_compression;
2931 unsigned char* writebuf_flush = &(writebuf[kMaxMediumLine]);
2932 // Save sample IDs unless bgen-omit-sample-id-block specified...
2933 if (exportf_flags & kfExportfBgenOmitSampleIdBlock) {
2934 memcpy(writebuf, "\24\0\0", 4);
2935 writebuf[23] = 0;
2936 } else {
2937 char* exported_sample_ids;
2938 uintptr_t max_exported_sample_id_blen;
2939 if (unlikely(ExportIdpaste(sample_include, siip, use_zstd_compression? "bgen-1.3" : "bgen-1.2", "bgen", sample_ct, exportf_id_paste, exportf_id_delim, &max_exported_sample_id_blen, &exported_sample_ids))) {
2940 goto ExportBgen13_ret_NOMEM;
2941 }
2942 // Compute total length of sample ID block now; this is necessary to fill
2943 // in bytes 0-3 and 24-27 correctly; and we must do this now since we may
2944 // flush them before we're done rendering the block.
2945 uintptr_t sample_id_block_len = 2 * sample_ct + 8;
2946 const char* exported_sample_ids_iter = exported_sample_ids;
2947 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
2948 sample_id_block_len += strlen(exported_sample_ids_iter);
2949 exported_sample_ids_iter = &(exported_sample_ids_iter[max_exported_sample_id_blen]);
2950 }
2951 #ifdef __LP64__
2952 if (sample_id_block_len > 0xffffffffU - 20) {
2953 // ...or combined sample ID length is actually greater than 4 GiB, in
2954 // which case bgen-1.2/1.3 can't actually represent it.
2955 logerrputs("Warning: Omitting sample ID block from .bgen file since it would overflow (more\nthan 4 GiB). Consider using shorter IDs.\n");
2956 memcpy(writebuf, "\24\0\0", 4);
2957 writebuf[23] = 0; // bugfix (6 Aug 2024): forgot this
2958 } else {
2959 #endif
2960 uint32_t initial_bgen_offset = sample_id_block_len + 20;
2961 memcpy(writebuf, &initial_bgen_offset, 4);
2962 AppendU32(sample_id_block_len, &write_iter);
2963 AppendU32(sample_ct, &write_iter);
2964 exported_sample_ids_iter = exported_sample_ids;
2965 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
2966 const uint16_t cur_slen = strlen(exported_sample_ids_iter);
2967 AppendU16(cur_slen, &write_iter);
2968 write_iter = memcpyua(write_iter, exported_sample_ids_iter, cur_slen);
2969 exported_sample_ids_iter = &(exported_sample_ids_iter[max_exported_sample_id_blen]);
2970 if (unlikely(fwrite_uflush2(writebuf_flush, outfile, &write_iter))) {
2971 goto ExportBgen13_ret_WRITE_FAIL;
2972 }
2973 }
2974 #ifdef __LP64__
2975 }
2976 #endif
2977 BigstackReset(exported_sample_ids);
2978 }
2979
2980 const uintptr_t max_write_block_byte_ct = bigstack_left() / 4;
2981 uint32_t max_write_block_size = kPglVblockSize;
2982 for (; ; max_write_block_size /= 2) {
2983 // limit each write buffer to 1/4 of remaining workspace
2984 if ((S_CAST(uint64_t, bgen_compressed_buf_max + 2 * sizeof(int32_t))) * max_write_block_size <= max_write_block_byte_ct) {
2985 break;
2986 }
2987 // 5 bytes per sample * 500k samples = ~2.5 MB per variant; with
2988 // max_write_block_size lower limit of 256, minimum workspace is ~2.5 GB.
2989 // That's perfectly reasonable (and it's okay if PgenMtLoadInit raises
2990 // the requirement to, say, 4 times that).
2991 // Memory will get tighter once multiallelic variants are supported,
2992 // though.
2993 if (unlikely(max_write_block_size <= kBitsPerVec)) {
2994 goto ExportBgen13_ret_NOMEM;
2995 }
2996 }
2997
2998 // todo: test when this saturates
2999 uint32_t calc_thread_ct = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
3000 if (calc_thread_ct > max_write_block_size) {
3001 calc_thread_ct = max_write_block_size;
3002 }
3003
3004 if (unlikely(bigstack_alloc_uc(bgen_compressed_buf_max * max_write_block_size, &(ctx.writebufs[0])) ||
3005 bigstack_alloc_uc(bgen_compressed_buf_max * max_write_block_size, &(ctx.writebufs[1])) ||
3006 bigstack_alloc_u32(max_write_block_size * 2, &(ctx.variant_bytects[0])) ||
3007 bigstack_alloc_u32(max_write_block_size * 2, &(ctx.variant_bytects[1])) ||
3008 bigstack_alloc_wp(calc_thread_ct, &ctx.missing_acc1) ||
3009 bigstack_alloc_ucp(calc_thread_ct, &ctx.uncompressed_bgen_geno_bufs))) {
3010 goto ExportBgen13_ret_NOMEM;
3011 }
3012
3013 const uint32_t acc1_vec_ct = BitCtToVecCt(sample_ct);
3014 const uint32_t dosage_is_present = pgfip->gflags & kfPgenGlobalDosagePresent;
3015 const uintptr_t track_missing_cacheline_ct = VecCtToCachelineCt(acc1_vec_ct * 45);
3016 const uintptr_t thread_xalloc_cacheline_ct = track_missing_cacheline_ct + bgen_geno_cacheline_ct;
3017 STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
3018 ctx.phasepresents = nullptr;
3019 ctx.phaseinfos = nullptr;
3020 ctx.dosage_presents = nullptr;
3021 ctx.dosage_mains = nullptr;
3022 ctx.dphase_presents = nullptr;
3023 ctx.dphase_deltas = nullptr;
3024 uint32_t read_block_size;
3025 if (unlikely(PgenMtLoadInit(variant_include, sample_ct, raw_variant_ct, bigstack_left(), pgr_alloc_cacheline_ct, thread_xalloc_cacheline_ct, 0, 0, pgfip, &calc_thread_ct, &ctx.genovecs, nullptr, phase_is_present? (&ctx.phasepresents) : nullptr, phase_is_present? (&ctx.phaseinfos) : nullptr, dosage_is_present? (&ctx.dosage_presents) : nullptr, dosage_is_present? (&ctx.dosage_mains) : nullptr, phase_is_present? (&ctx.dphase_presents) : nullptr, phase_is_present? (&ctx.dphase_deltas) : nullptr, &read_block_size, nullptr, main_loadbufs, &ctx.pgr_ptrs, &ctx.read_variant_uidx_starts))) {
3026 goto ExportBgen13_ret_NOMEM;
3027 }
3028 // Ran this with and without --memory 640 on a 1000G phase 1 dataset
3029 // (chosen since it has dosages), and there was zero performance penalty in
3030 // the former case.
3031 //
3032 // So it probably makes sense to default to a much smaller chunk size, and
3033 // use the same type of thread-pool logic as the new bgzf writer.
3034 if (read_block_size > max_write_block_size) {
3035 read_block_size = max_write_block_size;
3036 }
3037
3038 const uint32_t ref_allele_last = !(exportf_flags & kfExportfRefFirst);
3039 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
3040 ctx.missing_acc1[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(track_missing_cacheline_ct * kCacheline));
3041 ctx.uncompressed_bgen_geno_bufs[tidx] = S_CAST(unsigned char*, bigstack_alloc_raw(bgen_geno_cacheline_ct * kCacheline));
3042 }
3043 ctx.sample_ct = sample_ct;
3044 ctx.variant_include = variant_include;
3045 ctx.allele_idx_offsets = allele_idx_offsets;
3046 ctx.sample_include = sample_include;
3047 ctx.sample_include_cumulative_popcounts = sample_include_cumulative_popcounts;
3048 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
3049 goto ExportBgen13_ret_NOMEM;
3050 }
3051 ctx.allele_permute = allele_permute;
3052 ctx.ref_allele_last = ref_allele_last;
3053 ctx.cip = cip;
3054 ctx.err_info = (~0LLU) << 32;
3055 if (!use_zstd_compression) {
3056 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
3057 ctx.libdeflate_compressors[tidx] = libdeflate_alloc_compressor(6);
3058 if (unlikely(!ctx.libdeflate_compressors[tidx])) {
3059 goto ExportBgen13_ret_NOMEM;
3060 }
3061 }
3062 }
3063 SetThreadFuncAndData(ExportBgen13Thread, &ctx, &tg);
3064
3065 // Main workflow:
3066 // 1. Set n=0, load/skip block 0
3067 //
3068 // 2. Spawn threads processing block n
3069 // 3. If n>0, write results for block (n-1)
3070 // 4. Increment n by 1
3071 // 5. Load/skip block n unless eof
3072 // 6. Join threads
3073 // 7. Goto step 2 unless eof
3074 //
3075 // 8. Write results for last block
3076 uintptr_t write_variant_uidx_base = 0;
3077 uintptr_t cur_bits = variant_include[0];
3078 uint32_t parity = 0;
3079 uint32_t read_block_idx = 0;
3080 uint32_t chr_fo_idx = UINT32_MAX;
3081 uint32_t chr_end = 0;
3082 uint32_t chr_slen = 0;
3083
3084 uint32_t prev_block_write_ct = 0;
3085 uint32_t pct = 0;
3086 uint32_t next_print_variant_idx = variant_ct / 100;
3087 logprintfww5("Writing %s ... ", outname);
3088 fputs("0%", stdout);
3089 fflush(stdout);
3090 uint32_t ref_allele_idx = 0;
3091 uint32_t alt1_allele_idx = 1;
3092 uint32_t allele_ct = 2;
3093 for (uint32_t variant_idx = 0; ; ) {
3094 const uint32_t cur_block_write_ct = MultireadNonempty(variant_include, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr);
3095 if (unlikely(reterr)) {
3096 goto ExportBgen13_ret_PGR_FAIL;
3097 }
3098 if (variant_idx) {
3099 JoinThreads(&tg);
3100 reterr = S_CAST(PglErr, ctx.err_info);
3101 if (unlikely(reterr)) {
3102 if (reterr == kPglRetInconsistentInput) {
3103 // temporary
3104 logputs("\n");
3105 logerrputs("Error: --export bgen-1.2/1.3 multiallelic variant support is under development.\n");
3106 } else {
3107 PgenErrPrintNV(reterr, ctx.err_info >> 32);
3108 }
3109 goto ExportBgen13_ret_1;
3110 }
3111 }
3112 if (!IsLastBlock(&tg)) {
3113 ctx.cur_block_write_ct = cur_block_write_ct;
3114 ComputeUidxStartPartition(variant_include, cur_block_write_ct, calc_thread_ct, read_block_idx * read_block_size, ctx.read_variant_uidx_starts);
3115 PgrCopyBaseAndOffset(pgfip, calc_thread_ct, ctx.pgr_ptrs);
3116 if (variant_idx + cur_block_write_ct == variant_ct) {
3117 DeclareLastThreadBlock(&tg);
3118 }
3119 if (unlikely(SpawnThreads(&tg))) {
3120 goto ExportBgen13_ret_THREAD_CREATE_FAIL;
3121 }
3122 }
3123 parity = 1 - parity;
3124 if (variant_idx) {
3125 // write *previous* block results
3126 const unsigned char* compressed_data_iter = ctx.writebufs[parity];
3127 const uint32_t* variant_bytect_iter = ctx.variant_bytects[parity];
3128 for (uint32_t variant_bidx = 0; variant_bidx != prev_block_write_ct; ++variant_bidx) {
3129 const uint32_t write_variant_uidx = BitIter1(variant_include, &write_variant_uidx_base, &cur_bits);
3130 if (write_variant_uidx >= chr_end) {
3131 do {
3132 ++chr_fo_idx;
3133 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
3134 } while (write_variant_uidx >= chr_end);
3135 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
3136 const char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
3137 chr_slen = chr_name_end - chr_buf;
3138 }
3139 const char* cur_variant_id = variant_ids[write_variant_uidx];
3140 const uint32_t id_slen = strlen(cur_variant_id);
3141 // low 16 bits = null "SNP ID"
3142 AppendU32(id_slen << 16, &write_iter);
3143 write_iter = memcpyua(write_iter, cur_variant_id, id_slen);
3144 AppendU16(chr_slen, &write_iter);
3145 write_iter = memcpyua(write_iter, chr_buf, chr_slen);
3146 AppendU32(variant_bps[write_variant_uidx], &write_iter);
3147 uintptr_t allele_idx_offset_base = write_variant_uidx * 2;
3148 if (allele_idx_offsets) {
3149 allele_idx_offset_base = allele_idx_offsets[write_variant_uidx];
3150 allele_ct = allele_idx_offsets[write_variant_uidx + 1] - allele_idx_offset_base;
3151 }
3152 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
3153 if (allele_permute) {
3154 ref_allele_idx = allele_permute[allele_idx_offset_base];
3155 alt1_allele_idx = allele_permute[allele_idx_offset_base + 1];
3156 }
3157 AppendU16(allele_ct, &write_iter);
3158 const char* ref_allele = cur_alleles[ref_allele_idx];
3159 const uint32_t ref_allele_slen = strlen(ref_allele);
3160 if (!ref_allele_last) {
3161 if (unlikely(fwrite_uflush2(writebuf_flush, outfile, &write_iter))) {
3162 goto ExportBgen13_ret_WRITE_FAIL;
3163 }
3164 AppendU32(ref_allele_slen, &write_iter);
3165 write_iter = memcpyua(write_iter, ref_allele, ref_allele_slen);
3166 }
3167 if (unlikely(fwrite_uflush2(writebuf_flush, outfile, &write_iter))) {
3168 goto ExportBgen13_ret_WRITE_FAIL;
3169 }
3170 const char* cur_alt_allele = cur_alleles[alt1_allele_idx];
3171 uint32_t alt_allele_slen = strlen(cur_alt_allele);
3172 AppendU32(alt_allele_slen, &write_iter);
3173 write_iter = memcpyua(write_iter, cur_alt_allele, alt_allele_slen);
3174 if (allele_ct > 2) {
3175 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
3176 if ((allele_idx == ref_allele_idx) || (allele_idx == alt1_allele_idx)) {
3177 continue;
3178 }
3179 if (unlikely(fwrite_uflush2(writebuf_flush, outfile, &write_iter))) {
3180 goto ExportBgen13_ret_WRITE_FAIL;
3181 }
3182 cur_alt_allele = cur_alleles[allele_idx];
3183 alt_allele_slen = strlen(cur_alt_allele);
3184 AppendU32(alt_allele_slen, &write_iter);
3185 write_iter = memcpyua(write_iter, cur_alt_allele, alt_allele_slen);
3186 }
3187 }
3188 if (ref_allele_last) {
3189 if (unlikely(fwrite_uflush2(writebuf_flush, outfile, &write_iter))) {
3190 goto ExportBgen13_ret_WRITE_FAIL;
3191 }
3192 AppendU32(ref_allele_slen, &write_iter);
3193 write_iter = memcpyua(write_iter, ref_allele, ref_allele_slen);
3194 }
3195 // compressed data length, then uncompressed data length
3196 write_iter = memcpyua(write_iter, variant_bytect_iter, 8);
3197 const uint32_t cur_compressed_bytect = *variant_bytect_iter - 4;
3198 variant_bytect_iter = &(variant_bytect_iter[2]);
3199 if (unlikely(fwrite_uflush2(writebuf_flush, outfile, &write_iter))) {
3200 goto ExportBgen13_ret_WRITE_FAIL;
3201 }
3202 // may want to elide this memcpy when possible
3203 write_iter = memcpyua(write_iter, compressed_data_iter, cur_compressed_bytect);
3204 compressed_data_iter = &(compressed_data_iter[bgen_compressed_buf_max]);
3205 if (unlikely(fwrite_uflush2(writebuf_flush, outfile, &write_iter))) {
3206 goto ExportBgen13_ret_WRITE_FAIL;
3207 }
3208 }
3209 }
3210 if (variant_idx == variant_ct) {
3211 break;
3212 }
3213 if (variant_idx >= next_print_variant_idx) {
3214 if (pct > 10) {
3215 putc_unlocked('\b', stdout);
3216 }
3217 pct = (variant_idx * 100LLU) / variant_ct;
3218 printf("\b\b%u%%", pct++);
3219 fflush(stdout);
3220 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
3221 }
3222 ++read_block_idx;
3223 prev_block_write_ct = cur_block_write_ct;
3224 variant_idx += cur_block_write_ct;
3225 pgfip->block_base = main_loadbufs[parity];
3226 }
3227 if (unlikely(fclose_uflush_null(writebuf_flush, write_iter, &outfile))) {
3228 goto ExportBgen13_ret_WRITE_FAIL;
3229 }
3230 if (pct > 10) {
3231 putc_unlocked('\b', stdout);
3232 }
3233 fputs("\b\b", stdout);
3234 logputs("done.\n");
3235 const uint32_t sample_ctav = acc1_vec_ct * kBitsPerVec;
3236 const uintptr_t acc32_offset = acc1_vec_ct * (13 * k1LU * kWordsPerVec);
3237 uint32_t* scrambled_missing_cts = DowncastWToU32(&(ctx.missing_acc1[0][acc32_offset]));
3238 for (uint32_t tidx = 1; tidx != calc_thread_ct; ++tidx) {
3239 const uint32_t* thread_scrambled_missing_cts = DowncastWToU32(&(ctx.missing_acc1[tidx][acc32_offset]));
3240 for (uint32_t uii = 0; uii != sample_ctav; ++uii) {
3241 scrambled_missing_cts[uii] += thread_scrambled_missing_cts[uii];
3242 }
3243 }
3244 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
3245 const uint32_t scrambled_idx = VcountScramble1(sample_idx);
3246 sample_missing_geno_cts[sample_idx] = scrambled_missing_cts[scrambled_idx];
3247 }
3248 }
3249 while (0) {
3250 ExportBgen13_ret_NOMEM:
3251 reterr = kPglRetNomem;
3252 break;
3253 ExportBgen13_ret_OPEN_FAIL:
3254 reterr = kPglRetOpenFail;
3255 break;
3256 ExportBgen13_ret_PGR_FAIL:
3257 PgenErrPrintN(reterr);
3258 break;
3259 ExportBgen13_ret_WRITE_FAIL:
3260 reterr = kPglRetWriteFail;
3261 break;
3262 ExportBgen13_ret_INCONSISTENT_INPUT:
3263 reterr = kPglRetInconsistentInput;
3264 break;
3265 ExportBgen13_ret_THREAD_CREATE_FAIL:
3266 reterr = kPglRetThreadCreateFail;
3267 break;
3268 }
3269 ExportBgen13_ret_1:
3270 CleanupThreads(&tg);
3271 if (ctx.libdeflate_compressors) {
3272 for (uint32_t tidx = 0; tidx != max_thread_ct; ++tidx) {
3273 if (!ctx.libdeflate_compressors[tidx]) {
3274 break;
3275 }
3276 libdeflate_free_compressor(ctx.libdeflate_compressors[tidx]);
3277 }
3278 }
3279 fclose_cond(outfile);
3280 BigstackReset(bigstack_mark);
3281 pgfip->block_base = nullptr;
3282 return reterr;
3283 }
3284
3285 PglErr ExportOxSample(const char* outname, const uintptr_t* sample_include, const char* sample_ids, const uint32_t* sample_missing_geno_cts, const uintptr_t* sex_nm, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const char* pheno_names, uint32_t sample_ct, uintptr_t max_sample_id_blen, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t variant_ct, uint32_t y_ct) {
3286 unsigned char* bigstack_mark = g_bigstack_base;
3287 FILE* outfile = nullptr;
3288 PglErr reterr = kPglRetSuccess;
3289 {
3290 logprintfww5("Writing %s ... ", outname);
3291 fflush(stdout);
3292 const uint32_t pheno_ctl = BitCtToWordCt(pheno_ct);
3293 char* writebuf;
3294 uintptr_t* is_basic_categorical;
3295 // if phenotype is categorical, and all (non-null) category names are of
3296 // the form C[positive integer], then it's best to emit the positive
3297 // integer in the name string instead of the internal index.
3298 if (unlikely(bigstack_calloc_w(pheno_ctl, &is_basic_categorical) ||
3299 bigstack_alloc_c(kMaxMediumLine + max_sample_id_blen + 32 + pheno_ct * MAXV(kMaxMissingPhenostrBlen, 16), &writebuf))) {
3300 goto ExportOxSample_ret_NOMEM;
3301 }
3302
3303 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
3304 goto ExportOxSample_ret_OPEN_FAIL;
3305 }
3306 char* writebuf_flush = &(writebuf[kMaxMediumLine]);
3307 char* write_iter = strcpya_k(writebuf, "ID_1 ID_2 missing sex");
3308 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
3309 *write_iter++ = ' ';
3310 write_iter = strcpya(write_iter, &(pheno_names[pheno_idx * max_pheno_name_blen]));
3311 const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_idx]);
3312 if (cur_pheno_col->type_code == kPhenoDtypeCat) {
3313 const uint32_t nn_cat_ct = cur_pheno_col->nonnull_category_ct;
3314 const char* const* cur_cat_names = cur_pheno_col->category_names;
3315 uint32_t cat_idx;
3316 for (cat_idx = 1; cat_idx <= nn_cat_ct; ++cat_idx) {
3317 const char* cat_name_iter = cur_cat_names[cat_idx];
3318 if (*cat_name_iter == 'C') {
3319 uint32_t char_code = *(++cat_name_iter);
3320 if ((char_code - 49) < 9) {
3321 uint32_t uii;
3322 if (!ScanPosintCapped(cat_name_iter, 0x7fffffff, &uii)) {
3323 continue;
3324 }
3325 }
3326 }
3327 break;
3328 }
3329 if (cat_idx == nn_cat_ct + 1) {
3330 SetBit(pheno_idx, is_basic_categorical);
3331 }
3332 }
3333 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
3334 goto ExportOxSample_ret_WRITE_FAIL;
3335 }
3336 }
3337 AppendBinaryEoln(&write_iter);
3338
3339 write_iter = strcpya_k(write_iter, "0 0 0 D");
3340 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
3341 *write_iter++ = ' ';
3342 const PhenoDtype cur_type_code = pheno_cols[pheno_idx].type_code;
3343 if (cur_type_code == kPhenoDtypeCc) {
3344 *write_iter++ = 'B';
3345 } else if (cur_type_code == kPhenoDtypeQt) {
3346 // .psam file does not distinguish between "continuous covariate" and
3347 // "continuous phenotype", that's lost on round-trip
3348 *write_iter++ = 'P';
3349 } else {
3350 *write_iter++ = 'D';
3351 }
3352 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
3353 goto ExportOxSample_ret_WRITE_FAIL;
3354 }
3355 }
3356 AppendBinaryEoln(&write_iter);
3357
3358 const double nonmale_geno_ct_recip = 1.0 / u31tod(variant_ct - y_ct);
3359 const double male_geno_ct_recip = 1.0 / u31tod(variant_ct);
3360 uintptr_t sample_uidx_base = 0;
3361 uintptr_t cur_bits = sample_include[0];
3362 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
3363 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
3364 const char* cur_sample_id = &(sample_ids[max_sample_id_blen * sample_uidx]);
3365 const char* fid_end = AdvToDelim(cur_sample_id, '\t');
3366 write_iter = memcpyax(write_iter, cur_sample_id, fid_end - cur_sample_id, ' ');
3367 write_iter = strcpya(write_iter, &(fid_end[1]));
3368 *write_iter++ = ' ';
3369 const int32_t cur_missing_geno_ct = sample_missing_geno_cts[sample_idx];
3370 if (IsSet(sex_male, sample_uidx)) {
3371 write_iter = dtoa_g(cur_missing_geno_ct * male_geno_ct_recip, write_iter);
3372 write_iter = strcpya_k(write_iter, " 1");
3373 } else {
3374 write_iter = dtoa_g(cur_missing_geno_ct * nonmale_geno_ct_recip, write_iter);
3375 *write_iter++ = ' ';
3376 if (IsSet(sex_nm, sample_uidx)) {
3377 *write_iter++ = '2';
3378 } else {
3379 write_iter = strcpya_k(write_iter, "NA");
3380 }
3381 }
3382 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
3383 *write_iter++ = ' ';
3384 const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_idx]);
3385 if (!IsSet(cur_pheno_col->nonmiss, sample_uidx)) {
3386 write_iter = strcpya_k(write_iter, "NA");
3387 } else {
3388 const PhenoDtype cur_type_code = cur_pheno_col->type_code;
3389 if (cur_type_code == kPhenoDtypeCc) {
3390 *write_iter++ = '0' + IsSet(cur_pheno_col->data.cc, sample_uidx);
3391 } else if (cur_type_code == kPhenoDtypeQt) {
3392 write_iter = dtoa_g(cur_pheno_col->data.qt[sample_uidx], write_iter);
3393 } else {
3394 const uint32_t cur_cat_idx = cur_pheno_col->data.cat[sample_uidx];
3395 if (IsSet(is_basic_categorical, pheno_idx)) {
3396 write_iter = strcpya(write_iter, &(cur_pheno_col->category_names[cur_cat_idx][1]));
3397 } else {
3398 write_iter = u32toa(cur_cat_idx, write_iter);
3399 }
3400 }
3401 }
3402 }
3403 AppendBinaryEoln(&write_iter);
3404 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
3405 goto ExportOxSample_ret_WRITE_FAIL;
3406 }
3407 }
3408 if (unlikely(fclose_flush_null(writebuf_flush, write_iter, &outfile))) {
3409 goto ExportOxSample_ret_WRITE_FAIL;
3410 }
3411 logputs("done.\n");
3412 }
3413 while (0) {
3414 ExportOxSample_ret_NOMEM:
3415 reterr = kPglRetNomem;
3416 break;
3417 ExportOxSample_ret_OPEN_FAIL:
3418 reterr = kPglRetOpenFail;
3419 break;
3420 ExportOxSample_ret_WRITE_FAIL:
3421 reterr = kPglRetWriteFail;
3422 break;
3423 }
3424 fclose_cond(outfile);
3425 BigstackReset(bigstack_mark);
3426 return reterr;
3427 }
3428
3429 PglErr ExportOxSampleV2(const char* outname, const uintptr_t* sample_include, const PedigreeIdInfo* piip, const uint32_t* sample_missing_geno_cts, const uintptr_t* sex_nm, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const char* pheno_names, uint32_t sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t variant_ct, uint32_t y_ct, IdpasteFlags exportf_id_paste, char exportf_id_delim) {
3430 unsigned char* bigstack_mark = g_bigstack_base;
3431 FILE* outfile = nullptr;
3432 PglErr reterr = kPglRetSuccess;
3433 {
3434 const char* paternal_ids = piip->parental_id_info.paternal_ids;
3435 const char* maternal_ids = piip->parental_id_info.maternal_ids;
3436 const uintptr_t max_sample_id_blen = piip->sii.max_sample_id_blen;
3437 const uintptr_t max_paternal_id_blen = piip->parental_id_info.max_paternal_id_blen;
3438 const uintptr_t max_maternal_id_blen = piip->parental_id_info.max_maternal_id_blen;
3439 uintptr_t writebuf_size = kMaxMediumLine + max_sample_id_blen + 32;
3440 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
3441 const PhenoDtype type_code = pheno_cols[pheno_idx].type_code;
3442 if (type_code == kPhenoDtypeCc) {
3443 writebuf_size += 2;
3444 } else if (type_code == kPhenoDtypeQt) {
3445 writebuf_size += kMaxDoubleGSlen + 1;
3446 } else {
3447 const uint32_t cat_ct = pheno_cols[pheno_idx].nonnull_category_ct + 1;
3448 const char** cat_names = pheno_cols[pheno_idx].category_names;
3449 uint32_t max_cat_slen = 2; // "NA"
3450 for (uint32_t cat_idx = 1; cat_idx != cat_ct; ++cat_idx) {
3451 const uint32_t cur_slen = strlen(cat_names[cat_idx]);
3452 if (cur_slen > max_cat_slen) {
3453 max_cat_slen = cur_slen;
3454 }
3455 }
3456 writebuf_size += max_cat_slen + 1;
3457 }
3458 }
3459 // possible todo: support column sets here
3460 const uint32_t write_parents = DataParentalColsAreRequired(sample_include, &(piip->sii), &(piip->parental_id_info), sample_ct, 1);
3461 if (write_parents) {
3462 writebuf_size += max_paternal_id_blen + max_maternal_id_blen;
3463 }
3464
3465 char* writebuf;
3466 if (unlikely(bigstack_alloc_c(writebuf_size, &writebuf))) {
3467 goto ExportOxSampleV2_ret_NOMEM;
3468 }
3469
3470 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
3471 goto ExportOxSampleV2_ret_OPEN_FAIL;
3472 }
3473 char* writebuf_flush = &(writebuf[kMaxMediumLine]);
3474 char* write_iter = strcpya_k(writebuf, "ID missing");
3475 if (write_parents) {
3476 write_iter = strcpya_k(write_iter, " father mother");
3477 }
3478 write_iter = strcpya_k(write_iter, " sex");
3479 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
3480 *write_iter++ = ' ';
3481 write_iter = strcpya(write_iter, &(pheno_names[pheno_idx * max_pheno_name_blen]));
3482 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
3483 goto ExportOxSampleV2_ret_WRITE_FAIL;
3484 }
3485 }
3486 AppendBinaryEoln(&write_iter);
3487
3488 write_iter = strcpya_k(write_iter, "0 0");
3489 if (write_parents) {
3490 write_iter = strcpya_k(write_iter, " D D");
3491 }
3492 write_iter = strcpya_k(write_iter, " D");
3493 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
3494 *write_iter++ = ' ';
3495 const PhenoDtype cur_type_code = pheno_cols[pheno_idx].type_code;
3496 if (cur_type_code == kPhenoDtypeCc) {
3497 *write_iter++ = 'B';
3498 } else if (cur_type_code == kPhenoDtypeQt) {
3499 // .psam file does not distinguish between "continuous covariate" and
3500 // "continuous phenotype", that's lost on round-trip
3501 *write_iter++ = 'P';
3502 } else {
3503 *write_iter++ = 'D';
3504 }
3505 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
3506 goto ExportOxSampleV2_ret_WRITE_FAIL;
3507 }
3508 }
3509 AppendBinaryEoln(&write_iter);
3510
3511 char* exported_sample_ids;
3512 uintptr_t max_exported_sample_id_blen;
3513 if (unlikely(ExportIdpaste(sample_include, &piip->sii, "sample-v2", "sample", sample_ct, exportf_id_paste, exportf_id_delim, &max_exported_sample_id_blen, &exported_sample_ids))) {
3514 goto ExportOxSampleV2_ret_NOMEM;
3515 }
3516
3517 logprintfww5("Writing %s ... ", outname);
3518 fflush(stdout);
3519 const double nonmale_geno_ct_recip = 1.0 / u31tod(variant_ct - y_ct);
3520 const double male_geno_ct_recip = 1.0 / u31tod(variant_ct);
3521 uintptr_t sample_uidx_base = 0;
3522 uintptr_t cur_bits = sample_include[0];
3523 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
3524 write_iter = strcpyax(write_iter, &(exported_sample_ids[sample_idx * max_exported_sample_id_blen]), ' ');
3525 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
3526 const int32_t cur_missing_geno_ct = sample_missing_geno_cts[sample_idx];
3527 const uint32_t is_male = IsSet(sex_male, sample_uidx);
3528 if (is_male) {
3529 write_iter = dtoa_g(cur_missing_geno_ct * male_geno_ct_recip, write_iter);
3530 } else {
3531 write_iter = dtoa_g(cur_missing_geno_ct * nonmale_geno_ct_recip, write_iter);
3532 }
3533 *write_iter++ = ' ';
3534 if (write_parents) {
3535 write_iter = strcpyax(write_iter, &(paternal_ids[max_paternal_id_blen * sample_uidx]), ' ');
3536 write_iter = strcpyax(write_iter, &(maternal_ids[max_maternal_id_blen * sample_uidx]), ' ');
3537 }
3538 if (IsSet(sex_nm, sample_uidx)) {
3539 *write_iter++ = '2' - is_male;
3540 } else {
3541 write_iter = strcpya_k(write_iter, "NA");
3542 }
3543 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
3544 *write_iter++ = ' ';
3545 const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_idx]);
3546 if (!IsSet(cur_pheno_col->nonmiss, sample_uidx)) {
3547 write_iter = strcpya_k(write_iter, "NA");
3548 } else {
3549 const PhenoDtype cur_type_code = cur_pheno_col->type_code;
3550 if (cur_type_code == kPhenoDtypeCc) {
3551 *write_iter++ = '0' + IsSet(cur_pheno_col->data.cc, sample_uidx);
3552 } else if (cur_type_code == kPhenoDtypeQt) {
3553 write_iter = dtoa_g(cur_pheno_col->data.qt[sample_uidx], write_iter);
3554 } else {
3555 const uint32_t cur_cat_idx = cur_pheno_col->data.cat[sample_uidx];
3556 write_iter = strcpya(write_iter, cur_pheno_col->category_names[cur_cat_idx]);
3557 }
3558 }
3559 }
3560 AppendBinaryEoln(&write_iter);
3561 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
3562 goto ExportOxSampleV2_ret_WRITE_FAIL;
3563 }
3564 }
3565 if (unlikely(fclose_flush_null(writebuf_flush, write_iter, &outfile))) {
3566 goto ExportOxSampleV2_ret_WRITE_FAIL;
3567 }
3568 logputs("done.\n");
3569 }
3570 while (0) {
3571 ExportOxSampleV2_ret_NOMEM:
3572 reterr = kPglRetNomem;
3573 break;
3574 ExportOxSampleV2_ret_OPEN_FAIL:
3575 reterr = kPglRetOpenFail;
3576 break;
3577 ExportOxSampleV2_ret_WRITE_FAIL:
3578 reterr = kPglRetWriteFail;
3579 break;
3580 }
3581 fclose_cond(outfile);
3582 BigstackReset(bigstack_mark);
3583 return reterr;
3584 }
3585
3586 const unsigned char kValidVcf43ContigChars[256] = {
3587 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3588 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3589 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3590 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1,
3591 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3592 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1,
3593 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3594 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
3595 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3596 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3597 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3598 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3599 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3600 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3601 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3602 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3603
3604 uint32_t ValidVcfContigName(const char* name_start, const char* name_end, uint32_t v43) {
3605 // Name already guaranteed to not start with '#'.
3606 // With either VCF version, we don't allow the contig name to contain a ',',
3607 // even though the current specification doesn't prohibit it: it messes up
3608 // parsing of the ##contig header line too often in practice.
3609 // With v4.3 only, we also prohibit '<', '>', '[', ']', and '*', all
3610 // characters with ASCII code >126, and first character '='.
3611 // Colons are *not* prohibited any more, as of 1 Feb 2020.
3612 const uint32_t slen = name_end - name_start;
3613 if (unlikely(memchr(name_start, ',', slen))) {
3614 logerrputs("Error: " PROG_NAME_STR " does not permit contig names in exported VCF files to contain\ncommas, since they are too likely to create parsing problems.\n");
3615 return 0;
3616 }
3617 if (!v43) {
3618 return 1;
3619 }
3620 if (unlikely((name_start[0] == '*') || (name_start[0] == '='))) {
3621 logerrputs("Error: VCFv4.3 contig names cannot start with '*' or '='.\n");
3622 return 0;
3623 }
3624 for (uint32_t uii = 0; uii != slen; ++uii) {
3625 unsigned char ucc = name_start[uii];
3626 if (unlikely(!kValidVcf43ContigChars[ucc])) {
3627 char* write_iter = strcpya_k(g_logbuf, "Error: Contig name '");
3628 write_iter = memcpya(write_iter, name_start, slen);
3629 strcpy_k(write_iter, "' is prohibited by the VCFv4.3 specification ('<', '>', '[', ']', and ASCII codes outside 33..126 not allowed).\n");
3630 WordWrapB(0);
3631 logerrputsb();
3632 return 0;
3633 }
3634 }
3635 return 1;
3636 }
3637
3638 // Similar to WriteRestOfHeaderLine() in plink2_data.
3639 BoolErr BgzfWriteRestOfHeaderLine(const char* hkvline_iter, const char* idval, const char* line_end, uint32_t id_slen, BgzfCompressStream* bgzfp) {
3640 if (idval > hkvline_iter) {
3641 // Copy entries before ",ID=".
3642 const char* idkey_prestart = &(idval[-4]);
3643 // 1-byte BgzfWrite call is annoying, but this is not the common case.
3644 if (unlikely(BgzfWrite(",", 1, bgzfp) ||
3645 BgzfWrite(hkvline_iter, idkey_prestart - hkvline_iter, bgzfp))) {
3646 return 1;
3647 }
3648 }
3649 const char* idval_end = &(idval[id_slen]);
3650 return BgzfWrite(idval_end, line_end - idval_end, bgzfp);
3651 }
3652
3653 // Similar to FixAndWriteContigHeaderLine() in plink2_data. However, there are
3654 // two changes to the input assumptions:
3655 // * Trailing comma after ID field is assumed to be written.
3656 // * line_end (pointing after the input '\n') replaces closing_gt, since we
3657 // never need to append an IDX= entry.
3658 // These reduce the number of BgzfWrite() calls.
3659 PglErr BgzfFixAndWriteContigHeaderLine(const char* hkvline_iter, const char* idval, const char* line_end, uint32_t id_slen, uint32_t contig_len, BgzfCompressStream* bgzfp) {
3660 if (hkvline_iter[-1] == '>') {
3661 // Only ID field present in input.
3662 // 20 = strlen("length=") + max 10 bytes for contig_len + '>' + Windows
3663 // EOLN
3664 // need to increase this buffer size if contig_len is changed to uint64_t
3665 char writebuf[20];
3666 char* write_iter = strcpya_k(writebuf, "length=");
3667 write_iter = u32toa_x(contig_len, '>', write_iter);
3668 AppendBinaryEoln(&write_iter);
3669 return BgzfWrite(writebuf, write_iter - writebuf, bgzfp)? kPglRetWriteFail : kPglRetSuccess;
3670 }
3671 const char* idval_end = &(idval[id_slen]);
3672 const char* lenvalstr_start;
3673 uint32_t lenval_slen;
3674 IntErr interr = HkvlineFindK(hkvline_iter, "length", &lenvalstr_start, &lenval_slen);
3675 if (interr) {
3676 if (unlikely(S_CAST(int32_t, interr) == 2)) {
3677 logerrputs("Error: Malformed ##contig line in .pvar file.\n");
3678 return kPglRetMalformedInput;
3679 }
3680 // Existing header line doesn't contain a length. Place the length
3681 // immediately after the ID, and then append the rest of the existing line.
3682 char writebuf[18];
3683 char* write_iter = strcpya_k(writebuf, "length=");
3684 write_iter = u32toa_x(contig_len, ',', write_iter);
3685 if (unlikely(BgzfWrite(writebuf, write_iter - writebuf, bgzfp))) {
3686 return kPglRetWriteFail;
3687 }
3688 if (idval < hkvline_iter) {
3689 return BgzfWrite(hkvline_iter, line_end - hkvline_iter, bgzfp)? kPglRetWriteFail : kPglRetSuccess;
3690 }
3691 // -3 to exclude "ID="
3692 const char* idkey_start = &(idval[-3]);
3693 if (unlikely(BgzfWrite(hkvline_iter, idkey_start - hkvline_iter, bgzfp) ||
3694 BgzfWrite(idval_end, line_end - idval_end, bgzfp))) {
3695 return kPglRetWriteFail;
3696 }
3697 return kPglRetSuccess;
3698 }
3699 const char* lenvalstr_end = &(lenvalstr_start[lenval_slen]);
3700 char writebuf[10];
3701 char* write_iter = u32toa(contig_len, writebuf);
3702 if (idval < lenvalstr_start) {
3703 // Usual case: ID was before length in input.
3704 if (idval < hkvline_iter) {
3705 if (unlikely(BgzfWrite(hkvline_iter, lenvalstr_start - hkvline_iter, bgzfp))) {
3706 return kPglRetWriteFail;
3707 }
3708 } else {
3709 const char* idkey_start = &(idval[-3]);
3710 if (unlikely(BgzfWrite(hkvline_iter, idkey_start - hkvline_iter, bgzfp) ||
3711 BgzfWrite(idval_end, lenvalstr_start - idval_end, bgzfp))) {
3712 return kPglRetWriteFail;
3713 }
3714 }
3715 if (unlikely(BgzfWrite(writebuf, write_iter - writebuf, bgzfp) ||
3716 BgzfWrite(lenvalstr_end, line_end - lenvalstr_end, bgzfp))) {
3717 return kPglRetWriteFail;
3718 }
3719 return kPglRetSuccess;
3720 }
3721 // ID is later.
3722 const char* idkey_prestart = &(idval[-4]);
3723 if (unlikely(BgzfWrite(hkvline_iter, lenvalstr_start - hkvline_iter, bgzfp) ||
3724 BgzfWrite(writebuf, write_iter - writebuf, bgzfp) ||
3725 BgzfWrite(lenvalstr_end, idkey_prestart - lenvalstr_end, bgzfp) ||
3726 BgzfWrite(idval_end, line_end - idval_end, bgzfp))) {
3727 return kPglRetWriteFail;
3728 }
3729 return kPglRetSuccess;
3730 }
3731
3732 uint32_t ValidVcfMetaLine(const char* line_start, uint32_t line_slen, uint32_t v43) {
3733 const char* first_eq = S_CAST(const char*, memchr(line_start, '=', line_slen));
3734 if (!first_eq) {
3735 logerrprintf("Error: Header line in .pvar file does not conform to the VCFv4.%c specification\n(no '=').\n", '2' + v43);
3736 return 0;
3737 }
3738 if (v43 && (first_eq[1] == '<')) {
3739 // If header line starts with "##key=<", ID is required to conform to the
3740 // VCFv4.3 (but not 4.2) specification.
3741 const char* hkvline_iter = &(first_eq[2]);
3742 const char* idval;
3743 uint32_t id_slen;
3744 if (HkvlineIdK(&hkvline_iter, &idval, &id_slen)) {
3745 logerrprintf("Error: Header line in .pvar file does not conform to the VCFv4.3 specification\n(value starts with '<', but that is not followed by an ID). This is permitted\nin VCFv4.2, so you may want to export that format instead.\n");
3746 return 0;
3747 }
3748 }
3749 return 1;
3750 }
3751
3752 uint32_t ValidVcfAlleleCode(const char* allele_code_iter) {
3753 // returns 1 if probably valid (angle-bracket case is not exhaustively
3754 // checked), 0 if definitely not
3755 // TODO: try vectorized loop for long strings (see
3756 // https://github.com/grailbio/bio/blob/master/biosimd/biosimd_amd64.s ),
3757 // combined with lookup table for short strings (always use lookup table for
3758 // first char, then continue using it up to vector boundary).
3759 uint32_t uii = ctou32(*allele_code_iter);
3760 if ((uii == '<') || ((uii == '*') && (!allele_code_iter[1]))) {
3761 return 1;
3762 }
3763 do {
3764 uii -= 64;
3765 // A = 1, C = 3, G = 7, N = 14, T = 20, so (0x10408a >> ucc) & 1 works as a
3766 // set membership test
3767 // (maybe should replace this with another 256-element lookup table...)
3768 #ifdef __LP64__
3769 if ((uii > 63) || (!((0x10408a0010408aLLU >> uii) & 1))) {
3770 // if '[', ']', or '.', assume breakend
3771 return ((uii == 27) || (uii == 29) || (uii == 0xffffffeeU))? 1 : 0;
3772 }
3773 #else
3774 if ((uii > 63) || (!((0x10408a >> (uii % 32)) & 1))) {
3775 return ((uii == 27) || (uii == 29) || (uii == 0xffffffeeU))? 1 : 0;
3776 }
3777 #endif
3778 uii = ctou32(*(++allele_code_iter));
3779 } while (uii);
3780 return 1;
3781 }
3782
3783 // Assumes trailing bits of genovec are clear up to word-PAIR boundary.
3784 void UpdateVcfPrevPhased(const uintptr_t* __restrict genovec, const uintptr_t* __restrict phasepresent, uint32_t sample_ct, uintptr_t* prev_phased) {
3785 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
3786 for (uint32_t widx = 0; widx != sample_ctl; ++widx) {
3787 const uintptr_t geno_lo = genovec[2 * widx];
3788 const uintptr_t geno_hi = genovec[2 * widx + 1];
3789 if (!(geno_lo || geno_hi)) {
3790 continue;
3791 }
3792 const uintptr_t het_word = PackWordToHalfwordMask5555(geno_lo & (~(geno_lo >> 1))) | (S_CAST(uintptr_t, PackWordToHalfwordMask5555(geno_hi & (~(geno_hi >> 1)))) << kBitsPerWordD2);
3793 const uintptr_t phasepresent_word = phasepresent[widx];
3794 prev_phased[widx] = (prev_phased[widx] & (~het_word)) | phasepresent_word;
3795 }
3796 }
3797
3798 char* PrintDiploidVcfDosage(uint32_t dosage_int, uint32_t write_ds, char* write_iter) {
3799 if (write_ds) {
3800 return PrintSmallDosage(dosage_int, write_iter);
3801 }
3802 // GP
3803 if (dosage_int <= kDosageMid) {
3804 write_iter = PrintSmallDosage(kDosageMid - dosage_int, write_iter);
3805 *write_iter++ = ',';
3806 write_iter = PrintSmallDosage(dosage_int, write_iter);
3807 return strcpya_k(write_iter, ",0");
3808 }
3809 write_iter = strcpya_k(write_iter, "0,");
3810 write_iter = PrintSmallDosage(kDosageMax - dosage_int, write_iter);
3811 *write_iter++ = ',';
3812 return PrintSmallDosage(dosage_int - kDosageMid, write_iter);
3813 }
3814
3815 static_assert(kDosageMax == 32768, "PrintHdsPair() needs to be updated.");
3816 char* PrintHdsPair(uint32_t dosage_int, int32_t dphase_delta, char* start) {
3817 // We print left and right dosages in [0, 1] separated by a comma, with the
3818 // minimum number of decimal places such that the sum
3819 // ([0, 32768] <-> [0.0, 2.0]) and difference
3820 // ([-16384, 16384] <-> [-1.0, 1.0]) round-trip. Since it's sum/difference
3821 // that's relevant, it makes sense to force the same number of digits on both
3822 // sides (though trailing zeroes are still omitted), rather than perform a
3823 // multiparameter search (especially since this needs to be extended to
3824 // multiallelic variants soon).
3825 //
3826 // The 4-decimal-place representation is constructed as follows, when it
3827 // exists:
3828 // 1. Check if multiples of 10^{-4} are in
3829 // ((dosage_int - 0.5)/16384, (dosage_int + 0.5)/16384)
3830 // and
3831 // ((dphase_delta - 0.5)/16384, (dphase_delta + 0.5)/16384)
3832 // If not, we can give up.
3833 // 2. Check if these have the same parity. If they do, (x+y)/2 and (x-y)/2
3834 // get the job done; otherwise we abort.
3835 // When this doesn't work, we render the left and right sides separately to
3836 // 5 decimal places. The difference and the sum can each be off by up to
3837 // 1/100000.
3838 // More generally, with k nonzero-dosage alleles and n decimal places, the
3839 // *omitted* allele difference and sum can each be off by up to (k-1)/(10^n),
3840 // and once that's >= 1/32768, we lose reliable round-tripping. So we will
3841 // go up to a 6-decimal-place fallback at k=5, 7 decimal places at k=32, etc.
3842 //
3843 // For diploid unphased dosages, we want (k-1)/(2 * 10^n) to be less than
3844 // 1/32768, so we go to six digits at k=8, seven digits at k=63, etc.
3845 // For haploid dosages, we want (k-1)/(10^n) to be less than 1/65536, so we
3846 // go to six digits at k=3, seven digits at k=17, etc.
3847
3848 // (dosage_int * 2) and (dphase_delta * 2) are in 32768ths
3849 // 32768 * 625 = 20480k, smallest common denominator with 10^4
3850 const uint32_t sum_rangetop_20480k = (dosage_int * 2 + 1) * 625;
3851
3852 // +32768 to force this to be nonnegative while keeping decimal part the same
3853 const uint32_t diffp1_rangetop_20480k = S_CAST(uint32_t, dphase_delta * 2 + 32769) * 625;
3854 if (((sum_rangetop_20480k % 2048) < 1250) && ((diffp1_rangetop_20480k % 20480) < 1250) && ((sum_rangetop_20480k & 2048) == (diffp1_rangetop_20480k & 2048))) {
3855 const uint32_t sum_x10k = sum_rangetop_20480k / 2048;
3856 const int32_t diff_x10k = (diffp1_rangetop_20480k / 2048) - 10000;
3857 const uint32_t left_x10k = (sum_x10k + diff_x10k) / 2;
3858 const uint32_t right_x10k = (sum_x10k - diff_x10k) / 2;
3859 if (left_x10k == 10000) {
3860 *start++ = '1';
3861 } else {
3862 *start++ = '0';
3863 if (left_x10k) {
3864 *start++ = '.';
3865 start = u32toa_trunc4(left_x10k, start);
3866 }
3867 }
3868 *start++ = ',';
3869 if (right_x10k == 10000) {
3870 *start++ = '1';
3871 } else {
3872 *start++ = '0';
3873 if (right_x10k) {
3874 *start++ = '.';
3875 start = u32toa_trunc4(right_x10k, start);
3876 }
3877 }
3878 return start;
3879 }
3880 // see PrintDdosageDecimal() banker's rounding
3881 uint32_t val_x32768 = dosage_int + dphase_delta;
3882 // bugfix (11 Dec 2018): Forgot to print leading digit and dot here.
3883 if (!(val_x32768 & 32767)) {
3884 *start++ = '0' + (val_x32768 == 32768);
3885 } else {
3886 const uint32_t five_decimal_places = ((3125 * val_x32768 + 512) / 1024) - ((val_x32768 % 2048) == 512);
3887 const uint32_t first_decimal_place = five_decimal_places / 10000;
3888 start = strcpya_k(start, "0.");
3889 *start++ = '0' + first_decimal_place;
3890 const uint32_t last_four_digits = five_decimal_places - first_decimal_place * 10000;
3891 if (last_four_digits) {
3892 start = u32toa_trunc4(last_four_digits, start);
3893 }
3894 }
3895 *start++ = ',';
3896 val_x32768 = dosage_int - dphase_delta;
3897 if (!(val_x32768 & 32767)) {
3898 *start++ = '0' + (val_x32768 == 32768);
3899 return start;
3900 }
3901 const uint32_t five_decimal_places = ((3125 * val_x32768 + 512) / 1024) - ((val_x32768 % 2048) == 512);
3902 const uint32_t first_decimal_place = five_decimal_places / 10000;
3903 start = strcpya_k(start, "0.");
3904 *start++ = '0' + first_decimal_place;
3905 const uint32_t last_four_digits = five_decimal_places - first_decimal_place * 10000;
3906 if (last_four_digits) {
3907 return u32toa_trunc4(last_four_digits, start);
3908 }
3909 return start;
3910 }
3911
3912
3913 char* AppendVcfMultiallelicDsForce01(uint32_t allele_ct_m2, uint32_t ds_only, uint32_t hds_force, AlleleCode ac, uint32_t is_hethap, char* write_iter) {
3914 *write_iter++ = '\t';
3915 if (!ds_only) {
3916 write_iter = strcpya_k(write_iter, "0/");
3917 write_iter = u32toa(ac, write_iter);
3918 *write_iter++ = ':';
3919 }
3920 // DS
3921 const uint32_t trailing_ac = allele_ct_m2 + 1 - ac;
3922 *write_iter++ = '0';
3923 write_iter = u16setsa(write_iter, 0x302c, ac - 2);
3924 write_iter = strcpya_k(write_iter, ",1");
3925 write_iter = u16setsa(write_iter, 0x302c, trailing_ac);
3926 if (hds_force) {
3927 write_iter = strcpya_k(write_iter, ":0");
3928 write_iter = u16setsa(write_iter, 0x302c, ac - 2);
3929 write_iter = strcpya_k(write_iter, ",0.5");
3930 if (!is_hethap) {
3931 // trailing_ac after, 1 + (ac - 2) before
3932 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
3933 write_iter = strcpya_k(write_iter, ",0.5");
3934 }
3935 write_iter = u16setsa(write_iter, 0x302c, trailing_ac);
3936 }
3937 return write_iter;
3938 }
3939
3940 char* AppendVcfMultiallelicDsForce10Het(uint32_t allele_ct_m2, uint32_t ds_only, uint32_t hds_force, AlleleCode ac0, AlleleCode ac1, uint32_t is_hethap, char* write_iter) {
3941 *write_iter++ = '\t';
3942 if (!ds_only) {
3943 write_iter = u32toa_x(ac0, '/', write_iter);
3944 write_iter = u32toa_x(ac1, ':', write_iter);
3945 }
3946 const uint32_t leading_ac = ac0 - 1;
3947 const uint32_t middle_ac = ac1 - ac0 - 1;
3948 const uint32_t trailing_ac = allele_ct_m2 + 1 - ac1;
3949 write_iter = u16setsa(write_iter, 0x2c30, leading_ac);
3950 *write_iter++ = '1';
3951 write_iter = u16setsa(write_iter, 0x302c, middle_ac);
3952 write_iter = strcpya_k(write_iter, ",1");
3953 write_iter = u16setsa(write_iter, 0x302c, trailing_ac);
3954 if (hds_force) {
3955 *write_iter++ = ':';
3956 write_iter = u16setsa(write_iter, 0x2c30, leading_ac);
3957 write_iter = strcpya_k(write_iter, "0.5");
3958 write_iter = u16setsa(write_iter, 0x302c, middle_ac);
3959 write_iter = strcpya_k(write_iter, ",0.5");
3960 if (!is_hethap) {
3961 write_iter = u16setsa(write_iter, 0x302c, trailing_ac + leading_ac);
3962 write_iter = strcpya_k(write_iter, ",0.5");
3963 write_iter = u16setsa(write_iter, 0x302c, middle_ac);
3964 write_iter = strcpya_k(write_iter, ",0.5");
3965 }
3966 write_iter = u16setsa(write_iter, 0x302c, trailing_ac);
3967 }
3968 return write_iter;
3969 }
3970
3971 char* AppendVcfMultiallelicDsForce10HomDiploid(uint32_t allele_ct_m2, uint32_t ds_only, uint32_t hds_force, AlleleCode ac, char phase_char, char* write_iter) {
3972 *write_iter++ = '\t';
3973 if (!ds_only) {
3974 write_iter = u32toa_x(ac, phase_char, write_iter);
3975 write_iter = u32toa(ac, write_iter);
3976 *write_iter++ = ':';
3977 }
3978 // ac >= 2 guaranteed
3979 const uint32_t trailing_ac = allele_ct_m2 + 1 - ac;
3980 *write_iter++ = '0';
3981 write_iter = u16setsa(write_iter, 0x302c, ac - 2);
3982 write_iter = strcpya_k(write_iter, ",2");
3983 write_iter = u16setsa(write_iter, 0x302c, trailing_ac);
3984 if (hds_force) {
3985 write_iter = strcpya_k(write_iter, ":0");
3986 write_iter = u16setsa(write_iter, 0x302c, ac - 2);
3987 write_iter = strcpya_k(write_iter, ",1");
3988 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
3989 write_iter = strcpya_k(write_iter, ",1");
3990 write_iter = u16setsa(write_iter, 0x302c, trailing_ac);
3991 }
3992 return write_iter;
3993 }
3994
3995 char* AppendVcfMultiallelicDsForce10Haploid(uint32_t allele_ct_m2, uint32_t ds_only, uint32_t hds_force, AlleleCode ac, char* write_iter) {
3996 *write_iter++ = '\t';
3997 if (!ds_only) {
3998 write_iter = u32toa(ac, write_iter);
3999 *write_iter++ = ':';
4000 }
4001 // ac >= 2 guaranteed
4002 const uint32_t trailing_ac = allele_ct_m2 + 1 - ac;
4003 *write_iter++ = '0';
4004 write_iter = u16setsa(write_iter, 0x302c, ac - 2);
4005 write_iter = strcpya_k(write_iter, ",1");
4006 write_iter = u16setsa(write_iter, 0x302c, trailing_ac);
4007 if (hds_force) {
4008 write_iter = strcpya_k(write_iter, ":0");
4009 write_iter = u16setsa(write_iter, 0x302c, ac - 2);
4010 write_iter = strcpya_k(write_iter, ",1");
4011 write_iter = u16setsa(write_iter, 0x302c, trailing_ac);
4012 }
4013 return write_iter;
4014 }
4015
4016 char* AppendVcfMultiallelicDsForcePhased(uint32_t allele_ct_m2, uint32_t hds_force, AlleleCode ac0, AlleleCode ac1, uint32_t phaseinfo_hw_masked, char* write_iter) {
4017 AlleleCode ac_left = ac0;
4018 AlleleCode ac_right = ac1;
4019 if (phaseinfo_hw_masked) {
4020 ac_left = ac1;
4021 ac_right = ac0;
4022 }
4023 *write_iter++ = '\t';
4024 write_iter = u32toa_x(ac_left, '|', write_iter);
4025 write_iter = u32toa_x(ac_right, ':', write_iter);
4026 // DS
4027 // Don't define leading_ac since ac0 == 0 is possible.
4028 const uint32_t middle_ac = ac1 - ac0 - 1;
4029 const uint32_t trailing_ac = allele_ct_m2 + 1 - ac1;
4030 if (ac0) {
4031 write_iter = u16setsa(write_iter, 0x2c30, ac0 - 1);
4032 write_iter = strcpya_k(write_iter, "1,");
4033 }
4034 write_iter = u16setsa(write_iter, 0x2c30, middle_ac);
4035 *write_iter++ = '1';
4036 write_iter = u16setsa(write_iter, 0x302c, trailing_ac);
4037 if (hds_force) {
4038 *write_iter++ = ':';
4039 if (ac_left) {
4040 write_iter = u16setsa(write_iter, 0x2c30, ac_left - 1);
4041 write_iter = strcpya_k(write_iter, "1,");
4042 }
4043 write_iter = u16setsa(write_iter, 0x2c30, allele_ct_m2 + 1 - ac_left);
4044 if (ac_right) {
4045 write_iter = u16setsa(write_iter, 0x2c30, ac_right - 1);
4046 write_iter = strcpya_k(write_iter, "1,");
4047 }
4048 write_iter = u16setsa(write_iter, 0x2c30, allele_ct_m2 + 1 - ac_right);
4049 // remove trailing comma
4050 --write_iter;
4051 }
4052 return write_iter;
4053 }
4054
4055 PglErr ExportVcf(const uintptr_t* sample_include, const uint32_t* sample_include_cumulative_popcounts, const SampleIdInfo* siip, const uintptr_t* sex_male_collapsed, 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 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 uint32_t* contig_lens, uintptr_t xheader_blen, InfoFlags info_flags, uint32_t sample_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_slen, uint32_t max_filter_slen, uint32_t info_reload_slen, uint32_t max_thread_ct, ExportfFlags exportf_flags, VcfExportMode vcf_mode, IdpasteFlags exportf_id_paste, char exportf_id_delim, char* xheader, PgenFileInfo* pgfip, PgenReader* simple_pgrp, char* outname, char* outname_end) {
4056 unsigned char* bigstack_mark = g_bigstack_base;
4057 PglErr reterr = kPglRetSuccess;
4058 TextStream pvar_reload_txs;
4059 BgzfCompressStream bgzf;
4060 PreinitTextStream(&pvar_reload_txs);
4061 PreinitBgzfCompressStream(&bgzf);
4062 {
4063 {
4064 uint32_t clvl = 0;
4065 if (!(exportf_flags & kfExportfBgz)) {
4066 snprintf(outname_end, kMaxOutfnameExtBlen, ".vcf");
4067 } else {
4068 snprintf(outname_end, kMaxOutfnameExtBlen, ".vcf.gz");
4069 clvl = kBgzfDefaultClvl;
4070 }
4071 reterr = InitBgzfCompressStreamEx(outname, 0, clvl, max_thread_ct, &bgzf);
4072 if (unlikely(reterr)) {
4073 if (reterr == kPglRetOpenFail) {
4074 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
4075 }
4076 goto ExportVcf_ret_1;
4077 }
4078 }
4079 const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
4080 // CHROM, POS, ID, REF, one ALT, eoln
4081 uintptr_t writebuf_blen = kMaxIdSlen + 32 + max_chr_blen + 2 * max_allele_slen;
4082 // QUAL, FILTER, INFO, FORMAT, genotypes, eoln
4083 // needs to be larger for >9 alt alleles
4084 uint32_t write_some_dosage = 0;
4085 uint32_t write_ds = 0;
4086 uint32_t write_hds = 0;
4087 uint32_t ds_force = 0;
4088 uint32_t ds_only = 0;
4089 uint32_t hds_force = 0;
4090 if (vcf_mode != kVcfExport0) {
4091 write_some_dosage = 1;
4092 if (vcf_mode != kVcfExportGp) {
4093 write_ds = 1;
4094 if (vcf_mode == kVcfExportDsForce) {
4095 ds_force = 1;
4096 } else if (vcf_mode == kVcfExportDsOnly) {
4097 // quasi-bugfix (16 Mar 2022): DS-only is now prohibited when partly-
4098 // haploid or all-haploid variants are present, since without GT
4099 // there to indicate ploidy, 0..1 vs. 0..2 scaling is not adequately
4100 // defined.
4101 if (unlikely((cip->haploid_mask[0] & 1) ||
4102 XymtIsNonempty(variant_include, cip, kChrOffsetX) ||
4103 XymtIsNonempty(variant_include, cip, kChrOffsetY) ||
4104 XymtIsNonempty(variant_include, cip, kChrOffsetMT))) {
4105 logerrputs("Error: --export vcf-dosage=DS-only mode can only be used with all-diploid data.\n");
4106 goto ExportVcf_ret_INCONSISTENT_INPUT;
4107 }
4108 ds_force = 1;
4109 ds_only = 1;
4110 } else if (vcf_mode != kVcfExportDs) {
4111 write_hds = 1;
4112 if (vcf_mode == kVcfExportHdsForce) {
4113 ds_force = 1;
4114 hds_force = 1;
4115 }
4116 }
4117 }
4118 }
4119 if ((!ds_force) && write_some_dosage && (!(pgfip->gflags & kfPgenGlobalDosagePresent))) {
4120 write_some_dosage = 0;
4121 logerrprintf("Warning: No dosage data present. %s will not be exported.\n", write_hds? "DS and HDS fields" : (write_ds? "DS field" : "GP field"));
4122 write_ds = 0;
4123 write_hds = 0;
4124 }
4125 // max_allele_ct == 2:
4126 // GT: 4 bytes (unless ds_only)
4127 // GP: 3 limited-precision numbers, up to (7 chars + delim) * 3
4128 // DS + HDS: also 3 limited precision numbers
4129 // DS only: 1 limited-precision number
4130 // max_allele_ct > 2:
4131 // GT: 2 + 2 * UintSlen(max_allele_ct + 1) (unless ds_only)
4132 // GP: if requested, check max_gp_allele_ct among multiallelic-dosage
4133 // variants.
4134 // if none found (always true for now), 24 chars.
4135 // if present, (max_gp_allele_ct * (max_gp_allele_ct + 1) / 2) * 8,
4136 // which sucks ass
4137 // DS + HDS: 3 * (max_allele_ct - 1) limited-precision numbers
4138 // DS only: (max_allele_ct - 1) limited-precision numbers
4139 uintptr_t output_bytes_per_sample;
4140 if (!allele_idx_offsets) {
4141 if (write_some_dosage) {
4142 if (ds_only) {
4143 output_bytes_per_sample = 8;
4144 } else {
4145 output_bytes_per_sample = (write_ds && (!write_hds))? 12 : 28;
4146 }
4147 } else {
4148 output_bytes_per_sample = 4;
4149 }
4150 } else {
4151 const uint32_t max_allele_ct = PgrGetMaxAlleleCt(simple_pgrp);
4152 if (ds_only) {
4153 output_bytes_per_sample = 8 * (max_allele_ct - 1);
4154 } else {
4155 output_bytes_per_sample = 2 + 2 * UintSlen(max_allele_ct + 1);
4156 if (write_some_dosage) {
4157 if (write_ds) {
4158 if (write_hds) {
4159 output_bytes_per_sample += 24 * (max_allele_ct - 1);
4160 } else {
4161 output_bytes_per_sample += 8 * (max_allele_ct - 1);
4162 }
4163 } else {
4164 // GP should only be written for biallelic variants, for now
4165 // would need to take max of this and GT length, but this is always
4166 // larger
4167 output_bytes_per_sample = 28;
4168 }
4169 }
4170 }
4171 }
4172 const uintptr_t writebuf_blen_lbound = sample_ct * output_bytes_per_sample + 32 + max_filter_slen + info_reload_slen;
4173 if (writebuf_blen < writebuf_blen_lbound) {
4174 writebuf_blen = writebuf_blen_lbound;
4175 }
4176 writebuf_blen += kMaxMediumLine;
4177 char* writebuf;
4178 if (unlikely(bigstack_alloc_c(writebuf_blen, &writebuf))) {
4179 goto ExportVcf_ret_NOMEM;
4180 }
4181 char* writebuf_flush = &(writebuf[kMaxMediumLine]);
4182 char* write_iter = writebuf;
4183 const uint32_t v43 = (exportf_flags / kfExportfVcf43) & 1;
4184 AppendVcfHeaderStart(v43, &write_iter);
4185 if (cip->chrset_source) {
4186 AppendChrsetLine(cip, &write_iter);
4187 }
4188 if (unlikely(BgzfWrite(writebuf, write_iter - writebuf, &bgzf))) {
4189 goto ExportVcf_ret_WRITE_FAIL;
4190 }
4191 const uint32_t chr_ctl = BitCtToWordCt(cip->chr_ct);
4192 uintptr_t* written_contig_header_lines;
4193 if (unlikely(bigstack_calloc_w(chr_ctl, &written_contig_header_lines))) {
4194 goto ExportVcf_ret_NOMEM;
4195 }
4196 // bugfix (30 Aug 2018): remove extraneous PAR1/PAR2 ##contig header lines,
4197 // count them as part of chrX
4198 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
4199 const uint32_t par1_code = cip->xymt_codes[kChrOffsetPAR1];
4200 const uint32_t par2_code = cip->xymt_codes[kChrOffsetPAR2];
4201 uint32_t contig_zero_written = 0;
4202 uint32_t x_contig_line_written = 0;
4203 if (xheader) {
4204 memcpyo_k(writebuf, "##contig=<ID=", 13);
4205 char* xheader_end = &(xheader[xheader_blen]);
4206 for (char* line_end = xheader; line_end != xheader_end; ) {
4207 char* xheader_iter = line_end;
4208 line_end = AdvPastDelim(xheader_iter, '\n');
4209 if (StrStartsWithUnsafe(xheader_iter, "##contig=<")) {
4210 xheader_iter = &(xheader_iter[strlen("##contig=<")]);
4211 char* idval;
4212 uint32_t id_slen;
4213 if (unlikely(HkvlineId(&xheader_iter, &idval, &id_slen))) {
4214 logerrputs("Error: Malformed ##contig line in .pvar file.\n");
4215 goto ExportVcf_ret_MALFORMED_INPUT;
4216 }
4217 if (xheader_iter[-1] == '>') {
4218 // regenerate instead of keeping
4219 continue;
4220 }
4221 // if GetChrCodeCounted() is modified to not mutate idval[], xheader
4222 // can be changed to const char*
4223 const uint32_t chr_idx = GetChrCodeCounted(cip, id_slen, idval);
4224 // bugfix (8 Sep 2018): must exclude ##contig lines not present in
4225 // input, otherwise chr_fo_idx == 0xffffffffU, etc.
4226 if (IsI32Neg(chr_idx) || (!IsSet(cip->chr_mask, chr_idx)) || (chr_idx == par1_code) || (chr_idx == par2_code)) {
4227 continue;
4228 }
4229 if (chr_idx == x_code) {
4230 x_contig_line_written = 1;
4231 }
4232 const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[chr_idx];
4233 if (unlikely(IsSet(written_contig_header_lines, chr_fo_idx))) {
4234 logerrputs("Error: Duplicate ##contig line in .pvar file.\n");
4235 goto ExportVcf_ret_MALFORMED_INPUT;
4236 }
4237 SetBit(chr_fo_idx, written_contig_header_lines);
4238 // if --output-chr was used at some point, we need to sync the
4239 // ##contig chromosome code with the code in the VCF body.
4240 char* contig_write_start = &(writebuf[13]);
4241 write_iter = chrtoa(cip, chr_idx, contig_write_start);
4242 if ((*contig_write_start == '0') && (write_iter == &(contig_write_start[1]))) {
4243 // --allow-extra-chr 0 special case
4244 contig_zero_written = 1; // technically we write this a bit later
4245 continue;
4246 }
4247 if (unlikely(!ValidVcfContigName(contig_write_start, write_iter, v43))) {
4248 goto ExportVcf_ret_MALFORMED_INPUT;
4249 }
4250 if (contig_lens && contig_lens[chr_idx]) {
4251 *write_iter++ = ',';
4252 if (unlikely(BgzfWrite(writebuf, write_iter - writebuf, &bgzf))) {
4253 goto ExportVcf_ret_WRITE_FAIL;
4254 }
4255 reterr = BgzfFixAndWriteContigHeaderLine(xheader_iter, idval, line_end, id_slen, contig_lens[chr_idx], &bgzf);
4256 if (unlikely(reterr)) {
4257 goto ExportVcf_ret_1;
4258 }
4259 } else {
4260 if (unlikely(BgzfWrite(writebuf, write_iter - writebuf, &bgzf) ||
4261 BgzfWriteRestOfHeaderLine(xheader_iter, idval, line_end, id_slen, &bgzf))) {
4262 goto ExportVcf_ret_WRITE_FAIL;
4263 }
4264 }
4265 } else if (xheader_iter[1] == '#') {
4266 // quasi-bugfix (23 Jan 2021): don't export pre-#CHROM header lines
4267 // starting with a single '#'
4268 const uint32_t slen = line_end - xheader_iter;
4269 if (unlikely(!ValidVcfMetaLine(xheader_iter, slen, v43))) {
4270 goto ExportVcf_ret_INCONSISTENT_INPUT;
4271 }
4272 if (unlikely(BgzfWrite(xheader_iter, slen, &bgzf))) {
4273 goto ExportVcf_ret_WRITE_FAIL;
4274 }
4275 }
4276 }
4277 }
4278 write_iter = writebuf;
4279 // fill in the missing ##contig lines
4280 if (contig_zero_written) {
4281 write_iter = strcpya_k(write_iter, "##contig=<ID=0>" EOLN_STR);
4282 }
4283 uint32_t chrx_exists = 0;
4284 for (uint32_t chr_fo_idx = 0; chr_fo_idx != cip->chr_ct; ++chr_fo_idx) {
4285 if (IsSet(written_contig_header_lines, chr_fo_idx)) {
4286 continue;
4287 }
4288 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
4289 if ((!IsSet(cip->chr_mask, chr_idx)) || AllBitsAreZero(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], cip->chr_fo_vidx_start[chr_fo_idx + 1])) {
4290 continue;
4291 }
4292 if ((chr_idx == x_code) || (chr_idx == par1_code) || (chr_idx == par2_code)) {
4293 chrx_exists = 1;
4294 continue;
4295 }
4296 char* chr_name_write_start = strcpya_k(write_iter, "##contig=<ID=");
4297 char* chr_name_write_end = chrtoa(cip, chr_idx, chr_name_write_start);
4298 if ((*chr_name_write_start == '0') && (chr_name_write_end == &(chr_name_write_start[1]))) {
4299 // --allow-extra-chr 0 special case
4300 if (contig_zero_written) {
4301 continue;
4302 }
4303 contig_zero_written = 1;
4304 write_iter = chr_name_write_end;
4305 } else {
4306 if (unlikely(!ValidVcfContigName(chr_name_write_start, chr_name_write_end, v43))) {
4307 goto ExportVcf_ret_MALFORMED_INPUT;
4308 }
4309 write_iter = chr_name_write_end;
4310 if (contig_lens && contig_lens[chr_idx]) {
4311 write_iter = strcpya_k(write_iter, ",length=");
4312 write_iter = u32toa(contig_lens[chr_idx], write_iter);
4313 }
4314 }
4315 *write_iter++ = '>';
4316 AppendBinaryEoln(&write_iter);
4317 if (unlikely(bgzfwrite_ck(writebuf_flush, &bgzf, &write_iter))) {
4318 goto ExportVcf_ret_WRITE_FAIL;
4319 }
4320 }
4321 if (chrx_exists && (!x_contig_line_written)) {
4322 char* chr_name_write_start = strcpya_k(write_iter, "##contig=<ID=");
4323 char* chr_name_write_end = chrtoa(cip, x_code, chr_name_write_start);
4324 write_iter = strcpya_k(chr_name_write_end, ">" EOLN_STR);
4325 if (unlikely(bgzfwrite_ck(writebuf_flush, &bgzf, &write_iter))) {
4326 goto ExportVcf_ret_WRITE_FAIL;
4327 }
4328 }
4329 BigstackReset(written_contig_header_lines);
4330 const uintptr_t* nonref_flags = pgfip->nonref_flags;
4331 const uint32_t all_nonref = (pgfip->gflags & kfPgenGlobalAllNonref) && (!nonref_flags);
4332 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
4333 uint32_t write_pr = all_nonref;
4334 if (nonref_flags) {
4335 write_pr = !IntersectionIsEmpty(variant_include, nonref_flags, raw_variant_ctl);
4336 }
4337 const uint32_t info_pr_flag_present = (info_flags / kfInfoPrFlagPresent) & 1;
4338 if (write_pr) {
4339 if (unlikely(info_flags & kfInfoPrNonflagPresent)) {
4340 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");
4341 goto ExportVcf_ret_INCONSISTENT_INPUT;
4342 }
4343 if (!info_pr_flag_present) {
4344 write_iter = strcpya_k(write_iter, "##INFO=<ID=PR,Number=0,Type=Flag,Description=\"Provisional reference allele, may not be based on real reference genome\">" EOLN_STR);
4345 }
4346 }
4347 if (write_ds) {
4348 write_iter = strcpya_k(write_iter, "##FORMAT=<ID=DS,Number=A,Type=Float,Description=\"Estimated Alternate Allele Dosage : [P(0/1)+2*P(1/1)]\">" EOLN_STR);
4349 if (write_hds) {
4350 // bugfix (3 May 2018): 'Number=2' was inaccurate for haploid calls.
4351
4352 // Note that HDS ploidy intentionally does NOT match GT ploidy in the
4353 // unphased het haploid case.
4354 write_iter = strcpya_k(write_iter, "##FORMAT=<ID=HDS,Number=.,Type=Float,Description=\"Estimated Haploid Alternate Allele Dosage \">" EOLN_STR);
4355 }
4356 } else if (write_some_dosage) {
4357 write_iter = strcpya_k(write_iter, "##FORMAT=<ID=GP,Number=G,Type=Float,Description=\"Estimated Posterior Probabilities for Genotypes 0/0, 0/1 and 1/1 \">" EOLN_STR);
4358 }
4359 // possible todo: if there is ever a real standard for encoding pedigree
4360 // information in the VCF header, do it here and make --vcf be able to read
4361 // it
4362 if (!ds_only) {
4363 write_iter = strcpya_k(write_iter, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">" EOLN_STR);
4364 }
4365 write_iter = strcpya_k(write_iter, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT");
4366 char* exported_sample_ids;
4367 uintptr_t max_exported_sample_id_blen;
4368 if (unlikely(ExportIdpaste(sample_include, siip, "vcf", "vcf", sample_ct, exportf_id_paste, exportf_id_delim, &max_exported_sample_id_blen, &exported_sample_ids))) {
4369 goto ExportVcf_ret_NOMEM;
4370 }
4371 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
4372 *write_iter++ = '\t';
4373 write_iter = strcpya(write_iter, &(exported_sample_ids[sample_idx * max_exported_sample_id_blen]));
4374 if (unlikely(bgzfwrite_ck(writebuf_flush, &bgzf, &write_iter))) {
4375 goto ExportVcf_ret_WRITE_FAIL;
4376 }
4377 }
4378 AppendBinaryEoln(&write_iter);
4379 BigstackReset(exported_sample_ids);
4380
4381 logprintfww5("--export vcf%s to %s ... ", (exportf_flags & kfExportfBgz)? " bgz" : "", outname);
4382 fputs("0%", stdout);
4383 fflush(stdout);
4384
4385 // includes trailing tab
4386 char* chr_buf;
4387
4388 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
4389 PgenVariant pgv;
4390 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf) ||
4391 bigstack_alloc_w(sample_ctl * 2, &pgv.genovec))) {
4392 goto ExportVcf_ret_NOMEM;
4393 }
4394 pgv.genovec[sample_ctl * 2 - 1] = 0;
4395 pgv.patch_01_set = nullptr;
4396 pgv.patch_01_vals = nullptr;
4397 pgv.patch_10_set = nullptr;
4398 pgv.patch_10_vals = nullptr;
4399 if (allele_idx_offsets) {
4400 if (unlikely(bigstack_alloc_w(sample_ctl, &(pgv.patch_01_set)) ||
4401 bigstack_alloc_ac(sample_ct, &(pgv.patch_01_vals)) ||
4402 bigstack_alloc_w(sample_ctl, &(pgv.patch_10_set)) ||
4403 bigstack_alloc_ac(sample_ct * 2, &(pgv.patch_10_vals)))) {
4404 goto ExportVcf_ret_NOMEM;
4405 }
4406 }
4407 // For now, if phased data is present, each homozygous call is represented
4408 // as phased iff the previous heterozygous call was phased. (If no
4409 // previous heterozygous call exists, it's treated as phased.) This does
4410 // the right thing when the entire genome is phased, and it induces about
4411 // as good a phase set approximation as you can get without explicitly
4412 // saving that info. But that approximation is still pretty inaccurate; as
4413 // soon as we have any use for them, explicit phase set support should be
4414 // added to pgenlib.
4415 // Note that prev_phased is NOT reinitialized at the beginning of each
4416 // chromosome.
4417 const uint32_t load_dphase = write_hds && (pgfip->gflags & kfPgenGlobalDosagePhasePresent);
4418 const uint32_t some_phased = (!ds_only) && ((pgfip->gflags & kfPgenGlobalHardcallPhasePresent) || load_dphase);
4419 uintptr_t* prev_phased = nullptr;
4420 pgv.phasepresent = nullptr;
4421 pgv.phaseinfo = nullptr;
4422 if (some_phased) {
4423 if (unlikely(bigstack_alloc_w(sample_ctl, &prev_phased) ||
4424 bigstack_alloc_w(sample_ctl, &(pgv.phasepresent)) ||
4425 bigstack_alloc_w(sample_ctl, &(pgv.phaseinfo)))) {
4426 goto ExportVcf_ret_NOMEM;
4427 }
4428 SetAllBits(sample_ct, prev_phased);
4429 }
4430
4431 pgv.dosage_present = nullptr;
4432 pgv.dosage_main = nullptr;
4433 pgv.dphase_present = nullptr;
4434 pgv.dphase_delta = nullptr;
4435 if (write_some_dosage && (pgfip->gflags & kfPgenGlobalDosagePresent)) {
4436 if (unlikely(bigstack_alloc_w(sample_ctl, &(pgv.dosage_present)) ||
4437 bigstack_alloc_dosage(sample_ct, &(pgv.dosage_main)))) {
4438 goto ExportVcf_ret_NOMEM;
4439 }
4440 if (load_dphase) {
4441 if (unlikely(bigstack_alloc_w(sample_ctl, &(pgv.dphase_present)) ||
4442 bigstack_alloc_dphase(sample_ct, &(pgv.dphase_delta)))) {
4443 goto ExportVcf_ret_NOMEM;
4444 }
4445 }
4446 }
4447
4448 char* pvar_reload_line_iter = nullptr;
4449 uint32_t info_col_idx = 0;
4450 if (pvar_info_reload) {
4451 reterr = PvarInfoOpenAndReloadHeader(pvar_info_reload, 1 + (max_thread_ct > 1), &pvar_reload_txs, &pvar_reload_line_iter, &info_col_idx);
4452 if (unlikely(reterr)) {
4453 goto ExportVcf_ret_TSTREAM_FAIL;
4454 }
4455 }
4456
4457 // assumes little-endian
4458 // maybe want to pass references to these arrays later, but leave as
4459 // C-style for now
4460 // \t0/0 \t0/1 \t1/1 \t./.
4461 const uint32_t basic_genotext[4] = {0x302f3009, 0x312f3009, 0x312f3109, 0x2e2f2e09};
4462
4463 // 4-genotype-at-a-time lookup in basic case
4464 uint32_t basic_genotext4[1024] ALIGNV16;
4465 basic_genotext4[0] = basic_genotext[0];
4466 basic_genotext4[4] = basic_genotext[1];
4467 basic_genotext4[8] = basic_genotext[2];
4468 basic_genotext4[12] = basic_genotext[3];
4469 InitLookup256x4bx4(basic_genotext4);
4470
4471 // 2-genotype-at-a-time lookup in basic phased case
4472 uint32_t phased_genotext2[492];
4473 phased_genotext2[0] = basic_genotext[0];
4474 phased_genotext2[2] = basic_genotext[1];
4475 phased_genotext2[4] = basic_genotext[2];
4476 phased_genotext2[6] = basic_genotext[3];
4477 phased_genotext2[32] = 0x307c3009;
4478 phased_genotext2[34] = 0x317c3009;
4479 phased_genotext2[36] = 0x317c3109;
4480 phased_genotext2[38] = 0x2e7c2e09;
4481 phased_genotext2[162] = 0x307c3109; // 1|0
4482 InitVcfPhaseLookup4b(phased_genotext2);
4483
4484 uint32_t haploid_genotext_blen[8];
4485 // lengths [0], [2], and [3] reset at beginning of chromosome
4486 // chrX: nonmales are diploid and use indices 0..3, males are 4..7
4487 // other: all haploid, indices 0..3
4488 haploid_genotext_blen[1] = 4;
4489 haploid_genotext_blen[4] = 2;
4490 haploid_genotext_blen[5] = 4;
4491 haploid_genotext_blen[6] = 2;
4492 haploid_genotext_blen[7] = 2;
4493 // don't bother exporting GP for hardcalls
4494 // usually don't bother for DS, but DS-force is an exception
4495
4496 // 4..7 = haploid, 5 should never be looked up
4497 // :0 :1 :2 :. :0 !! :1 :.
4498 // ':' replaced with '\t' if ds_only
4499 uint16_t ds_inttext[8] = {0x303a, 0x313a, 0x323a, 0x2e3a, 0x303a, 0x2121, 0x313a, 0x2e3a};
4500 uint16_t ds_inttext4[1024];
4501 if (ds_only) {
4502 ds_inttext[0] = 0x3009;
4503 ds_inttext[1] = 0x3109;
4504 ds_inttext[2] = 0x3209;
4505 ds_inttext[3] = 0x2e09;
4506 ds_inttext[4] = 0x3009;
4507 ds_inttext[6] = 0x3109;
4508 ds_inttext[7] = 0x2e09;
4509
4510 ds_inttext4[0] = 0x3009;
4511 ds_inttext4[4] = 0x3109;
4512 ds_inttext4[8] = 0x3209;
4513 ds_inttext4[12] = 0x2e09;
4514 InitLookup256x2bx4(ds_inttext4);
4515 }
4516
4517 // 0..3 = diploid unphased
4518 // 4..5 = phased, phaseinfo=0 first
4519 // update (1 Aug 2018): HDS ploidy should be more trustworthy than GT
4520 // ploidy when there's a conflict, since GT must render unphased het
4521 // haploids as 0/1. So under HDS-force, diploid missing value is '.,.'
4522 // instead of '.'. (Since we're only interested in storing a trustworthy
4523 // ploidy, we don't add more missing entries in the multiallelic case.)
4524
4525 // could make this include DS text in front
4526 // could expand this to e.g. 10 cases and make [4], [5] less fiddly
4527 // :0,0 :0.5,0.5 :1,1 :.,. :0,1 :1,0
4528 const uint64_t hds_inttext[6] = {0x302c303a, 0x352e302c352e303aLLU, 0x312c313a, 0x2e2c2e3a, 0x312c303a, 0x302c313a};
4529
4530 // [4]..[7] = haploid unphased; == 4 for phased
4531 uint32_t hds_inttext_blen[8];
4532
4533 // lengths [0]-[3] reset at beginning of chromosome
4534 hds_inttext_blen[4] = 2;
4535 hds_inttext_blen[5] = 4;
4536 hds_inttext_blen[6] = 2;
4537 hds_inttext_blen[7] = 2;
4538 const char* dot_ptr = &(g_one_char_strs[92]);
4539 const uint32_t sample_ctl2_m1 = (sample_ct - 1) / kBitsPerWordD2;
4540 PgrSampleSubsetIndex pssi;
4541 PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi);
4542 uintptr_t variant_uidx_base = 0;
4543 uintptr_t cur_bits = variant_include[0];
4544 uint32_t chr_fo_idx = UINT32_MAX;
4545 uint32_t chr_end = 0;
4546 uint32_t chr_buf_blen = 0;
4547 uint32_t is_x = 0;
4548 uint32_t is_haploid = 0; // includes chrX and chrY
4549 uint32_t pct = 0;
4550 uint32_t next_print_variant_idx = variant_ct / 100;
4551 uint32_t rls_variant_uidx = 0;
4552 uint32_t ref_allele_idx = 0;
4553 uint32_t alt1_allele_idx = 1;
4554 uint32_t allele_ct = 2;
4555 uint32_t invalid_allele_code_seen = 0;
4556 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
4557 // a lot of this is redundant with write_pvar(), may want to factor the
4558 // commonalities out
4559 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
4560 if (variant_uidx >= chr_end) {
4561 do {
4562 ++chr_fo_idx;
4563 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
4564 } while (variant_uidx >= chr_end);
4565 uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
4566 is_x = (chr_idx == cip->xymt_codes[kChrOffsetX]);
4567 is_haploid = IsSet(cip->haploid_mask, chr_idx);
4568 // forced --merge-par, with diploid male output (is_x NOT set, but
4569 // chromosome code is X/chrX)
4570 if ((chr_idx == cip->xymt_codes[kChrOffsetPAR1]) || (chr_idx == cip->xymt_codes[kChrOffsetPAR2])) {
4571 chr_idx = cip->xymt_codes[kChrOffsetX];
4572 }
4573 char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
4574 *chr_name_end = '\t';
4575 chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
4576 // bugfix (3 May 2018): forgot to update hds_inttext_blen[]
4577 hds_inttext_blen[0] = 4;
4578 hds_inttext_blen[1] = 8;
4579 hds_inttext_blen[2] = 4;
4580 hds_inttext_blen[3] = 4;
4581 if (is_haploid) {
4582 if (is_x) {
4583 haploid_genotext_blen[0] = 4;
4584 haploid_genotext_blen[2] = 4;
4585 haploid_genotext_blen[3] = 4;
4586 } else {
4587 haploid_genotext_blen[0] = 2;
4588 haploid_genotext_blen[2] = 2;
4589 haploid_genotext_blen[3] = 2;
4590 hds_inttext_blen[0] = 2;
4591 hds_inttext_blen[1] = 4;
4592 hds_inttext_blen[2] = 2;
4593 hds_inttext_blen[3] = 2;
4594 }
4595 }
4596 }
4597 // #CHROM
4598 write_iter = memcpya(write_iter, chr_buf, chr_buf_blen);
4599
4600 // POS
4601 write_iter = u32toa_x(variant_bps[variant_uidx], '\t', write_iter);
4602
4603 // ID
4604 write_iter = strcpyax(write_iter, variant_ids[variant_uidx], '\t');
4605
4606 // REF, ALT
4607 uintptr_t allele_idx_offset_base = variant_uidx * 2;
4608 if (allele_idx_offsets) {
4609 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
4610 allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
4611 }
4612 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
4613 if (allele_permute) {
4614 ref_allele_idx = allele_permute[allele_idx_offset_base];
4615 alt1_allele_idx = allele_permute[allele_idx_offset_base + 1];
4616 }
4617 if (cur_alleles[ref_allele_idx] != dot_ptr) {
4618 write_iter = strcpya(write_iter, cur_alleles[ref_allele_idx]);
4619 if (!invalid_allele_code_seen) {
4620 invalid_allele_code_seen = !ValidVcfAlleleCode(cur_alleles[ref_allele_idx]);
4621 }
4622 } else {
4623 *write_iter++ = 'N';
4624 }
4625 *write_iter++ = '\t';
4626 write_iter = strcpya(write_iter, cur_alleles[alt1_allele_idx]);
4627 if (!invalid_allele_code_seen) {
4628 invalid_allele_code_seen = !ValidVcfAlleleCode(cur_alleles[alt1_allele_idx]);
4629 }
4630 if (unlikely(bgzfwrite_ck(writebuf_flush, &bgzf, &write_iter))) {
4631 goto ExportVcf_ret_WRITE_FAIL;
4632 }
4633 if (allele_ct > 2) {
4634 for (uint32_t cur_allele_uidx = 0; cur_allele_uidx != allele_ct; ++cur_allele_uidx) {
4635 if ((cur_allele_uidx == ref_allele_idx) || (cur_allele_uidx == alt1_allele_idx)) {
4636 // if this is noticeably suboptimal, have two loops, with inner
4637 // loop going up to cur_allele_stop.
4638 // (also wrap this in a function, this comes up a bunch of times)
4639 continue;
4640 }
4641 *write_iter++ = ',';
4642 write_iter = strcpya(write_iter, cur_alleles[cur_allele_uidx]);
4643 if (!invalid_allele_code_seen) {
4644 invalid_allele_code_seen = !ValidVcfAlleleCode(cur_alleles[cur_allele_uidx]);
4645 }
4646 if (unlikely(bgzfwrite_ck(writebuf_flush, &bgzf, &write_iter))) {
4647 goto ExportVcf_ret_WRITE_FAIL;
4648 }
4649 }
4650 }
4651
4652 // QUAL
4653 *write_iter++ = '\t';
4654 if ((!pvar_qual_present) || (!IsSet(pvar_qual_present, variant_uidx))) {
4655 *write_iter++ = '.';
4656 } else {
4657 write_iter = ftoa_g(pvar_quals[variant_uidx], write_iter);
4658 }
4659
4660 // FILTER
4661 *write_iter++ = '\t';
4662 if ((!pvar_filter_present) || (!IsSet(pvar_filter_present, variant_uidx))) {
4663 *write_iter++ = '.';
4664 } else if (!IsSet(pvar_filter_npass, variant_uidx)) {
4665 write_iter = strcpya_k(write_iter, "PASS");
4666 } else {
4667 write_iter = strcpya(write_iter, pvar_filter_storage[variant_uidx]);
4668 }
4669
4670 // INFO
4671 *write_iter++ = '\t';
4672 const uint32_t is_pr = all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx));
4673 if (pvar_reload_line_iter) {
4674 reterr = PvarInfoReloadAndWrite(info_pr_flag_present, info_col_idx, variant_uidx, is_pr, &pvar_reload_txs, &pvar_reload_line_iter, &write_iter, &rls_variant_uidx);
4675 if (unlikely(reterr)) {
4676 goto ExportVcf_ret_TSTREAM_FAIL;
4677 }
4678 } else {
4679 if (is_pr) {
4680 write_iter = strcpya_k(write_iter, "PR");
4681 } else {
4682 *write_iter++ = '.';
4683 }
4684 }
4685
4686 // FORMAT
4687 if (!ds_only) {
4688 write_iter = strcpya_k(write_iter, "\tGT");
4689 }
4690
4691 // could defensively zero out more counts
4692 pgv.dosage_ct = 0;
4693 pgv.dphase_ct = 0;
4694 uint32_t inner_loop_last = kBitsPerWordD2 - 1;
4695 if (allele_ct == 2) {
4696 if (!some_phased) {
4697 // biallelic, nothing phased in entire file
4698 // (technically possible for dosage-phase to be present, if no
4699 // hardcalls are phased and HDS output not requested)
4700 if (!write_some_dosage) {
4701 reterr = PgrGet(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgv.genovec);
4702 } else {
4703 reterr = PgrGetD(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &(pgv.dosage_ct));
4704 }
4705 if (unlikely(reterr)) {
4706 PgenErrPrintNV(reterr, variant_uidx);
4707 goto ExportVcf_ret_1;
4708 }
4709 if (!alt1_allele_idx) {
4710 // assumes biallelic
4711 GenovecInvertUnsafe(sample_ct, pgv.genovec);
4712 if (pgv.dosage_ct) {
4713 BiallelicDosage16Invert(pgv.dosage_ct, pgv.dosage_main);
4714 }
4715 }
4716 if ((!pgv.dosage_ct) && (!ds_force)) {
4717 if (!is_haploid) {
4718 // always 4 bytes wide, exploit that
4719 GenoarrLookup256x4bx4(pgv.genovec, basic_genotext4, sample_ct, write_iter);
4720 write_iter = &(write_iter[sample_ct * 4]);
4721 } else {
4722 // chrX: male homozygous/missing calls use only one character +
4723 // tab
4724 // other haploid/MT: this is true for nonmales too
4725 for (uint32_t widx = 0; ; ++widx) {
4726 if (widx >= sample_ctl2_m1) {
4727 if (widx > sample_ctl2_m1) {
4728 break;
4729 }
4730 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
4731 }
4732 uintptr_t genovec_word = pgv.genovec[widx];
4733 uint32_t sex_male_hw = is_x * (DowncastKWToHW(sex_male_collapsed)[widx]);
4734 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
4735 const uint32_t cur_geno = genovec_word & 3;
4736 const uint32_t cur_is_male = sex_male_hw & 1;
4737 memcpy(write_iter, &(basic_genotext[cur_geno]), 4);
4738 write_iter = &(write_iter[haploid_genotext_blen[cur_geno + cur_is_male * 4]]);
4739 genovec_word >>= 2;
4740 sex_male_hw >>= 1;
4741 }
4742 }
4743 }
4744 } else if ((!pgv.dosage_ct) && ds_only && (!is_haploid)) {
4745 write_iter = strcpya_k(write_iter, "\tDS");
4746 // always 2 bytes wide, exploit that
4747 GenoarrLookup256x2bx4(pgv.genovec, ds_inttext4, sample_ct, write_iter);
4748 write_iter = &(write_iter[sample_ct * 2]);
4749 } else {
4750 // some dosages present, or {H}DS-force; unphased
4751 if (write_ds) {
4752 if (ds_only) {
4753 write_iter = strcpya_k(write_iter, "\tDS");
4754 } else {
4755 write_iter = strcpya_k(write_iter, ":DS");
4756 if (hds_force) {
4757 write_iter = strcpya_k(write_iter, ":HDS");
4758 }
4759 }
4760 } else {
4761 write_iter = strcpya_k(write_iter, ":GP");
4762 }
4763 Dosage* dosage_main_iter = pgv.dosage_main;
4764 uint32_t dosage_present_hw = 0;
4765 if (!is_haploid) {
4766 // autosomal diploid, unphased
4767 for (uint32_t widx = 0; ; ++widx) {
4768 if (widx >= sample_ctl2_m1) {
4769 if (widx > sample_ctl2_m1) {
4770 break;
4771 }
4772 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
4773 }
4774 uintptr_t genovec_word = pgv.genovec[widx];
4775 if (pgv.dosage_ct) {
4776 dosage_present_hw = DowncastWToHW(pgv.dosage_present)[widx];
4777 }
4778 if (ds_only) {
4779 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
4780 const uint32_t cur_geno = genovec_word & 3;
4781 if (dosage_present_hw & 1) {
4782 *write_iter++ = '\t';
4783 const uint32_t dosage_int = *dosage_main_iter++;
4784 write_iter = PrintDiploidVcfDosage(dosage_int, write_ds, write_iter);
4785 } else {
4786 write_iter = memcpya_k(write_iter, &(ds_inttext[cur_geno]), 2);
4787 }
4788 genovec_word >>= 2;
4789 dosage_present_hw >>= 1;
4790 }
4791 } else {
4792 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
4793 const uint32_t cur_geno = genovec_word & 3;
4794 write_iter = memcpya(write_iter, &(basic_genotext[cur_geno]), 4);
4795 if (dosage_present_hw & 1) {
4796 *write_iter++ = ':';
4797 const uint32_t dosage_int = *dosage_main_iter++;
4798 write_iter = PrintDiploidVcfDosage(dosage_int, write_ds, write_iter);
4799 if (hds_force) {
4800 *write_iter++ = ':';
4801 char* write_iter2 = PrintHaploidNonintDosage(dosage_int, write_iter);
4802 write_iter2[0] = ',';
4803 write_iter = memcpya(&(write_iter2[1]), write_iter, write_iter2 - write_iter);
4804 }
4805 } else if (ds_force) {
4806 write_iter = memcpya_k(write_iter, &(ds_inttext[cur_geno]), 2);
4807 if (hds_force) {
4808 memcpy(write_iter, &(hds_inttext[cur_geno]), 8);
4809 write_iter = &(write_iter[hds_inttext_blen[cur_geno]]);
4810 }
4811 }
4812 genovec_word >>= 2;
4813 dosage_present_hw >>= 1;
4814 }
4815 }
4816 }
4817 } else {
4818 // at least partly haploid, unphased
4819 const char ds_prechar = ds_only? '\t' : ':';
4820 uint32_t sex_male_hw = 0;
4821 for (uint32_t widx = 0; ; ++widx) {
4822 if (widx >= sample_ctl2_m1) {
4823 if (widx > sample_ctl2_m1) {
4824 break;
4825 }
4826 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
4827 }
4828 uintptr_t genovec_word = pgv.genovec[widx];
4829 if (is_x) {
4830 sex_male_hw = DowncastKWToHW(sex_male_collapsed)[widx];
4831 }
4832 if (pgv.dosage_ct) {
4833 dosage_present_hw = DowncastWToHW(pgv.dosage_present)[widx];
4834 }
4835 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
4836 const uint32_t cur_geno = genovec_word & 3;
4837 const uint32_t cur_is_male = sex_male_hw & 1;
4838 const uint32_t cur_genotext_blen = haploid_genotext_blen[cur_geno + cur_is_male * 4];
4839 memcpy(write_iter, &(basic_genotext[cur_geno]), 4);
4840 write_iter = &(write_iter[cur_genotext_blen]);
4841 if (dosage_present_hw & 1) {
4842 *write_iter++ = ds_prechar;
4843 uint32_t dosage_int = *dosage_main_iter++;
4844 if (cur_genotext_blen == 2) {
4845 // render current hardcall as haploid
4846 if (write_ds) {
4847 char* write_iter2 = PrintHaploidNonintDosage(dosage_int, write_iter);
4848 if (hds_force) {
4849 write_iter2[0] = ':';
4850 write_iter2 = memcpya(&(write_iter2[1]), write_iter, write_iter2 - write_iter);
4851 }
4852 write_iter = write_iter2;
4853 } else {
4854 // GP
4855 write_iter = PrintHaploidNonintDosage(kDosageMax - dosage_int, write_iter);
4856 *write_iter++ = ',';
4857 write_iter = PrintHaploidNonintDosage(dosage_int, write_iter);
4858 }
4859 } else {
4860 // render current hardcall as diploid (female X, or het
4861 // haploid)
4862 write_iter = PrintDiploidVcfDosage(dosage_int, write_ds, write_iter);
4863 if (hds_force) {
4864 *write_iter++ = ':';
4865 char* write_iter2 = PrintHaploidNonintDosage(dosage_int, write_iter);
4866 if (is_x && (!cur_is_male)) {
4867 // but do not render phased-dosage as diploid in het
4868 // haploid case
4869 write_iter2[0] = ',';
4870 write_iter2 = memcpya(&(write_iter2[1]), write_iter, write_iter2 - write_iter);
4871 }
4872 write_iter = write_iter2;
4873 }
4874 }
4875 } else if (ds_force) {
4876 write_iter = memcpya_k(write_iter, &(ds_inttext[cur_geno + 8 - 2 * cur_genotext_blen]), 2);
4877 if (hds_force) {
4878 memcpy(write_iter, &(hds_inttext[cur_geno]), 8);
4879 write_iter = &(write_iter[hds_inttext_blen[cur_is_male * 4 + cur_geno]]);
4880 }
4881 }
4882 genovec_word >>= 2;
4883 sex_male_hw >>= 1;
4884 dosage_present_hw >>= 1;
4885 }
4886 }
4887 }
4888 }
4889 } else {
4890 // biallelic, phased
4891 if (!write_some_dosage) {
4892 reterr = PgrGetP(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgv.genovec, pgv.phasepresent, pgv.phaseinfo, &(pgv.phasepresent_ct));
4893 } else {
4894 reterr = PgrGetDp(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &pgv);
4895 }
4896 if (unlikely(reterr)) {
4897 PgenErrPrintNV(reterr, variant_uidx);
4898 goto ExportVcf_ret_1;
4899 }
4900 if (!alt1_allele_idx) {
4901 // assumes biallelic
4902 GenovecInvertUnsafe(sample_ct, pgv.genovec);
4903 if (pgv.phasepresent_ct) {
4904 BitvecInvert(sample_ctl, pgv.phaseinfo);
4905 }
4906 if (pgv.dosage_ct) {
4907 BiallelicDosage16Invert(pgv.dosage_ct, pgv.dosage_main);
4908 if (pgv.dphase_ct) {
4909 BiallelicDphase16Invert(pgv.dphase_ct, pgv.dphase_delta);
4910 }
4911 }
4912 }
4913 // little point in trying to optimize this case, thanks to
4914 // prev_phased. Instead, we might want to have a fast path for the
4915 // all-phased case.
4916 if (!pgv.phasepresent_ct) {
4917 ZeroWArr(sample_ctl, pgv.phasepresent);
4918 }
4919 if ((!pgv.dosage_ct) && (!ds_force)) {
4920 if (!is_haploid) {
4921 ZeroTrailingNyps(sample_ct, pgv.genovec);
4922 UpdateVcfPrevPhased(pgv.genovec, pgv.phasepresent, sample_ct, prev_phased);
4923 BitvecAnd(pgv.phasepresent, sample_ctl, pgv.phaseinfo);
4924 VcfPhaseLookup4b(pgv.genovec, prev_phased, pgv.phaseinfo, phased_genotext2, sample_ct, write_iter);
4925 write_iter = &(write_iter[sample_ct * 4]);
4926 } else {
4927 uint32_t is_male_hw = 0;
4928 for (uint32_t widx = 0; ; ++widx) {
4929 if (widx >= sample_ctl2_m1) {
4930 if (widx > sample_ctl2_m1) {
4931 break;
4932 }
4933 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
4934 }
4935 uintptr_t genovec_word = pgv.genovec[widx];
4936 if (is_x) {
4937 is_male_hw = DowncastKWToHW(sex_male_collapsed)[widx];
4938 }
4939 uint32_t prev_phased_halfword = DowncastWToHW(prev_phased)[widx];
4940
4941 const uint32_t phasepresent_hw = DowncastWToHW(pgv.phasepresent)[widx];
4942 const uint32_t phaseinfo_hw = DowncastWToHW(pgv.phaseinfo)[widx];
4943 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
4944 const uint32_t cur_geno = genovec_word & 3;
4945 const uint32_t cur_is_male = is_male_hw & 1;
4946 const uint32_t cur_blen = haploid_genotext_blen[cur_geno + cur_is_male * 4];
4947 memcpy(write_iter, &(basic_genotext[cur_geno]), 4);
4948 write_iter = &(write_iter[cur_blen]);
4949 if (cur_blen == 4) {
4950 if (cur_geno == 1) {
4951 // a bit redundant with how is_male_hw is handled, but
4952 // updating this on every loop iteration doesn't seem
4953 // better
4954 const uint32_t cur_shift = (1U << sample_idx_lowbits);
4955 if (phasepresent_hw & cur_shift) {
4956 prev_phased_halfword |= cur_shift;
4957 if (phaseinfo_hw & cur_shift) {
4958 memcpy(&(write_iter[-4]), "\t1|0", 4);
4959 } else {
4960 write_iter[-2] = '|';
4961 }
4962 } else {
4963 prev_phased_halfword &= ~cur_shift;
4964 }
4965 } else if ((prev_phased_halfword >> sample_idx_lowbits) & 1) {
4966 write_iter[-2] = '|';
4967 }
4968 }
4969 genovec_word >>= 2;
4970 is_male_hw >>= 1;
4971 }
4972 DowncastWToHW(prev_phased)[widx] = prev_phased_halfword;
4973 }
4974 }
4975 } else {
4976 // both dosage (or {H}DS-force) and phase present
4977 if (write_ds) {
4978 write_iter = strcpya_k(write_iter, ":DS");
4979 if (hds_force || pgv.dphase_ct ||
4980 (write_hds && pgv.phasepresent_ct && pgv.dosage_ct && (!IntersectionIsEmpty(pgv.phasepresent, pgv.dosage_present, sample_ctl)))) {
4981 write_iter = strcpya_k(write_iter, ":HDS");
4982 // dphase_present can be nullptr, so we zero-initialize
4983 // dphase_present_hw and never refresh it when dphase_ct == 0.
4984 }
4985 } else {
4986 write_iter = strcpya_k(write_iter, ":GP");
4987 }
4988 Dosage* dosage_main_iter = pgv.dosage_main;
4989 SDosage* dphase_delta_iter = pgv.dphase_delta;
4990 uint32_t dosage_present_hw = 0;
4991 uint32_t dphase_present_hw = 0;
4992 if (!is_haploid) {
4993 for (uint32_t widx = 0; ; ++widx) {
4994 if (widx >= sample_ctl2_m1) {
4995 if (widx > sample_ctl2_m1) {
4996 break;
4997 }
4998 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
4999 }
5000 uintptr_t genovec_word = pgv.genovec[widx];
5001 uint32_t prev_phased_halfword = DowncastWToHW(prev_phased)[widx];
5002 const uint32_t phasepresent_hw = DowncastWToHW(pgv.phasepresent)[widx];
5003 const uint32_t phaseinfo_hw = DowncastWToHW(pgv.phaseinfo)[widx];
5004 if (pgv.dosage_ct) {
5005 dosage_present_hw = DowncastWToHW(pgv.dosage_present)[widx];
5006 if (pgv.dphase_ct) {
5007 dphase_present_hw = DowncastWToHW(pgv.dphase_present)[widx];
5008 }
5009 }
5010 uint32_t cur_shift = 1;
5011 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
5012 const uint32_t cur_geno = genovec_word & 3;
5013 write_iter = memcpya(write_iter, &(basic_genotext[cur_geno]), 4);
5014 if (cur_geno == 1) {
5015 if (phasepresent_hw & cur_shift) {
5016 prev_phased_halfword |= cur_shift;
5017 if (phaseinfo_hw & cur_shift) {
5018 memcpy(&(write_iter[-4]), "\t1|0", 4);
5019 }
5020 } else {
5021 prev_phased_halfword &= ~cur_shift;
5022 }
5023 }
5024 if (prev_phased_halfword & cur_shift) {
5025 write_iter[-2] = '|';
5026 }
5027 if (dosage_present_hw & cur_shift) {
5028 *write_iter++ = ':';
5029 const uint32_t dosage_int = *dosage_main_iter++;
5030 write_iter = PrintDiploidVcfDosage(dosage_int, write_ds, write_iter);
5031 // bugfix (29 May 2018): don't print HDS field if not
5032 // requested
5033 if (write_hds) {
5034 if ((phasepresent_hw | dphase_present_hw) & cur_shift) {
5035 int32_t cur_dphase_delta;
5036 if (dphase_present_hw & cur_shift) {
5037 cur_dphase_delta = *dphase_delta_iter++;
5038 } else {
5039 cur_dphase_delta = DosageHomdist(dosage_int);
5040 if (!(phaseinfo_hw & cur_shift)) {
5041 cur_dphase_delta = -cur_dphase_delta;
5042 }
5043 }
5044 *write_iter++ = ':';
5045 write_iter = PrintHdsPair(dosage_int, cur_dphase_delta, write_iter);
5046 } else if (hds_force) {
5047 *write_iter++ = ':';
5048 char* write_iter2 = PrintHaploidNonintDosage(dosage_int, write_iter);
5049 write_iter2[0] = ',';
5050 write_iter = memcpya(&(write_iter2[1]), write_iter, write_iter2 - write_iter);
5051 }
5052 }
5053 } else if (ds_force) {
5054 write_iter = memcpya_k(write_iter, &(ds_inttext[cur_geno]), 2);
5055 if (hds_force) {
5056 uint32_t hds_inttext_index = cur_geno;
5057 uint32_t tmp_blen = hds_inttext_blen[cur_geno];
5058 if (phasepresent_hw & cur_shift) {
5059 // do we want to remove this branch? doubt it's
5060 // worthwhile since variable-length memcpy will branch
5061 // anyway...
5062 hds_inttext_index = 4 + ((phaseinfo_hw >> sample_idx_lowbits) & 1);
5063 tmp_blen = 4;
5064 }
5065 memcpy(write_iter, &(hds_inttext[hds_inttext_index]), 8);
5066 write_iter = &(write_iter[tmp_blen]);
5067 }
5068 }
5069 genovec_word >>= 2;
5070 cur_shift <<= 1;
5071 }
5072 DowncastWToHW(prev_phased)[widx] = prev_phased_halfword;
5073 }
5074 } else {
5075 // dosage (or {H}DS-force) and phase present, partly/fully
5076 // haploid
5077 uint32_t is_male_hw = 0;
5078 for (uint32_t widx = 0; ; ++widx) {
5079 if (widx >= sample_ctl2_m1) {
5080 if (widx > sample_ctl2_m1) {
5081 break;
5082 }
5083 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
5084 }
5085 uintptr_t genovec_word = pgv.genovec[widx];
5086 if (is_x) {
5087 is_male_hw = DowncastKWToHW(sex_male_collapsed)[widx];
5088 }
5089 uint32_t prev_phased_halfword = DowncastWToHW(prev_phased)[widx];
5090 const uint32_t phasepresent_hw = DowncastWToHW(pgv.phasepresent)[widx];
5091 const uint32_t phaseinfo_hw = DowncastWToHW(pgv.phaseinfo)[widx];
5092 if (pgv.dosage_ct) {
5093 dosage_present_hw = DowncastWToHW(pgv.dosage_present)[widx];
5094 if (pgv.dphase_ct) {
5095 dphase_present_hw = DowncastWToHW(pgv.dphase_present)[widx];
5096 }
5097 }
5098 uint32_t cur_shift = 1;
5099 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
5100 const uint32_t cur_geno = genovec_word & 3;
5101 const uint32_t cur_is_male = is_male_hw & 1;
5102 const uint32_t cur_blen = haploid_genotext_blen[cur_geno + cur_is_male * 4];
5103 memcpy(write_iter, &(basic_genotext[cur_geno]), 4);
5104 write_iter = &(write_iter[cur_blen]);
5105 if (cur_blen == 4) {
5106 // render current hardcall as diploid (chrX nonmale, or het
5107 // haploid)
5108 if (cur_geno == 1) {
5109 if (phasepresent_hw & cur_shift) {
5110 prev_phased_halfword |= cur_shift;
5111 if (phaseinfo_hw & cur_shift) {
5112 memcpy(&(write_iter[-4]), "\t1|0", 4);
5113 }
5114 } else {
5115 prev_phased_halfword &= ~cur_shift;
5116 }
5117 }
5118 if (prev_phased_halfword & cur_shift) {
5119 write_iter[-2] = '|';
5120 }
5121 if (dosage_present_hw & cur_shift) {
5122 *write_iter++ = ':';
5123 const uint32_t dosage_int = *dosage_main_iter++;
5124 write_iter = PrintDiploidVcfDosage(dosage_int, write_ds, write_iter);
5125 if (write_hds) {
5126 if ((phasepresent_hw | dphase_present_hw) & cur_shift) {
5127 int32_t cur_dphase_delta;
5128 if (dphase_present_hw & cur_shift) {
5129 cur_dphase_delta = *dphase_delta_iter++;
5130 } else {
5131 cur_dphase_delta = DosageHomdist(dosage_int);
5132 if (!(phaseinfo_hw & cur_shift)) {
5133 cur_dphase_delta = -cur_dphase_delta;
5134 }
5135 }
5136 *write_iter++ = ':';
5137 write_iter = PrintHdsPair(dosage_int, cur_dphase_delta, write_iter);
5138 } else if (hds_force) {
5139 *write_iter++ = ':';
5140 char* write_iter2 = PrintHaploidNonintDosage(dosage_int, write_iter);
5141 // do not render phased-dosage as diploid in unphased
5142 // het haploid case
5143 if (is_x && (!cur_is_male)) {
5144 write_iter2[0] = ',';
5145 write_iter2 = memcpya(&(write_iter2[1]), write_iter, write_iter2 - write_iter);
5146 }
5147 write_iter = write_iter2;
5148 }
5149 }
5150 } else if (ds_force) {
5151 write_iter = memcpya_k(write_iter, &(ds_inttext[cur_geno]), 2);
5152 if (hds_force) {
5153 uint32_t hds_inttext_index = cur_geno;
5154 uint32_t tmp_blen;
5155 if (phasepresent_hw & cur_shift) {
5156 // do we want to remove this branch? doubt it's
5157 // worthwhile since variable-length memcpy will
5158 // branch anyway...
5159 hds_inttext_index = 4 + ((phaseinfo_hw >> sample_idx_lowbits) & 1);
5160 tmp_blen = 4;
5161 } else {
5162 // do not render phased-dosage as diploid in het
5163 // haploid case
5164 tmp_blen = hds_inttext_blen[cur_is_male * 4 + cur_geno];
5165 }
5166 memcpy(write_iter, &(hds_inttext[hds_inttext_index]), 8);
5167 write_iter = &(write_iter[tmp_blen]);
5168 }
5169 }
5170 } else {
5171 // render current hardcall as haploid
5172 // (can't get here for hardcall-phased)
5173 if (dosage_present_hw & cur_shift) {
5174 *write_iter++ = ':';
5175 const uint32_t dosage_int = *dosage_main_iter++;
5176 if (write_ds) {
5177 write_iter = PrintHaploidNonintDosage(dosage_int, write_iter);
5178 if (dphase_present_hw & cur_shift) {
5179 // explicit dosage-phase, so render HDS as diploid
5180 const int32_t cur_dphase_delta = *dphase_delta_iter++;
5181 *write_iter++ = ':';
5182 write_iter = PrintHdsPair(dosage_int, cur_dphase_delta, write_iter);
5183 } else if (hds_force) {
5184 *write_iter++ = ':';
5185 write_iter = PrintHaploidNonintDosage(dosage_int, write_iter);
5186 }
5187 } else {
5188 // GP
5189 write_iter = PrintHaploidNonintDosage(kDosageMax - dosage_int, write_iter);
5190 *write_iter++ = ',';
5191 write_iter = PrintHaploidNonintDosage(dosage_int, write_iter);
5192 }
5193 } else if (ds_force) {
5194 write_iter = memcpya_k(write_iter, &(ds_inttext[cur_geno + 4]), 2);
5195 if (hds_force) {
5196 memcpy(write_iter, &(hds_inttext[cur_geno]), 8);
5197 write_iter = &(write_iter[hds_inttext_blen[cur_geno + 4]]);
5198 }
5199 }
5200 }
5201 genovec_word >>= 2;
5202 is_male_hw >>= 1;
5203 cur_shift <<= 1;
5204 }
5205 DowncastWToHW(prev_phased)[widx] = prev_phased_halfword;
5206 }
5207 }
5208 }
5209 }
5210 } else {
5211 // multiallelic cases
5212 // multiallelic dosage not supported yet
5213 // don't bother supporting multiallelic GP export when dosages present:
5214 // no clean way to handle e.g. dosage(A) = dosage(C) = dosage(G) =
5215 // dosage(T)=0.5
5216 if (ref_allele_idx || (alt1_allele_idx != 1)) {
5217 // todo: rotation function that can also be used by --make-pgen
5218 // maybe add a PgrGetM2() function too
5219 logputs("\n");
5220 logerrputs("Error: VCF-export multiallelic rotation is under development.\n");
5221 reterr = kPglRetNotYetSupported;
5222 goto ExportVcf_ret_1;
5223 }
5224 if (!some_phased) {
5225 reterr = PgrGetM(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &pgv);
5226 if (unlikely(reterr)) {
5227 PgenErrPrintNV(reterr, variant_uidx);
5228 goto ExportVcf_ret_1;
5229 }
5230 if (!ds_force) {
5231 if (!is_haploid) {
5232 if (allele_ct <= 10) {
5233 GenoarrLookup256x4bx4(pgv.genovec, basic_genotext4, sample_ct, write_iter);
5234 if (pgv.patch_01_ct) {
5235 // Patch some 0/1 entries to 0/x.
5236 char* genotext_offset3 = &(write_iter[3]);
5237 uintptr_t sample_idx_base = 0;
5238 uintptr_t patch_01_bits = pgv.patch_01_set[0];
5239 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
5240 const uintptr_t sample_idx = BitIter1(pgv.patch_01_set, &sample_idx_base, &patch_01_bits);
5241 genotext_offset3[4 * sample_idx] = '0' + pgv.patch_01_vals[uii];
5242 }
5243 }
5244 if (pgv.patch_10_ct) {
5245 // Patch some 1/1 entries to x/y.
5246 char* genotext_offset1 = &(write_iter[1]);
5247 uintptr_t sample_idx_base = 0;
5248 uintptr_t patch_10_bits = pgv.patch_10_set[0];
5249 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
5250 const uintptr_t sample_idx = BitIter1(pgv.patch_10_set, &sample_idx_base, &patch_10_bits);
5251 genotext_offset1[4 * sample_idx] = '0' + pgv.patch_10_vals[2 * uii];
5252 genotext_offset1[4 * sample_idx + 2] = '0' + pgv.patch_10_vals[2 * uii + 1];
5253 }
5254 }
5255 write_iter = &(write_iter[sample_ct * 4]);
5256 } else {
5257 if (!pgv.patch_01_ct) {
5258 ZeroWArr(sample_ctl, pgv.patch_01_set);
5259 }
5260 if (!pgv.patch_10_ct) {
5261 ZeroWArr(sample_ctl, pgv.patch_10_set);
5262 }
5263 const AlleleCode* patch_01_vals_iter = pgv.patch_01_vals;
5264 const AlleleCode* patch_10_vals_iter = pgv.patch_10_vals;
5265 for (uint32_t widx = 0; ; ++widx) {
5266 if (widx >= sample_ctl2_m1) {
5267 if (widx > sample_ctl2_m1) {
5268 break;
5269 }
5270 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
5271 }
5272 uintptr_t genovec_word = pgv.genovec[widx];
5273 uint32_t multiallelic_hw = (DowncastKWToHW(pgv.patch_01_set)[widx]) | (DowncastKWToHW(pgv.patch_10_set)[widx]);
5274 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
5275 const uint32_t cur_geno = genovec_word & 3;
5276 if (!(multiallelic_hw & 1)) {
5277 write_iter = memcpya(write_iter, &(basic_genotext[cur_geno]), 4);
5278 } else if (cur_geno == 1) {
5279 write_iter = strcpya_k(write_iter, "\t0/");
5280 const AlleleCode ac = *patch_01_vals_iter++;
5281 write_iter = u32toa(ac, write_iter);
5282 } else {
5283 AlleleCode ac = *patch_10_vals_iter++;
5284 *write_iter++ = '\t';
5285 write_iter = u32toa_x(ac, '/', write_iter);
5286 ac = *patch_10_vals_iter++;
5287 write_iter = u32toa(ac, write_iter);
5288 }
5289 genovec_word >>= 2;
5290 multiallelic_hw >>= 1;
5291 }
5292 }
5293 }
5294 } else {
5295 if (!pgv.patch_01_ct) {
5296 ZeroWArr(sample_ctl, pgv.patch_01_set);
5297 }
5298 if (!pgv.patch_10_ct) {
5299 ZeroWArr(sample_ctl, pgv.patch_10_set);
5300 }
5301 // at least partially haploid, !ds_force
5302 // We don't separately the allele_ct <= 10 vs. > 10 cases when
5303 // entries are already variable-width in the <= 10 case.
5304 const AlleleCode* patch_01_vals_iter = pgv.patch_01_vals;
5305 const AlleleCode* patch_10_vals_iter = pgv.patch_10_vals;
5306 for (uint32_t widx = 0; ; ++widx) {
5307 if (widx >= sample_ctl2_m1) {
5308 if (widx > sample_ctl2_m1) {
5309 break;
5310 }
5311 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
5312 }
5313 uintptr_t genovec_word = pgv.genovec[widx];
5314 uint32_t sex_male_hw = is_x * (DowncastKWToHW(sex_male_collapsed)[widx]);
5315 // no need to separate patch_01 and patch_10 since this
5316 // information is redundant with genovec_word contents
5317 uint32_t multiallelic_hw = (DowncastKWToHW(pgv.patch_01_set)[widx]) | (DowncastKWToHW(pgv.patch_10_set)[widx]);
5318 // probable todo: multiallelic_hw == 0 fast path, check
5319 // whether <= inner_loop_last vs. < inner_loop_end makes a
5320 // difference, etc.
5321 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
5322 const uint32_t cur_geno = genovec_word & 3;
5323 const uint32_t cur_is_male = sex_male_hw & 1;
5324 if (!(multiallelic_hw & 1)) {
5325 memcpy(write_iter, &(basic_genotext[cur_geno]), 4);
5326 write_iter = &(write_iter[haploid_genotext_blen[cur_geno + cur_is_male * 4]]);
5327 } else if (cur_geno == 1) {
5328 // always heterozygous, 4 characters
5329 write_iter = strcpya_k(write_iter, "\t0/");
5330 const AlleleCode ac = *patch_01_vals_iter++;
5331 write_iter = u32toa(ac, write_iter);
5332 } else {
5333 const AlleleCode ac0 = *patch_10_vals_iter++;
5334 const AlleleCode ac1 = *patch_10_vals_iter++;
5335 *write_iter++ = '\t';
5336 write_iter = u32toa(ac0, write_iter);
5337 if ((ac0 != ac1) || (haploid_genotext_blen[2 + cur_is_male * 4] == 4)) {
5338 *write_iter++ = '/';
5339 write_iter = u32toa(ac1, write_iter);
5340 }
5341 }
5342 genovec_word >>= 2;
5343 sex_male_hw >>= 1;
5344 multiallelic_hw >>= 1;
5345 }
5346 }
5347 }
5348 } else {
5349 if (!pgv.patch_01_ct) {
5350 ZeroWArr(sample_ctl, pgv.patch_01_set);
5351 }
5352 if (!pgv.patch_10_ct) {
5353 ZeroWArr(sample_ctl, pgv.patch_10_set);
5354 }
5355 // ds_force, !some_phased
5356 if (ds_only) {
5357 write_iter = strcpya_k(write_iter, "\tDS");
5358 } else {
5359 write_iter = strcpya_k(write_iter, ":DS");
5360 if (hds_force) {
5361 write_iter = strcpya_k(write_iter, ":HDS");
5362 }
5363 }
5364 const uint32_t allele_ct_m2 = allele_ct - 2;
5365 const AlleleCode* patch_01_vals_iter = pgv.patch_01_vals;
5366 const AlleleCode* patch_10_vals_iter = pgv.patch_10_vals;
5367 if (!is_haploid) {
5368 // DS-force, autosomal diploid, unphased, dosage_ct == 0
5369 for (uint32_t widx = 0; ; ++widx) {
5370 if (widx >= sample_ctl2_m1) {
5371 if (widx > sample_ctl2_m1) {
5372 break;
5373 }
5374 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
5375 }
5376 uintptr_t genovec_word = pgv.genovec[widx];
5377 uint32_t multiallelic_hw = (DowncastKWToHW(pgv.patch_01_set)[widx]) | (DowncastKWToHW(pgv.patch_10_set)[widx]);
5378 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
5379 const uint32_t cur_geno = genovec_word & 3;
5380 if (!(multiallelic_hw & 1)) {
5381 if (!ds_only) {
5382 write_iter = memcpya(write_iter, &(basic_genotext[cur_geno]), 4);
5383 }
5384 // DS
5385 write_iter = memcpya_k(write_iter, &(ds_inttext[cur_geno]), 2);
5386 if (cur_geno != 3) {
5387 // repeat ",0" if nonmissing
5388 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
5389 if (hds_force) {
5390 uint64_t cur_inttext = hds_inttext[cur_geno];
5391 const uint32_t hap_blen = hds_inttext_blen[cur_geno + 4];
5392 memcpy(write_iter, &cur_inttext, 4);
5393 write_iter = &(write_iter[hap_blen]);
5394 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
5395 cur_inttext = cur_inttext >> (8 * hap_blen);
5396 memcpy(write_iter, &cur_inttext, 4);
5397 write_iter = &(write_iter[hap_blen]);
5398 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
5399 }
5400 } else {
5401 if (hds_force) {
5402 write_iter = strcpya_k(write_iter, ":.,.");
5403 }
5404 }
5405 } else if (cur_geno == 1) {
5406 const AlleleCode ac = *patch_01_vals_iter++;
5407 write_iter = AppendVcfMultiallelicDsForce01(allele_ct_m2, ds_only, ds_force, ac, 0, write_iter);
5408 } else {
5409 const AlleleCode ac0 = *patch_10_vals_iter++;
5410 const AlleleCode ac1 = *patch_10_vals_iter++;
5411 if (ac0 != ac1) {
5412 write_iter = AppendVcfMultiallelicDsForce10Het(allele_ct_m2, ds_only, hds_force, ac0, ac1, 0, write_iter);
5413 } else {
5414 write_iter = AppendVcfMultiallelicDsForce10HomDiploid(allele_ct_m2, ds_only, hds_force, ac0, '/', write_iter);
5415 }
5416 }
5417 genovec_word >>= 2;
5418 multiallelic_hw >>= 1;
5419 }
5420 }
5421 } else {
5422 // DS-force, at least partly haploid, unphased
5423 uint32_t sex_male_hw = 0;
5424 for (uint32_t widx = 0; ; ++widx) {
5425 if (widx >= sample_ctl2_m1) {
5426 if (widx > sample_ctl2_m1) {
5427 break;
5428 }
5429 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
5430 }
5431 uintptr_t genovec_word = pgv.genovec[widx];
5432 if (is_x) {
5433 sex_male_hw = DowncastKWToHW(sex_male_collapsed)[widx];
5434 }
5435 uint32_t multiallelic_hw = (DowncastKWToHW(pgv.patch_01_set)[widx]) | (DowncastKWToHW(pgv.patch_10_set)[widx]);
5436 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
5437 const uint32_t cur_geno = genovec_word & 3;
5438 const uint32_t cur_is_male = sex_male_hw & 1;
5439 const uint32_t should_be_diploid = is_x && (!cur_is_male);
5440 if (!(multiallelic_hw & 1)) {
5441 const uint32_t cur_genotext_blen = haploid_genotext_blen[cur_geno + cur_is_male * 4];
5442 memcpy(write_iter, &(basic_genotext[cur_geno]), 4);
5443 write_iter = &(write_iter[cur_genotext_blen]);
5444 // DS
5445 write_iter = memcpya(write_iter, &(ds_inttext[cur_geno + 8 - 2 * cur_genotext_blen]), 2);
5446 if (cur_geno != 3) {
5447 // repeat ",0"
5448 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
5449 if (hds_force) {
5450 uint64_t cur_inttext = hds_inttext[cur_geno];
5451 const uint32_t hap_blen = hds_inttext_blen[4 + cur_geno];
5452 memcpy(write_iter, &cur_inttext, 4);
5453 write_iter = &(write_iter[hap_blen]);
5454 if (should_be_diploid) {
5455 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
5456 cur_inttext = cur_inttext >> (8 * hap_blen);
5457 memcpy(write_iter, &cur_inttext, 4);
5458 write_iter = &(write_iter[hap_blen]);
5459 }
5460 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
5461 }
5462 } else {
5463 if (hds_force) {
5464 strcpy_k(write_iter, ":.,.");
5465 write_iter = &(write_iter[2 + 2 * (is_x & (~cur_is_male))]);
5466 }
5467 }
5468 } else if (cur_geno == 1) {
5469 const AlleleCode ac = *patch_01_vals_iter++;
5470 write_iter = AppendVcfMultiallelicDsForce01(allele_ct_m2, ds_only, hds_force, ac, !should_be_diploid, write_iter);
5471 } else {
5472 const AlleleCode ac0 = *patch_10_vals_iter++;
5473 const AlleleCode ac1 = *patch_10_vals_iter++;
5474 if (ac0 != ac1) {
5475 write_iter = AppendVcfMultiallelicDsForce10Het(allele_ct_m2, ds_only, hds_force, ac0, ac1, !should_be_diploid, write_iter);
5476 } else if (haploid_genotext_blen[cur_geno + cur_is_male * 4] == 2) {
5477 write_iter = AppendVcfMultiallelicDsForce10Haploid(allele_ct_m2, ds_only, hds_force, ac0, write_iter);
5478 } else {
5479 write_iter = AppendVcfMultiallelicDsForce10HomDiploid(allele_ct_m2, ds_only, hds_force, ac0, '/', write_iter);
5480 }
5481 }
5482 genovec_word >>= 2;
5483 multiallelic_hw >>= 1;
5484 }
5485 }
5486 }
5487 }
5488 } else {
5489 // multiallelic, phased
5490 reterr = PgrGetMP(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &pgv);
5491 if (unlikely(reterr)) {
5492 PgenErrPrintNV(reterr, variant_uidx);
5493 goto ExportVcf_ret_1;
5494 }
5495 if (!pgv.patch_01_ct) {
5496 ZeroWArr(sample_ctl, pgv.patch_01_set);
5497 }
5498 if (!pgv.patch_10_ct) {
5499 ZeroWArr(sample_ctl, pgv.patch_10_set);
5500 }
5501 if (!pgv.phasepresent_ct) {
5502 ZeroWArr(sample_ctl, pgv.phasepresent);
5503 }
5504 const AlleleCode* patch_01_vals_iter = pgv.patch_01_vals;
5505 const AlleleCode* patch_10_vals_iter = pgv.patch_10_vals;
5506 if (!ds_force) {
5507 if (!is_haploid) {
5508 if (allele_ct <= 10) {
5509 for (uint32_t widx = 0; ; ++widx) {
5510 if (widx >= sample_ctl2_m1) {
5511 if (widx > sample_ctl2_m1) {
5512 break;
5513 }
5514 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
5515 }
5516 uintptr_t genovec_word = pgv.genovec[widx];
5517 const uint32_t multiallelic_hw = (DowncastKWToHW(pgv.patch_01_set)[widx]) | (DowncastKWToHW(pgv.patch_10_set)[widx]);
5518 uint32_t prev_phased_halfword = DowncastWToHW(prev_phased)[widx];
5519 const uint32_t phasepresent_hw = DowncastWToHW(pgv.phasepresent)[widx];
5520 const uint32_t phaseinfo_hw = DowncastWToHW(pgv.phaseinfo)[widx];
5521 uint32_t cur_shift = 1;
5522 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
5523 const uintptr_t cur_geno = genovec_word & 3;
5524 uint32_t cur_basic_genotext;
5525 if (!(multiallelic_hw & cur_shift)) {
5526 // usually "\t0/0", etc.
5527 cur_basic_genotext = basic_genotext[cur_geno];
5528 if (cur_geno == 1) {
5529 if (phasepresent_hw & cur_shift) {
5530 prev_phased_halfword |= cur_shift;
5531 if (phaseinfo_hw & cur_shift) {
5532 cur_basic_genotext ^= 0x1000100; // 0|1 -> 1|0
5533 }
5534 } else {
5535 prev_phased_halfword &= ~cur_shift;
5536 }
5537 }
5538 } else {
5539 AlleleCode ac0;
5540 AlleleCode ac1;
5541 if (cur_geno == 1) {
5542 ac0 = 0;
5543 ac1 = *patch_01_vals_iter++;
5544 } else {
5545 ac0 = *patch_10_vals_iter++;
5546 ac1 = *patch_10_vals_iter++;
5547 }
5548 if (ac0 != ac1) {
5549 if (phasepresent_hw & cur_shift) {
5550 prev_phased_halfword |= cur_shift;
5551 if (phaseinfo_hw & cur_shift) {
5552 const AlleleCode ac_swap = ac0;
5553 ac0 = ac1;
5554 ac1 = ac_swap;
5555 }
5556 } else {
5557 prev_phased_halfword &= ~cur_shift;
5558 }
5559 }
5560 cur_basic_genotext = 0x302f3009 + (ac0 * 256) + (ac1 * 0x1000000);
5561 }
5562 // '/' = ascii 47, '|' = ascii 124
5563 CAppendU32(cur_basic_genotext + 0x4d0000 * ((prev_phased_halfword >> sample_idx_lowbits) & 1), &write_iter);
5564 genovec_word >>= 2;
5565 cur_shift = cur_shift * 2;
5566 }
5567 DowncastWToHW(prev_phased)[widx] = prev_phased_halfword;
5568 }
5569 } else {
5570 // phased, allele_ct > 10, !is_haploid, !ds_force
5571 for (uint32_t widx = 0; ; ++widx) {
5572 if (widx >= sample_ctl2_m1) {
5573 if (widx > sample_ctl2_m1) {
5574 break;
5575 }
5576 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
5577 }
5578 uintptr_t genovec_word = pgv.genovec[widx];
5579 const uint32_t multiallelic_hw = (DowncastKWToHW(pgv.patch_01_set)[widx]) | (DowncastKWToHW(pgv.patch_10_set)[widx]);
5580 uint32_t prev_phased_halfword = DowncastWToHW(prev_phased)[widx];
5581 const uint32_t phasepresent_hw = DowncastWToHW(pgv.phasepresent)[widx];
5582 const uint32_t phaseinfo_hw = DowncastWToHW(pgv.phaseinfo)[widx];
5583 uint32_t cur_shift = 1;
5584 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
5585 const uint32_t cur_geno = genovec_word & 3;
5586 if (!(multiallelic_hw & cur_shift)) {
5587 write_iter = memcpya(write_iter, &(basic_genotext[cur_geno]), 4);
5588 if (cur_geno == 1) {
5589 if (phasepresent_hw & cur_shift) {
5590 prev_phased_halfword |= cur_shift;
5591 if (phaseinfo_hw & cur_shift) {
5592 memcpy(&(write_iter[-4]), "\t1|0", 4);
5593 }
5594 } else {
5595 prev_phased_halfword &= ~cur_shift;
5596 }
5597 }
5598 if (prev_phased_halfword & cur_shift) {
5599 write_iter[-2] = '|';
5600 }
5601 } else {
5602 AlleleCode ac0;
5603 AlleleCode ac1;
5604 if (cur_geno == 1) {
5605 ac0 = 0;
5606 ac1 = *patch_01_vals_iter++;
5607 } else {
5608 ac0 = *patch_10_vals_iter++;
5609 ac1 = *patch_10_vals_iter++;
5610 }
5611 if (ac0 != ac1) {
5612 if (phasepresent_hw & cur_shift) {
5613 prev_phased_halfword |= cur_shift;
5614 if (phaseinfo_hw & cur_shift) {
5615 const AlleleCode ac_swap = ac0;
5616 ac0 = ac1;
5617 ac1 = ac_swap;
5618 }
5619 } else {
5620 prev_phased_halfword &= ~cur_shift;
5621 }
5622 }
5623 *write_iter++ = '\t';
5624 write_iter = u32toa(ac0, write_iter);
5625 if (prev_phased_halfword & cur_shift) {
5626 *write_iter++ = '|';
5627 } else {
5628 *write_iter++ = '/';
5629 }
5630 write_iter = u32toa(ac1, write_iter);
5631 }
5632 genovec_word >>= 2;
5633 cur_shift = cur_shift * 2;
5634 }
5635 DowncastWToHW(prev_phased)[widx] = prev_phased_halfword;
5636 }
5637 }
5638 } else {
5639 // phased, at least partially haploid, !ds_force
5640 // probable todo: merge this with biallelic code, do the same for
5641 // other less-common biallelic-variable-width cases
5642 uint32_t is_male_hw = 0;
5643 for (uint32_t widx = 0; ; ++widx) {
5644 if (widx >= sample_ctl2_m1) {
5645 if (widx > sample_ctl2_m1) {
5646 break;
5647 }
5648 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
5649 }
5650 uintptr_t genovec_word = pgv.genovec[widx];
5651 if (is_x) {
5652 is_male_hw = DowncastKWToHW(sex_male_collapsed)[widx];
5653 }
5654 const uint32_t multiallelic_hw = (DowncastKWToHW(pgv.patch_01_set)[widx]) | (DowncastKWToHW(pgv.patch_10_set)[widx]);
5655 uint32_t prev_phased_halfword = DowncastWToHW(prev_phased)[widx];
5656 const uint32_t phasepresent_hw = DowncastWToHW(pgv.phasepresent)[widx];
5657 const uint32_t phaseinfo_hw = DowncastWToHW(pgv.phaseinfo)[widx];
5658 uint32_t cur_shift = 1;
5659 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
5660 const uint32_t cur_geno = genovec_word & 3;
5661 const uint32_t cur_is_male = is_male_hw & 1;
5662 if (!(multiallelic_hw & cur_shift)) {
5663 const uint32_t cur_blen = haploid_genotext_blen[cur_geno + cur_is_male * 4];
5664 memcpy(write_iter, &(basic_genotext[cur_geno]), 4);
5665 write_iter = &(write_iter[cur_blen]);
5666 if (cur_blen == 4) {
5667 if (cur_geno == 1) {
5668 if (phasepresent_hw & cur_shift) {
5669 prev_phased_halfword |= cur_shift;
5670 if (phaseinfo_hw & cur_shift) {
5671 memcpy(&(write_iter[-4]), "\t1|0", 4);
5672 } else {
5673 write_iter[-2] = '|';
5674 }
5675 } else {
5676 prev_phased_halfword &= ~cur_shift;
5677 }
5678 } else if ((prev_phased_halfword >> sample_idx_lowbits) & 1) {
5679 write_iter[-2] = '|';
5680 }
5681 }
5682 } else {
5683 AlleleCode ac0;
5684 AlleleCode ac1;
5685 if (cur_geno == 1) {
5686 ac0 = 0;
5687 ac1 = *patch_01_vals_iter++;
5688 } else {
5689 ac0 = *patch_10_vals_iter++;
5690 ac1 = *patch_10_vals_iter++;
5691 }
5692 *write_iter++ = '\t';
5693 if ((ac0 != ac1) || (haploid_genotext_blen[2 + cur_is_male * 4] == 4)) {
5694 if (ac0 != ac1) {
5695 if (phasepresent_hw & cur_shift) {
5696 prev_phased_halfword |= cur_shift;
5697 if (phaseinfo_hw & cur_shift) {
5698 const AlleleCode ac_swap = ac0;
5699 ac0 = ac1;
5700 ac1 = ac_swap;
5701 }
5702 } else {
5703 prev_phased_halfword &= ~cur_shift;
5704 }
5705 }
5706 write_iter = u32toa(ac0, write_iter);
5707 if (prev_phased_halfword & cur_shift) {
5708 *write_iter++ = '|';
5709 } else {
5710 *write_iter++ = '/';
5711 }
5712 }
5713 write_iter = u32toa(ac1, write_iter);
5714 }
5715 genovec_word >>= 2;
5716 is_male_hw >>= 1;
5717 cur_shift = cur_shift * 2;
5718 }
5719 DowncastWToHW(prev_phased)[widx] = prev_phased_halfword;
5720 }
5721 }
5722 } else {
5723 // phased, ds_force
5724 write_iter = strcpya_k(write_iter, ":DS");
5725 if (hds_force) {
5726 write_iter = strcpya_k(write_iter, ":HDS");
5727 }
5728 const uint32_t allele_ct_m2 = allele_ct - 2;
5729 if (!is_haploid) {
5730 for (uint32_t widx = 0; ; ++widx) {
5731 if (widx >= sample_ctl2_m1) {
5732 if (widx > sample_ctl2_m1) {
5733 break;
5734 }
5735 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
5736 }
5737 uintptr_t genovec_word = pgv.genovec[widx];
5738 const uint32_t multiallelic_hw = (DowncastKWToHW(pgv.patch_01_set)[widx]) | (DowncastKWToHW(pgv.patch_10_set)[widx]);
5739 uint32_t prev_phased_halfword = DowncastWToHW(prev_phased)[widx];
5740 const uint32_t phasepresent_hw = DowncastWToHW(pgv.phasepresent)[widx];
5741 const uint32_t phaseinfo_hw = DowncastWToHW(pgv.phaseinfo)[widx];
5742 uint32_t cur_shift = 1;
5743 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
5744 const uint32_t cur_geno = genovec_word & 3;
5745 if (!(multiallelic_hw & cur_shift)) {
5746 write_iter = memcpya(write_iter, &(basic_genotext[cur_geno]), 4);
5747 if (cur_geno == 1) {
5748 if (phasepresent_hw & cur_shift) {
5749 prev_phased_halfword |= cur_shift;
5750 if (phaseinfo_hw & cur_shift) {
5751 memcpy(&(write_iter[-4]), "\t1|0", 4);
5752 }
5753 } else {
5754 prev_phased_halfword &= ~cur_shift;
5755 }
5756 }
5757 if (prev_phased_halfword & cur_shift) {
5758 write_iter[-2] = '|';
5759 }
5760 // DS
5761 write_iter = memcpya_k(write_iter, &(ds_inttext[cur_geno]), 2);
5762 if (cur_geno != 3) {
5763 // repeat ",0" if nonmissing
5764 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
5765 if (hds_force) {
5766 uint32_t hds_inttext_index = cur_geno;
5767 // bugfix (8 Mar 2020): hap_blen was set incorrectly in
5768 // phased case
5769 uint32_t hap_blen = 2;
5770 if (phasepresent_hw & cur_shift) {
5771 hds_inttext_index = 4 + ((phaseinfo_hw >> sample_idx_lowbits) & 1);
5772 } else {
5773 hap_blen = hds_inttext_blen[hds_inttext_index] / 2;
5774 }
5775 uint64_t cur_inttext = hds_inttext[hds_inttext_index];
5776 memcpy(write_iter, &cur_inttext, 4);
5777 write_iter = &(write_iter[hap_blen]);
5778 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
5779 cur_inttext = cur_inttext >> (8 * hap_blen);
5780 memcpy(write_iter, &cur_inttext, 4);
5781 write_iter = &(write_iter[hap_blen]);
5782 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
5783 }
5784 } else {
5785 if (hds_force) {
5786 write_iter = strcpya_k(write_iter, ":.,.");
5787 }
5788 }
5789 } else {
5790 AlleleCode ac0;
5791 AlleleCode ac1;
5792 if (cur_geno == 1) {
5793 ac0 = 0;
5794 ac1 = *patch_01_vals_iter++;
5795 } else {
5796 ac0 = *patch_10_vals_iter++;
5797 ac1 = *patch_10_vals_iter++;
5798 }
5799 if (ac0 != ac1) {
5800 if (phasepresent_hw & cur_shift) {
5801 prev_phased_halfword |= cur_shift;
5802 write_iter = AppendVcfMultiallelicDsForcePhased(allele_ct_m2, hds_force, ac0, ac1, phaseinfo_hw & cur_shift, write_iter);
5803 } else {
5804 prev_phased_halfword &= ~cur_shift;
5805 if (!ac0) {
5806 write_iter = AppendVcfMultiallelicDsForce01(allele_ct_m2, 0, hds_force, ac1, 0, write_iter);
5807 } else {
5808 write_iter = AppendVcfMultiallelicDsForce10Het(allele_ct_m2, 0, hds_force, ac0, ac1, 0, write_iter);
5809 }
5810 }
5811 } else {
5812 write_iter = AppendVcfMultiallelicDsForce10HomDiploid(allele_ct_m2, 0, hds_force, ac0, (prev_phased_halfword & cur_shift)? '|' : '/', write_iter);
5813 }
5814 }
5815 genovec_word >>= 2;
5816 cur_shift <<= 1;
5817 }
5818 DowncastWToHW(prev_phased)[widx] = prev_phased_halfword;
5819 }
5820 } else {
5821 // dosage (or {H}DS-force) and phase present, partly/fully
5822 // haploid
5823 uint32_t is_male_hw = 0;
5824 for (uint32_t widx = 0; ; ++widx) {
5825 if (widx >= sample_ctl2_m1) {
5826 if (widx > sample_ctl2_m1) {
5827 break;
5828 }
5829 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
5830 }
5831 uintptr_t genovec_word = pgv.genovec[widx];
5832 if (is_x) {
5833 is_male_hw = DowncastKWToHW(sex_male_collapsed)[widx];
5834 }
5835 const uint32_t multiallelic_hw = (DowncastKWToHW(pgv.patch_01_set)[widx]) | (DowncastKWToHW(pgv.patch_10_set)[widx]);
5836 uint32_t prev_phased_halfword = DowncastWToHW(prev_phased)[widx];
5837 const uint32_t phasepresent_hw = DowncastWToHW(pgv.phasepresent)[widx];
5838 const uint32_t phaseinfo_hw = DowncastWToHW(pgv.phaseinfo)[widx];
5839 uint32_t cur_shift = 1;
5840 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
5841 const uint32_t cur_geno = genovec_word & 3;
5842 const uint32_t cur_is_male = is_male_hw & 1;
5843 const uint32_t should_be_diploid = is_x && (!cur_is_male);
5844 // bugfix (29 Dec 2018): need to check correct bit here
5845 if (!(multiallelic_hw & cur_shift)) {
5846 const uint32_t cur_blen = haploid_genotext_blen[cur_geno + cur_is_male * 4];
5847 memcpy(write_iter, &(basic_genotext[cur_geno]), 4);
5848 write_iter = &(write_iter[cur_blen]);
5849 if (cur_blen == 4) {
5850 // render current hardcall as diploid (chrX nonmale, or
5851 // het haploid)
5852 if (cur_geno == 1) {
5853 if (phasepresent_hw & cur_shift) {
5854 prev_phased_halfword |= cur_shift;
5855 if (phaseinfo_hw & cur_shift) {
5856 memcpy(&(write_iter[-4]), "\t1|0", 4);
5857 }
5858 } else {
5859 prev_phased_halfword &= ~cur_shift;
5860 }
5861 }
5862 if (prev_phased_halfword & cur_shift) {
5863 write_iter[-2] = '|';
5864 }
5865 // DS
5866 write_iter = memcpya_k(write_iter, &(ds_inttext[cur_geno]), 2);
5867 if (cur_geno != 3) {
5868 // repeat ",0"
5869 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
5870 if (hds_force) {
5871 uint32_t hds_inttext_index = cur_geno;
5872 uint32_t hap_blen = 2;
5873 if (phasepresent_hw & cur_shift) {
5874 hds_inttext_index = 4 + ((phaseinfo_hw >> sample_idx_lowbits) & 1);
5875 } else {
5876 hap_blen = hds_inttext_blen[hds_inttext_index] / 2;
5877 }
5878 uint64_t cur_inttext = hds_inttext[hds_inttext_index];
5879 memcpy(write_iter, &cur_inttext, 4);
5880 write_iter = &(write_iter[hap_blen]);
5881 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
5882 // Don't render unphased het haploid as diploid here
5883 if (should_be_diploid || (phasepresent_hw & cur_shift)) {
5884 cur_inttext = cur_inttext >> (8 * hap_blen);
5885 memcpy(write_iter, &cur_inttext, 4);
5886 write_iter = &(write_iter[hap_blen]);
5887 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
5888 }
5889 }
5890 } else {
5891 if (hds_force) {
5892 strcpy_k(write_iter, ":.,.");
5893 write_iter = &(write_iter[2 + 2 * should_be_diploid]);
5894 }
5895 }
5896 } else {
5897 // render current hardcall as haploid
5898 // (can't get here for hardcall-phased)
5899 write_iter = memcpya_k(write_iter, &(ds_inttext[cur_geno + 4]), 2);
5900 if (cur_geno != 3) {
5901 // repeat ",0"
5902 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
5903 if (hds_force) {
5904 // don't need to perform generic copy from
5905 // hds_inttext, since only possibilities are :0 and
5906 // :1
5907 CAppendU16(0x303a + 128 * cur_geno, &write_iter);
5908 write_iter = u16setsa(write_iter, 0x302c, allele_ct_m2);
5909 }
5910 } else {
5911 if (hds_force) {
5912 write_iter = strcpya_k(write_iter, ":.");
5913 }
5914 }
5915 }
5916 } else {
5917 AlleleCode ac0;
5918 AlleleCode ac1;
5919 if (cur_geno == 1) {
5920 ac0 = 0;
5921 ac1 = *patch_01_vals_iter++;
5922 } else {
5923 ac0 = *patch_10_vals_iter++;
5924 ac1 = *patch_10_vals_iter++;
5925 }
5926 if (ac0 != ac1) {
5927 if (phasepresent_hw & cur_shift) {
5928 prev_phased_halfword |= cur_shift;
5929 write_iter = AppendVcfMultiallelicDsForcePhased(allele_ct_m2, hds_force, ac0, ac1, phaseinfo_hw & cur_shift, write_iter);
5930 } else {
5931 prev_phased_halfword &= ~cur_shift;
5932 if (!ac0) {
5933 write_iter = AppendVcfMultiallelicDsForce01(allele_ct_m2, 0, hds_force, ac1, !should_be_diploid, write_iter);
5934 } else {
5935 write_iter = AppendVcfMultiallelicDsForce10Het(allele_ct_m2, 0, hds_force, ac0, ac1, !should_be_diploid, write_iter);
5936 }
5937 }
5938 } else {
5939 if (should_be_diploid) {
5940 write_iter = AppendVcfMultiallelicDsForce10HomDiploid(allele_ct_m2, 0, hds_force, ac0, (prev_phased_halfword & cur_shift)? '|' : '/', write_iter);
5941 } else {
5942 write_iter = AppendVcfMultiallelicDsForce10Haploid(allele_ct_m2, 0, hds_force, ac0, write_iter);
5943 }
5944 }
5945 }
5946 genovec_word >>= 2;
5947 is_male_hw >>= 1;
5948 cur_shift <<= 1;
5949 }
5950 DowncastWToHW(prev_phased)[widx] = prev_phased_halfword;
5951 }
5952 }
5953 }
5954 }
5955 }
5956 AppendBinaryEoln(&write_iter);
5957 if (unlikely(bgzfwrite_ck(writebuf_flush, &bgzf, &write_iter))) {
5958 goto ExportVcf_ret_WRITE_FAIL;
5959 }
5960 if (variant_idx >= next_print_variant_idx) {
5961 if (pct > 10) {
5962 putc_unlocked('\b', stdout);
5963 }
5964 pct = (variant_idx * 100LLU) / variant_ct;
5965 printf("\b\b%u%%", pct++);
5966 fflush(stdout);
5967 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
5968 }
5969 }
5970 if (unlikely(bgzfclose_flush(writebuf_flush, write_iter, &bgzf, &reterr))) {
5971 goto ExportVcf_ret_1;
5972 }
5973 if (pct > 10) {
5974 putc_unlocked('\b', stdout);
5975 }
5976 fputs("\b\b", stdout);
5977 logputs("done.\n");
5978 if (invalid_allele_code_seen) {
5979 logerrputs("Warning: At least one VCF allele code violates the official specification;\nother tools may not accept the file. (Valid codes must either start with a\n'<', only contain characters in {A,C,G,T,N,a,c,g,t,n}, be an isolated '*', or\nrepresent a breakend.)\n");
5980 }
5981 }
5982 while (0) {
5983 ExportVcf_ret_NOMEM:
5984 reterr = kPglRetNomem;
5985 break;
5986 ExportVcf_ret_TSTREAM_FAIL:
5987 TextStreamErrPrint(pvar_info_reload, &pvar_reload_txs);
5988 break;
5989 ExportVcf_ret_WRITE_FAIL:
5990 reterr = kPglRetWriteFail;
5991 break;
5992 ExportVcf_ret_MALFORMED_INPUT:
5993 reterr = kPglRetMalformedInput;
5994 break;
5995 ExportVcf_ret_INCONSISTENT_INPUT:
5996 reterr = kPglRetInconsistentInput;
5997 break;
5998 }
5999 ExportVcf_ret_1:
6000 CleanupTextStream2(pvar_info_reload, &pvar_reload_txs, &reterr);
6001 CleanupBgzfCompressStream(&bgzf, &reterr);
6002 BigstackReset(bigstack_mark);
6003 return reterr;
6004 }
6005
6006 PglErr AddToFifHtable(unsigned char* arena_bottom, const char* key, uint32_t htable_size, uint32_t key_slen, unsigned char prechar, unsigned char** arena_top_ptr, char** keys, uint32_t* htable, uint32_t* key_ct_ptr, uint32_t* cur_idx_ptr) {
6007 const uint32_t key_ct = *key_ct_ptr;
6008 const uint32_t cur_idx = IdHtableAddNnt(key, TO_CONSTCPCONSTP(keys), key_slen, htable_size, key_ct, htable);
6009 if (cur_idx == UINT32_MAX) {
6010 if (StoreStringAndPrecharAtEnd(arena_bottom, key, prechar, key_slen, arena_top_ptr, &(keys[key_ct]))) {
6011 return kPglRetNomem;
6012 }
6013 *cur_idx_ptr = key_ct;
6014 *key_ct_ptr = key_ct + 1;
6015 return kPglRetSuccess;
6016 }
6017 // Key already present. Only permit this if previous instance was FILTER and
6018 // this is INFO, or vice versa, or this is a FORMAT key.
6019 // INFO entries always have prechar bit 0 set and 3 unset, while FILTER
6020 // entries are the reverse. FORMAT keys have prechar == 0.
6021 char* existing_key = keys[cur_idx];
6022 const unsigned char new_prechar = S_CAST(unsigned char, existing_key[-1]) ^ prechar;
6023 if (unlikely(prechar && ((new_prechar & 9) != 9))) {
6024 char* write_iter = strcpya_k(g_logbuf, "Error: Multiple ");
6025 if (prechar & 8) {
6026 write_iter = strcpya_k(write_iter, "FILTER");
6027 } else {
6028 write_iter = strcpya_k(write_iter, "INFO");
6029 }
6030 *write_iter++ = ':';
6031 write_iter = memcpya(write_iter, key, key_slen);
6032 strcpy_k(write_iter, " header lines.\n");
6033 WordWrapB(0);
6034 logerrputsb();
6035 return kPglRetMalformedInput;
6036 }
6037 existing_key[-1] = new_prechar;
6038 // bugfix (3 Jan 2021): forgot to return this
6039 *cur_idx_ptr = cur_idx;
6040 return kPglRetSuccess;
6041 }
6042
6043 // Assumes ii is not in 0x80000000..0x80000007.
6044 char* AppendBcfTypedInt(int32_t ii, char* write_iter) {
6045 // 0x80..0x87 reserved
6046 if ((ii >= -120) && (ii < 128)) {
6047 *write_iter++ = 0x11;
6048 *write_iter++ = ii;
6049 return write_iter;
6050 }
6051 if ((ii >= -32760) && (ii < 32768)) {
6052 *write_iter++ = 0x12;
6053 int16_t sii = ii;
6054 memcpy(write_iter, &sii, sizeof(int16_t));
6055 return &(write_iter[2]);
6056 }
6057 *write_iter++ = 0x13;
6058 memcpy(write_iter, &ii, sizeof(int32_t));
6059 return &(write_iter[4]);
6060 }
6061
6062 char* AppendBcfVecType(uint32_t type_code, uint32_t len, char* write_iter) {
6063 if (len < 15) {
6064 *write_iter++ = (len << 4) | type_code;
6065 return write_iter;
6066 }
6067 *write_iter++ = 0xf0 | type_code;
6068 return AppendBcfTypedInt(len, write_iter);
6069 }
6070
6071 char* AppendBcfCountedString(const char* ss, uint32_t slen, char* write_iter) {
6072 write_iter = AppendBcfVecType(7, slen, write_iter);
6073 write_iter = memcpya(write_iter, ss, slen);
6074 return write_iter;
6075 }
6076
6077 static inline char* AppendBcfString(const char* ss, char* write_iter) {
6078 const uint32_t slen = strlen(ss);
6079 return AppendBcfCountedString(ss, slen, write_iter);
6080 }
6081
6082
6083 // TODO: SSE4-optimized versions of many of these functions. See
6084 // InverseMovemaskFF().
6085 // For each male non-het, replace the second GT byte with 0x81 (END_OF_VECTOR).
6086 void FixBcfMaleXGtPloidy(const uintptr_t* genovec, const uintptr_t* sex_male, uint32_t sample_ct, char* __restrict gt_start) {
6087 const Halfword* sex_male_alias = DowncastKWToHW(sex_male);
6088 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
6089 char* gt_offset1 = &(gt_start[1]);
6090 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
6091 const uint32_t cur_male_hw = sex_male_alias[widx];
6092 const uintptr_t geno_word = genovec[widx];
6093 const uint32_t geno_nonhet_hw = PackWordToHalfwordMask5555((~geno_word) | (geno_word >> 1));
6094 uint32_t male_nonhet_hw = cur_male_hw & geno_nonhet_hw;
6095 if (male_nonhet_hw) {
6096 char* cur_gt_offset1 = &(gt_offset1[widx * kBitsPerWord]);
6097 do {
6098 const uint32_t sample_idx_lowbits = ctzu32(male_nonhet_hw);
6099 cur_gt_offset1[sample_idx_lowbits * 2] = 0x81;
6100 male_nonhet_hw &= male_nonhet_hw - 1;
6101 } while (male_nonhet_hw);
6102 }
6103 }
6104 }
6105
6106 // For each female missing call, replace all byte(s) with 0x81 END_OF_VECTOR.
6107 void FixBcfFemaleYGtPloidy2(const uintptr_t* genovec, const uintptr_t* sex_female, uint32_t sample_ct, char* __restrict gt_start_orig) {
6108 const Halfword* sex_female_alias = DowncastKWToHW(sex_female);
6109 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
6110 const uint16_t end_of_vector = 0x8181;
6111 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
6112 const uint32_t cur_female_hw = sex_female_alias[widx];
6113 const uint32_t geno_missing_hw = Pack11ToHalfword(genovec[widx]);
6114 uint32_t female_missing_hw = cur_female_hw & geno_missing_hw;
6115 if (female_missing_hw) {
6116 unsigned char* cur_gt_start = CToUc(&(gt_start_orig[widx * kBitsPerWord]));
6117 do {
6118 const uint32_t sample_idx_lowbits = ctzu32(female_missing_hw);
6119 CopyToUnalignedOffsetU16(cur_gt_start, &end_of_vector, sample_idx_lowbits);
6120 female_missing_hw &= female_missing_hw - 1;
6121 } while (female_missing_hw);
6122 }
6123 }
6124 }
6125
6126 void FixBcfFemaleYGtPloidy1(const uintptr_t* genovec, const uintptr_t* sex_female, uint32_t sample_ct, char* __restrict gt_start) {
6127 const Halfword* sex_female_alias = DowncastKWToHW(sex_female);
6128 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
6129 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
6130 const uint32_t cur_female_hw = sex_female_alias[widx];
6131 const uint32_t geno_missing_hw = Pack11ToHalfword(genovec[widx]);
6132 uint32_t female_missing_hw = cur_female_hw & geno_missing_hw;
6133 if (female_missing_hw) {
6134 char* cur_gt_start = &(gt_start[widx * kBitsPerWordD2]);
6135 do {
6136 const uint32_t sample_idx_lowbits = ctzu32(female_missing_hw);
6137 cur_gt_start[sample_idx_lowbits] = 0x81;
6138 female_missing_hw &= female_missing_hw - 1;
6139 } while (female_missing_hw);
6140 }
6141 }
6142 }
6143
6144 void FillBcfDsPloidy1(const PgenVariant* pgvp, const uintptr_t* __restrict sex_female, const uint32_t* __restrict ds_y_genobytes2, const uint32_t* __restrict ds_haploid_genobytes4, uint32_t sample_ct, uint32_t forced, uint32_t is_y, void* __restrict ds_start_orig) {
6145 const uintptr_t* genovec = pgvp->genovec;
6146 // ds_start not required to be 4-byte aligned
6147 if (forced) {
6148 if (is_y) {
6149 // most dosages 0..1, het-hap = 0..2, female missing -> END_OF_VECTOR
6150 GenoarrSexLookup4b(genovec, sex_female, ds_y_genobytes2, sample_ct, ds_start_orig);
6151 } else {
6152 // most dosages 0..1, het-hap = 0..2
6153 GenoarrLookup256x4bx4(genovec, ds_haploid_genobytes4, sample_ct, ds_start_orig);
6154 }
6155 }
6156 const uint32_t dosage_ct = pgvp->dosage_ct;
6157 if (!dosage_ct) {
6158 return;
6159 }
6160 const Halfword* dosage_present_alias = DowncastKWToHW(pgvp->dosage_present);
6161 const Dosage* dosage_main_stop = &(pgvp->dosage_main[dosage_ct]);
6162 unsigned char* ds_start_uc = S_CAST(unsigned char*, ds_start_orig);
6163 uint32_t widx = UINT32_MAX; // deliberate overflow
6164 for (const Dosage* dosage_main_iter = pgvp->dosage_main; dosage_main_iter != dosage_main_stop; ) {
6165 uint32_t dosage_present_hw;
6166 do {
6167 dosage_present_hw = dosage_present_alias[++widx];
6168 } while (!dosage_present_hw);
6169 const uintptr_t geno_word = genovec[widx];
6170 const uint32_t cur_hets = PackWordToHalfwordMask5555(geno_word & (~(geno_word >> 1)));
6171 unsigned char* cur_ds = &(ds_start_uc[widx * (kBitsPerWord * 2)]);
6172 do {
6173 const uint32_t sample_idx_lowbits = ctzu32(dosage_present_hw);
6174 const uint32_t dosage_int = *dosage_main_iter++;
6175 const uint32_t scaled_dosage_int = dosage_int << ((cur_hets >> sample_idx_lowbits) & 1); // het-haps on 0..2 scale
6176 const float dosage_f = S_CAST(float, scaled_dosage_int) * S_CAST(float, kRecipDosageMax);
6177 CopyToUnalignedOffsetF(cur_ds, &dosage_f, sample_idx_lowbits);
6178 dosage_present_hw &= dosage_present_hw - 1;
6179 } while (dosage_present_hw);
6180 }
6181 }
6182
6183 // Biallelic.
6184 void FillBcfDs(const PgenVariant* pgvp, const uintptr_t* __restrict sex_male, const uintptr_t* __restrict sex_female, const uint32_t* __restrict ds_genobytes4, const uint32_t* __restrict ds_x_genobytes2, const uint32_t* __restrict ds_y_genobytes2, const uint32_t* __restrict ds_haploid_genobytes4, uint32_t sample_ct, uint32_t ds_force, uint32_t is_x, uint32_t is_y, uint32_t is_haploid, void* __restrict ds_start_orig) {
6185 unsigned char* ds_start_uc = S_CAST(unsigned char*, ds_start_orig);
6186 if (!ds_force) {
6187 // ds_start not required to be 4-byte aligned
6188 const uint32_t end_of_vector = 0x7f800002;
6189 for (uint32_t uii = 0; uii != sample_ct; ++uii) {
6190 // END_OF_VECTOR is more appropriate than MISSING here
6191 // see "Vectors of mixed length" section in the spec
6192 CopyToUnalignedOffsetU32(ds_start_uc, &end_of_vector, uii);
6193 }
6194 }
6195 const uintptr_t* genovec = pgvp->genovec;
6196 const uintptr_t* dosage_present = pgvp->dosage_present;
6197 const Dosage* dosage_main = pgvp->dosage_main;
6198 if (!is_haploid) {
6199 if (ds_force) {
6200 GenoarrLookup256x4bx4(genovec, ds_genobytes4, sample_ct, ds_start_uc);
6201 }
6202 // these loops are optimized for sparse dosages. possible todo: branch on
6203 // dosage_ct/sample_ct ratio.
6204 uint32_t widx = UINT32_MAX; // deliberate overflow
6205 for (uint32_t dosage_idx = 0; dosage_idx != pgvp->dosage_ct; ) {
6206 uintptr_t dosage_present_word;
6207 do {
6208 dosage_present_word = dosage_present[++widx];
6209 } while (!dosage_present_word);
6210 unsigned char* cur_ds = &(ds_start_uc[widx * (kBitsPerWord * k1LU * 4)]);
6211 do {
6212 const uint32_t sample_idx_lowbits = ctzw(dosage_present_word);
6213 const uint32_t dosage_int = dosage_main[dosage_idx++];
6214 const float dosage_f = S_CAST(float, dosage_int) * S_CAST(float, kRecipDosageMid);
6215 CopyToUnalignedOffsetF(cur_ds, &dosage_f, sample_idx_lowbits);
6216 dosage_present_word &= dosage_present_word - 1;
6217 } while (dosage_present_word);
6218 }
6219 return;
6220 }
6221 if (!is_x) {
6222 FillBcfDsPloidy1(pgvp, sex_female, ds_y_genobytes2, ds_haploid_genobytes4, sample_ct, ds_force, is_y, ds_start_uc);
6223 return;
6224 }
6225 if (ds_force) {
6226 // most male dosages 0..1, het-hap = 0..2
6227 GenoarrSexLookup4b(genovec, sex_male, ds_x_genobytes2, sample_ct, ds_start_uc);
6228 }
6229 const uint32_t dosage_ct = pgvp->dosage_ct;
6230 if (!dosage_ct) {
6231 return;
6232 }
6233 const Halfword* sex_male_alias = DowncastKWToHW(sex_male);
6234 const Halfword* dosage_present_alias = DowncastKWToHW(dosage_present);
6235 const Dosage* dosage_main_stop = &(dosage_main[dosage_ct]);
6236 uint32_t widx = UINT32_MAX; // deliberate overflow
6237 for (const Dosage* dosage_main_iter = dosage_main; dosage_main_iter != dosage_main_stop; ) {
6238 uint32_t dosage_present_hw;
6239 do {
6240 dosage_present_hw = dosage_present_alias[++widx];
6241 } while (!dosage_present_hw);
6242 const uintptr_t geno_word = genovec[widx];
6243 const uint32_t cur_hets = PackWordToHalfwordMask5555(geno_word & (~(geno_word >> 1)));
6244 const uint32_t male_hw = sex_male_alias[widx];
6245 const uint32_t ploidy_2_hw = cur_hets | (~male_hw);
6246 unsigned char* cur_ds = &(ds_start_uc[widx * (kBitsPerWord * 2)]);
6247 do {
6248 const uint32_t sample_idx_lowbits = ctzu32(dosage_present_hw);
6249 const uint32_t is_ploidy_2 = 1 & (ploidy_2_hw >> sample_idx_lowbits);
6250 const uint32_t scaled_dosage_int = (*dosage_main_iter++) << is_ploidy_2;
6251 const float dosage_f = S_CAST(float, scaled_dosage_int) * S_CAST(float, kRecipDosageMax);
6252 CopyToUnalignedOffsetF(cur_ds, &dosage_f, sample_idx_lowbits);
6253 dosage_present_hw &= dosage_present_hw - 1;
6254 } while (dosage_present_hw);
6255 }
6256 }
6257
6258 void FillBcfPhasedGt(const uintptr_t* __restrict genovec, const uintptr_t* __restrict phasepresent, const uintptr_t* __restrict phaseinfo, const uint16_t* __restrict phased_genobytes2, uint32_t sample_ct, uintptr_t* __restrict prev_phased, char* __restrict gt_start) {
6259 // Assumes trailing bits of genovec zeroed up to word-PAIR, and phaseinfo has
6260 // been anded with phasepresent.
6261 // No need to handle chrX separately since FixBcfMaleXGtPloidy() converts all
6262 // male phased-hom calls generated by this function into ploidy-1.
6263 // Similarly, no need to handle chrY separately.
6264 UpdateVcfPrevPhased(genovec, phasepresent, sample_ct, prev_phased);
6265 VcfPhaseLookup2b(genovec, prev_phased, phaseinfo, phased_genobytes2, sample_ct, gt_start);
6266 }
6267
6268 void FixBcfMaleXHdsPloidy(const uintptr_t* __restrict phasepresent, const uintptr_t* __restrict dphase_present, const uintptr_t* __restrict sex_male, uint32_t sample_ct, void* __restrict hds_start) {
6269 // Keep male HDS encoded as ploidy 2 when either phasepresent or
6270 // dphase_present bit set.
6271 // Otherwise replace the second value with 0x7f800002.
6272 // This does some unnecessary work when the missingness rate is high, but we
6273 // can live with that.
6274 unsigned char* hds_offset1_uc = &(S_CAST(unsigned char*, hds_start)[4]);
6275 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
6276 const uint32_t end_of_vector = 0x7f800002;
6277 if (!dphase_present) {
6278 for (uint32_t widx = 0; widx != sample_ctl; ++widx) {
6279 const uintptr_t male_word = sex_male[widx];
6280 const uintptr_t phasepresent_word = phasepresent[widx];
6281 uintptr_t male_unphased_word = male_word & (~phasepresent_word);
6282 if (male_unphased_word) {
6283 unsigned char* cur_hds_offset1 = &(hds_offset1_uc[widx * (kBitsPerWord * k1LU * 8)]);
6284 do {
6285 const uint32_t sample_idx_lowbits = ctzw(male_unphased_word);
6286 CopyToUnalignedOffsetU32(cur_hds_offset1, &end_of_vector, sample_idx_lowbits * 2);
6287 male_unphased_word &= male_unphased_word - 1;
6288 } while (male_unphased_word);
6289 }
6290 }
6291 return;
6292 }
6293 for (uint32_t widx = 0; widx != sample_ctl; ++widx) {
6294 const uintptr_t male_word = sex_male[widx];
6295 const uintptr_t phasepresent_word = phasepresent[widx] | dphase_present[widx];
6296 uintptr_t male_unphased_word = male_word & (~phasepresent_word);
6297 if (male_unphased_word) {
6298 unsigned char* cur_hds_offset1 = &(hds_offset1_uc[widx * (kBitsPerWord * k1LU * 8)]);
6299 do {
6300 const uint32_t sample_idx_lowbits = ctzw(male_unphased_word);
6301 CopyToUnalignedOffsetU32(cur_hds_offset1, &end_of_vector, sample_idx_lowbits * 2);
6302 male_unphased_word &= male_unphased_word - 1;
6303 } while (male_unphased_word);
6304 }
6305 }
6306 }
6307
6308 // Replace first HDS entry for each female missing call with 0x7f800002
6309 // END_OF_VECTOR.
6310 void FixBcfFemaleYHdsPloidy2(const uintptr_t* __restrict genovec, const uintptr_t* __restrict dosage_present, const uintptr_t* __restrict sex_female, uint32_t sample_ct, void* __restrict hds_start) {
6311 unsigned char* hds_uc = S_CAST(unsigned char*, hds_start);
6312 const Halfword* sex_female_alias = DowncastKWToHW(sex_female);
6313 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
6314 const uint32_t end_of_vector = 0x7f800002;
6315 if (!dosage_present) {
6316 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
6317 const uint32_t cur_female_hw = sex_female_alias[widx];
6318 const uint32_t geno_missing_hw = Pack11ToHalfword(genovec[widx]);
6319 uint32_t female_missing_hw = cur_female_hw & geno_missing_hw;
6320 if (female_missing_hw) {
6321 unsigned char* cur_hds = &(hds_uc[widx * (kBitsPerWord * k1LU * 4)]);
6322 do {
6323 const uint32_t sample_idx_lowbits = ctzu32(female_missing_hw);
6324 CopyToUnalignedOffsetU32(cur_hds, &end_of_vector, sample_idx_lowbits * 2);
6325 female_missing_hw &= female_missing_hw - 1;
6326 } while (female_missing_hw);
6327 }
6328 }
6329 return;
6330 }
6331 const Halfword* dosage_present_alias = DowncastKWToHW(dosage_present);
6332 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
6333 const uint32_t cur_female_hw = sex_female_alias[widx];
6334 const uint32_t geno_missing_hw = Pack11ToHalfword(genovec[widx]);
6335 const uint32_t dosage_nm_hw = dosage_present_alias[widx];
6336 uint32_t female_missing_hw = cur_female_hw & geno_missing_hw & (~dosage_nm_hw);
6337 if (female_missing_hw) {
6338 unsigned char* cur_hds = &(hds_uc[widx * (kBitsPerWord * k1LU * 4)]);
6339 do {
6340 const uint32_t sample_idx_lowbits = ctzu32(female_missing_hw);
6341 CopyToUnalignedOffsetU32(cur_hds, &end_of_vector, sample_idx_lowbits * 2);
6342 female_missing_hw &= female_missing_hw - 1;
6343 } while (female_missing_hw);
6344 }
6345 }
6346 }
6347
6348 void FixBcfFemaleY64allelicGtPloidy2(const uintptr_t* genovec, const uintptr_t* sex_female, uint32_t sample_ct, char* __restrict gt_start_orig) {
6349 const Halfword* sex_female_alias = DowncastKWToHW(sex_female);
6350 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
6351 const uint32_t end_of_vector = 0x80018001U;
6352 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
6353 const uint32_t cur_female_hw = sex_female_alias[widx];
6354 const uint32_t geno_missing_hw = Pack11ToHalfword(genovec[widx]);
6355 uint32_t female_missing_hw = cur_female_hw & geno_missing_hw;
6356 if (female_missing_hw) {
6357 unsigned char* cur_gt_start = CToUc(&(gt_start_orig[widx * (kBitsPerWord * 2)]));
6358 do {
6359 const uint32_t sample_idx_lowbits = ctzu32(female_missing_hw);
6360 CopyToUnalignedOffsetU32(cur_gt_start, &end_of_vector, sample_idx_lowbits);
6361 female_missing_hw &= female_missing_hw - 1;
6362 } while (female_missing_hw);
6363 }
6364 }
6365 }
6366
6367 void FixBcfFemaleY64allelicGtPloidy1(const uintptr_t* genovec, const uintptr_t* sex_female, uint32_t sample_ct, char* __restrict gt_start_orig) {
6368 const Halfword* sex_female_alias = DowncastKWToHW(sex_female);
6369 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
6370 const uint16_t end_of_vector = 0x8001;
6371 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
6372 const uint32_t cur_female_hw = sex_female_alias[widx];
6373 const uint32_t geno_missing_hw = Pack11ToHalfword(genovec[widx]);
6374 uint32_t female_missing_hw = cur_female_hw & geno_missing_hw;
6375 if (female_missing_hw) {
6376 unsigned char* cur_gt_start = CToUc(&(gt_start_orig[widx * kBitsPerWord]));
6377 do {
6378 const uint32_t sample_idx_lowbits = ctzu32(female_missing_hw);
6379 CopyToUnalignedOffsetU16(cur_gt_start, &end_of_vector, sample_idx_lowbits);
6380 female_missing_hw &= female_missing_hw - 1;
6381 } while (female_missing_hw);
6382 }
6383 }
6384 }
6385
6386 // Just like DS, except with no het-hap special case.
6387 void FillBcfHdsPloidy1(const PgenVariant* pgvp, const uintptr_t* __restrict sex_female, const uint32_t* __restrict hds_y_genobytes2, const uint32_t* __restrict hds_haploid_genobytes4, uint32_t sample_ct, uint32_t forced, uint32_t is_y, void* __restrict hds_start_orig) {
6388 const uintptr_t* genovec = pgvp->genovec;
6389 if (forced) {
6390 if (is_y) {
6391 // most dosages 0..1, female missing -> END_OF_VECTOR
6392 GenoarrSexLookup4b(genovec, sex_female, hds_y_genobytes2, sample_ct, hds_start_orig);
6393 } else {
6394 // all dosages 0..1
6395 GenoarrLookup256x4bx4(genovec, hds_haploid_genobytes4, sample_ct, hds_start_orig);
6396 }
6397 }
6398 const uint32_t dosage_ct = pgvp->dosage_ct;
6399 if (!dosage_ct) {
6400 return;
6401 }
6402 const uintptr_t* dosage_present = pgvp->dosage_present;
6403 const Dosage* dosage_main_stop = &(pgvp->dosage_main[dosage_ct]);
6404 unsigned char* hds_start_uc = S_CAST(unsigned char*, hds_start_orig);
6405 uint32_t widx = UINT32_MAX; // deliberate overflow
6406 for (const Dosage* dosage_main_iter = pgvp->dosage_main; dosage_main_iter != dosage_main_stop; ) {
6407 uintptr_t dosage_present_word;
6408 do {
6409 dosage_present_word = dosage_present[++widx];
6410 } while (!dosage_present_word);
6411 unsigned char* cur_hds_start = &(hds_start_uc[widx * (kBitsPerWord * k1LU * 4)]);
6412 do {
6413 const uint32_t sample_idx_lowbits = ctzw(dosage_present_word);
6414 const uint32_t dosage_int = *dosage_main_iter++;
6415 const float dosage_f = S_CAST(float, dosage_int) * S_CAST(float, kRecipDosageMax);
6416 CopyToUnalignedOffsetF(cur_hds_start, &dosage_f, sample_idx_lowbits);
6417 dosage_present_word &= dosage_present_word - 1;
6418 } while (dosage_present_word);
6419 }
6420 }
6421
6422 void FillBcfGpPloidy2(const PgenVariant* pgvp, const uintptr_t* __restrict sex_male, uint32_t sample_ct, uint32_t is_x, void* __restrict gp_start_orig) {
6423 unsigned char* gp_start_uc = S_CAST(unsigned char*, gp_start_orig);
6424 const uint32_t eov_bits = 0x7f800002;
6425 for (uint32_t uii = 0; uii != 3 * sample_ct; ++uii) {
6426 CopyToUnalignedOffsetU32(gp_start_uc, &eov_bits, uii);
6427 }
6428 const uint32_t dosage_ct = pgvp->dosage_ct;
6429 if (!dosage_ct) {
6430 return;
6431 }
6432 // dosage_main, etc. now guaranteed to be non-null
6433 const uintptr_t* dosage_present = pgvp->dosage_present;
6434 const Dosage* dosage_main_stop = &(pgvp->dosage_main[dosage_ct]);
6435 uint32_t widx = UINT32_MAX; // deliberate overflow
6436 const float zero = 0.0;
6437 if (!is_x) {
6438 for (const Dosage* dosage_main_iter = pgvp->dosage_main; dosage_main_iter != dosage_main_stop; ) {
6439 uintptr_t dosage_present_word;
6440 do {
6441 dosage_present_word = dosage_present[++widx];
6442 } while (!dosage_present_word);
6443 unsigned char* gp_word_uc = &(gp_start_uc[widx * (kBitsPerWord * k1LU * 12)]);
6444 do {
6445 const uint32_t sample_idx_lowbits = ctzw(dosage_present_word);
6446 unsigned char* cur_gp = &(gp_word_uc[12 * sample_idx_lowbits]);
6447 const uint32_t dosage_int = *dosage_main_iter++;
6448 if (dosage_int < kDosageMid) {
6449 const float dosage0 = S_CAST(float, kDosageMid - dosage_int) * S_CAST(float, kRecipDosageMid);
6450 const float dosage1 = S_CAST(float, dosage_int) * S_CAST(float, kRecipDosageMid);
6451 CopyToUnalignedF(cur_gp, &dosage0);
6452 CopyToUnalignedOffsetF(cur_gp, &dosage1, 1);
6453 CopyToUnalignedOffsetF(cur_gp, &zero, 2);
6454 } else {
6455 const float dosage1 = S_CAST(float, kDosageMax - dosage_int) * S_CAST(float, kRecipDosageMid);
6456 const float dosage2 = S_CAST(float, dosage_int - kDosageMid) * S_CAST(float, kRecipDosageMid);
6457 CopyToUnalignedF(cur_gp, &zero);
6458 CopyToUnalignedOffsetF(cur_gp, &dosage1, 1);
6459 CopyToUnalignedOffsetF(cur_gp, &dosage2, 2);
6460 }
6461 dosage_present_word &= dosage_present_word - 1;
6462 } while (dosage_present_word);
6463 }
6464 return;
6465 }
6466 for (const Dosage* dosage_main_iter = pgvp->dosage_main; dosage_main_iter != dosage_main_stop; ) {
6467 uintptr_t dosage_present_word;
6468 do {
6469 dosage_present_word = dosage_present[++widx];
6470 } while (!dosage_present_word);
6471 const uintptr_t male_word = sex_male[widx];
6472 unsigned char* gp_word_uc = &(gp_start_uc[widx * (kBitsPerWord * k1LU * 12)]);
6473 do {
6474 const uint32_t sample_idx_lowbits = ctzw(dosage_present_word);
6475 unsigned char* cur_gp = &(gp_word_uc[12 * sample_idx_lowbits]);
6476 const uint32_t dosage_int = *dosage_main_iter++;
6477 if ((male_word >> sample_idx_lowbits) & 1) {
6478 const float ref_prob = S_CAST(float, dosage_int) * S_CAST(float, kRecipDosageMax);
6479 const float dosage1 = S_CAST(float, 1.0) - ref_prob;
6480 CopyToUnalignedF(cur_gp, &ref_prob);
6481 CopyToUnalignedOffsetF(cur_gp, &dosage1, 1);
6482 CopyToUnalignedOffsetU32(cur_gp, &eov_bits, 2);
6483 } else {
6484 if (dosage_int < kDosageMid) {
6485 const float het_prob = S_CAST(float, dosage_int) * S_CAST(float, kRecipDosageMid);
6486 const float dosage0 = S_CAST(float, 1.0) - het_prob;
6487 CopyToUnalignedF(cur_gp, &dosage0);
6488 CopyToUnalignedOffsetF(cur_gp, &het_prob, 1);
6489 CopyToUnalignedOffsetF(cur_gp, &zero, 2);
6490 } else {
6491 const float het_prob = S_CAST(float, kDosageMax - dosage_int) * S_CAST(float, kRecipDosageMid);
6492 const float dosage2 = S_CAST(float, 1.0) - het_prob;
6493 CopyToUnalignedF(cur_gp, &zero);
6494 CopyToUnalignedOffsetF(cur_gp, &het_prob, 1);
6495 CopyToUnalignedOffsetF(cur_gp, &dosage2, 2);
6496 }
6497 }
6498 dosage_present_word &= dosage_present_word - 1;
6499 } while (dosage_present_word);
6500 }
6501 }
6502
6503 void FillBcfGpPloidy1(const PgenVariant* pgvp, uint32_t sample_ct, void* __restrict gp_start_orig) {
6504 unsigned char* gp_start_uc = S_CAST(unsigned char*, gp_start_orig);
6505 const uint64_t end_of_vector = 0x7f8000027f800002LLU;
6506 for (uint32_t uii = 0; uii != sample_ct; ++uii) {
6507 CopyToUnalignedOffsetU64(gp_start_uc, &end_of_vector, uii);
6508 }
6509 const uint32_t dosage_ct = pgvp->dosage_ct;
6510 if (!dosage_ct) {
6511 return;
6512 }
6513 const uintptr_t* dosage_present = pgvp->dosage_present;
6514 const Dosage* dosage_main_stop = &(pgvp->dosage_main[dosage_ct]);
6515 uint32_t widx = UINT32_MAX; // deliberate overflow
6516 for (const Dosage* dosage_main_iter = pgvp->dosage_main; dosage_main_iter != dosage_main_stop; ) {
6517 uintptr_t dosage_present_word;
6518 do {
6519 dosage_present_word = dosage_present[++widx];
6520 } while (!dosage_present_word);
6521 unsigned char* gp_word_uc = &(gp_start_uc[widx * (kBitsPerWord * k1LU * 8)]);
6522 do {
6523 const uint32_t sample_idx_lowbits = ctzw(dosage_present_word);
6524 unsigned char* cur_gp = &(gp_word_uc[8 * sample_idx_lowbits]);
6525 const uint32_t dosage_int = *dosage_main_iter++;
6526 const float alt_prob = S_CAST(float, dosage_int) * S_CAST(float, kRecipDosageMax);
6527 const float dosage0 = S_CAST(float, 1.0) - alt_prob;
6528 CopyToUnalignedF(cur_gp, &dosage0);
6529 CopyToUnalignedOffsetF(cur_gp, &alt_prob, 1);
6530 dosage_present_word &= dosage_present_word - 1;
6531 } while (dosage_present_word);
6532 }
6533 }
6534
6535
6536 // todo: benchmark this against the biallelic-specialized function, and delete
6537 // the latter if it isn't significantly faster.
6538 void FixBcfMaleX3allelicGtPloidy(const uintptr_t* __restrict sex_male, uint32_t sample_ct, char* __restrict gt_start) {
6539 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
6540 for (uint32_t widx = 0; widx != sample_ctl; ++widx) {
6541 uintptr_t male_word = sex_male[widx];
6542 if (male_word) {
6543 char* cur_gt = &(gt_start[widx * kBitsPerWord * 2]);
6544 do {
6545 const uint32_t sample_idx_lowbits = ctzw(male_word);
6546 const uint32_t gt_low = ctou32(cur_gt[2 * sample_idx_lowbits]);
6547 // clear phase bit
6548 const uint32_t gt_high = ctou32(cur_gt[2 * sample_idx_lowbits + 1]) & 0xfe;
6549 if (gt_low == gt_high) {
6550 cur_gt[2 * sample_idx_lowbits + 1] = 0x81;
6551 }
6552 male_word &= male_word - 1;
6553 } while (male_word);
6554 }
6555 }
6556 }
6557
6558 void FixBcfMaleX64allelicGtPloidy(const uintptr_t* __restrict sex_male, uint32_t sample_ct, char* __restrict gt_start) {
6559 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
6560 const uint16_t end_of_vector = 0x8001;
6561 for (uint32_t widx = 0; widx != sample_ctl; ++widx) {
6562 uintptr_t male_word = sex_male[widx];
6563 if (male_word) {
6564 unsigned char* cur_gt = CToUc(&(gt_start[widx * (kBitsPerWord * k1LU * 4)]));
6565 do {
6566 const uint32_t sample_idx_lowbits = ctzw(male_word);
6567 const uint32_t gt_low = CopyFromUnalignedOffsetU16ZX(cur_gt, 2 * sample_idx_lowbits);
6568 const uint32_t gt_high = CopyFromUnalignedOffsetU16ZX(cur_gt, 2 * sample_idx_lowbits + 1) & 0xfffe;
6569 if (gt_low == gt_high) {
6570 CopyToUnalignedOffsetU16(cur_gt, &end_of_vector, 2 * sample_idx_lowbits + 1);
6571 }
6572 male_word &= male_word - 1;
6573 } while (male_word);
6574 }
6575 }
6576 }
6577
6578 void FillBcf3allelicGtPloidy2(const PgenVariant* pgvp, const uint16_t* __restrict basic_genobytes4, uint32_t sample_ct, char* __restrict gt_start) {
6579 GenoarrLookup256x2bx4(pgvp->genovec, basic_genobytes4, sample_ct, gt_start);
6580 const uint32_t patch_01_ct = pgvp->patch_01_ct;
6581 if (patch_01_ct) {
6582 const uintptr_t* patch_01_set = pgvp->patch_01_set;
6583 const AlleleCode* patch_01_vals = pgvp->patch_01_vals;
6584 char* gt_offset1 = &(gt_start[1]);
6585 uintptr_t sample_idx_base = 0;
6586 uintptr_t patch_01_bits = patch_01_set[0];
6587 for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
6588 const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &patch_01_bits);
6589 gt_offset1[2 * sample_idx] = patch_01_vals[uii] * 2 + 2;
6590 }
6591 }
6592 const uint32_t patch_10_ct = pgvp->patch_10_ct;
6593 if (patch_10_ct) {
6594 const uintptr_t* patch_10_set = pgvp->patch_10_set;
6595 const DoubleAlleleCode* patch_10_vals_alias = R_CAST(const DoubleAlleleCode*, pgvp->patch_10_vals);
6596 uintptr_t sample_idx_base = 0;
6597 uintptr_t patch_10_bits = patch_10_set[0];
6598 for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
6599 const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &patch_10_bits);
6600 const uint16_t cur_u16 = patch_10_vals_alias[uii] * 2 + 0x202;
6601 CopyToUnalignedOffsetU16(CToUc(gt_start), &cur_u16, sample_idx);
6602 }
6603 }
6604 }
6605
6606 // Convert homozygous and missing GT to ploidy 1.
6607 // Homozygous GT may have been phased.
6608 void FixBcf3allelicGtHh(uint32_t sample_ct, char* __restrict gt_start) {
6609 #ifdef USE_SSE2
6610 const uint32_t fullvec_ct = sample_ct / (kBytesPerVec / 2);
6611 const VecU16 inv_m8 = vecu16_set1(0xff00);
6612 const VecU16 high_nophase_mask = vecu16_set1(0xfe00);
6613 const VecU16 eov = vecu16_set1(0x8100);
6614 char* gt_stop = &(gt_start[fullvec_ct * kBytesPerVec]);
6615 for (char* gt_iter = gt_start; gt_iter != gt_stop; gt_iter += kBytesPerVec) {
6616 const VecU16 vv_orig = vecu16_loadu(gt_iter);
6617 const VecU16 vv_lshift8 = vecu16_slli(vv_orig, 8);
6618 const VecU16 vv_high_nophase = vv_orig & high_nophase_mask;
6619 const VecU16 vv_replace_mask = (vv_lshift8 == vv_high_nophase) & inv_m8;
6620 const VecU16 vv_final = vecu16_blendv(vv_orig, eov, vv_replace_mask);
6621 vecu16_storeu(gt_iter, vv_final);
6622 }
6623 uint32_t sample_idx = fullvec_ct * (kBytesPerVec / 2);
6624 #else // !USE_SSE2
6625 uint32_t sample_idx = 0;
6626 #endif
6627 for (; sample_idx != sample_ct; ++sample_idx) {
6628 const uint32_t gt_low = ctou32(gt_start[2 * sample_idx]);
6629 const uint32_t gt_high = ctou32(gt_start[2 * sample_idx + 1]) & 0xfe;
6630 if (gt_low == gt_high) {
6631 gt_start[2 * sample_idx + 1] = 0x81;
6632 }
6633 }
6634 }
6635
6636 void FillBcf3allelicGtPloidy1(const PgenVariant* pgvp, const unsigned char* __restrict haploid_genobytes4, uint32_t sample_ct, char* __restrict gt_start) {
6637 GenoarrLookup256x1bx4(pgvp->genovec, haploid_genobytes4, sample_ct, gt_start);
6638 // patch_01_ct guaranteed to be zero; all patch_10 entries guaranteed to be
6639 // homozygous
6640 const uint32_t patch_10_ct = pgvp->patch_10_ct;
6641 const uintptr_t* patch_10_set = pgvp->patch_10_set;
6642 const AlleleCode* patch_10_vals = pgvp->patch_10_vals;
6643 uintptr_t sample_idx_base = 0;
6644 uintptr_t patch_10_bits = patch_10_set[0];
6645 for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
6646 const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &patch_10_bits);
6647 gt_start[sample_idx] = patch_10_vals[2 * uii] * 2 + 2;
6648 }
6649 }
6650
6651 void FillBcf64allelicGtPloidy2(const PgenVariant* pgvp, const uint32_t* __restrict wide_genobytes4, uint32_t sample_ct, char* __restrict gt_start) {
6652 GenoarrLookup256x4bx4(pgvp->genovec, wide_genobytes4, sample_ct, gt_start);
6653 const uint32_t patch_01_ct = pgvp->patch_01_ct;
6654 if (patch_01_ct) {
6655 const uintptr_t* patch_01_set = pgvp->patch_01_set;
6656 const AlleleCode* patch_01_vals = pgvp->patch_01_vals;
6657 unsigned char* gt_offset1 = CToUc(&(gt_start[2]));
6658 uintptr_t sample_idx_base = 0;
6659 uintptr_t patch_01_bits = patch_01_set[0];
6660 for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
6661 const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &patch_01_bits);
6662 const uint16_t cur_u16 = patch_01_vals[uii] * 2 + 2;
6663 CopyToUnalignedOffsetU16(gt_offset1, &cur_u16, 2 * sample_idx);
6664 }
6665 }
6666 const uint32_t patch_10_ct = pgvp->patch_10_ct;
6667 if (patch_10_ct) {
6668 const uintptr_t* patch_10_set = pgvp->patch_10_set;
6669 const AlleleCode* patch_10_vals_iter = pgvp->patch_10_vals;
6670 uintptr_t sample_idx_base = 0;
6671 uintptr_t patch_10_bits = patch_10_set[0];
6672 for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
6673 const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &patch_10_bits);
6674 const uint32_t ac0 = *patch_10_vals_iter++;
6675 const uint32_t ac1 = *patch_10_vals_iter++;
6676 uint16_t cur_u16 = ac0 * 2 + 2;
6677 CopyToUnalignedOffsetU16(CToUc(gt_start), &cur_u16, 2 * sample_idx);
6678 cur_u16 = ac1 * 2 + 2;
6679 CopyToUnalignedOffsetU16(CToUc(gt_start), &cur_u16, 2 * sample_idx + 1);
6680 }
6681 }
6682 }
6683
6684 void FillBcf64allelicGtPloidy1(const PgenVariant* pgvp, const uint16_t* __restrict wide_haploid_genobytes4, uint32_t sample_ct, char* __restrict gt_start) {
6685 GenoarrLookup256x2bx4(pgvp->genovec, wide_haploid_genobytes4, sample_ct, gt_start);
6686 // patch_01_ct guaranteed to be zero; all patch_10 entries guaranteed to be
6687 // homozygous
6688 const uint32_t patch_10_ct = pgvp->patch_10_ct;
6689 const uintptr_t* patch_10_set = pgvp->patch_10_set;
6690 const AlleleCode* patch_10_vals = pgvp->patch_10_vals;
6691 uintptr_t sample_idx_base = 0;
6692 uintptr_t patch_10_bits = patch_10_set[0];
6693 for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
6694 const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &patch_10_bits);
6695 const uint32_t ac = patch_10_vals[2 * uii];
6696 const uint16_t cur_u16 = ac * 2 + 2;
6697 CopyToUnalignedOffsetU16(CToUc(gt_start), &cur_u16, sample_idx);
6698 }
6699 }
6700
6701 // Convert homozygous and missing GT to ploidy 1.
6702 void FixBcf64allelicGtHh(uint32_t sample_ct, char* __restrict gt_start) {
6703 #ifdef USE_SSE2
6704 const uint32_t fullvec_ct = sample_ct / (kBytesPerVec / 4);
6705 const VecU32 inv_m16 = vecu32_set1(0xffff0000U);
6706 const VecU32 high_nophase_mask = vecu32_set1(0xfffe0000U);
6707 const VecU32 eov = vecu32_set1(0x80010000U);
6708 char* gt_stop = &(gt_start[fullvec_ct * (k1LU * kBytesPerVec)]);
6709 for (char* gt_iter = gt_start; gt_iter != gt_stop; gt_iter += kBytesPerVec) {
6710 const VecU32 vv_orig = vecu32_loadu(gt_iter);
6711 const VecU32 vv_lshift16 = vecu32_slli(vv_orig, 16);
6712 const VecU32 vv_high_nophase = vv_orig & high_nophase_mask;
6713 const VecU32 vv_replace_mask = (vv_lshift16 == vv_high_nophase) & inv_m16;
6714 const VecU32 vv_final = vecu32_blendv(vv_orig, eov, vv_replace_mask);
6715 vecu32_storeu(gt_iter, vv_final);
6716 }
6717 uint32_t sample_idx = fullvec_ct * (kBytesPerVec / 4);
6718 #else // !USE_SSE2
6719 uint32_t sample_idx = 0;
6720 #endif
6721 unsigned char* gt_start_uc = CToUc(gt_start);
6722 const uint16_t end_of_vector = 0x8001;
6723 for (; sample_idx != sample_ct; ++sample_idx) {
6724 const uint32_t gt_low = CopyFromUnalignedOffsetU16ZX(gt_start_uc, 2 * sample_idx);
6725 const uint32_t gt_high = CopyFromUnalignedOffsetU16ZX(gt_start_uc, 2 * sample_idx + 1) & 0xfffe;
6726 if (gt_low == gt_high) {
6727 CopyToUnalignedOffsetU16(gt_start_uc, &end_of_vector, 2 * sample_idx + 1);
6728 }
6729 }
6730 }
6731
6732 // Assumes trailing bits of genovec are zeroed out to next word-PAIR.
6733 // Assumes patch_01_set is zeroed out if patch_01_ct is zero; ditto for
6734 // patch_10.
6735 // See AppendVcfMultiallelicDsForce...().
6736 void FillBcfMultiallelicDsForce(const PgenVariant* pgvp, const uintptr_t* __restrict sex_male, const uintptr_t* __restrict sex_female, uint32_t sample_ct, uint32_t alt_allele_ct, uint32_t is_x, uint32_t is_y, uint32_t is_haploid, void* __restrict ds_start_orig) {
6737 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
6738 const uint32_t ds_wstride = alt_allele_ct * (kBitsPerWord * 4);
6739 const uintptr_t* genovec = pgvp->genovec;
6740 const uintptr_t* patch_01_set = pgvp->patch_01_set;
6741 const AlleleCode* patch_01_vals_iter = pgvp->patch_01_vals;
6742 const uintptr_t* patch_10_set = pgvp->patch_10_set;
6743 const AlleleCode* patch_10_vals_iter = pgvp->patch_10_vals;
6744 // float 1.0 = 0x3f800000 float 2.0 = 0x40000000
6745 const uint32_t one_fbits = 0x3f800000;
6746 const uint32_t ds_hom_val = ((!is_haploid) || is_x)? 0x40000000 : one_fbits;
6747 memset(ds_start_orig, 0, sample_ct * sizeof(int32_t) * alt_allele_ct);
6748 unsigned char* ds_start_uc = S_CAST(unsigned char*, ds_start_orig);
6749 const uint32_t missing_fbits = 0x7f800001;
6750 const uint32_t end_of_vector = 0x7f800002;
6751 for (uint32_t widx = 0; widx != sample_ctl; ++widx) {
6752 const uintptr_t geno_lo = genovec[2 * widx];
6753 const uintptr_t geno_hi = genovec[2 * widx + 1];
6754 if (!(geno_lo || geno_hi)) {
6755 continue;
6756 }
6757 // overflow of uint32 doesn't matter since we'd error out before writing
6758 // this variant
6759 unsigned char* ds_word_uc = &(ds_start_uc[widx * ds_wstride]);
6760
6761 uintptr_t geno_word1 = PackWordToHalfwordMask5555(geno_lo) | (S_CAST(uintptr_t, PackWordToHalfwordMask5555(geno_hi)) << kBitsPerWordD2);
6762 uintptr_t geno_word2 = PackWordToHalfwordMaskAAAA(geno_lo) | (S_CAST(uintptr_t, PackWordToHalfwordMaskAAAA(geno_hi)) << kBitsPerWordD2);
6763 uintptr_t geno_missing_word = geno_word1 & geno_word2;
6764 geno_word1 ^= geno_missing_word;
6765 if (geno_word1) {
6766 uintptr_t patch_01_word = patch_01_set[widx];
6767 // 0/1
6768 geno_word1 ^= patch_01_word;
6769 while (geno_word1) {
6770 const uint32_t sample_idx_lowbits = ctzw(geno_word1);
6771 CopyToUnalignedOffsetU32(ds_word_uc, &one_fbits, sample_idx_lowbits * alt_allele_ct);
6772 geno_word1 &= geno_word1 - 1;
6773 }
6774 // 0/x
6775 if (patch_01_word) {
6776 unsigned char* ds_word_uc_sub1 = &(ds_word_uc[-4]);
6777 do {
6778 const uint32_t sample_idx_lowbits = ctzw(patch_01_word);
6779 const uint32_t ac = *patch_01_vals_iter++;
6780 CopyToUnalignedOffsetU32(ds_word_uc_sub1, &one_fbits, sample_idx_lowbits * alt_allele_ct + ac);
6781 patch_01_word &= patch_01_word - 1;
6782 } while (patch_01_word);
6783 }
6784 }
6785 geno_word2 ^= geno_missing_word;
6786 if (geno_word2) {
6787 uintptr_t patch_10_word = patch_10_set[widx];
6788 geno_word2 ^= patch_10_word;
6789 if (!is_x) {
6790 // 1/1
6791 while (geno_word2) {
6792 const uint32_t sample_idx_lowbits = ctzw(geno_word2);
6793 CopyToUnalignedOffsetU32(ds_word_uc, &ds_hom_val, sample_idx_lowbits * alt_allele_ct);
6794 geno_word2 &= geno_word2 - 1;
6795 }
6796 // x/y
6797 if (patch_10_word) {
6798 unsigned char* ds_word_uc_sub1 = &(ds_word_uc[-4]);
6799 do {
6800 const uint32_t sample_idx_lowbits = ctzw(patch_10_word);
6801 const uint32_t ac0 = *patch_10_vals_iter++;
6802 const uint32_t ac1 = *patch_10_vals_iter++;
6803 unsigned char* cur_ds_sub1 = &(ds_word_uc_sub1[sample_idx_lowbits * alt_allele_ct * 4]);
6804 if (ac0 == ac1) {
6805 CopyToUnalignedOffsetU32(cur_ds_sub1, &ds_hom_val, ac0);
6806 } else {
6807 CopyToUnalignedOffsetU32(cur_ds_sub1, &one_fbits, ac0);
6808 CopyToUnalignedOffsetU32(cur_ds_sub1, &one_fbits, ac1);
6809 }
6810 patch_10_word &= patch_10_word - 1;
6811 } while (patch_10_word);
6812 }
6813 } else {
6814 const uintptr_t male_word = sex_male[widx];
6815 while (geno_word2) {
6816 const uint32_t sample_idx_lowbits = ctzw(geno_word2);
6817 const uint32_t is_male = (male_word >> sample_idx_lowbits) & 1;
6818 const uint32_t cur_u32 = 0x40000000 - (is_male << 23);
6819 CopyToUnalignedOffsetU32(ds_word_uc, &cur_u32, sample_idx_lowbits * alt_allele_ct);
6820 geno_word2 &= geno_word2 - 1;
6821 }
6822 if (patch_10_word) {
6823 unsigned char* ds_word_uc_sub1 = &(ds_word_uc[-4]);
6824 do {
6825 const uint32_t sample_idx_lowbits = ctzw(patch_10_word);
6826 const uint32_t ac0 = *patch_10_vals_iter++;
6827 const uint32_t ac1 = *patch_10_vals_iter++;
6828 unsigned char* cur_ds_sub1 = &(ds_word_uc_sub1[sample_idx_lowbits * alt_allele_ct * 4]);
6829 if (ac0 == ac1) {
6830 const uint32_t is_male = (male_word >> sample_idx_lowbits) & 1;
6831 const uint32_t cur_u32 = 0x40000000 - (is_male << 23);
6832 CopyToUnalignedOffsetU32(cur_ds_sub1, &cur_u32, ac0);
6833 } else {
6834 CopyToUnalignedOffsetU32(cur_ds_sub1, &one_fbits, ac0);
6835 CopyToUnalignedOffsetU32(cur_ds_sub1, &one_fbits, ac1);
6836 }
6837 patch_10_word &= patch_10_word - 1;
6838 } while (patch_10_word);
6839 }
6840 }
6841 }
6842 if (geno_missing_word) {
6843 if (!is_y) {
6844 do {
6845 const uint32_t sample_idx_lowbits = ctzw(geno_missing_word);
6846 unsigned char* cur_ds_uc = &(ds_word_uc[sample_idx_lowbits * alt_allele_ct * 4]);
6847 CopyToUnalignedU32(cur_ds_uc, &missing_fbits);
6848 // To match VCF-encoding behavior, we store just one missing value
6849 // followed by END_OF_VECTOR, instead of a whole bunch of missing
6850 // values.
6851 for (uint32_t uii = 1; uii != alt_allele_ct; ++uii) {
6852 CopyToUnalignedOffsetU32(cur_ds_uc, &end_of_vector, uii);
6853 }
6854 geno_missing_word &= geno_missing_word - 1;
6855 } while (geno_missing_word);
6856 } else {
6857 const uintptr_t female_word = sex_female[widx];
6858 do {
6859 const uint32_t sample_idx_lowbits = ctzw(geno_missing_word);
6860 const uint32_t is_female = (female_word >> sample_idx_lowbits) & 1;
6861 unsigned char* cur_ds_uc = &(ds_word_uc[sample_idx_lowbits * alt_allele_ct * 4]);
6862 // end-of-vector instead of missing if female
6863 const uint32_t cur_u32 = 0x7f800001 + is_female;
6864 CopyToUnalignedU32(cur_ds_uc, &cur_u32);
6865 for (uint32_t uii = 1; uii != alt_allele_ct; ++uii) {
6866 CopyToUnalignedOffsetU32(cur_ds_uc, &end_of_vector, uii);
6867 }
6868 geno_missing_word &= geno_missing_word - 1;
6869 } while (geno_missing_word);
6870 }
6871 }
6872 }
6873 }
6874
6875 void FillBcf3allelicPhasedGt(const PgenVariant* pgvp, uint32_t sample_ct, uint32_t is_haploid, uintptr_t* __restrict prev_phased, char* __restrict gt_start) {
6876 // * For every homozygous call, use the existing prev_phased bit.
6877 // * For every heterozygous call, use the phasepresent bit, update
6878 // prev_phased, and if phased, swap GT entry from x|y to y|x when phaseinfo
6879 // bit is set.
6880 // * For every missing call, do nothing.
6881 // * No need to handle chrX separately since FixBcfMaleXGtPloidy() converts
6882 // all male phased-hom calls generated by this function into ploidy-1.
6883 // Similarly, no need to handle chrY separately.
6884 // If we want to change this to a FillBcfPhasedGt() call followed by a
6885 // sparse-patch, phased[_hh]_genobytes2 should be extended to at least 251x2
6886 // entries.
6887 const uintptr_t* genovec = pgvp->genovec;
6888 const Halfword* patch_01_set_alias = DowncastKWToHW(pgvp->patch_01_set);
6889 const AlleleCode* patch_01_iter = pgvp->patch_01_vals;
6890 const Halfword* patch_10_set_alias = DowncastKWToHW(pgvp->patch_10_set);
6891 const AlleleCode* patch_10_iter = pgvp->patch_10_vals;
6892 const Halfword* phasepresent_alias = DowncastKWToHW(pgvp->phasepresent);
6893 const Halfword* phaseinfo_alias = DowncastKWToHW(pgvp->phaseinfo);
6894 uint16_t gt_base[4] = {0x202, 0x402, 0x404, 0};
6895 if (is_haploid) {
6896 gt_base[0] = 0x8102;
6897 gt_base[2] = 0x8104;
6898 gt_base[3] = 0x8100;
6899 }
6900 const uint32_t sample_ctl2_m1 = (sample_ct - 1) / kBitsPerWordD2;
6901 Halfword* prev_phased_alias = DowncastWToHW(prev_phased);
6902 uint32_t loop_len = kBitsPerWordD2;
6903 for (uint32_t widx = 0; ; ++widx) {
6904 if (widx >= sample_ctl2_m1) {
6905 if (widx > sample_ctl2_m1) {
6906 return;
6907 }
6908 loop_len = ModNz(sample_ct, kBitsPerWordD2);
6909 }
6910 uintptr_t geno_word = genovec[widx];
6911 const uint32_t patch_01_set_hw = patch_01_set_alias[widx];
6912 const uint32_t patch_10_set_hw = patch_10_set_alias[widx];
6913 const uint32_t phasepresent_hw = phasepresent_alias[widx];
6914 const uint32_t phaseinfo_hw = phaseinfo_alias[widx];
6915 uint32_t prev_phased_hw = prev_phased_alias[widx];
6916 unsigned char* cur_gt = CToUc(&(gt_start[widx * kBitsPerWord]));
6917 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
6918 const uintptr_t cur_geno = geno_word & 3;
6919 uint32_t cur_gt_base = gt_base[cur_geno];
6920 if ((cur_geno == 1) || (cur_geno == 2)) {
6921 const uint32_t cur_shift = 1U << sample_idx_lowbits;
6922 uint32_t is_het;
6923 if (cur_geno == 1) {
6924 is_het = 1;
6925 if (patch_01_set_hw & cur_shift) {
6926 const uint32_t ac = *patch_01_iter++;
6927 cur_gt_base = ((ac + 1) << 9) | 2;
6928 }
6929 } else {
6930 is_het = 0;
6931 if (patch_10_set_hw & cur_shift) {
6932 const uint32_t ac0 = *patch_10_iter++;
6933 const uint32_t ac1 = *patch_10_iter++;
6934 const uint32_t ac0_p1 = ac0 + 1;
6935 if (ac0 == ac1) {
6936 if (!is_haploid) {
6937 cur_gt_base = ac0_p1 * 0x202;
6938 } else {
6939 cur_gt_base = 0x8100 | (ac0_p1 << 1);
6940 }
6941 } else {
6942 is_het = 1;
6943 cur_gt_base = (ac0_p1 << 1) | ((ac1 + 1) << 9);
6944 }
6945 }
6946 }
6947 if (is_het) {
6948 if (phasepresent_hw & cur_shift) {
6949 prev_phased_hw |= cur_shift;
6950 if (phaseinfo_hw & cur_shift) {
6951 cur_gt_base = (cur_gt_base >> 8) | ((cur_gt_base & 0xff) << 8);
6952 }
6953 } else {
6954 prev_phased_hw &= ~cur_shift;
6955 }
6956 }
6957 }
6958 const uint16_t cur_u16 = cur_gt_base | (((prev_phased_hw >> sample_idx_lowbits) & 1) << 8);
6959 CopyToUnalignedOffsetU16(cur_gt, &cur_u16, sample_idx_lowbits);
6960 geno_word >>= 2;
6961 }
6962 prev_phased_alias[widx] = prev_phased_hw;
6963 }
6964 }
6965
6966 void FillBcf64allelicPhasedGt(const PgenVariant* pgvp, uint32_t sample_ct, uint32_t is_haploid, uintptr_t* __restrict prev_phased, char* __restrict gt_start) {
6967 const uintptr_t* genovec = pgvp->genovec;
6968 const Halfword* patch_01_set_alias = DowncastKWToHW(pgvp->patch_01_set);
6969 const AlleleCode* patch_01_iter = pgvp->patch_01_vals;
6970 const Halfword* patch_10_set_alias = DowncastKWToHW(pgvp->patch_10_set);
6971 const AlleleCode* patch_10_iter = pgvp->patch_10_vals;
6972 const Halfword* phasepresent_alias = DowncastKWToHW(pgvp->phasepresent);
6973 const Halfword* phaseinfo_alias = DowncastKWToHW(pgvp->phaseinfo);
6974 uint32_t gt_base[4] = {0x20002, 0x40002, 0x40004, 0};
6975 if (is_haploid) {
6976 gt_base[0] = 0x80010002U;
6977 gt_base[2] = 0x80010004U;
6978 gt_base[3] = 0x80010000U;
6979 }
6980 const uint32_t sample_ctl2_m1 = (sample_ct - 1) / kBitsPerWordD2;
6981 Halfword* prev_phased_alias = DowncastWToHW(prev_phased);
6982 uint32_t loop_len = kBitsPerWordD2;
6983 for (uint32_t widx = 0; ; ++widx) {
6984 if (widx >= sample_ctl2_m1) {
6985 if (widx > sample_ctl2_m1) {
6986 return;
6987 }
6988 loop_len = ModNz(sample_ct, kBitsPerWordD2);
6989 }
6990 uintptr_t geno_word = genovec[widx];
6991 const uint32_t patch_01_set_hw = patch_01_set_alias[widx];
6992 const uint32_t patch_10_set_hw = patch_10_set_alias[widx];
6993 const uint32_t phasepresent_hw = phasepresent_alias[widx];
6994 const uint32_t phaseinfo_hw = phaseinfo_alias[widx];
6995 uint32_t prev_phased_hw = prev_phased_alias[widx];
6996 unsigned char* cur_gt = CToUc(&(gt_start[widx * (kBitsPerWord * 2)]));
6997 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
6998 const uintptr_t cur_geno = geno_word & 3;
6999 uint32_t cur_gt_base = gt_base[cur_geno];
7000 if ((cur_geno == 1) || (cur_geno == 2)) {
7001 const uint32_t cur_shift = 1U << sample_idx_lowbits;
7002 uint32_t is_het;
7003 if (cur_geno == 1) {
7004 is_het = 1;
7005 if (patch_01_set_hw & cur_shift) {
7006 const uint32_t ac = *patch_01_iter++;
7007 cur_gt_base = ((ac + 1) << 17) | 2;
7008 }
7009 } else {
7010 is_het = 0;
7011 if (patch_10_set_hw & cur_shift) {
7012 const uint32_t ac0 = *patch_10_iter++;
7013 const uint32_t ac1 = *patch_10_iter++;
7014 const uint32_t ac0_p1 = ac0 + 1;
7015 if (ac0 == ac1) {
7016 if (!is_haploid) {
7017 cur_gt_base = ac0_p1 * 0x20002;
7018 } else {
7019 cur_gt_base = 0x80010000U | (ac0_p1 << 1);
7020 }
7021 } else {
7022 is_het = 1;
7023 cur_gt_base = (ac0_p1 << 1) | ((ac1 + 1) << 17);
7024 }
7025 }
7026 }
7027 if (is_het) {
7028 if (phasepresent_hw & cur_shift) {
7029 prev_phased_hw |= cur_shift;
7030 if (phaseinfo_hw & cur_shift) {
7031 cur_gt_base = (cur_gt_base >> 16) | ((cur_gt_base & 0xffff) << 16);
7032 }
7033 } else {
7034 prev_phased_hw &= ~cur_shift;
7035 }
7036 }
7037 }
7038 const uint32_t cur_u32 = cur_gt_base | (((prev_phased_hw >> sample_idx_lowbits) & 1) << 16);
7039 CopyToUnalignedOffsetU32(cur_gt, &cur_u32, sample_idx_lowbits);
7040 geno_word >>= 2;
7041 }
7042 prev_phased_alias[widx] = prev_phased_hw;
7043 }
7044 }
7045
7046 void FillBcfMultiallelicHdsForce(const PgenVariant* pgvp, const uintptr_t* __restrict sex_male, const uintptr_t* __restrict sex_female, uint32_t sample_ct, uint32_t alt_allele_ct, uint32_t is_x, uint32_t is_y, uint32_t is_haploid, void* __restrict hds_start_orig) {
7047 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
7048 const uintptr_t* genovec = pgvp->genovec;
7049 const uintptr_t* patch_01_set = pgvp->patch_01_set;
7050 const AlleleCode* patch_01_vals_iter = pgvp->patch_01_vals;
7051 const uintptr_t* patch_10_set = pgvp->patch_10_set;
7052 const AlleleCode* patch_10_vals_iter = pgvp->patch_10_vals;
7053 uint32_t* hds_u32 = S_CAST(uint32_t*, hds_start_orig);
7054 if ((!is_haploid) || is_x || pgvp->phasepresent_ct) {
7055 const uintptr_t* phasepresent = pgvp->phasepresent;
7056 const uintptr_t* phaseinfo = pgvp->phaseinfo;
7057 memset(hds_start_orig, 0, sample_ct * sizeof(int32_t) * 2 * alt_allele_ct);
7058 const uint32_t hds_wstride = alt_allele_ct * 2 * kBitsPerWord;
7059 for (uint32_t widx = 0; widx != sample_ctl; ++widx) {
7060 const uintptr_t geno_lo = genovec[2 * widx];
7061 const uintptr_t geno_hi = genovec[2 * widx + 1];
7062 if (!(geno_lo || geno_hi)) {
7063 continue;
7064 }
7065 // overflow of uint32 doesn't matter since we'd error out before writing
7066 // this variant
7067 uint32_t* hds_word_u32 = &(hds_u32[widx * hds_wstride]);
7068 const uintptr_t phasepresent_word = phasepresent[widx];
7069 const uintptr_t phaseinfo_word = phaseinfo[widx];
7070
7071 uintptr_t geno_word1 = PackWordToHalfwordMask5555(geno_lo) | (S_CAST(uintptr_t, PackWordToHalfwordMask5555(geno_hi)) << kBitsPerWordD2);
7072 uintptr_t geno_word2 = PackWordToHalfwordMaskAAAA(geno_lo) | (S_CAST(uintptr_t, PackWordToHalfwordMaskAAAA(geno_hi)) << kBitsPerWordD2);
7073 uintptr_t geno_missing_word = geno_word1 & geno_word2;
7074 geno_word1 ^= geno_missing_word;
7075 if (geno_word1) {
7076 uintptr_t patch_01_word = patch_01_set[widx];
7077 // 0/1
7078 geno_word1 ^= patch_01_word;
7079 while (geno_word1) {
7080 const uint32_t sample_idx_lowbits = ctzw(geno_word1);
7081 const uintptr_t lowbit = geno_word1 & (-geno_word1);
7082 uint32_t* cur_hds = &(hds_word_u32[sample_idx_lowbits * alt_allele_ct * 2]);
7083 if (!(phasepresent_word & lowbit)) {
7084 // float 0.5
7085 cur_hds[0] = 0x3f000000;
7086 cur_hds[alt_allele_ct] = 0x3f000000;
7087 } else {
7088 // if phaseinfo bit unset, second entry is 1.0; otherwise, first
7089 // entry.
7090 cur_hds[alt_allele_ct * (1 & (~(phaseinfo_word >> sample_idx_lowbits)))] = 0x3f800000;
7091 }
7092 geno_word1 ^= lowbit;
7093 }
7094 // 0/x
7095 if (patch_01_word) {
7096 uint32_t* hds_word_u32_sub1 = &(hds_word_u32[-1]);
7097 do {
7098 const uint32_t sample_idx_lowbits = ctzw(patch_01_word);
7099 const uintptr_t lowbit = patch_01_word & (-patch_01_word);
7100 const uint32_t ac = *patch_01_vals_iter++;
7101 uint32_t* cur_hds_ac = &(hds_word_u32_sub1[sample_idx_lowbits * alt_allele_ct * 2 + ac]);
7102 if (!(phasepresent_word & lowbit)) {
7103 cur_hds_ac[0] = 0x3f000000;
7104 cur_hds_ac[alt_allele_ct] = 0x3f000000;
7105 } else {
7106 cur_hds_ac[alt_allele_ct * (1 & (~(phaseinfo_word >> sample_idx_lowbits)))] = 0x3f800000;
7107 }
7108 patch_01_word ^= lowbit;
7109 } while (patch_01_word);
7110 }
7111 }
7112 geno_word2 ^= geno_missing_word;
7113 if (geno_word2) {
7114 uintptr_t patch_10_word = patch_10_set[widx];
7115 geno_word2 ^= patch_10_word;
7116 // 1/1
7117 while (geno_word2) {
7118 const uint32_t sample_idx_lowbits = ctzw(geno_word2);
7119 uint32_t* cur_hds = &(hds_word_u32[sample_idx_lowbits * 2 * alt_allele_ct]);
7120 cur_hds[0] = 0x3f800000;
7121 cur_hds[alt_allele_ct] = 0x3f800000;
7122 geno_word2 &= geno_word2 - 1;
7123 }
7124 // x/y
7125 if (patch_10_word) {
7126 do {
7127 const uint32_t sample_idx_lowbits = ctzw(patch_10_word);
7128 const uint32_t ac0 = *patch_10_vals_iter++;
7129 const uint32_t ac1 = *patch_10_vals_iter++;
7130 const uint32_t ac0_m1 = ac0 - 1;
7131 uint32_t* cur_hds = &(hds_word_u32[sample_idx_lowbits * 2 * alt_allele_ct]);
7132 if (ac0 == ac1) {
7133 cur_hds[ac0_m1] = 0x3f800000;
7134 cur_hds[ac0_m1 + alt_allele_ct] = 0x3f800000;
7135 } else {
7136 const uintptr_t lowbit = patch_10_word & (-patch_10_word);
7137 const uint32_t ac1_m1 = ac1 - 1;
7138 if (!(phasepresent_word & lowbit)) {
7139 cur_hds[ac0_m1] = 0x3f000000;
7140 cur_hds[ac1_m1] = 0x3f000000;
7141 cur_hds[alt_allele_ct + ac0_m1] = 0x3f000000;
7142 cur_hds[alt_allele_ct + ac1_m1] = 0x3f000000;
7143 } else {
7144 const uintptr_t phaseinfo_bit = (phaseinfo_word >> sample_idx_lowbits) & 1;
7145 cur_hds[ac0_m1 + alt_allele_ct * phaseinfo_bit] = 0x3f800000;
7146 cur_hds[ac1_m1 + alt_allele_ct * (1 ^ phaseinfo_bit)] = 0x3f800000;
7147 }
7148 }
7149 patch_10_word &= patch_10_word - 1;
7150 } while (patch_10_word);
7151 }
7152 }
7153 if (geno_missing_word) {
7154 if (!is_y) {
7155 do {
7156 const uint32_t sample_idx_lowbits = ctzw(geno_missing_word);
7157 uint32_t* cur_hds_u32 = &(hds_word_u32[sample_idx_lowbits * 2 * alt_allele_ct]);
7158 // To match VCF-encoding behavior, we only store 1 or 2 missing
7159 // values (depending on ploidy), instead of a whole bunch of
7160 // missing values.
7161 cur_hds_u32[0] = 0x7f800001;
7162 cur_hds_u32[1] = 0x7f800001;
7163 for (uint32_t uii = 2; uii != 2 * alt_allele_ct; ++uii) {
7164 cur_hds_u32[uii] = 0x7f800002;
7165 }
7166 geno_missing_word &= geno_missing_word - 1;
7167 } while (geno_missing_word);
7168 } else {
7169 const uintptr_t female_word = sex_female[widx];
7170 do {
7171 const uint32_t sample_idx_lowbits = ctzw(geno_missing_word);
7172 const uint32_t is_female = (female_word >> sample_idx_lowbits) & 1;
7173 uint32_t* cur_hds_u32 = &(hds_word_u32[sample_idx_lowbits * 2 * alt_allele_ct]);
7174 // end-of-vector instead of missing if female
7175 cur_hds_u32[0] = 0x7f800001 + is_female;
7176 // Only need to fill first half; second half will be filled with
7177 // END_OF_VECTOR values later, since this is chrY
7178 for (uint32_t uii = 1; uii != alt_allele_ct; ++uii) {
7179 cur_hds_u32[uii] = 0x7f800002;
7180 }
7181 geno_missing_word &= geno_missing_word - 1;
7182 } while (geno_missing_word);
7183 }
7184 }
7185 }
7186 if (!is_haploid) {
7187 return;
7188 }
7189 uint32_t* hds_second = &(hds_u32[alt_allele_ct]);
7190 if (!is_x) {
7191 // Set all ploidies to 1 except when phase present.
7192 for (uint32_t widx = 0; widx != sample_ctl; ++widx) {
7193 uintptr_t unphased_word = sex_male[widx] & (~(phasepresent[widx]));
7194 if (!unphased_word) {
7195 continue;
7196 }
7197 uint32_t* hds_word_second_u32 = &(hds_second[widx * hds_wstride]);
7198 do {
7199 const uint32_t sample_idx_lowbits = ctzw(unphased_word);
7200 uint32_t* cur_hds_u32 = &(hds_word_second_u32[sample_idx_lowbits * 2 * alt_allele_ct]);
7201 for (uint32_t uii = 0; uii != alt_allele_ct; ++uii) {
7202 cur_hds_u32[uii] = 0x7f800002; // END_OF_VECTOR
7203 }
7204 unphased_word &= unphased_word - 1;
7205 } while (unphased_word);
7206 }
7207 } else {
7208 // Set male ploidy to 1 except when phase present.
7209 for (uint32_t widx = 0; widx != sample_ctl; ++widx) {
7210 uintptr_t male_unphased_word = sex_male[widx] & (~(phasepresent[widx]));
7211 if (!male_unphased_word) {
7212 continue;
7213 }
7214 uint32_t* hds_word_second_u32 = &(hds_second[widx * hds_wstride]);
7215 do {
7216 const uint32_t sample_idx_lowbits = ctzw(male_unphased_word);
7217 uint32_t* cur_hds_u32 = &(hds_word_second_u32[sample_idx_lowbits * 2 * alt_allele_ct]);
7218 for (uint32_t uii = 0; uii != alt_allele_ct; ++uii) {
7219 cur_hds_u32[uii] = 0x7f800002;
7220 }
7221 male_unphased_word &= male_unphased_word - 1;
7222 } while (male_unphased_word);
7223 }
7224 }
7225 return;
7226 }
7227 memset(hds_start_orig, 0, sample_ct * sizeof(int32_t) * alt_allele_ct);
7228 const uint32_t hds_wstride = alt_allele_ct * kBitsPerWord;
7229 for (uint32_t widx = 0; widx != sample_ctl; ++widx) {
7230 const uintptr_t geno_lo = genovec[2 * widx];
7231 const uintptr_t geno_hi = genovec[2 * widx + 1];
7232 if (!(geno_lo || geno_hi)) {
7233 continue;
7234 }
7235 uint32_t* hds_word_u32 = &(hds_u32[widx * hds_wstride]);
7236
7237 uintptr_t geno_word1 = PackWordToHalfwordMask5555(geno_lo) | (S_CAST(uintptr_t, PackWordToHalfwordMask5555(geno_hi)) << kBitsPerWordD2);
7238 uintptr_t geno_word2 = PackWordToHalfwordMaskAAAA(geno_lo) | (S_CAST(uintptr_t, PackWordToHalfwordMaskAAAA(geno_hi)) << kBitsPerWordD2);
7239 uintptr_t geno_missing_word = geno_word1 & geno_word2;
7240 geno_word1 ^= geno_missing_word;
7241 if (geno_word1) {
7242 uintptr_t patch_01_word = patch_01_set[widx];
7243 // 0/1
7244 geno_word1 ^= patch_01_word;
7245 while (geno_word1) {
7246 const uint32_t sample_idx_lowbits = ctzw(geno_word1);
7247 hds_word_u32[sample_idx_lowbits * alt_allele_ct] = 0x3f000000;
7248 geno_word1 &= geno_word1 - 1;
7249 }
7250 // 0/x
7251 if (patch_01_word) {
7252 uint32_t* hds_word_u32_sub1 = &(hds_word_u32[-1]);
7253 do {
7254 const uint32_t sample_idx_lowbits = ctzw(patch_01_word);
7255 const uint32_t ac = *patch_01_vals_iter++;
7256 hds_word_u32_sub1[sample_idx_lowbits * alt_allele_ct + ac] = 0x3f000000;
7257 patch_01_word &= patch_01_word - 1;
7258 } while (patch_01_word);
7259 }
7260 }
7261 geno_word2 ^= geno_missing_word;
7262 if (geno_word2) {
7263 uintptr_t patch_10_word = patch_10_set[widx];
7264 geno_word2 ^= patch_10_word;
7265 // 1/1
7266 while (geno_word2) {
7267 const uint32_t sample_idx_lowbits = ctzw(geno_word2);
7268 hds_word_u32[sample_idx_lowbits * alt_allele_ct] = 0x3f800000;
7269 geno_word2 &= geno_word2 - 1;
7270 }
7271 // x/y
7272 if (patch_10_word) {
7273 do {
7274 const uint32_t sample_idx_lowbits = ctzw(patch_10_word);
7275 const uint32_t ac0 = *patch_10_vals_iter++;
7276 const uint32_t ac1 = *patch_10_vals_iter++;
7277 uint32_t* cur_hds = &(hds_word_u32[sample_idx_lowbits * alt_allele_ct]);
7278 if (ac0 == ac1) {
7279 cur_hds[ac0 - 1] = 0x3f800000;
7280 } else {
7281 cur_hds[ac0 - 1] = 0x3f000000;
7282 cur_hds[ac1 - 1] = 0x3f000000;
7283 }
7284 patch_10_word &= patch_10_word - 1;
7285 } while (patch_10_word);
7286 }
7287 }
7288 if (geno_missing_word) {
7289 if (!is_y) {
7290 do {
7291 const uint32_t sample_idx_lowbits = ctzw(geno_missing_word);
7292 uint32_t* cur_hds_u32 = &(hds_word_u32[sample_idx_lowbits * alt_allele_ct]);
7293 cur_hds_u32[0] = 0x7f800001;
7294 for (uint32_t uii = 1; uii != alt_allele_ct; ++uii) {
7295 cur_hds_u32[uii] = 0x7f800002;
7296 }
7297 geno_missing_word &= geno_missing_word - 1;
7298 } while (geno_missing_word);
7299 } else {
7300 const uintptr_t female_word = sex_female[widx];
7301 do {
7302 const uint32_t sample_idx_lowbits = ctzw(geno_missing_word);
7303 const uint32_t is_female = (female_word >> sample_idx_lowbits) & 1;
7304 uint32_t* cur_hds_u32 = &(hds_word_u32[sample_idx_lowbits * alt_allele_ct]);
7305 cur_hds_u32[0] = 0x7f800001 + is_female;
7306 for (uint32_t uii = 1; uii != alt_allele_ct; ++uii) {
7307 cur_hds_u32[uii] = 0x7f800002;
7308 }
7309 geno_missing_word &= geno_missing_word - 1;
7310 } while (geno_missing_word);
7311 }
7312 }
7313 }
7314 }
7315
7316 void MakeRlenWarningStr(const char* variant_id) {
7317 char* err_write_iter = strcpya_k(g_logbuf, "Warning: Unexpected INFO/END value for variant");
7318 // 50 chars + strlen(variant_id), split into two lines if >79
7319 const uint32_t variant_id_slen = strlen(variant_id);
7320 *err_write_iter++ = (variant_id_slen < 30)? ' ' : '\n';
7321 *err_write_iter++ = '\'';
7322 err_write_iter = memcpya(err_write_iter, variant_id, variant_id_slen);
7323 strcpy_k(err_write_iter, "'.\n");
7324 }
7325
7326 static_assert(sizeof(AlleleCode) == 1, "ExportBcf() needs to be updated.");
7327 PglErr ExportBcf(const uintptr_t* sample_include, const uint32_t* sample_include_cumulative_popcounts, const SampleIdInfo* siip, const uintptr_t* sex_male_collapsed, const uintptr_t* sex_female_collapsed, 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 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 uint32_t* contig_lens, uintptr_t xheader_blen, InfoFlags info_flags, uint32_t sample_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_slen, uint32_t max_filter_slen, uint32_t info_reload_slen, uint32_t max_thread_ct, ExportfFlags exportf_flags, VcfExportMode vcf_mode, IdpasteFlags exportf_id_paste, char exportf_id_delim, char* xheader, PgenFileInfo* pgfip, PgenReader* simple_pgrp, char* outname, char* outname_end) {
7328 unsigned char* bigstack_mark = g_bigstack_base;
7329 PglErr reterr = kPglRetSuccess;
7330 TextStream pvar_reload_txs;
7331 BgzfCompressStream bgzf;
7332 PreinitTextStream(&pvar_reload_txs);
7333 PreinitBgzfCompressStream(&bgzf);
7334 {
7335 {
7336 snprintf(outname_end, kMaxOutfnameExtBlen, ".bcf");
7337 reterr = InitBgzfCompressStreamEx(outname, 0, kBgzfDefaultClvl, max_thread_ct, &bgzf);
7338 if (unlikely(reterr)) {
7339 if (reterr == kPglRetOpenFail) {
7340 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
7341 }
7342 goto ExportBcf_ret_1;
7343 }
7344 }
7345 const uint32_t max_chr_slen = GetMaxChrSlen(cip);
7346 uint32_t write_some_dosage = 0;
7347 uint32_t write_ds = 0;
7348 uint32_t write_hds = 0;
7349 uint32_t ds_force = 0;
7350 uint32_t ds_only = 0;
7351 uint32_t hds_force = 0;
7352 if (vcf_mode != kVcfExport0) {
7353 write_some_dosage = 1;
7354 if (vcf_mode != kVcfExportGp) {
7355 write_ds = 1;
7356 if (vcf_mode == kVcfExportDsForce) {
7357 ds_force = 1;
7358 } else if (vcf_mode == kVcfExportDsOnly) {
7359 if (unlikely((cip->haploid_mask[0] & 1) ||
7360 XymtIsNonempty(variant_include, cip, kChrOffsetX) ||
7361 XymtIsNonempty(variant_include, cip, kChrOffsetY) ||
7362 XymtIsNonempty(variant_include, cip, kChrOffsetMT))) {
7363 logerrputs("Error: --export vcf-dosage=DS-only mode can only be used with all-diploid data.\n");
7364 goto ExportBcf_ret_INCONSISTENT_INPUT;
7365 }
7366 ds_force = 1;
7367 ds_only = 1;
7368 } else if (vcf_mode != kVcfExportDs) {
7369 write_hds = 1;
7370 if (vcf_mode == kVcfExportHdsForce) {
7371 ds_force = 1;
7372 hds_force = 1;
7373 }
7374 }
7375 }
7376 }
7377 if ((!ds_force) && write_some_dosage && (!(pgfip->gflags & kfPgenGlobalDosagePresent))) {
7378 write_some_dosage = 0;
7379 logerrprintf("Warning: No dosage data present. %s will not be exported.\n", write_hds? "DS and HDS fields" : (write_ds? "DS field" : "GP field"));
7380 write_ds = 0;
7381 write_hds = 0;
7382 }
7383 const uintptr_t* nonref_flags = pgfip->nonref_flags;
7384 const uint32_t all_nonref = (pgfip->gflags & kfPgenGlobalAllNonref) && (!nonref_flags);
7385 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
7386 uint32_t write_pr = all_nonref;
7387 if (nonref_flags) {
7388 write_pr = !IntersectionIsEmpty(variant_include, nonref_flags, raw_variant_ctl);
7389 }
7390 const uint32_t info_pr_flag_present = (info_flags / kfInfoPrFlagPresent) & 1;
7391 // Count FILTER/INFO/FORMAT keys for hash table sizing purposes. Slight
7392 // overestimate ok, so we don't bother to avoid double-counting
7393 // FILTER/PASS, or counting FORMAT/HDS when it won't actually be used, etc.
7394 uint32_t fif_key_ct_ubound = 5;
7395 if (xheader) {
7396 const char* xheader_end = &(xheader[xheader_blen]);
7397 for (const char* xheader_iter = xheader; xheader_iter != xheader_end; xheader_iter = AdvPastDelim(xheader_iter, '\n')) {
7398 fif_key_ct_ubound += StrStartsWithUnsafe(xheader_iter, "##FILTER=<") || StrStartsWithUnsafe(xheader_iter, "##INFO=<");
7399 }
7400 }
7401 const uint32_t fif_keys_htable_size = GetHtableFastSize(fif_key_ct_ubound);
7402 // The byte size of the header must be stored in bytes [5,9). So we
7403 // generate the entire header, fill in its size, and only then do we flush.
7404 // (In principle, we could compute its exact size and then generate the
7405 // contents incrementally to save memory in extreme cases, but it's limited
7406 // to 4 GiB anyway so I won't bother.)
7407 // Ways for the actual header to exceed xheader_blen bytes:
7408 // * New FILTER/PASS, INFO/PR, and FORMAT header lines, and beginning of
7409 // #CHROM line. These add up to less than 1 KB.
7410 // * ",IDX=<#>" appended to existing FILTER/INFO header lines. The number
7411 // of added bytes is less than (5 + UintSlen(fif_key_ct_ubound - 1)) *
7412 // fif_key_ct_ubound.
7413 // * ",IDX=<#>" appended to existing contig lines, or entirely new contig
7414 // lines. This is less than chr_ct * <small constant> + sum of extra-chr
7415 // string string lengths.
7416 // * ",length=<#>" inserted into existing contig lines. This is also
7417 // accounted for in the previous term.
7418 // * Sample IDs.
7419 uintptr_t header_ubound = xheader_blen + 1024 + (5 + UintSlen(fif_key_ct_ubound - 1)) * S_CAST(uintptr_t, fif_key_ct_ubound);
7420 const uint32_t chr_ct = cip->chr_ct;
7421 {
7422 const uint32_t max_code = cip->max_code;
7423 for (uint32_t chr_fo_idx = 0; chr_fo_idx != chr_ct; ++chr_fo_idx) {
7424 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
7425 if (!IsSet(cip->chr_mask, chr_idx)) {
7426 continue;
7427 }
7428 // ##contig=<ID=chr99,length=1000000000,IDX=12345>
7429 // 37 + kMaxChrCodeDigits + strlen(EOLN_STR) + length of contig ID
7430 header_ubound += 37 + kMaxChrCodeDigits + strlen(EOLN_STR);
7431 if (chr_idx <= max_code) {
7432 // regular code
7433 header_ubound += kMaxChrTextnumSlen + 3;
7434 } else {
7435 header_ubound += strlen(cip->nonstd_names[chr_idx]);
7436 }
7437 }
7438 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
7439 uintptr_t max_sid_blen = siip->max_sid_blen;
7440 const char* sids = siip->sids;
7441 const uint32_t write_sid = DataSidColIsRequired(sample_include, sids, sample_ct, max_sid_blen, exportf_id_paste / kfIdpasteMaybesid);
7442 if (write_sid && (!sids)) {
7443 max_sid_blen = 2;
7444 }
7445 const uintptr_t max_exported_sample_id_blen = max_sample_id_blen + write_sid * max_sid_blen;
7446 header_ubound += max_exported_sample_id_blen * sample_ct;
7447 }
7448 // We need these three data structures in the main BCF-writing loop.
7449 char** fif_keys_mutable;
7450 uint32_t* fif_keys_htable;
7451 ChrIdx* chr_fo_to_bcf_idx;
7452 // We'll also need writebuf, but it'll be resized.
7453 // All bigstack-base allocations after writebuf in this section are
7454 // temporary.
7455 char* writebuf;
7456 if (unlikely(bigstack_alloc_u32(fif_keys_htable_size, &fif_keys_htable) ||
7457 bigstack_calloc_cp(fif_key_ct_ubound, &fif_keys_mutable) ||
7458 bigstack_alloc_chridx(chr_ct, &chr_fo_to_bcf_idx) ||
7459 bigstack_alloc_c(header_ubound + 9, &writebuf))) {
7460 goto ExportBcf_ret_NOMEM;
7461 }
7462 SetAllU32Arr(fif_keys_htable_size, fif_keys_htable);
7463 char* write_iter = memcpya_k(writebuf, "BCF\2\2\0\0\0", 9);
7464 const uint32_t v43 = (exportf_flags / kfExportfBcf43) & 1;
7465 uint32_t pr_key_idx = UINT32_MAX;
7466 uint32_t end_key_idx = UINT32_MAX;
7467 uint32_t dosage_key_idx = UINT32_MAX;
7468 uint32_t hds_key_idx = UINT32_MAX;
7469 uint32_t gt_key_idx = UINT32_MAX;
7470 uint32_t info_end_exists = 0;
7471 uint32_t fif_key_ct = 0;
7472 {
7473 // Now generate the header body and build the string dictionaries.
7474 // We store additional information about each FILTER/INFO/FORMAT key in
7475 // fif_keys[index][-1]:
7476 // bits 0-2: INFO type (1 = Flag, 3 = Integer, 5 = Float,
7477 // 7 = String/Character)
7478 // bit 3: FILTER?
7479 // bits 4-7 unused for now
7480 char* header_start = write_iter;
7481 AppendVcfHeaderStart(v43, &write_iter);
7482 if (cip->chrset_source) {
7483 AppendChrsetLine(cip, &write_iter);
7484 }
7485 const uint32_t chr_ctl = BitCtToWordCt(chr_ct);
7486 uintptr_t* written_contig_header_lines;
7487 if (unlikely(bigstack_calloc_w(chr_ctl, &written_contig_header_lines))) {
7488 goto ExportBcf_ret_NOMEM;
7489 }
7490 unsigned char* tmp_alloc_end = g_bigstack_end;
7491 // Match htslib/bcftools behavior of always putting an explicit
7492 // FILTER/PASS header line first.
7493 write_iter = strcpya_k(write_iter, "##FILTER=<ID=PASS,Description=\"All filters passed\",IDX=0>" EOLN_STR);
7494 {
7495 uint32_t cur_idx;
7496 reterr = AddToFifHtable(g_bigstack_base, "PASS", fif_keys_htable_size, strlen("PASS"), 8, &tmp_alloc_end, fif_keys_mutable, fif_keys_htable, &fif_key_ct, &cur_idx);
7497 if (unlikely(reterr)) {
7498 goto ExportBcf_ret_1;
7499 }
7500 }
7501
7502 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
7503 const uint32_t par1_code = cip->xymt_codes[kChrOffsetPAR1];
7504 const uint32_t par2_code = cip->xymt_codes[kChrOffsetPAR2];
7505 uint32_t contig_zero_written = 0;
7506 uint32_t x_contig_line_written = 0;
7507 uint32_t contig_string_idx_end = 0;
7508 if (xheader) {
7509 char* xheader_end = &(xheader[xheader_blen]);
7510 for (char* line_end = xheader; line_end != xheader_end; ) {
7511 char* line_start = line_end;
7512 line_end = AdvPastDelim(&(line_start[1]), '\n');
7513 if (line_start[1] != '#') {
7514 continue;
7515 }
7516 char* line_main = &(line_start[2]);
7517 const uint32_t is_filter_line = StrStartsWithUnsafe(line_main, "FILTER=<");
7518 const uint32_t is_info_line = StrStartsWithUnsafe(line_main, "INFO=<");
7519 if ((!is_filter_line) && (!is_info_line)) {
7520 if (!StrStartsWithUnsafe(line_main, "contig=<")) {
7521 const uint32_t slen = line_end - line_start;
7522 if (unlikely(!ValidVcfMetaLine(line_start, slen, v43))) {
7523 goto ExportBcf_ret_INCONSISTENT_INPUT;
7524 }
7525 write_iter = memcpya(write_iter, line_start, slen);
7526 continue;
7527 }
7528 char* hkvline_iter = &(line_main[strlen("contig=<")]);
7529 char* idval;
7530 uint32_t id_slen;
7531 if (unlikely(HkvlineId(&hkvline_iter, &idval, &id_slen))) {
7532 logerrputs("Error: Malformed ##contig header line in .pvar file.\n");
7533 goto ExportBcf_ret_MALFORMED_INPUT;
7534 }
7535 if (hkvline_iter[-1] == '>') {
7536 // Otherwise-empty line. Regenerate instead of copying it.
7537 continue;
7538 }
7539 // if GetChrCodeCounted() is modified to not mutate idval, xheader
7540 // can be changed to const char*
7541 const uint32_t chr_idx = GetChrCodeCounted(cip, id_slen, idval);
7542 if (IsI32Neg(chr_idx) || (!IsSet(cip->chr_mask, chr_idx)) || (chr_idx == par1_code) || (chr_idx == par2_code)) {
7543 continue;
7544 }
7545 if (chr_idx == x_code) {
7546 x_contig_line_written = 1;
7547 }
7548 const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[chr_idx];
7549 if (unlikely(IsSet(written_contig_header_lines, chr_fo_idx))) {
7550 logerrputs("Error: Duplicate ##contig line in .pvar file.\n");
7551 goto ExportBcf_ret_MALFORMED_INPUT;
7552 }
7553 SetBit(chr_fo_idx, written_contig_header_lines);
7554 char* contig_write_start = strcpya_k(write_iter, "##contig=<ID=");
7555 char* contig_write_end = chrtoa(cip, chr_idx, contig_write_start);
7556 if ((*contig_write_start == '0') && (contig_write_end == &(contig_write_start[1]))) {
7557 // --allow-extra-chr 0 special case
7558 // note that write_iter has *not* been advanced
7559 contig_zero_written = 1; // technically we write this later
7560 continue;
7561 }
7562 write_iter = contig_write_end;
7563 if (unlikely(!ValidVcfContigName(contig_write_start, write_iter, v43))) {
7564 goto ExportBcf_ret_MALFORMED_INPUT;
7565 }
7566 char* closing_gt = &(line_end[-2]);
7567 while (ctou32(*closing_gt) <= 32) {
7568 --closing_gt;
7569 }
7570 if (unlikely(*closing_gt != '>')) {
7571 logerrputs("Error: ##contig header line in .pvar file doesn't end with '>'.\n");
7572 goto ExportBcf_ret_MALFORMED_INPUT;
7573 }
7574 if (contig_lens && contig_lens[chr_idx]) {
7575 if (unlikely(FixAndWriteContigHeaderLine(hkvline_iter, idval, closing_gt, id_slen, contig_lens[chr_idx], &write_iter))) {
7576 goto ExportBcf_ret_MALFORMED_INPUT;
7577 }
7578 } else {
7579 write_iter = WriteRestOfHeaderLine(hkvline_iter, idval, closing_gt, id_slen, write_iter);
7580 }
7581 write_iter = strcpya_k(write_iter, ",IDX=");
7582 write_iter = u32toa(contig_string_idx_end, write_iter);
7583 write_iter = strcpya_k(write_iter, ">" EOLN_STR);
7584 chr_fo_to_bcf_idx[chr_fo_idx] = contig_string_idx_end++;
7585 continue;
7586 }
7587 char* hkvline_iter = &(line_main[8 - 2 * is_info_line]);
7588 char* idval;
7589 uint32_t id_slen;
7590 if (unlikely(HkvlineId(&hkvline_iter, &idval, &id_slen))) {
7591 // This part of INFO line should have already been lexed
7592 // successfully during .pvar load.
7593 assert(is_filter_line);
7594 logerrputs("Error: Malformed FILTER header line in .pvar file.\n");
7595 goto ExportBcf_ret_MALFORMED_INPUT;
7596 }
7597 char* idval_end = &(idval[id_slen]);
7598 if (unlikely(id_slen > kMaxIdSlen)) {
7599 logerrputs("Error: " PROG_NAME_STR " does not support FILTER/INFO keys longer than " MAX_ID_SLEN_STR " characters.\n");
7600 goto ExportBcf_ret_MALFORMED_INPUT;
7601 }
7602 unsigned char prechar = 8;
7603 if (is_info_line) {
7604 char* typestr;
7605 uint32_t type_slen;
7606 if (unlikely(HkvlineFind(hkvline_iter, "Type", &typestr, &type_slen))) {
7607 *idval_end = '\0';
7608 snprintf(g_logbuf, kLogbufSize, "Error: Invalid INFO/%s header line in .pvar file.\n", idval);
7609 goto ExportBcf_ret_MALFORMED_INPUT_WW;
7610 }
7611 if (strequal_k(typestr, "Flag", type_slen)) {
7612 prechar = 1;
7613 } else if (strequal_k(typestr, "Integer", type_slen)) {
7614 prechar = 3;
7615 if (!info_end_exists) {
7616 // ignore when this isn't of integer type
7617 info_end_exists = strequal_k(idval, "END", id_slen);
7618 }
7619 } else if (strequal_k(typestr, "Float", type_slen)) {
7620 prechar = 5;
7621 } else if (likely(strequal_k(typestr, "String", type_slen) ||
7622 strequal_k(typestr, "Character", type_slen))) {
7623 prechar = 7;
7624 } else {
7625 *idval_end = '\0';
7626 snprintf(g_logbuf, kLogbufSize, "Error: Invalid INFO/%s header line in .pvar file.\n", idval);
7627 goto ExportBcf_ret_MALFORMED_INPUT_WW;
7628 }
7629 } else if (strequal_k(idval, "PASS", id_slen)) {
7630 // Don't duplicate this.
7631 continue;
7632 }
7633 char* closing_gt = &(line_end[-2]);
7634 while (ctou32(*closing_gt) <= 32) {
7635 --closing_gt;
7636 }
7637 if (unlikely(*closing_gt != '>')) {
7638 *idval_end = '\0';
7639 snprintf(g_logbuf, kLogbufSize, "Error: %s:%s header line in .pvar file doesn't end with '>'.\n", is_info_line? "INFO" : "FILTER", idval);
7640 goto ExportBcf_ret_MALFORMED_INPUT;
7641 }
7642 uint32_t cur_idx;
7643 reterr = AddToFifHtable(g_bigstack_base, idval, fif_keys_htable_size, id_slen, prechar, &tmp_alloc_end, fif_keys_mutable, fif_keys_htable, &fif_key_ct, &cur_idx);
7644 if (unlikely(reterr)) {
7645 goto ExportBcf_ret_1;
7646 }
7647 write_iter = memcpya(write_iter, line_start, closing_gt - line_start);
7648 write_iter = strcpya_k(write_iter, ",IDX=");
7649 write_iter = u32toa(cur_idx, write_iter);
7650 write_iter = strcpya_k(write_iter, ">" EOLN_STR);
7651 }
7652 }
7653 // fill in the missing ##contig lines
7654 if (contig_zero_written) {
7655 write_iter = strcpya_k(write_iter, "##contig=<ID=0>" EOLN_STR);
7656 }
7657 uint32_t chrx_exists = 0;
7658 for (uint32_t chr_fo_idx = 0; chr_fo_idx != cip->chr_ct; ++chr_fo_idx) {
7659 if (IsSet(written_contig_header_lines, chr_fo_idx)) {
7660 continue;
7661 }
7662 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
7663 if ((!IsSet(cip->chr_mask, chr_idx)) || AllBitsAreZero(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], cip->chr_fo_vidx_start[chr_fo_idx + 1])) {
7664 continue;
7665 }
7666 if ((chr_idx == x_code) || (chr_idx == par1_code) || (chr_idx == par2_code)) {
7667 chrx_exists = 1;
7668 continue;
7669 }
7670 char* chr_name_write_start = strcpya_k(write_iter, "##contig=<ID=");
7671 char* chr_name_write_end = chrtoa(cip, chr_idx, chr_name_write_start);
7672 if ((*chr_name_write_start == '0') && (chr_name_write_end == &(chr_name_write_start[1]))) {
7673 // --allow-extra-chr 0 special case
7674 if (contig_zero_written) {
7675 continue;
7676 }
7677 contig_zero_written = 1;
7678 write_iter = chr_name_write_end;
7679 } else {
7680 write_iter = chr_name_write_end;
7681 if (contig_lens && contig_lens[chr_idx]) {
7682 write_iter = strcpya_k(write_iter, ",length=");
7683 write_iter = u32toa(contig_lens[chr_idx], write_iter);
7684 }
7685 }
7686 write_iter = strcpya_k(write_iter, ",IDX=");
7687 write_iter = u32toa(contig_string_idx_end, write_iter);
7688 write_iter = strcpya_k(write_iter, ">" EOLN_STR);
7689 chr_fo_to_bcf_idx[chr_fo_idx] = contig_string_idx_end++;
7690 }
7691 if (chrx_exists) {
7692 uint32_t x_contig_string_idx;
7693 if (!x_contig_line_written) {
7694 char* chr_name_write_start = strcpya_k(write_iter, "##contig=<ID=");
7695 char* chr_name_write_end = chrtoa(cip, x_code, chr_name_write_start);
7696 write_iter = strcpya_k(chr_name_write_end, ",IDX=");
7697 write_iter = u32toa(contig_string_idx_end, write_iter);
7698 write_iter = strcpya_k(write_iter, ">" EOLN_STR);
7699 x_contig_string_idx = contig_string_idx_end;
7700 if ((!IsI32Neg(x_code)) && IsSet(cip->chr_mask, x_code)) {
7701 const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[x_code];
7702 chr_fo_to_bcf_idx[chr_fo_idx] = contig_string_idx_end;
7703 }
7704 ++contig_string_idx_end;
7705 } else {
7706 const uint32_t x_chr_fo_idx = cip->chr_idx_to_foidx[x_code];
7707 x_contig_string_idx = chr_fo_to_bcf_idx[x_chr_fo_idx];
7708 }
7709 if ((!IsI32Neg(par1_code)) && IsSet(cip->chr_mask, par1_code)) {
7710 const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[par1_code];
7711 chr_fo_to_bcf_idx[chr_fo_idx] = x_contig_string_idx;
7712 }
7713 if ((!IsI32Neg(par2_code)) && IsSet(cip->chr_mask, par2_code)) {
7714 const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[par2_code];
7715 chr_fo_to_bcf_idx[chr_fo_idx] = x_contig_string_idx;
7716 }
7717 }
7718 BigstackReset(written_contig_header_lines);
7719 if (write_pr) {
7720 if (unlikely(info_flags & kfInfoPrNonflagPresent)) {
7721 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");
7722 goto ExportBcf_ret_INCONSISTENT_INPUT;
7723 }
7724 if (!info_pr_flag_present) {
7725 write_iter = strcpya_k(write_iter, "##INFO=<ID=PR,Number=0,Type=Flag,Description=\"Provisional reference allele, may not be based on real reference genome\",IDX=");
7726 reterr = AddToFifHtable(g_bigstack_base, "PR", fif_keys_htable_size, strlen("PR"), 1, &tmp_alloc_end, fif_keys_mutable, fif_keys_htable, &fif_key_ct, &pr_key_idx);
7727 if (unlikely(reterr)) {
7728 goto ExportBcf_ret_1;
7729 }
7730 write_iter = u32toa(pr_key_idx, write_iter);
7731 write_iter = strcpya_k(write_iter, ">" EOLN_STR);
7732 } else {
7733 pr_key_idx = IdHtableFind("PR", TO_CONSTCPCONSTP(fif_keys_mutable), fif_keys_htable, strlen("PR"), fif_keys_htable_size);
7734 assert(pr_key_idx != UINT32_MAX);
7735 }
7736 }
7737 end_key_idx = IdHtableFind("END", TO_CONSTCPCONSTP(fif_keys_mutable), fif_keys_htable, strlen("END"), fif_keys_htable_size);
7738 if (end_key_idx != UINT32_MAX) {
7739 if ((fif_keys_mutable[end_key_idx][-1] & 7) != 3) {
7740 // Not an INFO key of type integer; ignore.
7741 end_key_idx = UINT32_MAX;
7742 }
7743 }
7744 if (write_ds) {
7745 write_iter = strcpya_k(write_iter, "##FORMAT=<ID=DS,Number=A,Type=Float,Description=\"Estimated Alternate Allele Dosage : [P(0/1)+2*P(1/1)]\",IDX=");
7746 reterr = AddToFifHtable(g_bigstack_base, "DS", fif_keys_htable_size, strlen("DS"), 0, &tmp_alloc_end, fif_keys_mutable, fif_keys_htable, &fif_key_ct, &dosage_key_idx);
7747 if (unlikely(reterr)) {
7748 goto ExportBcf_ret_1;
7749 }
7750 write_iter = u32toa(dosage_key_idx, write_iter);
7751 write_iter = strcpya_k(write_iter, ">" EOLN_STR);
7752 if (write_hds) {
7753 // Note that HDS ploidy intentionally does NOT match GT ploidy in the
7754 // unphased het haploid case.
7755 write_iter = strcpya_k(write_iter, "##FORMAT=<ID=HDS,Number=.,Type=Float,Description=\"Estimated Haploid Alternate Allele Dosage \",IDX=");
7756 reterr = AddToFifHtable(g_bigstack_base, "HDS", fif_keys_htable_size, strlen("HDS"), 0, &tmp_alloc_end, fif_keys_mutable, fif_keys_htable, &fif_key_ct, &hds_key_idx);
7757 if (unlikely(reterr)) {
7758 goto ExportBcf_ret_1;
7759 }
7760 write_iter = u32toa(hds_key_idx, write_iter);
7761 write_iter = strcpya_k(write_iter, ">" EOLN_STR);
7762 }
7763 } else if (write_some_dosage) {
7764 write_iter = strcpya_k(write_iter, "##FORMAT=<ID=GP,Number=G,Type=Float,Description=\"Estimated Posterior Probabilities for Genotypes 0/0, 0/1 and 1/1 \",IDX=");
7765 reterr = AddToFifHtable(g_bigstack_base, "GP", fif_keys_htable_size, strlen("GP"), 0, &tmp_alloc_end, fif_keys_mutable, fif_keys_htable, &fif_key_ct, &dosage_key_idx);
7766 if (unlikely(reterr)) {
7767 goto ExportBcf_ret_1;
7768 }
7769 write_iter = u32toa(dosage_key_idx, write_iter);
7770 write_iter = strcpya_k(write_iter, ">" EOLN_STR);
7771 }
7772 // possible todo: optionally export .psam information as
7773 // PEDIGREE/META/SAMPLE lines in header, and make --vcf/--bcf be able to
7774 // read it
7775 if (!ds_only) {
7776 write_iter = strcpya_k(write_iter, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\",IDX=");
7777 reterr = AddToFifHtable(g_bigstack_base, "GT", fif_keys_htable_size, strlen("GT"), 0, &tmp_alloc_end, fif_keys_mutable, fif_keys_htable, &fif_key_ct, &gt_key_idx);
7778 if (unlikely(reterr)) {
7779 goto ExportBcf_ret_1;
7780 }
7781 write_iter = u32toa(gt_key_idx, write_iter);
7782 write_iter = strcpya_k(write_iter, ">" EOLN_STR);
7783 }
7784 write_iter = strcpya_k(write_iter, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT");
7785 BigstackEndSet(tmp_alloc_end);
7786
7787 char* exported_sample_ids;
7788 uintptr_t max_exported_sample_id_blen;
7789 if (unlikely(ExportIdpaste(sample_include, siip, "bcf", "bcf", sample_ct, exportf_id_paste, exportf_id_delim, &max_exported_sample_id_blen, &exported_sample_ids))) {
7790 goto ExportBcf_ret_NOMEM;
7791 }
7792 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
7793 *write_iter++ = '\t';
7794 write_iter = strcpya(write_iter, &(exported_sample_ids[sample_idx * max_exported_sample_id_blen]));
7795 }
7796 AppendBinaryEoln(&write_iter);
7797 *write_iter++ = '\0';
7798 assert(S_CAST(uintptr_t, write_iter - header_start) <= header_ubound);
7799 #ifdef __LP64__
7800 if (unlikely(S_CAST(uintptr_t, write_iter - header_start) > 0xffffffffU)) {
7801 logerrputs("Error: Cannot export BCF, since header would be too large.\n");
7802 goto ExportBcf_ret_INCONSISTENT_INPUT;
7803 }
7804 #endif
7805 const uint32_t l_header = write_iter - header_start;
7806 memcpy(&(writebuf[5]), &l_header, sizeof(int32_t));
7807 }
7808 char* writebuf_flush = &(writebuf[kMaxMediumLine]);
7809 if (unlikely(bgzfwrite_ck(writebuf_flush, &bgzf, &write_iter))) {
7810 goto ExportBcf_ret_WRITE_FAIL;
7811 }
7812 // max_allele_ct == 2:
7813 // GT: 2 bytes
7814 // GP: 3 floats = 12 bytes
7815 // DS + HDS: 3 floats = 12 bytes
7816 // DS only: 1 float = 4 bytes
7817 // max_allele_ct > 2:
7818 // GT: 2 bytes if max_allele_ct < 64, 4 bytes otherwise
7819 // GP: if requested, check max_gp_allele_ct among multiallelic-dosage
7820 // variants.
7821 // if none found (always true for now), 12 bytes.
7822 // if present, (max_gp_allele_ct * (max_gp_allele_ct + 1) / 2) * 8,
7823 // which sucks ass
7824 // DS + HDS: 3 * (max_allele_ct - 1) floats
7825 // DS only: (max_allele_ct - 1) floats
7826 const uint32_t max_allele_ct = PgrGetMaxAlleleCt(simple_pgrp);
7827 uintptr_t output_bytes_per_sample;
7828 if (!allele_idx_offsets) {
7829 if (write_some_dosage) {
7830 if (ds_only) {
7831 output_bytes_per_sample = 4;
7832 } else {
7833 output_bytes_per_sample = (write_ds && (!write_hds))? 6 : 14;
7834 }
7835 } else {
7836 output_bytes_per_sample = 2;
7837 }
7838 } else {
7839 if (ds_only) {
7840 output_bytes_per_sample = 4 * (max_allele_ct - 1);
7841 } else {
7842 output_bytes_per_sample = 2 + 2 * (max_allele_ct > 63);
7843 if (write_some_dosage) {
7844 if (write_ds) {
7845 if (write_hds) {
7846 output_bytes_per_sample += 12 * (max_allele_ct - 1);
7847 } else {
7848 output_bytes_per_sample += 4 * (max_allele_ct - 1);
7849 }
7850 } else {
7851 // GP should only be written for biallelic variants, for now
7852 // would need to take max of this and GT length, but this is always
7853 // larger
7854 output_bytes_per_sample = 14;
7855 }
7856 }
7857 }
7858 }
7859 // FILTER entries past the first always require 2+ .pvar bytes, and never
7860 // require more than 4 output bytes.
7861 // INFO worst case is also a 2:4 ratio.
7862 uint64_t writebuf_blen = max_chr_slen + S_CAST(uint64_t, kMaxIdSlen) + (max_filter_slen + info_reload_slen) * 2 + S_CAST(uint64_t, sample_ct) * output_bytes_per_sample + 128;
7863 {
7864 // Also need to fit all alleles simultaneously; we can't follow our usual
7865 // strategy of flushing after every allele.
7866 uintptr_t max_allele_length_bytes = 1;
7867 if (max_allele_slen > 14) {
7868 // Need 2-5 additional bytes to encode overflow-size.
7869 if (max_allele_slen < 128) {
7870 max_allele_length_bytes = 3;
7871 } else if (max_allele_slen < 32768) {
7872 max_allele_length_bytes = 4;
7873 } else {
7874 max_allele_length_bytes = 6;
7875 }
7876 }
7877 uint64_t allele_ubound = (S_CAST(uint64_t, max_allele_slen) + max_allele_length_bytes) * max_allele_ct;
7878 if (allele_ubound > 1000000000) {
7879 // Compute a tighter bound. Could multithread this if it ever comes up
7880 // regularly.
7881 allele_ubound = 0;
7882 uintptr_t variant_uidx_base = 0;
7883 uintptr_t cur_bits = variant_include[0];
7884 uint32_t allele_ct = 2;
7885 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
7886 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
7887 uintptr_t allele_idx_offset_base = variant_uidx * 2;
7888 if (allele_idx_offsets) {
7889 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
7890 allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
7891 }
7892 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
7893 uint64_t cur_ubound = allele_ct * max_allele_length_bytes;
7894 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
7895 cur_ubound += strlen(cur_alleles[allele_idx]);
7896 }
7897 if (cur_ubound > allele_ubound) {
7898 allele_ubound = cur_ubound;
7899 }
7900 }
7901 }
7902 writebuf_blen += allele_ubound;
7903 }
7904 writebuf_blen += kMaxMediumLine;
7905 BigstackReset(writebuf);
7906 if (unlikely(bigstack_alloc64_c(writebuf_blen, &writebuf))) {
7907 goto ExportBcf_ret_NOMEM;
7908 }
7909
7910 logprintfww5("--export bcf to %s ... ", outname);
7911 fputs("0%", stdout);
7912 fflush(stdout);
7913 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
7914 PgenVariant pgv;
7915 // a few branches assume genovec is allocated up to word-pair boundary, and
7916 // that extra word is zeroed out if there is one
7917 if (unlikely(bigstack_alloc_w(sample_ctl * 2, &pgv.genovec))) {
7918 goto ExportBcf_ret_NOMEM;
7919 }
7920 pgv.genovec[sample_ctl * 2 - 1] = 0;
7921 pgv.patch_01_set = nullptr;
7922 pgv.patch_01_vals = nullptr;
7923 pgv.patch_10_set = nullptr;
7924 pgv.patch_10_vals = nullptr;
7925 if (allele_idx_offsets) {
7926 if (unlikely(bigstack_alloc_w(sample_ctl, &(pgv.patch_01_set)) ||
7927 bigstack_alloc_ac(sample_ct, &(pgv.patch_01_vals)) ||
7928 bigstack_alloc_w(sample_ctl, &(pgv.patch_10_set)) ||
7929 bigstack_alloc_ac(sample_ct * 2, &(pgv.patch_10_vals)))) {
7930 goto ExportBcf_ret_NOMEM;
7931 }
7932 }
7933 // See ExportVcf() common on how prev_phased works.
7934 const uint32_t load_dphase = write_hds && (pgfip->gflags & kfPgenGlobalDosagePhasePresent);
7935 const uint32_t some_phased = (!ds_only) && ((pgfip->gflags & kfPgenGlobalHardcallPhasePresent) || load_dphase);
7936 uintptr_t* prev_phased = nullptr;
7937 pgv.phasepresent = nullptr;
7938 pgv.phaseinfo = nullptr;
7939 if (some_phased) {
7940 if (unlikely(bigstack_alloc_w(sample_ctl, &prev_phased) ||
7941 bigstack_alloc_w(sample_ctl, &(pgv.phasepresent)) ||
7942 bigstack_alloc_w(sample_ctl, &(pgv.phaseinfo)))) {
7943 goto ExportBcf_ret_NOMEM;
7944 }
7945 SetAllBits(sample_ct, prev_phased);
7946 }
7947
7948 pgv.dosage_present = nullptr;
7949 pgv.dosage_main = nullptr;
7950 pgv.dphase_present = nullptr;
7951 pgv.dphase_delta = nullptr;
7952 if (write_some_dosage && (pgfip->gflags & kfPgenGlobalDosagePresent)) {
7953 if (unlikely(bigstack_alloc_w(sample_ctl, &(pgv.dosage_present)) ||
7954 bigstack_alloc_dosage(sample_ct, &(pgv.dosage_main)))) {
7955 goto ExportBcf_ret_NOMEM;
7956 }
7957 if (load_dphase) {
7958 if (unlikely(bigstack_alloc_w(sample_ctl, &(pgv.dphase_present)) ||
7959 bigstack_alloc_dphase(sample_ct, &(pgv.dphase_delta)))) {
7960 goto ExportBcf_ret_NOMEM;
7961 }
7962 }
7963 }
7964 const uint32_t fif_key_ctl = BitCtToWordCt(fif_key_ct);
7965 uintptr_t* fif_seen;
7966 if (unlikely(bigstack_alloc_w(fif_key_ctl, &fif_seen))) {
7967 goto ExportBcf_ret_NOMEM;
7968 }
7969
7970 // assumes little-endian
7971 // maybe want to pass references to these arrays later, but leave as
7972 // C-style for now
7973 // 4-genotype-at-a-time lookup in basic case
7974 // these lookup tables are getting large enough to belong in workspace
7975 // rather than stack memory.
7976 uint16_t* basic_genobytes4;
7977 unsigned char* haploid_genobytes4;
7978 uint16_t* haploid_hh_genobytes4;
7979 uint16_t* phased_genobytes2;
7980 uint16_t* phased_hh_genobytes2;
7981 uint32_t* ds_genobytes4;
7982 uint32_t* ds_haploid_genobytes4;
7983 uint32_t* hds_haploid_genobytes4;
7984 if (unlikely(bigstack_alloc_u16(1024, &basic_genobytes4) ||
7985 bigstack_alloc_uc(kLookup256x1bx4Size, &haploid_genobytes4) ||
7986 bigstack_alloc_u16(1024, &haploid_hh_genobytes4) ||
7987 bigstack_alloc_u16(492, &phased_genobytes2) ||
7988 bigstack_alloc_u16(492, &phased_hh_genobytes2) ||
7989 bigstack_alloc_u32(1024, &ds_genobytes4) ||
7990 bigstack_alloc_u32(1024, &ds_haploid_genobytes4) ||
7991 bigstack_alloc_u32(1024, &hds_haploid_genobytes4))) {
7992 goto ExportBcf_ret_NOMEM;
7993 }
7994 // 0/0 0/1 1/1 ./.
7995 basic_genobytes4[0] = 0x0202;
7996 basic_genobytes4[4] = 0x0402;
7997 basic_genobytes4[8] = 0x0404;
7998 basic_genobytes4[12] = 0;
7999 InitLookup256x2bx4(basic_genobytes4);
8000
8001 haploid_genobytes4[0] = 2;
8002 haploid_genobytes4[4] = 0;
8003 haploid_genobytes4[8] = 4;
8004 haploid_genobytes4[12] = 0;
8005 InitLookup256x1bx4(haploid_genobytes4);
8006
8007 haploid_hh_genobytes4[0] = 0x8102;
8008 haploid_hh_genobytes4[4] = 0x0402;
8009 haploid_hh_genobytes4[8] = 0x8104;
8010 haploid_hh_genobytes4[12] = 0x8100;
8011 InitLookup256x2bx4(haploid_hh_genobytes4);
8012
8013 phased_genobytes2[0] = 0x0202;
8014 phased_genobytes2[2] = 0x0402;
8015 phased_genobytes2[4] = 0x0404;
8016 phased_genobytes2[6] = 0;
8017 phased_genobytes2[32] = 0x0302;
8018 phased_genobytes2[34] = 0x0502;
8019 phased_genobytes2[36] = 0x0504;
8020 phased_genobytes2[38] = 0x100;
8021 phased_genobytes2[162] = 0x0304;
8022 InitVcfPhaseLookup2b(phased_genobytes2);
8023
8024 phased_hh_genobytes2[0] = 0x8102;
8025 phased_hh_genobytes2[2] = 0x0402;
8026 phased_hh_genobytes2[4] = 0x8104;
8027 phased_hh_genobytes2[6] = 0x8100;
8028 phased_hh_genobytes2[32] = 0x8102;
8029 phased_hh_genobytes2[34] = 0x0502;
8030 phased_hh_genobytes2[36] = 0x8104;
8031 phased_hh_genobytes2[38] = 0x8100;
8032 phased_hh_genobytes2[162] = 0x0304;
8033 InitVcfPhaseLookup2b(phased_hh_genobytes2);
8034
8035 // don't bother exporting GP for hardcalls
8036 // usually don't bother for DS, but DS-force is an exception
8037 ds_genobytes4[0] = 0;
8038 ds_genobytes4[4] = 0x3f800000; // float 1.0
8039 ds_genobytes4[8] = 0x40000000; // float 2.0
8040 // in ds_force case, use MISSING instead of END_OF_VECTOR
8041 ds_genobytes4[12] = 0x7f800001;
8042 InitLookup256x4bx4(ds_genobytes4);
8043
8044 // N.B. het-haps are interpreted as ploidy-2, so DS is 1 instead of 0.5.
8045 ds_haploid_genobytes4[0] = 0;
8046 ds_haploid_genobytes4[4] = 0x3f800000;
8047 ds_haploid_genobytes4[8] = 0x3f800000;
8048 ds_haploid_genobytes4[12] = 0x7f800001;
8049 InitLookup256x4bx4(ds_haploid_genobytes4);
8050
8051 // HDS has no special treatment of het-haploids.
8052 hds_haploid_genobytes4[0] = 0;
8053 hds_haploid_genobytes4[4] = 0x3f000000; // float 0.5
8054 hds_haploid_genobytes4[8] = 0x3f800000;
8055 hds_haploid_genobytes4[12] = 0x7f800001;
8056 InitLookup256x4bx4(hds_haploid_genobytes4);
8057
8058 uint32_t* wide_genobytes4 = nullptr;
8059 uint16_t* wide_haploid_genobytes4 = nullptr;
8060 if (max_allele_ct > 63) {
8061 if (unlikely(bigstack_alloc_u32(1024, &wide_genobytes4) ||
8062 bigstack_alloc_u16(1024, &wide_haploid_genobytes4))) {
8063 goto ExportBcf_ret_NOMEM;
8064 }
8065 wide_genobytes4[0] = 0x20002;
8066 wide_genobytes4[4] = 0x40002;
8067 wide_genobytes4[8] = 0x40004;
8068 wide_genobytes4[12] = 0;
8069 InitLookup256x4bx4(wide_genobytes4);
8070
8071 wide_haploid_genobytes4[0] = 2;
8072 wide_haploid_genobytes4[4] = 0;
8073 wide_haploid_genobytes4[8] = 4;
8074 wide_haploid_genobytes4[12] = 0;
8075 InitLookup256x2bx4(wide_haploid_genobytes4);
8076 }
8077
8078 int32_t* info_int_buf = nullptr;
8079 char* pvar_reload_line_iter = nullptr;
8080 uint32_t info_col_idx = 0;
8081 if (pvar_info_reload) {
8082 // Defend against the worst case for now. Could parse INFO-header-line
8083 // Number fields and enforce associated limitations in the future, but
8084 // we'd still use this integer-buffer size if there are any
8085 // Type=Integer,Number=. declarations.
8086 if (unlikely(bigstack_alloc_i32((info_reload_slen + 1) / 2, &info_int_buf))) {
8087 goto ExportBcf_ret_NOMEM;
8088 }
8089 reterr = PvarInfoOpenAndReloadHeader(pvar_info_reload, 1 + (max_thread_ct > 1), &pvar_reload_txs, &pvar_reload_line_iter, &info_col_idx);
8090 if (unlikely(reterr)) {
8091 goto ExportBcf_ret_TSTREAM_FAIL;
8092 }
8093 }
8094
8095 uint32_t ds_x_genobytes2[128];
8096 ds_x_genobytes2[0] = 0;
8097 ds_x_genobytes2[2] = 0x3f800000;
8098 ds_x_genobytes2[4] = 0x40000000;
8099 ds_x_genobytes2[6] = 0x7f800001;
8100 ds_x_genobytes2[32] = 0;
8101 ds_x_genobytes2[34] = 0x3f800000; // male het-hap
8102 ds_x_genobytes2[36] = 0x3f800000;
8103 ds_x_genobytes2[38] = 0x7f800001;
8104 // this performs the correct initialization for GenoarrSexLookup4b(), even
8105 // though phase is not relevant
8106 InitPhaseXNohhLookup4b(ds_x_genobytes2);
8107
8108 uint32_t ds_y_genobytes2[128];
8109 ds_y_genobytes2[0] = 0;
8110 ds_y_genobytes2[2] = 0x3f800000;
8111 ds_y_genobytes2[4] = 0x3f800000;
8112 ds_y_genobytes2[6] = 0x7f800001;
8113 ds_y_genobytes2[32] = 0;
8114 ds_y_genobytes2[34] = 0x3f800000;
8115 ds_y_genobytes2[36] = 0x3f800000;
8116 ds_y_genobytes2[38] = 0x7f800002;
8117 InitPhaseXNohhLookup4b(ds_y_genobytes2);
8118
8119 // HDS ploidy should be more trustworthy than GT ploidy when there's a
8120 // conflict, since GT must render unphased het haploids as 0/1. So under
8121 // HDS-force, diploid missing value is '.,.' instead of '.'. (Since we're
8122 // only interested in storing a trustworthy ploidy, we don't add more
8123 // missing entries in the multiallelic case.)
8124
8125 uint64_t hds_genobytes2[112] ALIGNV16;
8126 hds_genobytes2[0] = 0;
8127 hds_genobytes2[2] = 0x3f0000003f000000LLU; // 0.5,0.5
8128 hds_genobytes2[4] = 0x3f8000003f800000LLU; // 1,1
8129 hds_genobytes2[6] = 0x7f8000017f800001LLU; // .,.
8130 hds_genobytes2[34] = 0x3f80000000000000LLU; // 0,1
8131 hds_genobytes2[38] = 0x3f800000; // 1,0
8132 InitPhaseLookup8b(hds_genobytes2);
8133
8134 uint64_t hds_unphased_x_genobytes2[128] ALIGNV16;
8135 hds_unphased_x_genobytes2[0] = 0;
8136 hds_unphased_x_genobytes2[2] = 0x3f0000003f000000LLU; // 0.5,0.5
8137 hds_unphased_x_genobytes2[4] = 0x3f8000003f800000LLU; // 1,1
8138 hds_unphased_x_genobytes2[6] = 0x7f8000017f800001LLU; // .,.
8139 hds_unphased_x_genobytes2[32] = 0x7f80000200000000LLU; // 0
8140 hds_unphased_x_genobytes2[34] = 0x7f8000023f000000LLU; // 0.5
8141 hds_unphased_x_genobytes2[36] = 0x7f8000023f800000LLU; // 1
8142 hds_unphased_x_genobytes2[38] = 0x7f8000027f800001LLU; // .
8143 InitPhaseXNohhLookup8b(hds_unphased_x_genobytes2);
8144
8145 uint64_t hds_hh_genobytes2[112] ALIGNV16;
8146 hds_hh_genobytes2[0] = 0x7f80000200000000LLU;
8147 hds_hh_genobytes2[2] = 0x7f8000023f000000LLU; // 0.5
8148 hds_hh_genobytes2[4] = 0x7f8000023f800000LLU; // 1
8149 hds_hh_genobytes2[6] = 0x7f8000027f800001LLU; // .
8150 hds_hh_genobytes2[34] = 0x3f80000000000000LLU; // 0,1
8151 hds_hh_genobytes2[38] = 0x3f800000; // 1,0
8152 InitPhaseLookup8b(hds_hh_genobytes2);
8153
8154 uint32_t hds_y_genobytes2[128];
8155 hds_y_genobytes2[0] = 0;
8156 hds_y_genobytes2[2] = 0x3f000000;
8157 hds_y_genobytes2[4] = 0x3f800000;
8158 hds_y_genobytes2[6] = 0x7f800001;
8159 hds_y_genobytes2[32] = 0;
8160 hds_y_genobytes2[34] = 0x3f000000;
8161 hds_y_genobytes2[36] = 0x3f800000;
8162 hds_y_genobytes2[38] = 0x7f800002;
8163 InitPhaseXNohhLookup4b(hds_y_genobytes2);
8164
8165 const char* const* fif_keys = TO_CONSTCPCONSTP(fif_keys_mutable);
8166 const uint32_t inf_bits[2] = {0x7f800000, 0xff800000U};
8167 const char* dot_ptr = &(g_one_char_strs[92]);
8168 const uint32_t male_ct = PopcountWords(sex_male_collapsed, sample_ctl);
8169 const uint32_t female_ct = PopcountWords(sex_female_collapsed, sample_ctl);
8170 PgrSampleSubsetIndex pssi;
8171 PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi);
8172 uintptr_t variant_uidx_base = 0;
8173 uintptr_t cur_bits = variant_include[0];
8174 uint32_t chr_fo_idx = UINT32_MAX;
8175 uint32_t chr_end = 0;
8176 uint32_t chr_bcf_idx = 0;
8177 uint32_t is_x = 0;
8178 uint32_t is_y = 0;
8179 uint32_t is_haploid = 0; // includes chrX and chrY
8180 uint32_t pct = 0;
8181 uint32_t next_print_variant_idx = variant_ct / 100;
8182 uint32_t rls_variant_uidx = 0;
8183 uint32_t ref_allele_idx = 0;
8184 uint32_t alt1_allele_idx = 1;
8185 uint32_t allele_ct = 2;
8186 uint32_t invalid_allele_code_seen = 0;
8187 uint32_t first_rlen_warning_idxs[3];
8188 uint32_t rlen_warning_ct = 0;
8189 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
8190 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
8191 if (variant_uidx >= chr_end) {
8192 do {
8193 ++chr_fo_idx;
8194 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
8195 } while (variant_uidx >= chr_end);
8196 uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
8197 is_x = 0;
8198 is_y = 0;
8199 is_haploid = IsSet(cip->haploid_mask, chr_idx);
8200 if (chr_idx == cip->xymt_codes[kChrOffsetX]) {
8201 if (!male_ct) {
8202 // No male chrX ploidy fix needed if there are no males.
8203 is_haploid = 0;
8204 } else if (male_ct != sample_ct) {
8205 // Can use generic haploid encoder if all males.
8206 is_x = 1;
8207 }
8208 } else if ((chr_idx == cip->xymt_codes[kChrOffsetY]) && female_ct) {
8209 // No female chrY ploidy fix needed if there are no females.
8210 is_y = 1;
8211 }
8212 chr_bcf_idx = chr_fo_to_bcf_idx[chr_fo_idx];
8213 }
8214 char* rec_start = write_iter;
8215 // first 8 bytes are l_shared and l_indiv, fill them later
8216 memcpy(&(rec_start[8]), &chr_bcf_idx, sizeof(int32_t)); // CHROM
8217 const int32_t bp0 = S_CAST(int32_t, variant_bps[variant_uidx] - 1);
8218 memcpy(&(rec_start[12]), &bp0, sizeof(int32_t)); // POS
8219 // [16,20) is rlen, which may depend on INFO/END... er, VCF 4.5 spec says
8220 // INFO/SVLEN and FORMAT/LEN should be consulted instead
8221
8222 if ((!pvar_quals) || (!IsSet(pvar_qual_present, variant_uidx))) {
8223 const uint32_t missing_val = 0x7f800001;
8224 memcpy(&(rec_start[20]), &missing_val, 4);
8225 } else {
8226 memcpy(&(rec_start[20]), &(pvar_quals[variant_uidx]), 4);
8227 }
8228
8229 // [24,26) is n_info
8230 // [26,28) is n_allele
8231 memcpy(&(rec_start[28]), &sample_ct, sizeof(int32_t));
8232 // [31] is n_fmt
8233 write_iter = &(rec_start[32]);
8234
8235 // ID
8236 const char* variant_id = variant_ids[variant_uidx];
8237 if (strequal_k_unsafe(variant_id, ".")) {
8238 *write_iter++ = '\7';
8239 } else {
8240 write_iter = AppendBcfString(variant_id, write_iter);
8241 }
8242
8243 // REF, ALT
8244 uintptr_t allele_idx_offset_base = variant_uidx * 2;
8245 if (allele_idx_offsets) {
8246 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
8247 allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
8248 }
8249 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
8250 if (allele_permute) {
8251 ref_allele_idx = allele_permute[allele_idx_offset_base];
8252 alt1_allele_idx = allele_permute[allele_idx_offset_base + 1];
8253 }
8254 const char* ref_allele = cur_alleles[ref_allele_idx];
8255 uint32_t rlen = strlen(ref_allele);
8256 if (ref_allele != dot_ptr) {
8257 write_iter = AppendBcfCountedString(ref_allele, rlen, write_iter);
8258 if (!invalid_allele_code_seen) {
8259 invalid_allele_code_seen = !ValidVcfAlleleCode(ref_allele);
8260 }
8261 } else {
8262 write_iter = AppendBcfString("N", write_iter);
8263 }
8264 const char* alt1_allele = cur_alleles[alt1_allele_idx];
8265 uint16_t n_allele = allele_ct;
8266 if (alt1_allele != dot_ptr) {
8267 write_iter = AppendBcfString(alt1_allele, write_iter);
8268 if (!invalid_allele_code_seen) {
8269 invalid_allele_code_seen = !ValidVcfAlleleCode(alt1_allele);
8270 }
8271 if (allele_ct > 2) {
8272 for (uint32_t cur_allele_uidx = 0; cur_allele_uidx != allele_ct; ++cur_allele_uidx) {
8273 if ((cur_allele_uidx == ref_allele_idx) || (cur_allele_uidx == alt1_allele_idx)) {
8274 // if this is noticeably suboptimal, have two loops, with inner
8275 // loop going up to cur_allele_stop.
8276 // (also wrap this in a function, this comes up a bunch of times)
8277 continue;
8278 }
8279 const char* cur_allele = cur_alleles[cur_allele_uidx];
8280 write_iter = AppendBcfString(cur_allele, write_iter);
8281 if (!invalid_allele_code_seen) {
8282 invalid_allele_code_seen = !ValidVcfAlleleCode(cur_allele);
8283 }
8284 }
8285 }
8286 } else {
8287 if (unlikely(allele_ct > 2)) {
8288 snprintf(g_logbuf, kLogbufSize, "Error: --export bcf: Multiallelic variant '%s' has a missing ALT allele.\n", variant_id);
8289 goto ExportBcf_ret_MALFORMED_INPUT_WW;
8290 }
8291 n_allele = 1;
8292 }
8293
8294 // QUAL already filled
8295
8296 // FILTER
8297 if ((!pvar_filter_present) || (!IsSet(pvar_filter_present, variant_uidx))) {
8298 *write_iter++ = '\0';
8299 } else if (!IsSet(pvar_filter_npass, variant_uidx)) {
8300 *write_iter++ = 0x11;
8301 *write_iter++ = '\0';
8302 } else {
8303 const char* cur_filter_iter = pvar_filter_storage[variant_uidx];
8304 // two passes; determine type descriptor during first pass (and may as
8305 // well deduplicate and sort while we're at it)
8306 ZeroWArr(fif_key_ctl, fif_seen);
8307 while (1) {
8308 // bugfix (3 Jan 2021): this is semicolon, not comma, delimited
8309 const char* tok_end = strchrnul(cur_filter_iter, ';');
8310 const uint32_t fif_idx = IdHtableFindNnt(cur_filter_iter, fif_keys, fif_keys_htable, tok_end - cur_filter_iter, fif_keys_htable_size);
8311 // Second predicate verifies this is actually a FILTER key.
8312 if (unlikely((fif_idx == UINT32_MAX) || (!(fif_keys[fif_idx][-1] & 8)))) {
8313 snprintf(g_logbuf, kLogbufSize, "Error: --export bcf: Variant '%s' has a FILTER value with no corresponding header line.\n", variant_id);
8314 goto ExportBcf_ret_MALFORMED_INPUT_WW;
8315 }
8316 SetBit(fif_idx, fif_seen);
8317 if ((*tok_end) == '\0') {
8318 break;
8319 }
8320 cur_filter_iter = &(tok_end[1]);
8321 }
8322 const uint32_t nfilter = PopcountWords(fif_seen, fif_key_ctl);
8323 const uint32_t max_idx = FindLast1BitBefore(fif_seen, fif_key_ct);
8324 uintptr_t fif_idx_base = 0;
8325 uintptr_t fif_seen_bits = fif_seen[0];
8326 if (max_idx <= 127) {
8327 write_iter = AppendBcfVecType(1, nfilter, write_iter);
8328 for (uint32_t uii = 0; uii != nfilter; ++uii) {
8329 *write_iter++ = BitIter1(fif_seen, &fif_idx_base, &fif_seen_bits);
8330 }
8331 } else if (max_idx <= 32767) {
8332 write_iter = AppendBcfVecType(2, nfilter, write_iter);
8333 for (uint32_t uii = 0; uii != nfilter; ++uii) {
8334 const uint16_t fif_idx = BitIter1(fif_seen, &fif_idx_base, &fif_seen_bits);
8335 memcpy(write_iter, &fif_idx, sizeof(int16_t));
8336 write_iter += sizeof(int16_t);
8337 }
8338 } else {
8339 write_iter = AppendBcfVecType(3, nfilter, write_iter);
8340 for (uint32_t uii = 0; uii != nfilter; ++uii) {
8341 const uint32_t fif_idx = BitIter1(fif_seen, &fif_idx_base, &fif_seen_bits);
8342 memcpy(write_iter, &fif_idx, sizeof(int32_t));
8343 write_iter += sizeof(int32_t);
8344 }
8345 }
8346 }
8347
8348 // INFO
8349 const uint32_t is_pr = all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx));
8350 uint16_t n_info = 0;
8351 if (pvar_reload_line_iter) {
8352 reterr = PvarInfoReload(info_col_idx, variant_uidx, &pvar_reload_txs, &pvar_reload_line_iter, &rls_variant_uidx);
8353 if (unlikely(reterr)) {
8354 goto ExportBcf_ret_TSTREAM_FAIL;
8355 }
8356 // BCF translation of PvarInfoWrite().
8357 char* info_iter = pvar_reload_line_iter;
8358 char* info_end = CurTokenEnd(info_iter);
8359 uint32_t n_info_raw = 0;
8360 ZeroWArr(fif_key_ctl, fif_seen);
8361 if ((*info_iter != '.') || (&(info_iter[1]) != info_end)) {
8362 const char orig_info_end_char = *info_end;
8363 *info_end = ';';
8364 char* info_stop = &(info_end[1]);
8365 do {
8366 char* key_end = S_CAST(char*, rawmemchr2(info_iter, '=', ';'));
8367 const uint32_t fif_idx = IdHtableFindNnt(info_iter, fif_keys, fif_keys_htable, key_end - info_iter, fif_keys_htable_size);
8368 // Second predicate verifies this is actually an INFO key.
8369 uint32_t info_type_code = 0;
8370 if (fif_idx != UINT32_MAX) {
8371 info_type_code = ctou32(fif_keys[fif_idx][-1]) & 7;
8372 }
8373 if (unlikely(!(info_type_code & 1))) {
8374 snprintf(g_logbuf, kLogbufSize, "Error: --export bcf: Variant '%s' has an INFO key with no corresponding header line.\n", variant_id);
8375 goto ExportBcf_ret_MALFORMED_INPUT_WW;
8376 }
8377 if (unlikely(IsSet(fif_seen, fif_idx))) {
8378 snprintf(g_logbuf, kLogbufSize, "Error: --export bcf: Variant '%s' has multiple INFO/%s entries.\n", variant_id, fif_keys[fif_idx]);
8379 goto ExportBcf_ret_MALFORMED_INPUT_WW;
8380 }
8381 SetBit(fif_idx, fif_seen);
8382 ++n_info_raw;
8383 write_iter = AppendBcfTypedInt(fif_idx, write_iter);
8384 if (*key_end == ';') {
8385 // bugfix (8 Jan 2023): this previously errored out on non-flag
8386 // keys, but VCFv4.3 (though not v4.2) allows non-flag keys to
8387 // have no value.
8388
8389 // Anything goes here. As of this writing, the spec suggests
8390 // 0x11 0x01 (single int8 equal to 1), but bcftools emits the
8391 // more compact 0x00 (typeless missing value); we imitate
8392 // bcftools.
8393 *write_iter++ = '\0';
8394 info_iter = &(key_end[1]);
8395 continue;
8396 }
8397 char* value_start = &(key_end[1]);
8398 char* value_end = S_CAST(char*, rawmemchr(value_start, ';'));
8399 if (info_type_code == 7) {
8400 // No need to count commas in this case.
8401 write_iter = AppendBcfCountedString(value_start, value_end - value_start, write_iter);
8402 } else {
8403 const uint32_t value_ct = 1 + CountByte(value_start, ',', value_end - value_start);
8404 *value_end = ',';
8405 if (info_type_code == 3) {
8406 // Integer
8407 // We don't know upfront whether int8, int16, or int32 is best.
8408 // We could use two passes, but ScanmovIntBounded32() is slower
8409 // than the other steps here. So we instead decode to an
8410 // int32[] buffer while tracking whether any numbers are
8411 // actually out of int8/int16 range, and then convert to the
8412 // final encoding afterward.
8413 const char* value_iter = value_start;
8414 uint32_t encode_as_small_ints = 2; // 2 = int8, 1 = int16
8415 for (uint32_t value_idx = 0; value_idx != value_ct; ++value_idx) {
8416 int32_t cur_val;
8417 if (*value_iter == '.') {
8418 cur_val = -2147483647 - 1; // missing
8419 ++value_iter;
8420 } else {
8421 if (unlikely(ScanmovIntBounded(0x7ffffff8, 0x7fffffff, &value_iter, &cur_val))) {
8422 snprintf(g_logbuf, kLogbufSize, "Error: --export bcf: Variant '%s' has an invalid INFO/%s value.\n", variant_id, fif_keys[fif_idx]);
8423 goto ExportBcf_ret_MALFORMED_INPUT_WW;
8424 }
8425 if (encode_as_small_ints) {
8426 if ((cur_val < -32760) || (cur_val > 32767)) {
8427 encode_as_small_ints = 0;
8428 } else if ((encode_as_small_ints == 2) && ((cur_val < -120) || (cur_val > 127))) {
8429 encode_as_small_ints = 1;
8430 }
8431 }
8432 }
8433 if (unlikely(*value_iter != ',')) {
8434 snprintf(g_logbuf, kLogbufSize, "Error: --export bcf: Variant '%s' has an invalid INFO/%s value.\n", variant_id, fif_keys[fif_idx]);
8435 goto ExportBcf_ret_MALFORMED_INPUT_WW;
8436 }
8437 info_int_buf[value_idx] = cur_val;
8438 ++value_iter;
8439 }
8440 write_iter = AppendBcfVecType(3 - encode_as_small_ints, value_ct, write_iter);
8441 if (!encode_as_small_ints) {
8442 // int32
8443 write_iter = memcpya(write_iter, info_int_buf, value_ct * sizeof(int32_t));
8444 } else if (encode_as_small_ints == 1) {
8445 // int16
8446 for (uint32_t value_idx = 0; value_idx != value_ct; ++value_idx) {
8447 int32_t cur_val = info_int_buf[value_idx];
8448 if (cur_val == (-2147483647 - 1)) {
8449 cur_val = -32768;
8450 }
8451 const int16_t cur_i16 = cur_val;
8452 CopyToUnalignedOffsetI16(CToUc(write_iter), &cur_i16, value_idx);
8453 }
8454 write_iter = &(write_iter[value_ct * sizeof(int16_t)]);
8455 } else {
8456 // int8
8457 for (uint32_t value_idx = 0; value_idx != value_ct; ++value_idx) {
8458 int32_t cur_val = info_int_buf[value_idx];
8459 if (cur_val == (-2147483647 - 1)) {
8460 cur_val = -128;
8461 }
8462 write_iter[value_idx] = cur_val;
8463 }
8464 write_iter = &(write_iter[value_ct]);
8465 }
8466 if ((fif_idx == end_key_idx) && (value_ct == 1) && (info_int_buf[0] != (-2147483647 - 1))) {
8467 // Only save INFO/END-derived rlen when REF is a single base,
8468 // and info_end_rlen is positive.
8469 // Otherwise, print a warning if the two rlens aren't equal.
8470 // TODO: process INFO/SVLEN and FORMAT/LEN as directed by the
8471 // VCF 4.5 specification instead.
8472 const uint32_t info_end_rlen = 1 + info_int_buf[0] - variant_bps[variant_uidx];
8473 if ((rlen == 1) && (S_CAST(int32_t, info_end_rlen) > 0)) {
8474 rlen = info_end_rlen;
8475 } else if (rlen != info_end_rlen) {
8476 MakeRlenWarningStr(variant_id);
8477 if (!rlen_warning_ct) {
8478 logputs_silent("\n");
8479 }
8480 logputs_silent(g_logbuf);
8481 if (rlen_warning_ct < 3) {
8482 // Don't print to console now, since that has an annoying
8483 // interaction with the progress indicator.
8484 first_rlen_warning_idxs[rlen_warning_ct] = variant_uidx;
8485 }
8486 ++rlen_warning_ct;
8487 }
8488 }
8489 } else if (likely(info_type_code == 5)) {
8490 // Float
8491 // Permit nan and +/-inf, but prohibit floating-point overflow.
8492 write_iter = AppendBcfVecType(5, value_ct, write_iter);
8493 const char* value_iter = value_start;
8494 const uint32_t missing_bits = 0x7f800001;
8495 const uint32_t nan_bits = 0x7fc00000;
8496 unsigned char* write_uc = CToUc(write_iter);
8497 for (uint32_t value_idx = 0; value_idx != value_ct; ++value_idx) {
8498 if (*value_iter == '.') {
8499 CopyToUnalignedOffsetU32(write_uc, &missing_bits, value_idx);
8500 ++value_iter;
8501 } else {
8502 double dxx;
8503 const char* floatstr_end = ScanadvDouble(value_iter, &dxx);
8504 if (floatstr_end) {
8505 if (unlikely(fabs(dxx) > 3.4028235677973362e38)) {
8506 snprintf(g_logbuf, kLogbufSize, "Error: --export bcf: Variant '%s' has an out-of-range INFO/%s value.\n", variant_id, fif_keys[fif_idx]);
8507 goto ExportBcf_ret_MALFORMED_INPUT_WW;
8508 }
8509 const float fxx = S_CAST(float, dxx);
8510 CopyToUnalignedOffsetF(write_uc, &fxx, value_idx);
8511 value_iter = floatstr_end;
8512 } else {
8513 const char* next_comma = S_CAST(const char*, rawmemchr(value_iter, ','));
8514 const uint32_t slen = next_comma - value_iter;
8515 if (IsNanStr(value_iter, slen)) {
8516 CopyToUnalignedOffsetU32(write_uc, &nan_bits, value_idx);
8517 } else {
8518 uint32_t is_neg = 0;
8519 if (unlikely(!IsInfStr(value_iter, slen, &is_neg))) {
8520 snprintf(g_logbuf, kLogbufSize, "Error: --export bcf: Variant '%s' has an invalid INFO/%s value.\n", variant_id, fif_keys[fif_idx]);
8521 goto ExportBcf_ret_MALFORMED_INPUT_WW;
8522 }
8523 CopyToUnalignedOffsetU32(write_uc, &(inf_bits[is_neg]), value_idx);
8524 }
8525 value_iter = &(next_comma[1]);
8526 continue;
8527 }
8528 }
8529 if (unlikely(*value_iter != ',')) {
8530 snprintf(g_logbuf, kLogbufSize, "Error: --export bcf: Variant '%s' has an invalid INFO/%s value.\n", variant_id, fif_keys[fif_idx]);
8531 goto ExportBcf_ret_MALFORMED_INPUT_WW;
8532 }
8533 ++value_iter;
8534 }
8535 write_iter = &(write_iter[value_ct * sizeof(float)]);
8536 } else {
8537 snprintf(g_logbuf, kLogbufSize, "Error: --export bcf: INFO/%s for variant '%s' has a value, but is of type Flag.\n", fif_keys[fif_idx], variant_id);
8538 goto ExportBcf_ret_MALFORMED_INPUT_WW;
8539 }
8540 // *value_end = ';'; // don't actually need this
8541 }
8542 info_iter = &(value_end[1]);
8543 } while (info_iter != info_stop);
8544 *info_end = orig_info_end_char;
8545 }
8546 if (is_pr && (!IsSet(fif_seen, pr_key_idx))) {
8547 ++n_info_raw;
8548 write_iter = AppendBcfTypedInt(pr_key_idx, write_iter);
8549 *write_iter++ = '\0';
8550 }
8551 if (unlikely(n_info_raw > 0xffff)) {
8552 logputs("\n");
8553 logerrprintfww("Error: INFO component of variant '%s' has too many keys to represent as BCF.\n", variant_id);
8554 goto ExportBcf_ret_INCONSISTENT_INPUT;
8555 }
8556 n_info = n_info_raw;
8557 } else if (is_pr) {
8558 n_info = 1;
8559 write_iter = AppendBcfTypedInt(pr_key_idx, write_iter);
8560 *write_iter++ = '\0';
8561 }
8562
8563 #ifdef __LP64__
8564 if (unlikely(S_CAST(uintptr_t, write_iter - &(rec_start[8])) > UINT32_MAX)) {
8565 logputs("\n");
8566 logerrprintfww("Error: CHROM..INFO component of variant '%s' is too large to represent as BCF.\n", variant_id);
8567 goto ExportBcf_ret_INCONSISTENT_INPUT;
8568 }
8569 #endif
8570 const uint32_t l_shared = write_iter - &(rec_start[8]);
8571 memcpy(rec_start, &l_shared, sizeof(int32_t));
8572 memcpy(&(rec_start[16]), &rlen, sizeof(int32_t));
8573 memcpy(&(rec_start[24]), &n_info, sizeof(int16_t));
8574 memcpy(&(rec_start[26]), &n_allele, sizeof(int16_t));
8575 // Simplest for l_indiv [4,8) and n_fmt [31] calculation to wait until
8576 // the entire variant record is complete.
8577
8578 // could defensively zero out more counts
8579 pgv.dosage_ct = 0;
8580 pgv.dphase_ct = 0;
8581 char* indiv_start = write_iter;
8582 uint32_t n_fmt = 0;
8583 if (!ds_only) {
8584 write_iter = AppendBcfTypedInt(gt_key_idx, write_iter);
8585 n_fmt = 1;
8586 }
8587 if (allele_ct == 2) {
8588 if (!some_phased) {
8589 // biallelic, nothing phased in entire file (or ds_only)
8590 // (technically possible for dosage-phase to be present, if no
8591 // hardcalls are phased and HDS output not requested)
8592 if (!write_some_dosage) {
8593 reterr = PgrGet(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgv.genovec);
8594 } else {
8595 reterr = PgrGetD(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &(pgv.dosage_ct));
8596 }
8597 if (unlikely(reterr)) {
8598 PgenErrPrintNV(reterr, variant_uidx);
8599 goto ExportBcf_ret_1;
8600 }
8601 if (!alt1_allele_idx) {
8602 GenovecInvertUnsafe(sample_ct, pgv.genovec);
8603 if (pgv.dosage_ct) {
8604 BiallelicDosage16Invert(pgv.dosage_ct, pgv.dosage_main);
8605 }
8606 }
8607 if (!ds_only) {
8608 if ((!is_haploid) || is_x) {
8609 *write_iter++ = 0x21;
8610 GenoarrLookup256x2bx4(pgv.genovec, basic_genobytes4, sample_ct, write_iter);
8611 if (is_x) {
8612 FixBcfMaleXGtPloidy(pgv.genovec, sex_male_collapsed, sample_ct, write_iter);
8613 }
8614 write_iter = &(write_iter[sample_ct * 2]);
8615 } else {
8616 // Ploidy 1 unless there's a het-haploid.
8617 ZeroTrailingNyps(sample_ct, pgv.genovec);
8618 if (AtLeastOneHetUnsafe(pgv.genovec, sample_ct)) {
8619 *write_iter++ = 0x21;
8620 GenoarrLookup256x2bx4(pgv.genovec, haploid_hh_genobytes4, sample_ct, write_iter);
8621 if (is_y) {
8622 FixBcfFemaleYGtPloidy2(pgv.genovec, sex_female_collapsed, sample_ct, write_iter);
8623 }
8624 write_iter = &(write_iter[sample_ct * 2]);
8625 } else {
8626 *write_iter++ = 0x11;
8627 GenoarrLookup256x1bx4(pgv.genovec, haploid_genobytes4, sample_ct, write_iter);
8628 if (is_y) {
8629 FixBcfFemaleYGtPloidy1(pgv.genovec, sex_female_collapsed, sample_ct, write_iter);
8630 }
8631 write_iter = &(write_iter[sample_ct]);
8632 }
8633 }
8634 }
8635 if (pgv.dosage_ct || ds_force) {
8636 ++n_fmt;
8637 write_iter = AppendBcfTypedInt(dosage_key_idx, write_iter);
8638 if (write_ds) {
8639 *write_iter++ = 0x15;
8640 FillBcfDs(&pgv, sex_male_collapsed, sex_female_collapsed, ds_genobytes4, ds_x_genobytes2, ds_y_genobytes2, ds_haploid_genobytes4, sample_ct, ds_force, is_x, is_y, is_haploid, write_iter);
8641 write_iter = &(write_iter[sample_ct * sizeof(int32_t)]);
8642 if (hds_force) {
8643 ++n_fmt;
8644 write_iter = AppendBcfTypedInt(hds_key_idx, write_iter);
8645 if (!is_haploid) {
8646 *write_iter++ = 0x25;
8647 GenoarrLookup16x8bx2(pgv.genovec, hds_genobytes2, sample_ct, write_iter);
8648 uint32_t widx = 0;
8649 for (uint32_t dosage_idx = 0; dosage_idx != pgv.dosage_ct; ) {
8650 uintptr_t dosage_present_word;
8651 do {
8652 dosage_present_word = pgv.dosage_present[widx++];
8653 } while (!dosage_present_word);
8654 unsigned char* cur_hds = CToUc(&(write_iter[widx * (kBitsPerWord * 8 * k1LU)]));
8655 do {
8656 const uint32_t sample_idx_lowbits = ctzw(dosage_present_word);
8657 const uint32_t dosage_int = pgv.dosage_main[dosage_idx++];
8658 const float dosage_f = S_CAST(float, dosage_int) * S_CAST(float, kRecipDosageMid);
8659 CopyToUnalignedOffsetF(cur_hds, &dosage_f, 2 * sample_idx_lowbits);
8660 CopyToUnalignedOffsetF(cur_hds, &dosage_f, 2 * sample_idx_lowbits + 1);
8661 dosage_present_word &= dosage_present_word - 1;
8662 } while (dosage_present_word);
8663 }
8664 write_iter = &(write_iter[sample_ct * sizeof(int32_t) * 2]);
8665 } else if (is_x) {
8666 *write_iter++ = 0x25;
8667 // male dosages 0..1
8668 GenoarrSexLookup8b(pgv.genovec, sex_male_collapsed, hds_unphased_x_genobytes2, sample_ct, write_iter);
8669 uint32_t widx = 0;
8670 for (uint32_t dosage_idx = 0; dosage_idx != pgv.dosage_ct; ) {
8671 uintptr_t dosage_present_word;
8672 do {
8673 dosage_present_word = pgv.dosage_present[widx++];
8674 } while (!dosage_present_word);
8675 unsigned char* cur_hds = CToUc(&(write_iter[widx * (kBitsPerWord * 8 * k1LU)]));
8676 do {
8677 const uint32_t sample_idx_lowbits = ctzw(dosage_present_word);
8678 const uint32_t dosage_int = pgv.dosage_main[dosage_idx++];
8679 const float dosage_f = S_CAST(float, dosage_int) * S_CAST(float, kRecipDosageMid);
8680 CopyToUnalignedOffsetF(cur_hds, &dosage_f, 2 * sample_idx_lowbits);
8681 CopyToUnalignedOffsetF(cur_hds, &dosage_f, 2 * sample_idx_lowbits + 1);
8682 dosage_present_word &= dosage_present_word - 1;
8683 } while (dosage_present_word);
8684 }
8685 write_iter = &(write_iter[sample_ct * sizeof(int32_t) * 2]);
8686 } else {
8687 // max ploidy 1.
8688 *write_iter++ = 0x15;
8689 FillBcfHdsPloidy1(&pgv, sex_female_collapsed, hds_y_genobytes2, hds_haploid_genobytes4, sample_ct, 1, is_y, write_iter);
8690 write_iter = &(write_iter[sample_ct * sizeof(int32_t)]);
8691 }
8692 }
8693 } else {
8694 // GP
8695 if ((!is_haploid) || is_x) {
8696 *write_iter++ = 0x35;
8697 FillBcfGpPloidy2(&pgv, sex_male_collapsed, sample_ct, is_x, write_iter);
8698 write_iter = &(write_iter[sample_ct * sizeof(int32_t) * 3]);
8699 } else {
8700 *write_iter++ = 0x25;
8701 FillBcfGpPloidy1(&pgv, sample_ct, write_iter);
8702 write_iter = &(write_iter[sample_ct * sizeof(int32_t) * 2]);
8703 }
8704 }
8705 }
8706 } else {
8707 // biallelic, phased
8708 if (!write_some_dosage) {
8709 reterr = PgrGetP(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgv.genovec, pgv.phasepresent, pgv.phaseinfo, &(pgv.phasepresent_ct));
8710 } else {
8711 reterr = PgrGetDp(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &pgv);
8712 }
8713 if (unlikely(reterr)) {
8714 PgenErrPrintNV(reterr, variant_uidx);
8715 goto ExportBcf_ret_1;
8716 }
8717 if (!alt1_allele_idx) {
8718 GenovecInvertUnsafe(sample_ct, pgv.genovec);
8719 if (pgv.phasepresent_ct) {
8720 BitvecInvert(sample_ctl, pgv.phaseinfo);
8721 }
8722 if (pgv.dosage_ct) {
8723 BiallelicDosage16Invert(pgv.dosage_ct, pgv.dosage_main);
8724 if (pgv.dphase_ct) {
8725 BiallelicDphase16Invert(pgv.dphase_ct, pgv.dphase_delta);
8726 }
8727 }
8728 }
8729 // little point in trying to optimize this case, thanks to
8730 // prev_phased. Instead, we might want to have a fast path for the
8731 // all-phased case.
8732 if (!pgv.phasepresent_ct) {
8733 ZeroWArr(sample_ctl, pgv.phasepresent);
8734 }
8735 ZeroTrailingNyps(sample_ct, pgv.genovec);
8736 BitvecAnd(pgv.phasepresent, sample_ctl, pgv.phaseinfo);
8737 if ((!is_haploid) || is_x) {
8738 *write_iter++ = 0x21;
8739 FillBcfPhasedGt(pgv.genovec, pgv.phasepresent, pgv.phaseinfo, phased_genobytes2, sample_ct, prev_phased, write_iter);
8740 if (is_x) {
8741 FixBcfMaleXGtPloidy(pgv.genovec, sex_male_collapsed, sample_ct, write_iter);
8742 }
8743 write_iter = &(write_iter[sample_ct * 2]);
8744 } else {
8745 // Ploidy 1 unless there's a het-haploid.
8746 if (AtLeastOneHetUnsafe(pgv.genovec, sample_ct)) {
8747 *write_iter++ = 0x21;
8748 FillBcfPhasedGt(pgv.genovec, pgv.phasepresent, pgv.phaseinfo, phased_hh_genobytes2, sample_ct, prev_phased, write_iter);
8749 if (is_y) {
8750 FixBcfFemaleYGtPloidy2(pgv.genovec, sex_female_collapsed, sample_ct, write_iter);
8751 }
8752 write_iter = &(write_iter[sample_ct * 2]);
8753 } else {
8754 *write_iter++ = 0x11;
8755 GenoarrLookup256x1bx4(pgv.genovec, haploid_genobytes4, sample_ct, write_iter);
8756 if (is_y) {
8757 FixBcfFemaleYGtPloidy1(pgv.genovec, sex_female_collapsed, sample_ct, write_iter);
8758 }
8759 write_iter = &(write_iter[sample_ct]);
8760 }
8761 }
8762 if (pgv.dosage_ct || ds_force) {
8763 // both dosage (or {H}DS-force) and phase present
8764 ++n_fmt;
8765 write_iter = AppendBcfTypedInt(dosage_key_idx, write_iter);
8766 if (write_ds) {
8767 *write_iter++ = 0x15;
8768 FillBcfDs(&pgv, sex_male_collapsed, sex_female_collapsed, ds_genobytes4, ds_x_genobytes2, ds_y_genobytes2, ds_haploid_genobytes4, sample_ct, ds_force, is_x, is_y, is_haploid, write_iter);
8769 write_iter = &(write_iter[sample_ct * sizeof(int32_t)]);
8770 const uint32_t dphase_ct = pgv.dphase_ct;
8771 if (hds_force || dphase_ct ||
8772 (write_hds && pgv.phasepresent_ct && pgv.dosage_ct && (!IntersectionIsEmpty(pgv.phasepresent, pgv.dosage_present, sample_ctl)))) {
8773 ++n_fmt;
8774 write_iter = AppendBcfTypedInt(hds_key_idx, write_iter);
8775 // dphase_present can be nullptr, so we zero-initialize
8776 // dphase_present_word and never refresh it when dphase_ct==0.
8777 uintptr_t dphase_present_word = 0;
8778 if ((!is_haploid) || is_x) {
8779 *write_iter++ = 0x25;
8780 if (!hds_force) {
8781 const uint64_t end_of_vector = 0x7f8000027f800002LLU;
8782 for (uint32_t uii = 0; uii != sample_ct; ++uii) {
8783 CopyToUnalignedOffsetU64(CToUc(write_iter), &end_of_vector, uii);
8784 }
8785 } else {
8786 PhaseLookup8b(pgv.genovec, pgv.phasepresent, pgv.phaseinfo, hds_genobytes2, sample_ct, write_iter);
8787 }
8788 // Note that dosage_main may be nullptr in HDS-force case.
8789 // Guard against undefined behavior (pointer arithmetic on
8790 // nullptr).
8791 if (pgv.dosage_ct) {
8792 const uintptr_t* phasepresent = pgv.phasepresent;
8793 const uintptr_t* phaseinfo = pgv.phaseinfo;
8794 const uintptr_t* dosage_present = pgv.dosage_present;
8795 const Dosage* dosage_main_stop = &(pgv.dosage_main[pgv.dosage_ct]);
8796 const uintptr_t* dphase_present = pgv.dphase_present;
8797 const SDosage* dphase_delta_iter = pgv.dphase_delta;
8798 uint32_t widx = UINT32_MAX; // deliberate overflow
8799 for (const Dosage* dosage_main_iter = pgv.dosage_main; dosage_main_iter != dosage_main_stop; ) {
8800 uintptr_t dosage_present_word;
8801 do {
8802 dosage_present_word = dosage_present[++widx];
8803 } while (!dosage_present_word);
8804 const uintptr_t phasepresent_word = phasepresent[widx];
8805 const uintptr_t phaseinfo_word = phaseinfo[widx];
8806 if (dphase_ct) {
8807 dphase_present_word = dphase_present[widx];
8808 }
8809 unsigned char* cur_hds = CToUc(&(write_iter[widx * (kBitsPerWord * 8 * k1LU)]));
8810 do {
8811 const uint32_t sample_idx_lowbits = ctzw(dosage_present_word);
8812 const uintptr_t lowbit = dosage_present_word & (-dosage_present_word);
8813 const uint32_t dosage_int = *dosage_main_iter++;
8814 const uintptr_t is_phased = (phasepresent_word | dphase_present_word) & lowbit;
8815 if ((!hds_force) && (!is_phased)) {
8816 dosage_present_word ^= lowbit;
8817 continue;
8818 }
8819 float dosage0 = S_CAST(float, dosage_int) * S_CAST(float, kRecipDosageMax);
8820 float dosage1 = dosage0;
8821 if (is_phased) {
8822 int32_t cur_dphase_delta;
8823 if (dphase_present_word & lowbit) {
8824 cur_dphase_delta = *dphase_delta_iter++;
8825 } else {
8826 cur_dphase_delta = DosageHomdist(dosage_int);
8827 if (!(phaseinfo_word & lowbit)) {
8828 cur_dphase_delta = -cur_dphase_delta;
8829 }
8830 }
8831 const float dosage0_incr_f = S_CAST(float, cur_dphase_delta) * S_CAST(float, kRecipDosageMax);
8832 dosage0 += dosage0_incr_f;
8833 dosage1 -= dosage0_incr_f;
8834 }
8835 CopyToUnalignedOffsetF(cur_hds, &dosage0, 2 * sample_idx_lowbits);
8836 CopyToUnalignedOffsetF(cur_hds, &dosage1, 2 * sample_idx_lowbits + 1);
8837 dosage_present_word ^= lowbit;
8838 } while (dosage_present_word);
8839 }
8840 }
8841 if (is_x) {
8842 FixBcfMaleXHdsPloidy(pgv.phasepresent, dphase_ct? pgv.dphase_present : nullptr, sex_male_collapsed, sample_ct, write_iter);
8843 }
8844 write_iter = &(write_iter[sample_ct * sizeof(int32_t) * 2]);
8845 } else if (pgv.phasepresent_ct || pgv.dphase_ct) {
8846 // Supposed to be all haploid, but we must render as ploidy-2
8847 // anyway.
8848 // probable todo: merge this with the regular diploid case.
8849 *write_iter++ = 0x25;
8850 if (!hds_force) {
8851 const uint64_t end_of_vector = 0x7f8000027f800002LLU;
8852 for (uint32_t uii = 0; uii != sample_ct; ++uii) {
8853 CopyToUnalignedOffsetU64(CToUc(write_iter), &end_of_vector, uii);
8854 }
8855 } else {
8856 PhaseLookup8b(pgv.genovec, pgv.phasepresent, pgv.phaseinfo, hds_hh_genobytes2, sample_ct, write_iter);
8857 }
8858 if (pgv.dosage_ct) {
8859 const uintptr_t* phasepresent = pgv.phasepresent;
8860 const uintptr_t* phaseinfo = pgv.phaseinfo;
8861 const uintptr_t* dosage_present = pgv.dosage_present;
8862 const Dosage* dosage_main_stop = &(pgv.dosage_main[pgv.dosage_ct]);
8863 const uintptr_t* dphase_present = pgv.dphase_present;
8864 const SDosage* dphase_delta_iter = pgv.dphase_delta;
8865 const uint32_t eov_bits = 0x7f800002;
8866 uint32_t widx = UINT32_MAX; // deliberate overflow
8867 for (const Dosage* dosage_main_iter = pgv.dosage_main; dosage_main_iter != dosage_main_stop; ) {
8868 uintptr_t dosage_present_word;
8869 do {
8870 dosage_present_word = dosage_present[++widx];
8871 } while (!dosage_present_word);
8872 const uintptr_t phasepresent_word = phasepresent[widx];
8873 const uintptr_t phaseinfo_word = phaseinfo[widx];
8874 if (dphase_ct) {
8875 dphase_present_word = dphase_present[widx];
8876 }
8877 unsigned char* cur_hds = CToUc(&(write_iter[widx * (kBitsPerWord * 8 * k1LU)]));
8878 do {
8879 const uint32_t sample_idx_lowbits = ctzw(dosage_present_word);
8880 const uintptr_t lowbit = dosage_present_word & (-dosage_present_word);
8881 const uint32_t dosage_int = *dosage_main_iter++;
8882 const uintptr_t is_phased = (phasepresent_word | dphase_present_word) & lowbit;
8883 if ((!hds_force) && (!is_phased)) {
8884 dosage_present_word ^= lowbit;
8885 continue;
8886 }
8887 float dosage0 = S_CAST(float, dosage_int) * S_CAST(float, kRecipDosageMax);
8888 if (is_phased) {
8889 int32_t cur_dphase_delta;
8890 if (dphase_present_word & lowbit) {
8891 cur_dphase_delta = *dphase_delta_iter++;
8892 } else {
8893 cur_dphase_delta = DosageHomdist(dosage_int);
8894 if (!(phaseinfo_word & lowbit)) {
8895 cur_dphase_delta = -cur_dphase_delta;
8896 }
8897 }
8898 const float dosage0_incr_f = S_CAST(float, cur_dphase_delta) * S_CAST(float, kRecipDosageMax);
8899 const float fxx = dosage0 + dosage0_incr_f;
8900 const float fyy = dosage0 - dosage0_incr_f;
8901 CopyToUnalignedOffsetF(cur_hds, &fxx, 2 * sample_idx_lowbits);
8902 CopyToUnalignedOffsetF(cur_hds, &fyy, 2 * sample_idx_lowbits + 1);
8903 } else {
8904 CopyToUnalignedOffsetF(cur_hds, &dosage0, 2 * sample_idx_lowbits);
8905 CopyToUnalignedOffsetU32(cur_hds, &eov_bits, 2 * sample_idx_lowbits + 1);
8906 }
8907 dosage_present_word ^= lowbit;
8908 } while (dosage_present_word);
8909 }
8910 }
8911 if (is_y) {
8912 FixBcfFemaleYHdsPloidy2(pgv.genovec, pgv.dosage_ct? pgv.dosage_present : nullptr, sex_female_collapsed, sample_ct, write_iter);
8913 }
8914 write_iter = &(write_iter[sample_ct * sizeof(int32_t) * 2]);
8915 } else {
8916 *write_iter++ = 0x15;
8917 FillBcfHdsPloidy1(&pgv, sex_female_collapsed, hds_y_genobytes2, hds_haploid_genobytes4, sample_ct, 1, is_y, write_iter);
8918 write_iter = &(write_iter[sample_ct * sizeof(int32_t)]);
8919 }
8920 }
8921 } else {
8922 // GP ignores phase.
8923 if ((!is_haploid) || is_x) {
8924 *write_iter++ = 0x35;
8925 FillBcfGpPloidy2(&pgv, sex_male_collapsed, sample_ct, is_x, write_iter);
8926 write_iter = &(write_iter[sample_ct * sizeof(int32_t) * 3]);
8927 } else {
8928 *write_iter++ = 0x25;
8929 FillBcfGpPloidy1(&pgv, sample_ct, write_iter);
8930 write_iter = &(write_iter[sample_ct * sizeof(int32_t) * 2]);
8931 }
8932 }
8933 }
8934 }
8935 } else {
8936 // multiallelic cases
8937 // multiallelic dosage not supported yet
8938 if (ref_allele_idx || (alt1_allele_idx != 1)) {
8939 logputs("\n");
8940 logerrputs("Error: BCF-export multiallelic rotation is under development.\n");
8941 reterr = kPglRetNotYetSupported;
8942 goto ExportBcf_ret_1;
8943 }
8944 if (!some_phased) {
8945 reterr = PgrGetM(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &pgv);
8946 if (unlikely(reterr)) {
8947 PgenErrPrintNV(reterr, variant_uidx);
8948 goto ExportBcf_ret_1;
8949 }
8950 if (!ds_only) {
8951 if (allele_ct <= 63) {
8952 // Still 1 byte per entry. Almost identical to the biallelic
8953 // case, just need to patch in allele codes from patch_{01,10}
8954 // at the end.
8955 if ((!is_haploid) || is_x) {
8956 *write_iter++ = 0x21;
8957 FillBcf3allelicGtPloidy2(&pgv, basic_genobytes4, sample_ct, write_iter);
8958 if (is_x) {
8959 FixBcfMaleX3allelicGtPloidy(sex_male_collapsed, sample_ct, write_iter);
8960 }
8961 write_iter = &(write_iter[sample_ct * 2]);
8962 } else {
8963 // Ploidy 1 unless there's a het-haploid.
8964 if (AtLeastOneMultiallelicHet(&pgv, sample_ct)) {
8965 *write_iter++ = 0x21;
8966 FillBcf3allelicGtPloidy2(&pgv, basic_genobytes4, sample_ct, write_iter);
8967 FixBcf3allelicGtHh(sample_ct, write_iter);
8968 if (is_y) {
8969 FixBcfFemaleYGtPloidy2(pgv.genovec, sex_female_collapsed, sample_ct, write_iter);
8970 }
8971 write_iter = &(write_iter[sample_ct * 2]);
8972 } else {
8973 *write_iter++ = 0x11;
8974 FillBcf3allelicGtPloidy1(&pgv, haploid_genobytes4, sample_ct, write_iter);
8975 if (is_y) {
8976 FixBcfFemaleYGtPloidy1(pgv.genovec, sex_female_collapsed, sample_ct, write_iter);
8977 }
8978 write_iter = &(write_iter[sample_ct]);
8979 }
8980 }
8981 } else {
8982 // 2 bytes per entry, since allele_ct <= 255 for now.
8983 if ((!is_haploid) || is_x) {
8984 *write_iter++ = 0x22;
8985 FillBcf64allelicGtPloidy2(&pgv, wide_genobytes4, sample_ct, write_iter);
8986 if (is_x) {
8987 FixBcfMaleX64allelicGtPloidy(sex_male_collapsed, sample_ct, write_iter);
8988 }
8989 write_iter = &(write_iter[sample_ct * 4]);
8990 } else {
8991 // Ploidy 1 unless there's a het-haploid.
8992 if (AtLeastOneMultiallelicHet(&pgv, sample_ct)) {
8993 *write_iter++ = 0x22;
8994 FillBcf64allelicGtPloidy2(&pgv, wide_genobytes4, sample_ct, write_iter);
8995 FixBcf64allelicGtHh(sample_ct, write_iter);
8996 if (is_y) {
8997 FixBcfFemaleY64allelicGtPloidy2(pgv.genovec, sex_female_collapsed, sample_ct, write_iter);
8998 }
8999 write_iter = &(write_iter[sample_ct * 4]);
9000 } else {
9001 *write_iter++ = 0x12;
9002 FillBcf64allelicGtPloidy1(&pgv, wide_haploid_genobytes4, sample_ct, write_iter);
9003 if (is_y) {
9004 FixBcfFemaleY64allelicGtPloidy1(pgv.genovec, sex_female_collapsed, sample_ct, write_iter);
9005 }
9006 write_iter = &(write_iter[sample_ct * 2]);
9007 }
9008 }
9009 }
9010 }
9011 // yes, this will need to be reworked when proper multiallelic dosage
9012 // support is added
9013 if (ds_force) {
9014 ++n_fmt;
9015 write_iter = AppendBcfTypedInt(dosage_key_idx, write_iter);
9016 const uint32_t alt_allele_ct = allele_ct - 1;
9017 write_iter = AppendBcfVecType(5, alt_allele_ct, write_iter);
9018 ZeroTrailingNyps(sample_ct, pgv.genovec);
9019 if (!pgv.patch_01_ct) {
9020 ZeroWArr(sample_ctl, pgv.patch_01_set);
9021 }
9022 if (!pgv.patch_10_ct) {
9023 ZeroWArr(sample_ctl, pgv.patch_10_set);
9024 }
9025 FillBcfMultiallelicDsForce(&pgv, sex_male_collapsed, sex_female_collapsed, sample_ct, alt_allele_ct, is_x, is_y, is_haploid, write_iter);
9026 write_iter = &(write_iter[sample_ct * sizeof(int32_t) * alt_allele_ct]);
9027 if (hds_force) {
9028 ++n_fmt;
9029 write_iter = AppendBcfTypedInt(hds_key_idx, write_iter);
9030 const uint32_t max_ploidy = ((!is_haploid) || is_x)? 2 : 1;
9031 write_iter = AppendBcfVecType(5, max_ploidy * alt_allele_ct, write_iter);
9032 FillBcfMultiallelicHdsForce(&pgv, sex_male_collapsed, sex_female_collapsed, sample_ct, alt_allele_ct, is_x, is_y, is_haploid, write_iter);
9033 write_iter = &(write_iter[sample_ct * sizeof(int32_t) * alt_allele_ct * max_ploidy]);
9034 }
9035 }
9036 } else {
9037 // multiallelic phased
9038 reterr = PgrGetMP(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &pgv);
9039 if (unlikely(reterr)) {
9040 PgenErrPrintNV(reterr, variant_uidx);
9041 goto ExportBcf_ret_1;
9042 }
9043 if (!pgv.patch_01_ct) {
9044 ZeroWArr(sample_ctl, pgv.patch_01_set);
9045 }
9046 if (!pgv.patch_10_ct) {
9047 ZeroWArr(sample_ctl, pgv.patch_10_set);
9048 }
9049 if (!pgv.phasepresent_ct) {
9050 ZeroWArr(sample_ctl, pgv.phasepresent);
9051 }
9052 if (allele_ct <= 63) {
9053 if ((!is_haploid) || is_x) {
9054 *write_iter++ = 0x21;
9055 FillBcf3allelicPhasedGt(&pgv, sample_ct, 0, prev_phased, write_iter);
9056 if (is_x) {
9057 FixBcfMaleX3allelicGtPloidy(sex_male_collapsed, sample_ct, write_iter);
9058 }
9059 write_iter = &(write_iter[sample_ct * 2]);
9060 } else {
9061 // Ploidy 1 unless there's a het-haploid.
9062 if (AtLeastOneMultiallelicHet(&pgv, sample_ct)) {
9063 *write_iter++ = 0x21;
9064 FillBcf3allelicPhasedGt(&pgv, sample_ct, 1, prev_phased, write_iter);
9065 FixBcf3allelicGtHh(sample_ct, write_iter);
9066 if (is_y) {
9067 FixBcfFemaleYGtPloidy2(pgv.genovec, sex_female_collapsed, sample_ct, write_iter);
9068 }
9069 write_iter = &(write_iter[sample_ct * 2]);
9070 } else {
9071 *write_iter++ = 0x11;
9072 FillBcf3allelicGtPloidy1(&pgv, haploid_genobytes4, sample_ct, write_iter);
9073 if (is_y) {
9074 FixBcfFemaleYGtPloidy1(pgv.genovec, sex_female_collapsed, sample_ct, write_iter);
9075 }
9076 write_iter = &(write_iter[sample_ct]);
9077 }
9078 }
9079 } else {
9080 // 2 bytes per entry, since allele_ct <= 255 for now.
9081 if ((!is_haploid) || is_x) {
9082 *write_iter++ = 0x22;
9083 FillBcf64allelicPhasedGt(&pgv, sample_ct, 0, prev_phased, write_iter);
9084 if (is_x) {
9085 FixBcfMaleX64allelicGtPloidy(sex_male_collapsed, sample_ct, write_iter);
9086 }
9087 write_iter = &(write_iter[sample_ct * 4]);
9088 } else {
9089 // Ploidy 1 unless there's a het-haploid.
9090 if (AtLeastOneMultiallelicHet(&pgv, sample_ct)) {
9091 *write_iter++ = 0x22;
9092 FillBcf64allelicPhasedGt(&pgv, sample_ct, 1, prev_phased, write_iter);
9093 FixBcf64allelicGtHh(sample_ct, write_iter);
9094 if (is_y) {
9095 FixBcfFemaleY64allelicGtPloidy2(pgv.genovec, sex_female_collapsed, sample_ct, write_iter);
9096 }
9097 write_iter = &(write_iter[sample_ct * 4]);
9098 } else {
9099 *write_iter++ = 0x12;
9100 FillBcf64allelicGtPloidy1(&pgv, wide_haploid_genobytes4, sample_ct, write_iter);
9101 if (is_y) {
9102 FixBcfFemaleY64allelicGtPloidy1(pgv.genovec, sex_female_collapsed, sample_ct, write_iter);
9103 }
9104 write_iter = &(write_iter[sample_ct * 2]);
9105 }
9106 }
9107 }
9108 // yes, this will need to be reworked when proper multiallelic dosage
9109 // support is added
9110 if (ds_force) {
9111 ++n_fmt;
9112 write_iter = AppendBcfTypedInt(dosage_key_idx, write_iter);
9113 const uint32_t alt_allele_ct = allele_ct - 1;
9114 write_iter = AppendBcfVecType(5, alt_allele_ct, write_iter);
9115 ZeroTrailingNyps(sample_ct, pgv.genovec);
9116 FillBcfMultiallelicDsForce(&pgv, sex_male_collapsed, sex_female_collapsed, sample_ct, alt_allele_ct, is_x, is_y, is_haploid, write_iter);
9117 write_iter = &(write_iter[sample_ct * sizeof(int32_t) * alt_allele_ct]);
9118 if (hds_force) {
9119 ++n_fmt;
9120 write_iter = AppendBcfTypedInt(hds_key_idx, write_iter);
9121 const uint32_t max_ploidy = ((!is_haploid) || is_x || pgv.phasepresent_ct)? 2 : 1;
9122 write_iter = AppendBcfVecType(5, max_ploidy * alt_allele_ct, write_iter);
9123 FillBcfMultiallelicHdsForce(&pgv, sex_male_collapsed, sex_female_collapsed, sample_ct, alt_allele_ct, is_x, is_y, is_haploid, write_iter);
9124 write_iter = &(write_iter[sample_ct * sizeof(int32_t) * alt_allele_ct * max_ploidy]);
9125 }
9126 }
9127 }
9128 }
9129 #ifdef __LP64__
9130 if (S_CAST(uintptr_t, write_iter - indiv_start) > UINT32_MAX) {
9131 logerrprintfww("Error: Genotype/dosage component of variant '%s' is too large to represent as BCF.\n", variant_id);
9132 goto ExportBcf_ret_INCONSISTENT_INPUT;
9133 }
9134 #endif
9135 const uint32_t l_indiv = write_iter - indiv_start;
9136 memcpy(&(rec_start[4]), &l_indiv, sizeof(int32_t));
9137 rec_start[31] = n_fmt;
9138 if (unlikely(bgzfwrite_ck(writebuf_flush, &bgzf, &write_iter))) {
9139 goto ExportBcf_ret_WRITE_FAIL;
9140 }
9141 if (variant_idx >= next_print_variant_idx) {
9142 if (pct > 10) {
9143 putc_unlocked('\b', stdout);
9144 }
9145 pct = (variant_idx * 100LLU) / variant_ct;
9146 printf("\b\b%u%%", pct++);
9147 fflush(stdout);
9148 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
9149 }
9150 }
9151 if (unlikely(bgzfclose_flush(writebuf_flush, write_iter, &bgzf, &reterr))) {
9152 goto ExportBcf_ret_1;
9153 }
9154 if (pct > 10) {
9155 putc_unlocked('\b', stdout);
9156 }
9157 fputs("\b\b", stdout);
9158 if (rlen_warning_ct) {
9159 fputs("done.\n", stdout);
9160 const uint32_t rlen_warning_print_ct = MINV(3, rlen_warning_ct);
9161 for (uint32_t uii = 0; uii != rlen_warning_print_ct; ++uii) {
9162 const char* variant_id = variant_ids[first_rlen_warning_idxs[uii]];
9163 MakeRlenWarningStr(variant_id);
9164 logerrputsb();
9165 }
9166 if (rlen_warning_ct > 3) {
9167 fprintf(stderr, "%u more INFO/END warning%s; see log file.\n", rlen_warning_ct - 3, (rlen_warning_ct == 4)? "" : "s");
9168 }
9169 logputs_silent("BCF export done.\n");
9170 } else {
9171 logputs("done.\n");
9172 }
9173 if (invalid_allele_code_seen) {
9174 logerrputs("Warning: At least one BCF allele code violates the official specification;\nother tools may not accept the file. (Valid codes must either start with a\n'<', only contain characters in {A,C,G,T,N,a,c,g,t,n}, be an isolated '*', or\nrepresent a breakend.)\n");
9175 }
9176 }
9177 while (0) {
9178 ExportBcf_ret_NOMEM:
9179 reterr = kPglRetNomem;
9180 break;
9181 ExportBcf_ret_TSTREAM_FAIL:
9182 TextStreamErrPrint(pvar_info_reload, &pvar_reload_txs);
9183 break;
9184 ExportBcf_ret_WRITE_FAIL:
9185 reterr = kPglRetWriteFail;
9186 break;
9187 ExportBcf_ret_MALFORMED_INPUT_WW:
9188 logputs("\n");
9189 WordWrapB(0);
9190 logerrputsb();
9191 ExportBcf_ret_MALFORMED_INPUT:
9192 reterr = kPglRetMalformedInput;
9193 break;
9194 ExportBcf_ret_INCONSISTENT_INPUT:
9195 reterr = kPglRetInconsistentInput;
9196 break;
9197 }
9198 ExportBcf_ret_1:
9199 CleanupTextStream2(pvar_info_reload, &pvar_reload_txs, &reterr);
9200 CleanupBgzfCompressStream(&bgzf, &reterr);
9201 BigstackReset(bigstack_mark);
9202 return reterr;
9203 }
9204
9205 static const Dosage kGenoToDosage[4] = {0, 16384, 32768, 65535};
9206
9207 typedef struct DosageTransposeCtxStruct {
9208 const uintptr_t* variant_include;
9209 const char* const* export_allele_missing;
9210 const AlleleCode* export_allele;
9211 const uintptr_t* sample_include;
9212 const uint32_t* sample_include_cumulative_popcounts;
9213 uint32_t sample_ct;
9214 uintptr_t stride;
9215
9216 PgenReader** pgr_ptrs;
9217 uint32_t* read_variant_uidx_starts;
9218 uint32_t* write_vidx_starts;
9219 Dosage* smaj_dosagebuf;
9220
9221 uint32_t cur_block_write_ct;
9222
9223 uintptr_t** thread_write_genovecs;
9224 uintptr_t** thread_write_dosagepresents;
9225 Dosage** thread_write_dosagevals;
9226
9227 uint64_t err_info;
9228 } DosageTransposeCtx;
9229
9230 THREAD_FUNC_DECL DosageTransposeThread(void* raw_arg) {
9231 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
9232 const uintptr_t tidx = arg->tidx;
9233 DosageTransposeCtx* ctx = S_CAST(DosageTransposeCtx*, arg->sharedp->context);
9234
9235 const uint32_t sample_ct = ctx->sample_ct;
9236 const uint32_t sample_ctd4 = sample_ct / 4;
9237 const uint32_t sample_rem = sample_ct % 4;
9238 const uintptr_t sample_ctaw = BitCtToAlignedWordCt(sample_ct);
9239 const uint32_t sample_ctaw2 = NypCtToAlignedWordCt(sample_ct);
9240 const uint32_t sample_ctab2 = kBytesPerWord * sample_ctaw2;
9241 const uintptr_t stride = ctx->stride;
9242 const uintptr_t* variant_include = ctx->variant_include;
9243 const AlleleCode* export_allele = ctx->export_allele;
9244 const char* const* export_allele_missing = ctx->export_allele_missing;
9245 const uintptr_t* sample_include = ctx->sample_include;
9246
9247 PgenReader* pgrp = ctx->pgr_ptrs[tidx];
9248 PgrSampleSubsetIndex pssi;
9249 PgrSetSampleSubsetIndex(ctx->sample_include_cumulative_popcounts, pgrp, &pssi);
9250 uintptr_t* genovec_buf = ctx->thread_write_genovecs[tidx];
9251 uintptr_t* dosagepresent_buf = ctx->thread_write_dosagepresents[tidx];
9252 Dosage* dosagevals_buf = ctx->thread_write_dosagevals[tidx];
9253 uint32_t ref_allele_idx = 0;
9254 uint64_t new_err_info;
9255 do {
9256 const uint32_t cur_block_write_ct = ctx->cur_block_write_ct;
9257 const uint32_t vidx_end = ctx->write_vidx_starts[tidx + 1];
9258 uint32_t vidx_start = ctx->write_vidx_starts[tidx];
9259 if (cur_block_write_ct && (vidx_end != vidx_start)) {
9260 uintptr_t variant_uidx_base;
9261 uintptr_t variant_include_bits;
9262 BitIter1Start(variant_include, ctx->read_variant_uidx_starts[tidx], &variant_uidx_base, &variant_include_bits);
9263 Dosage* smaj_dosagebuf_iter = &(ctx->smaj_dosagebuf[vidx_start]);
9264 uint32_t dosage_cts[kDosagePerCacheline];
9265 do {
9266 uint32_t vidx_block_end = RoundDownPow2(vidx_start, kDosagePerCacheline) + kDosagePerCacheline;
9267 if (vidx_block_end > vidx_end) {
9268 vidx_block_end = vidx_end;
9269 }
9270 const uint32_t vidx_block_size = vidx_block_end - vidx_start;
9271
9272 // part 1: decompress data
9273 uintptr_t* genovec_iter = genovec_buf;
9274 uintptr_t* dosage_present_iter = dosagepresent_buf;
9275 Dosage* dosage_main_iter = dosagevals_buf;
9276 for (uint32_t vidx_offset = 0; vidx_offset != vidx_block_size; ++vidx_offset) {
9277 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
9278 if (export_allele) {
9279 ref_allele_idx = export_allele[variant_uidx];
9280 }
9281 uint32_t dosage_ct;
9282 const PglErr reterr = PgrGet1D(sample_include, pssi, sample_ct, variant_uidx, ref_allele_idx, pgrp, genovec_iter, dosage_present_iter, R_CAST(uint16_t*, dosage_main_iter), &dosage_ct);
9283 if (unlikely(reterr)) {
9284 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
9285 goto DosageTransposeThread_err;
9286 }
9287 if (export_allele_missing && export_allele_missing[variant_uidx]) {
9288 // only keep missing vs. nonmissing distinction, zero everything
9289 // else out
9290 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
9291 if (dosage_ct) {
9292 const Halfword* dosage_present_hw = DowncastKWToHW(dosage_present_iter);
9293 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
9294 genovec_iter[widx] = (Word11(genovec_iter[widx]) & (~UnpackHalfwordToWord(dosage_present_hw[widx]))) * 3;
9295 }
9296 dosage_ct = 0;
9297 } else {
9298 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
9299 genovec_iter[widx] = Word11(genovec_iter[widx]) * 3;
9300 }
9301 }
9302 }
9303 genovec_iter = &(genovec_iter[sample_ctaw2]);
9304 dosage_present_iter = &(dosage_present_iter[sample_ctaw]);
9305 dosage_main_iter = &(dosage_main_iter[sample_ct]);
9306 dosage_cts[vidx_offset] = dosage_ct;
9307 }
9308
9309 // part 2: process hardcalls for 4 samples at a time
9310 Dosage* dosagebuf_write_iter0 = smaj_dosagebuf_iter;
9311 for (uint32_t sample4_idx = 0; sample4_idx != sample_ctd4; ++sample4_idx) {
9312 Dosage* dosagebuf_write_iter1 = &(dosagebuf_write_iter0[stride]);
9313 Dosage* dosagebuf_write_iter2 = &(dosagebuf_write_iter1[stride]);
9314 Dosage* dosagebuf_write_iter3 = &(dosagebuf_write_iter2[stride]);
9315 const unsigned char* geno_read_iter = &(R_CAST(const unsigned char*, genovec_buf)[sample4_idx]);
9316 for (uint32_t vidx_offset = 0; vidx_offset != vidx_block_size; ++vidx_offset) {
9317 uint32_t cur_geno = *geno_read_iter;
9318 dosagebuf_write_iter0[vidx_offset] = kGenoToDosage[cur_geno & 3];
9319 dosagebuf_write_iter1[vidx_offset] = kGenoToDosage[(cur_geno >> 2) & 3];
9320 dosagebuf_write_iter2[vidx_offset] = kGenoToDosage[(cur_geno >> 4) & 3];
9321 dosagebuf_write_iter3[vidx_offset] = kGenoToDosage[(cur_geno >> 6) & 3];
9322 geno_read_iter = &(geno_read_iter[sample_ctab2]);
9323 }
9324 dosagebuf_write_iter0 = &(dosagebuf_write_iter3[stride]);
9325 }
9326 if (sample_rem) {
9327 const unsigned char* geno_read_iter = &(R_CAST(const unsigned char*, genovec_buf)[sample_ctd4]);
9328 for (uint32_t vidx_offset = 0; vidx_offset != vidx_block_size; ++vidx_offset) {
9329 uint32_t cur_geno = *geno_read_iter;
9330 Dosage* dosagebuf_write_iterx = &(dosagebuf_write_iter0[vidx_offset]);
9331 for (uint32_t sample_idx_lowbits = 0; ; ) {
9332 *dosagebuf_write_iterx = kGenoToDosage[cur_geno & 3];
9333 if (++sample_idx_lowbits == sample_rem) {
9334 break;
9335 }
9336 cur_geno >>= 2;
9337 dosagebuf_write_iterx = &(dosagebuf_write_iterx[stride]);
9338 }
9339 geno_read_iter = &(geno_read_iter[sample_ctab2]);
9340 }
9341 }
9342 // part 3: patch in dosages
9343 for (uint32_t vidx_offset = 0; vidx_offset != vidx_block_size; ++vidx_offset) {
9344 const uint32_t cur_dosage_ct = dosage_cts[vidx_offset];
9345 if (cur_dosage_ct) {
9346 const uintptr_t* dosage_present = &(dosagepresent_buf[vidx_offset * sample_ctaw]);
9347 const Dosage* dosage_main = &(dosagevals_buf[vidx_offset * sample_ct]);
9348 Dosage* cur_dosage_write = &(smaj_dosagebuf_iter[vidx_offset]);
9349 uintptr_t sample_idx_base = 0;
9350 uintptr_t dosage_present_bits = dosage_present[0];
9351 for (uint32_t dosage_idx = 0; dosage_idx != cur_dosage_ct; ++dosage_idx) {
9352 const uintptr_t sample_idx = BitIter1(dosage_present, &sample_idx_base, &dosage_present_bits);
9353 cur_dosage_write[sample_idx * stride] = dosage_main[dosage_idx];
9354 }
9355 }
9356 }
9357 vidx_start = vidx_block_end;
9358 smaj_dosagebuf_iter = &(smaj_dosagebuf_iter[vidx_block_size]);
9359 } while (vidx_start != vidx_end);
9360 }
9361 while (0) {
9362 DosageTransposeThread_err:
9363 UpdateU64IfSmaller(new_err_info, &ctx->err_info);
9364 }
9365 } while (!THREAD_BLOCK_FINISH(arg));
9366 THREAD_RETURN;
9367 }
9368
9369 static_assert(sizeof(Dosage) == 2, "Export012Smaj() needs to be updated.");
9370 PglErr Export012Smaj(const char* outname, const uintptr_t* orig_sample_include, const PedigreeIdInfo* piip, const uintptr_t* sex_nm, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const uintptr_t* variant_include, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const AlleleCode* export_allele, const char* const* export_allele_missing, const char* legacy_output_missing_pheno, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t pheno_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_slen, uint32_t include_dom, uint32_t include_uncounted, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, char exportf_delim, PgenFileInfo* pgfip) {
9371 unsigned char* bigstack_mark = g_bigstack_base;
9372 FILE* outfile = nullptr;
9373 PglErr reterr = kPglRetSuccess;
9374 ThreadGroup tg;
9375 PreinitThreads(&tg);
9376 DosageTransposeCtx ctx;
9377 {
9378 // Write header line; then fully load-and-transpose the first X samples,
9379 // flush them, load-and-transpose the next X, etc.
9380 // Similar to ExportIndMajorBed() and Export012Vmaj().
9381 // Priority is making the with-dosage case work well, since plink 1.9
9382 // already handles the no-dosage case.
9383 // (possible todo: have a separate no-dosage fast path)
9384 if (unlikely(variant_ct * (1 + include_dom) > (kMaxLongLine - 4 * kMaxIdSlen - 64) / 8)) {
9385 snprintf(g_logbuf, kLogbufSize, "Error: Too many variants for --export A%s. (Try to work with Av instead.)\n", include_dom? "D" : "");
9386 goto Export012Smaj_ret_INCONSISTENT_INPUT_2;
9387 }
9388 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
9389 goto Export012Smaj_ret_OPEN_FAIL;
9390 }
9391 char* writebuf = g_textbuf;
9392 if (max_allele_slen > kMaxMediumLine - 5) {
9393 if (unlikely(bigstack_alloc_c(kMaxMediumLine + 5 + max_allele_slen, &writebuf))) {
9394 goto Export012Smaj_ret_NOMEM;
9395 }
9396 }
9397 char* write_iter = writebuf;
9398 char* writebuf_flush = &(writebuf[kMaxMediumLine]);
9399 write_iter = strcpya_k(write_iter, "FID");
9400 *write_iter++ = exportf_delim;
9401 write_iter = strcpya_k(write_iter, "IID");
9402 *write_iter++ = exportf_delim;
9403 write_iter = strcpya_k(write_iter, "PAT");
9404 *write_iter++ = exportf_delim;
9405 write_iter = strcpya_k(write_iter, "MAT");
9406 *write_iter++ = exportf_delim;
9407 write_iter = strcpya_k(write_iter, "SEX");
9408 *write_iter++ = exportf_delim;
9409 write_iter = strcpya_k(write_iter, "PHENOTYPE");
9410 uintptr_t variant_uidx_base = 0;
9411 uintptr_t variant_include_bits = variant_include[0];
9412 uint32_t exported_allele_idx = 0;
9413 uint32_t cur_allele_ct = 2;
9414 uint64_t bytes_written = 0;
9415 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
9416 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
9417 *write_iter++ = exportf_delim;
9418 const char* cur_var_id = variant_ids[variant_uidx];
9419 const uint32_t cur_slen = strlen(cur_var_id);
9420 write_iter = memcpyax(write_iter, cur_var_id, cur_slen, '_');
9421 uintptr_t allele_idx_offset_base = variant_uidx * 2;
9422 if (allele_idx_offsets) {
9423 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
9424 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
9425 }
9426 if (export_allele) {
9427 exported_allele_idx = export_allele[variant_uidx];
9428 }
9429 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
9430 if (export_allele_missing && export_allele_missing[variant_uidx]) {
9431 write_iter = strcpya(write_iter, export_allele_missing[variant_uidx]);
9432 if (write_iter >= writebuf_flush) {
9433 bytes_written += write_iter - writebuf;
9434 if (unlikely(fwrite_flush2(writebuf_flush, outfile, &write_iter))) {
9435 goto Export012Smaj_ret_WRITE_FAIL;
9436 }
9437 }
9438 if (include_uncounted) {
9439 write_iter = strcpya_k(write_iter, "(/");
9440 write_iter = strcpya(write_iter, cur_alleles[exported_allele_idx]);
9441 if (write_iter >= writebuf_flush) {
9442 bytes_written += write_iter - writebuf;
9443 if (unlikely(fwrite_flush2(writebuf_flush, outfile, &write_iter))) {
9444 goto Export012Smaj_ret_WRITE_FAIL;
9445 }
9446 }
9447 }
9448 } else {
9449 write_iter = strcpya(write_iter, cur_alleles[exported_allele_idx]);
9450 if (write_iter >= writebuf_flush) {
9451 bytes_written += write_iter - writebuf;
9452 if (unlikely(fwrite_flush2(writebuf_flush, outfile, &write_iter))) {
9453 goto Export012Smaj_ret_WRITE_FAIL;
9454 }
9455 }
9456 if (include_uncounted) {
9457 write_iter = strcpya_k(write_iter, "(/");
9458 }
9459 }
9460 if (include_uncounted) {
9461 for (uint32_t allele_idx = 0; allele_idx != cur_allele_ct; ++allele_idx) {
9462 if (allele_idx == exported_allele_idx) {
9463 continue;
9464 }
9465 write_iter = strcpya(write_iter, cur_alleles[allele_idx]);
9466 if (write_iter >= writebuf_flush) {
9467 bytes_written += write_iter - writebuf;
9468 if (unlikely(fwrite_flush2(writebuf_flush, outfile, &write_iter))) {
9469 goto Export012Smaj_ret_WRITE_FAIL;
9470 }
9471 }
9472 *write_iter++ = ',';
9473 }
9474 write_iter[-1] = ')';
9475 }
9476 if (include_dom) {
9477 *write_iter++ = exportf_delim;
9478 write_iter = memcpya(write_iter, cur_var_id, cur_slen);
9479 write_iter = strcpya_k(write_iter, "_HET");
9480 if (write_iter >= writebuf_flush) {
9481 bytes_written += write_iter - writebuf;
9482 if (unlikely(fwrite_flush2(writebuf_flush, outfile, &write_iter))) {
9483 goto Export012Smaj_ret_WRITE_FAIL;
9484 }
9485 }
9486 }
9487 }
9488 AppendBinaryEoln(&write_iter);
9489 bytes_written += write_iter - writebuf;
9490 if (unlikely(bytes_written > kMaxLongLine)) {
9491 snprintf(g_logbuf, kLogbufSize, "Error: --export A%s header line too long (>2GiB).\n", include_dom? "D" : "");
9492 goto Export012Smaj_ret_INCONSISTENT_INPUT_2;
9493 }
9494
9495 uintptr_t* pheno_nm = nullptr;
9496 uintptr_t* pheno_cc = nullptr;
9497 double* pheno_qt = nullptr;
9498 // .raw files don't support categorical phenotypes
9499 const uint32_t pheno_idx = FirstCcOrQtPhenoIdx(pheno_cols, pheno_ct);
9500 if (pheno_idx != UINT32_MAX) {
9501 const PhenoDtype type_code = pheno_cols[pheno_idx].type_code;
9502 pheno_nm = pheno_cols[pheno_idx].nonmiss;
9503 if (type_code == kPhenoDtypeCc) {
9504 pheno_cc = pheno_cols[pheno_idx].data.cc;
9505 } else {
9506 pheno_qt = pheno_cols[pheno_idx].data.qt;
9507 }
9508 }
9509 const uint32_t lomp_slen = strlen(legacy_output_missing_pheno);
9510
9511 // Initially had the main read thread also perform decompression and
9512 // inversion, and the worker threads only unpacked/transposed the data to a
9513 // sample-major dosage matrix; but this made it pointless to have more than
9514 // 1 worker thread.
9515 //
9516 // So, moving closer to ExportIndMajorBed() strategy:
9517 // * Main read thread only loads raw bytes with PgfiMultiread().
9518 // * Worker thread(s) select subsets of the loaded variants to process in a
9519 // cacheline-aware manner: first worker's interval ends with variant_idx
9520 // divisible by (kCacheline / sizeof(Dosage)) == 32 (unless it's the
9521 // only active worker), and all other interval(s) start with variant_idx
9522 // divisible by 32.
9523
9524 // todo: check when this saturates
9525 uint32_t calc_thread_ct = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
9526 if (calc_thread_ct * kDosagePerCacheline > variant_ct) {
9527 calc_thread_ct = DivUp(variant_ct, kDosagePerCacheline);
9528 }
9529 STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
9530 uint32_t read_block_size;
9531
9532 // note that we only allow this to use 1/4 of remaining memory
9533 if (unlikely(PgenMtLoadInit(variant_include, sample_ct, variant_ct, bigstack_left() / 4, pgr_alloc_cacheline_ct, 0, 0, 0, pgfip, &calc_thread_ct, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &read_block_size, nullptr, main_loadbufs, &ctx.pgr_ptrs, &ctx.read_variant_uidx_starts))) {
9534 goto Export012Smaj_ret_NOMEM;
9535 }
9536
9537 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
9538 uintptr_t* sample_include;
9539 uint32_t* sample_include_cumulative_popcounts;
9540 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &sample_include) ||
9541 bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) ||
9542 bigstack_alloc_u32(calc_thread_ct + 1, &ctx.write_vidx_starts) ||
9543 bigstack_alloc_wp(calc_thread_ct, &ctx.thread_write_genovecs) ||
9544 bigstack_alloc_wp(calc_thread_ct, &ctx.thread_write_dosagepresents) ||
9545 bigstack_alloc_dosagep(calc_thread_ct, &ctx.thread_write_dosagevals))) {
9546 goto Export012Smaj_ret_NOMEM;
9547 }
9548
9549 // Remaining memory byte requirements:
9550 // calc_thread_ct * kDosagePerCacheline * kBytesPerWord *
9551 // read_sample_ctaw2 for per-thread genovecs buffers
9552 // calc_thread_ct * kDosagePerCacheline * kBytesPerWord *
9553 // read_sample_ctaw for per-thread dosage_presents buffers
9554 // calc_thread_ct * kDosagePerCacheline * read_sample_ct *
9555 // sizeof(Dosage) for per-thread dosage_main buffers
9556 // (dosage_ct buffers just go on the thread stacks)
9557 // read_sample_ct * stride * sizeof(Dosage) for ctx.smaj_dosagebuf
9558 // This is roughly
9559 // read_sample_ct *
9560 // (calc_thread_ct * kDosagePerCacheline * 2.375 + variant_ct * 2)
9561 uintptr_t bytes_avail = bigstack_left();
9562 // account for rounding
9563 const uintptr_t round_ceil = kCacheline + calc_thread_ct * (3 * kCacheline + kDosagePerCacheline * (2 * sizeof(intptr_t)));
9564 if (unlikely(bytes_avail < round_ceil)) {
9565 goto Export012Smaj_ret_NOMEM;
9566 }
9567 bytes_avail -= round_ceil;
9568 const uintptr_t stride = RoundUpPow2(variant_ct, kDosagePerCacheline);
9569 uint32_t read_sample_ct = sample_ct;
9570 uint32_t pass_ct = 1;
9571 const uintptr_t bytes_per_sample = calc_thread_ct * (kDosagePerCacheline / 8) * (3LLU + 8 * sizeof(Dosage)) + stride * sizeof(Dosage);
9572 if ((sample_ct * S_CAST(uint64_t, bytes_per_sample)) > bytes_avail) {
9573 read_sample_ct = bytes_avail / bytes_per_sample;
9574 if (unlikely(!read_sample_ct)) {
9575 goto Export012Smaj_ret_NOMEM;
9576 }
9577 if (read_sample_ct > 4) {
9578 read_sample_ct = RoundDownPow2(read_sample_ct, 4);
9579 }
9580 pass_ct = 1 + (sample_ct - 1) / read_sample_ct;
9581 }
9582 uintptr_t read_sample_ctaw = BitCtToAlignedWordCt(read_sample_ct);
9583 uintptr_t read_sample_ctaw2 = NypCtToAlignedWordCt(read_sample_ct);
9584 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
9585 ctx.thread_write_genovecs[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(kDosagePerCacheline * sizeof(intptr_t) * read_sample_ctaw2));
9586 ctx.thread_write_dosagepresents[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(kDosagePerCacheline * sizeof(intptr_t) * read_sample_ctaw));
9587 ctx.thread_write_dosagevals[tidx] = S_CAST(Dosage*, bigstack_alloc_raw(kDosagePerCacheline * sizeof(Dosage) * read_sample_ct));
9588 }
9589 ctx.variant_include = variant_include;
9590 ctx.export_allele = export_allele;
9591 ctx.export_allele_missing = export_allele_missing;
9592 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
9593 goto Export012Smaj_ret_NOMEM;
9594 }
9595 ctx.sample_ct = read_sample_ct;
9596 ctx.stride = stride;
9597 ctx.smaj_dosagebuf = S_CAST(Dosage*, bigstack_alloc_raw_rd(read_sample_ct * S_CAST(uintptr_t, ctx.stride) * sizeof(Dosage)));
9598 assert(g_bigstack_base <= g_bigstack_end);
9599 ctx.err_info = (~0LLU) << 32;
9600 SetThreadFuncAndData(DosageTransposeThread, &ctx, &tg);
9601
9602 const char* sample_ids = piip->sii.sample_ids;
9603 const char* paternal_ids = piip->parental_id_info.paternal_ids;
9604 const char* maternal_ids = piip->parental_id_info.maternal_ids;
9605 const uintptr_t max_sample_id_blen = piip->sii.max_sample_id_blen;
9606 const uintptr_t max_paternal_id_blen = piip->parental_id_info.max_paternal_id_blen;
9607 const uintptr_t max_maternal_id_blen = piip->parental_id_info.max_maternal_id_blen;
9608 uint32_t sample_uidx_start = AdvTo1Bit(orig_sample_include, 0);
9609 for (uint32_t pass_idx = 0; pass_idx != pass_ct; ++pass_idx) {
9610 memcpy(sample_include, orig_sample_include, raw_sample_ctl * sizeof(intptr_t));
9611 if (sample_uidx_start) {
9612 ClearBitsNz(0, sample_uidx_start, sample_include);
9613 }
9614 uint32_t sample_uidx_end;
9615 if (pass_idx + 1 == pass_ct) {
9616 read_sample_ct = sample_ct - pass_idx * read_sample_ct;
9617 ctx.sample_ct = read_sample_ct;
9618 sample_uidx_end = raw_sample_ct;
9619 read_sample_ctaw = BitCtToAlignedWordCt(read_sample_ct);
9620 read_sample_ctaw2 = NypCtToAlignedWordCt(read_sample_ct);
9621 } else {
9622 sample_uidx_end = FindNth1BitFrom(orig_sample_include, sample_uidx_start + 1, read_sample_ct);
9623 ClearBitsNz(sample_uidx_end, raw_sample_ct, sample_include);
9624 }
9625 FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts);
9626 ctx.sample_include = sample_include;
9627 ctx.sample_include_cumulative_popcounts = sample_include_cumulative_popcounts;
9628 if (pass_idx) {
9629 ReinitThreads(&tg);
9630 pgfip->block_base = main_loadbufs[0];
9631 PgrSetBaseAndOffset0(main_loadbufs[0], calc_thread_ct, ctx.pgr_ptrs);
9632 }
9633 putc_unlocked('\r', stdout);
9634 printf("--export A%s pass %u/%u: loading... 0%%", include_dom? "D" : "", pass_idx + 1, pass_ct);
9635 fflush(stdout);
9636 // Main workflow:
9637 // 1. Set n=0, load first calc_thread_ct * kDosagePerCacheline
9638 // post-filtering variants
9639 //
9640 // 2. Spawn threads processing batch n
9641 // 3. Load batch (n+1) unless eof
9642 // 4. Join threads
9643 // 5. Increment n by 1
9644 // 6. Goto step 2 unless eof
9645 uint32_t parity = 0;
9646 uint32_t read_block_idx = 0;
9647 uint32_t pct = 0;
9648 uint32_t next_print_idx = variant_ct / 100;
9649 for (uint32_t variant_idx = 0; ; ) {
9650 const uint32_t cur_block_write_ct = MultireadNonempty(variant_include, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr);
9651 if (unlikely(reterr)) {
9652 goto Export012Smaj_ret_PGR_FAIL;
9653 }
9654 if (variant_idx) {
9655 JoinThreads(&tg);
9656 reterr = S_CAST(PglErr, ctx.err_info);
9657 if (unlikely(reterr)) {
9658 PgenErrPrintNV(reterr, ctx.err_info >> 32);
9659 goto Export012Smaj_ret_1;
9660 }
9661 }
9662 if (!IsLastBlock(&tg)) {
9663 ctx.cur_block_write_ct = cur_block_write_ct;
9664 ComputePartitionAligned(variant_include, calc_thread_ct, read_block_idx * read_block_size, variant_idx, cur_block_write_ct, kDosagePerCacheline, ctx.read_variant_uidx_starts, ctx.write_vidx_starts);
9665 PgrCopyBaseAndOffset(pgfip, calc_thread_ct, ctx.pgr_ptrs);
9666 if (variant_idx + cur_block_write_ct == variant_ct) {
9667 DeclareLastThreadBlock(&tg);
9668 }
9669 if (unlikely(SpawnThreads(&tg))) {
9670 goto Export012Smaj_ret_THREAD_CREATE_FAIL;
9671 }
9672 }
9673 parity = 1 - parity;
9674 if (variant_idx == variant_ct) {
9675 break;
9676 }
9677 if (variant_idx >= next_print_idx) {
9678 if (pct > 10) {
9679 putc_unlocked('\b', stdout);
9680 }
9681 pct = (variant_idx * 100LLU) / variant_ct;
9682 printf("\b\b%u%%", pct++);
9683 fflush(stdout);
9684 next_print_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
9685 }
9686
9687 ++read_block_idx;
9688 variant_idx += cur_block_write_ct;
9689 pgfip->block_base = main_loadbufs[parity];
9690 }
9691 if (pct > 10) {
9692 fputs("\b \b", stdout);
9693 }
9694 fputs("\b\b\b\b\b\b\b\b\b\b\b\b\bwriting... 0%", stdout);
9695 fflush(stdout);
9696 pct = 0;
9697 next_print_idx = read_sample_ct / 100;
9698 uintptr_t sample_uidx_base;
9699 uintptr_t sample_include_bits;
9700 BitIter1Start(sample_include, sample_uidx_start, &sample_uidx_base, &sample_include_bits);
9701 const Dosage* cur_dosage_row = ctx.smaj_dosagebuf;
9702 for (uint32_t sample_idx = 0; sample_idx != read_sample_ct; ++sample_idx) {
9703 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &sample_include_bits);
9704 const char* cur_sample_fid = &(sample_ids[sample_uidx * max_sample_id_blen]);
9705 const char* fid_end = AdvToDelim(cur_sample_fid, '\t');
9706 write_iter = memcpyax(write_iter, cur_sample_fid, fid_end - cur_sample_fid, exportf_delim);
9707 write_iter = strcpyax(write_iter, &(fid_end[1]), exportf_delim);
9708 write_iter = strcpyax(write_iter, &(paternal_ids[sample_uidx * max_paternal_id_blen]), exportf_delim);
9709 write_iter = strcpyax(write_iter, &(maternal_ids[sample_uidx * max_maternal_id_blen]), exportf_delim);
9710 *write_iter++ = Sexchar(sex_nm, sex_male, sample_uidx);
9711 *write_iter++ = exportf_delim;
9712 if ((!pheno_nm) || (!IsSet(pheno_nm, sample_uidx))) {
9713 write_iter = memcpya(write_iter, legacy_output_missing_pheno, lomp_slen);
9714 } else if (pheno_cc) {
9715 *write_iter++ = '1' + IsSet(pheno_cc, sample_uidx);
9716 } else {
9717 write_iter = dtoa_g(pheno_qt[sample_uidx], write_iter);
9718 }
9719 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
9720 goto Export012Smaj_ret_WRITE_FAIL;
9721 }
9722 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
9723 *write_iter++ = exportf_delim;
9724 uint32_t cur_dosage_val = cur_dosage_row[variant_idx];
9725 if (cur_dosage_val != 65535) {
9726 write_iter = PrintSmallDosage(cur_dosage_val, write_iter);
9727 if (include_dom) {
9728 *write_iter++ = exportf_delim;
9729 write_iter = PrintSmallDosage(16384 - abs_i32(cur_dosage_val - 16384), write_iter);
9730 }
9731 } else {
9732 write_iter = strcpya_k(write_iter, "NA");
9733 if (include_dom) {
9734 *write_iter++ = exportf_delim;
9735 write_iter = strcpya_k(write_iter, "NA");
9736 }
9737 }
9738 // todo: try making this check less frequently
9739 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
9740 goto Export012Smaj_ret_WRITE_FAIL;
9741 }
9742 }
9743 AppendBinaryEoln(&write_iter);
9744 cur_dosage_row = &(cur_dosage_row[ctx.stride]);
9745 if (sample_idx >= next_print_idx) {
9746 if (pct > 10) {
9747 putc_unlocked('\b', stdout);
9748 }
9749 pct = (sample_idx * 100LLU) / read_sample_ct;
9750 printf("\b\b%u%%", pct++);
9751 fflush(stdout);
9752 next_print_idx = (pct * S_CAST(uint64_t, read_sample_ct)) / 100;
9753 }
9754 }
9755 sample_uidx_start = sample_uidx_end;
9756 if (pct > 10) {
9757 fputs("\b \b", stdout);
9758 }
9759 }
9760 if (unlikely(fclose_flush_null(writebuf_flush, write_iter, &outfile))) {
9761 goto Export012Smaj_ret_WRITE_FAIL;
9762 }
9763 fputs("\b\bdone.\n", stdout);
9764 logprintfww("--export A%s: %s written.\n", include_dom? "D" : "", outname);
9765 }
9766 while (0) {
9767 Export012Smaj_ret_NOMEM:
9768 reterr = kPglRetNomem;
9769 break;
9770 Export012Smaj_ret_OPEN_FAIL:
9771 reterr = kPglRetOpenFail;
9772 break;
9773 Export012Smaj_ret_PGR_FAIL:
9774 PgenErrPrintN(reterr);
9775 break;
9776 Export012Smaj_ret_WRITE_FAIL:
9777 reterr = kPglRetWriteFail;
9778 break;
9779 Export012Smaj_ret_INCONSISTENT_INPUT_2:
9780 logerrputsb();
9781 reterr = kPglRetInconsistentInput;
9782 break;
9783 Export012Smaj_ret_THREAD_CREATE_FAIL:
9784 reterr = kPglRetThreadCreateFail;
9785 break;
9786 }
9787 Export012Smaj_ret_1:
9788 CleanupThreads(&tg);
9789 fclose_cond(outfile);
9790 pgfip->block_base = nullptr;
9791 BigstackReset(bigstack_mark);
9792 return reterr;
9793 }
9794
9795 #ifdef USE_SHUFFLE8
9796 // Assumes outvec_ct is positive.
9797 void Subst4bitTo8(const void* src_vec, const VecW lookup, uint32_t outvec_ct, void* dst_vec) {
9798 // See Expand4bitTo8(); this just applies a substitution operation on top of
9799 // that.
9800 const VecW m4 = VCONST_W(kMask0F0F);
9801 const VecW* src_iter = S_CAST(const VecW*, src_vec);
9802 VecW* dst_iter = S_CAST(VecW*, dst_vec);
9803 VecW* dst_last = &(dst_iter[outvec_ct - 1]);
9804 while (1) {
9805 VecW cur_vec = *src_iter++;
9806 VecW vec_lo;
9807 VecW vec_hi;
9808 vecw_lo_and_hi_nybbles(cur_vec, m4, &vec_lo, &vec_hi);
9809 const VecW result_lo = vecw_shuffle8(lookup, vec_lo);
9810 const VecW result_hi = vecw_shuffle8(lookup, vec_hi);
9811 *dst_iter++ = result_lo;
9812 if (dst_iter >= dst_last) {
9813 if (dst_iter == dst_last) {
9814 *dst_iter = result_hi;
9815 }
9816 return;
9817 }
9818 *dst_iter++ = result_hi;
9819 }
9820 }
9821
9822 // Maps 0 -> nybble0, 1 -> (nybble0 | nybble2), 2 -> nybble2, 3 -> 15.
9823 void GenovecToNybblesSSE4(const uintptr_t* genovec, uint32_t sample_ct, uint32_t nybble0, uint32_t nybble2, uintptr_t* result_vec) {
9824 const uint32_t lo_u32 = (nybble0 * 0x101) | (nybble2 * 0x10100) | 0xf000000;
9825 const uint32_t first_u32 = lo_u32 | (nybble0 * 0x10101010);
9826 const uint32_t third_u32 = lo_u32 | (nybble2 * 0x10101010);
9827 const VecW lookup = vecw_setr32(first_u32, first_u32 | third_u32, third_u32, lo_u32 | 0xf0f0f0f0U);
9828 const uint32_t outvec_ct = NybbleCtToVecCt(sample_ct);
9829 Subst4bitTo8(genovec, lookup, outvec_ct, result_vec);
9830 }
9831
9832 // writes up to vector boundary
9833 static inline void NybblesToIupac(const uintptr_t* nybblevec, uint32_t entry_ct, uintptr_t* result_vec) {
9834 const VecW lookup = vecw_setr8('.', 'A', 'C', 'M', 'G', 'R', 'S', '.', 'T', 'W', 'Y', '.', 'K', '.', '.', 'N');
9835 const uint32_t outvec_ct = DivUp(entry_ct, kBytesPerVec);
9836 Subst4bitTo8(nybblevec, lookup, outvec_ct, result_vec);
9837 }
9838 #else
9839 // some of this may be moved to pgenlib_misc
9840
9841 void GenovecToNybblesNoSSE4(const uint16_t* const* genovec_to_nybble_tables, const uintptr_t* genovec, uint32_t sample_ct, uint32_t nybble0, uint32_t nybble2, uintptr_t* result_vec) {
9842 const uint32_t nybble0_table_idx = ctzu32(nybble0) + 4 * (nybble0 == 15);
9843 const uint32_t nybble2_table_idx = ctzu32(nybble2) + 4 * (nybble2 == 15);
9844 const uint32_t table_idx = nybble0_table_idx + 5 * nybble2_table_idx;
9845 const uint16_t* cur_genovec_to_nybble_table = genovec_to_nybble_tables[table_idx];
9846
9847 const unsigned char* genovec_alias = DowncastKToUc(genovec);
9848 uint16_t* result_alias = DowncastWToU16(result_vec);
9849 const uint32_t inbyte_ct = NypCtToByteCt(sample_ct);
9850 for (uint32_t inbyte_idx = 0; inbyte_idx != inbyte_ct; ++inbyte_idx) {
9851 result_alias[inbyte_idx] = cur_genovec_to_nybble_table[genovec_alias[inbyte_idx]];
9852 }
9853 }
9854
9855 # define PAIR_TABLE256(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) \
9856 {(a), (a), (b), (a), (c), (a), (d), (a), (e), (a), (f), (a), (g), (a), (h), (a), (i), (a), (j), (a), (k), (a), (l), (a), (m), (a), (n), (a), (o), (a), (p), (a), \
9857 (a), (b), (b), (b), (c), (b), (d), (b), (e), (b), (f), (b), (g), (b), (h), (b), (i), (b), (j), (b), (k), (b), (l), (b), (m), (b), (n), (b), (o), (b), (p), (b), \
9858 (a), (c), (b), (c), (c), (c), (d), (c), (e), (c), (f), (c), (g), (c), (h), (c), (i), (c), (j), (c), (k), (c), (l), (c), (m), (c), (n), (c), (o), (c), (p), (c), \
9859 (a), (d), (b), (d), (c), (d), (d), (d), (e), (d), (f), (d), (g), (d), (h), (d), (i), (d), (j), (d), (k), (d), (l), (d), (m), (d), (n), (d), (o), (d), (p), (d), \
9860 (a), (e), (b), (e), (c), (e), (d), (e), (e), (e), (f), (e), (g), (e), (h), (e), (i), (e), (j), (e), (k), (e), (l), (e), (m), (e), (n), (e), (o), (e), (p), (e), \
9861 (a), (f), (b), (f), (c), (f), (d), (f), (e), (f), (f), (f), (g), (f), (h), (f), (i), (f), (j), (f), (k), (f), (l), (f), (m), (f), (n), (f), (o), (f), (p), (f), \
9862 (a), (g), (b), (g), (c), (g), (d), (g), (e), (g), (f), (g), (g), (g), (h), (g), (i), (g), (j), (g), (k), (g), (l), (g), (m), (g), (n), (g), (o), (g), (p), (g), \
9863 (a), (h), (b), (h), (c), (h), (d), (h), (e), (h), (f), (h), (g), (h), (h), (h), (i), (h), (j), (h), (k), (h), (l), (h), (m), (h), (n), (h), (o), (h), (p), (h), \
9864 (a), (i), (b), (i), (c), (i), (d), (i), (e), (i), (f), (i), (g), (i), (h), (i), (i), (i), (j), (i), (k), (i), (l), (i), (m), (i), (n), (i), (o), (i), (p), (i), \
9865 (a), (j), (b), (j), (c), (j), (d), (j), (e), (j), (f), (j), (g), (j), (h), (j), (i), (j), (j), (j), (k), (j), (l), (j), (m), (j), (n), (j), (o), (j), (p), (j), \
9866 (a), (k), (b), (k), (c), (k), (d), (k), (e), (k), (f), (k), (g), (k), (h), (k), (i), (k), (j), (k), (k), (k), (l), (k), (m), (k), (n), (k), (o), (k), (p), (k), \
9867 (a), (l), (b), (l), (c), (l), (d), (l), (e), (l), (f), (l), (g), (l), (h), (l), (i), (l), (j), (l), (k), (l), (l), (l), (m), (l), (n), (l), (o), (l), (p), (l), \
9868 (a), (m), (b), (m), (c), (m), (d), (m), (e), (m), (f), (m), (g), (m), (h), (m), (i), (m), (j), (m), (k), (m), (l), (m), (m), (m), (n), (m), (o), (m), (p), (m), \
9869 (a), (n), (b), (n), (c), (n), (d), (n), (e), (n), (f), (n), (g), (n), (h), (n), (i), (n), (j), (n), (k), (n), (l), (n), (m), (n), (n), (n), (o), (n), (p), (n), \
9870 (a), (o), (b), (o), (c), (o), (d), (o), (e), (o), (f), (o), (g), (o), (h), (o), (i), (o), (j), (o), (k), (o), (l), (o), (m), (o), (n), (o), (o), (o), (p), (o), \
9871 (a), (p), (b), (p), (c), (p), (d), (p), (e), (p), (f), (p), (g), (p), (h), (p), (i), (p), (j), (p), (k), (p), (l), (p), (m), (p), (n), (p), (o), (p), (p), (p)}
9872
9873 void NybblearrLookup256x1bx2(const uintptr_t* nybblearr, const void* table256x1bx2, uint32_t entry_ct, void* __restrict result) {
9874 const uint16_t* table_alias = S_CAST(const uint16_t*, table256x1bx2);
9875 const unsigned char* nybblearr_alias = DowncastKToUc(nybblearr);
9876 unsigned char* resultb = S_CAST(unsigned char*, result);
9877 const uint32_t full_byte_ct = entry_ct / 2;
9878 for (uint32_t byte_idx = 0; byte_idx != full_byte_ct; ++byte_idx) {
9879 CopyToUnalignedOffsetU16(resultb, &(table_alias[nybblearr_alias[byte_idx]]), byte_idx);
9880 }
9881 if (entry_ct % 2) {
9882 resultb[full_byte_ct * sizeof(int16_t)] = table_alias[nybblearr_alias[full_byte_ct]];
9883 }
9884 }
9885
9886 void InitLookup256x05bx4(uint32_t nybble0, uint32_t nybble1, uint32_t nybble2, uint32_t nybble3, void* table256x05bx4) {
9887 unsigned char* table_iter = S_CAST(unsigned char*, table256x05bx4);
9888 const uint32_t nybble0_shifted = nybble0 << 4;
9889 const uint32_t nybble1_shifted = nybble1 << 4;
9890 const uint32_t nybble2_shifted = nybble2 << 4;
9891 const uint32_t nybble3_shifted = nybble3 << 4;
9892 unsigned char vals[16];
9893 vals[0] = nybble0 | nybble0_shifted;
9894 vals[1] = nybble1 | nybble0_shifted;
9895 vals[2] = nybble2 | nybble0_shifted;
9896 vals[3] = nybble3 | nybble0_shifted;
9897 vals[4] = nybble0 | nybble1_shifted;
9898 vals[5] = nybble1 | nybble1_shifted;
9899 vals[6] = nybble2 | nybble1_shifted;
9900 vals[7] = nybble3 | nybble1_shifted;
9901 vals[8] = nybble0 | nybble2_shifted;
9902 vals[9] = nybble1 | nybble2_shifted;
9903 vals[10] = nybble2 | nybble2_shifted;
9904 vals[11] = nybble3 | nybble2_shifted;
9905 vals[12] = nybble0 | nybble3_shifted;
9906 vals[13] = nybble1 | nybble3_shifted;
9907 vals[14] = nybble2 | nybble3_shifted;
9908 vals[15] = nybble3 | nybble3_shifted;
9909 for (uint32_t high_idx = 0; high_idx != 16; ++high_idx) {
9910 const uint32_t cur_high = vals[high_idx];
9911 for (uint32_t low_idx = 0; low_idx != 16; ++low_idx) {
9912 *table_iter++ = vals[low_idx];
9913 *table_iter++ = cur_high;
9914 }
9915 }
9916 }
9917
9918 static const unsigned char kNybblePairToIupac[512] = PAIR_TABLE256('.', 'A', 'C', 'M', 'G', 'R', 'S', '.', 'T', 'W', 'Y', '.', 'K', '.', '.', 'N');
9919
9920 static inline void NybblesToIupac(const uintptr_t* nybblevec, uint32_t entry_ct, uintptr_t* result_vec) {
9921 NybblearrLookup256x1bx2(nybblevec, kNybblePairToIupac, entry_ct, result_vec);
9922 }
9923 #endif
9924
9925 typedef struct PhylipReadCtxStruct {
9926 const uintptr_t* variant_include;
9927 const uintptr_t* allele_idx_offsets;
9928 const char* const* allele_storage;
9929 const uintptr_t* sample_include;
9930 const uint32_t* sample_include_cumulative_popcounts;
9931 unsigned char allele_nybble_table[256];
9932 // Precomputed 256-entry lookup tables.
9933 // Format depends on phased vs. unphased. No lookup table needed in unphased
9934 // SSE4+ case.
9935 const void* genovec_to_nybble_tables[25];
9936 uint32_t sample_ct;
9937
9938 PgenReader** pgr_ptrs;
9939 uintptr_t** genovecs;
9940 uintptr_t** thread_read_mhc;
9941 uintptr_t** phasepresents;
9942 uintptr_t** phaseinfos;
9943
9944 uint32_t* variant_uidx_starts;
9945 uint32_t cur_block_write_ct;
9946
9947 // nybble-encoded IUPAC codes
9948 uintptr_t* vmaj_readbuf;
9949
9950 uint32_t* write_sample_nm_cts;
9951
9952 uint64_t err_info;
9953 } PhylipReadCtx;
9954
9955 THREAD_FUNC_DECL PhylipReadThread(void* raw_arg) {
9956 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
9957 const uintptr_t tidx = arg->tidx;
9958 PhylipReadCtx* ctx = S_CAST(PhylipReadCtx*, arg->sharedp->context);
9959
9960 const uintptr_t* variant_include = ctx->variant_include;
9961 const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
9962 const char* const* allele_storage = ctx->allele_storage;
9963 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
9964 const uintptr_t* sample_include = ctx->sample_include;
9965 const unsigned char* allele_nybble_table = ctx->allele_nybble_table;
9966 #ifndef USE_SHUFFLE8
9967 const uint16_t* const* genovec_to_nybble_tables = R_CAST(const uint16_t* const*, ctx->genovec_to_nybble_tables);
9968 #endif
9969 const uint32_t read_sample_ct = ctx->sample_ct;
9970 const uintptr_t read_sample_ctaw4 = NybbleCtToAlignedWordCt(read_sample_ct);
9971 PgenReader* pgrp = ctx->pgr_ptrs[tidx];
9972 PgrSampleSubsetIndex pssi;
9973 PgrSetSampleSubsetIndex(ctx->sample_include_cumulative_popcounts, pgrp, &pssi);
9974 uintptr_t* genovec = ctx->genovecs[tidx];
9975 PgenVariant pgv;
9976 pgv.genovec = genovec;
9977 SetPgvThreadMhcNull(read_sample_ct, tidx, ctx->thread_read_mhc, &pgv);
9978 uint32_t* write_sample_nm_cts_iter = nullptr;
9979 uintptr_t prev_copy_ct = 0;
9980 uint64_t new_err_info = 0;
9981 uint32_t cur_allele_ct = 2;
9982 uint32_t allele_nybbles[4];
9983 do {
9984 const uintptr_t cur_block_copy_ct = ctx->cur_block_write_ct;
9985 const uint32_t cur_idx_end = ((tidx + 1) * cur_block_copy_ct) / calc_thread_ct;
9986 uintptr_t variant_uidx_base;
9987 uintptr_t cur_bits;
9988 BitIter1Start(variant_include, ctx->variant_uidx_starts[tidx], &variant_uidx_base, &cur_bits);
9989 const uint32_t cur_idx_start = (tidx * cur_block_copy_ct) / calc_thread_ct;
9990 uintptr_t* vmaj_readbuf_iter = &(ctx->vmaj_readbuf[(prev_copy_ct + cur_idx_start) * read_sample_ctaw4]);
9991 if (ctx->write_sample_nm_cts) {
9992 write_sample_nm_cts_iter = &(ctx->write_sample_nm_cts[prev_copy_ct + cur_idx_start]);
9993 }
9994 for (uint32_t cur_idx = cur_idx_start; cur_idx != cur_idx_end; ++cur_idx) {
9995 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
9996 uintptr_t allele_idx_offset_base = variant_uidx * 2;
9997 if (allele_idx_offsets) {
9998 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
9999 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
10000 if (unlikely(cur_allele_ct > 4)) {
10001 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, kPglRetInconsistentInput);
10002 goto PhylipReadThread_err;
10003 }
10004 }
10005 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
10006 for (uint32_t aidx = 0; aidx != cur_allele_ct; ++aidx) {
10007 const char* cur_allele = cur_alleles[aidx];
10008 allele_nybbles[aidx] = allele_nybble_table[S_CAST(unsigned char, cur_allele[0])];
10009 if (unlikely((!allele_nybbles[aidx]) || cur_allele[1])) {
10010 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, kPglRetInconsistentInput);
10011 goto PhylipReadThread_err;
10012 }
10013 }
10014 PglErr reterr;
10015 if (cur_allele_ct == 2) {
10016 reterr = PgrGet(sample_include, pssi, read_sample_ct, variant_uidx, pgrp, genovec);
10017 } else {
10018 reterr = PgrGetM(sample_include, pssi, read_sample_ct, variant_uidx, pgrp, &pgv);
10019 }
10020 if (unlikely(reterr)) {
10021 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
10022 goto PhylipReadThread_err;
10023 }
10024 ZeroTrailingNyps(read_sample_ct, genovec);
10025 const uint32_t nybble0 = allele_nybbles[0];
10026 const uint32_t nybble1 = allele_nybbles[1];
10027 #ifdef USE_SHUFFLE8
10028 GenovecToNybblesSSE4(genovec, read_sample_ct, nybble0, nybble1, vmaj_readbuf_iter);
10029 #else
10030 GenovecToNybblesNoSSE4(genovec_to_nybble_tables, genovec, read_sample_ct, nybble0, nybble1, vmaj_readbuf_iter);
10031 #endif
10032 uint32_t missing_allele_present = (nybble0 == 15) || (nybble1 == 15);
10033 if (cur_allele_ct > 2) {
10034 const uint32_t patch_01_ct = pgv.patch_01_ct;
10035 if (patch_01_ct) {
10036 uint32_t patch_01_nybbles[4];
10037 patch_01_nybbles[2] = nybble0 | allele_nybbles[2];
10038 missing_allele_present |= (allele_nybbles[2] == 15);
10039 if (cur_allele_ct == 4) {
10040 patch_01_nybbles[3] = nybble0 | allele_nybbles[3];
10041 missing_allele_present |= (allele_nybbles[3] == 15);
10042 }
10043 const uintptr_t* patch_01_set = pgv.patch_01_set;
10044 const AlleleCode* patch_01_vals = pgv.patch_01_vals;
10045 uintptr_t sample_widx = 0;
10046 uintptr_t patch_01_bits = patch_01_set[0];
10047 for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
10048 const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_widx, &patch_01_bits);
10049 const AlleleCode ac = patch_01_vals[uii];
10050 AssignNybblearrEntry(sample_idx, patch_01_nybbles[ac], vmaj_readbuf_iter);
10051 }
10052 }
10053 const uint32_t patch_10_ct = pgv.patch_10_ct;
10054 if (patch_10_ct) {
10055 const uintptr_t* patch_10_set = pgv.patch_10_set;
10056 const AlleleCode* patch_10_vals = pgv.patch_10_vals;
10057 uintptr_t sample_widx = 0;
10058 uintptr_t patch_10_bits = patch_10_set[0];
10059 for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
10060 const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_widx, &patch_10_bits);
10061 const AlleleCode ac0 = patch_10_vals[uii * 2];
10062 const AlleleCode ac1 = patch_10_vals[uii * 2 + 1];
10063 AssignNybblearrEntry(sample_idx, allele_nybbles[ac0] | allele_nybbles[ac1], vmaj_readbuf_iter);
10064 }
10065 }
10066 }
10067 if (write_sample_nm_cts_iter) {
10068 uint32_t missing_ct;
10069 if (missing_allele_present) {
10070 // REF=N or ALT=N is possible (see e.g. chrM POS=3107 in the original
10071 // 1000 Genomes phase 3 variant calls). They should also be counted
10072 // as missing.
10073 // (This is intentionally different from vcf2phylip.py's behavior.)
10074 missing_ct = CountNybble(vmaj_readbuf_iter, ~k0LU, read_sample_ct);
10075 } else {
10076 missing_ct = GenoarrCountMissingUnsafe(genovec, read_sample_ct);
10077 }
10078 *write_sample_nm_cts_iter += read_sample_ct - missing_ct;
10079 ++write_sample_nm_cts_iter;
10080 }
10081 vmaj_readbuf_iter = &(vmaj_readbuf_iter[read_sample_ctaw4]);
10082 }
10083 prev_copy_ct += cur_block_copy_ct;
10084 while (0) {
10085 PhylipReadThread_err:
10086 UpdateU64IfSmaller(new_err_info, &ctx->err_info);
10087 }
10088 } while (!THREAD_BLOCK_FINISH(arg));
10089 THREAD_RETURN;
10090 }
10091
10092 THREAD_FUNC_DECL PhylipPhasedReadThread(void* raw_arg) {
10093 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
10094 const uintptr_t tidx = arg->tidx;
10095 PhylipReadCtx* ctx = S_CAST(PhylipReadCtx*, arg->sharedp->context);
10096
10097 const uintptr_t* variant_include = ctx->variant_include;
10098 const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
10099 const char* const* allele_storage = ctx->allele_storage;
10100 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
10101 const uintptr_t* sample_include = ctx->sample_include;
10102 const unsigned char* allele_nybble_table = ctx->allele_nybble_table;
10103 const uint32_t* const* genovec_to_nybblepair_tables = R_CAST(const uint32_t* const*, ctx->genovec_to_nybble_tables);
10104 const uint32_t read_sample_ct = ctx->sample_ct;
10105 const uint32_t read_sample_ctl = BitCtToWordCt(read_sample_ct);
10106 const uintptr_t read_sample_ctaw8 = DivUp(read_sample_ct, kBytesPerVec) * kWordsPerVec;
10107 PgenReader* pgrp = ctx->pgr_ptrs[tidx];
10108 PgrSampleSubsetIndex pssi;
10109 PgrSetSampleSubsetIndex(ctx->sample_include_cumulative_popcounts, pgrp, &pssi);
10110 uintptr_t* genovec = ctx->genovecs[tidx];
10111 PgenVariant pgv;
10112 pgv.genovec = genovec;
10113 SetPgvThreadMhcNull(read_sample_ct, tidx, ctx->thread_read_mhc, &pgv);
10114 uintptr_t* phasepresent = nullptr;
10115 uintptr_t* phaseinfo = nullptr;
10116 if (ctx->phasepresents) {
10117 phasepresent = ctx->phasepresents[tidx];
10118 phaseinfo = ctx->phaseinfos[tidx];
10119 }
10120 pgv.phasepresent = phasepresent;
10121 pgv.phaseinfo = phaseinfo;
10122 uint32_t* write_sample_nm_cts_iter = nullptr;
10123 uintptr_t prev_copy_ct = 0;
10124 uint64_t new_err_info = 0;
10125 uint32_t cur_allele_ct = 2;
10126 uint32_t allele_nybbles[4];
10127 do {
10128 const uintptr_t cur_block_copy_ct = ctx->cur_block_write_ct;
10129 const uint32_t cur_idx_end = ((tidx + 1) * cur_block_copy_ct) / calc_thread_ct;
10130 uintptr_t variant_uidx_base;
10131 uintptr_t cur_bits;
10132 BitIter1Start(variant_include, ctx->variant_uidx_starts[tidx], &variant_uidx_base, &cur_bits);
10133 const uint32_t cur_idx_start = (tidx * cur_block_copy_ct) / calc_thread_ct;
10134 uintptr_t* vmaj_readbuf_iter = &(ctx->vmaj_readbuf[(prev_copy_ct + cur_idx_start) * read_sample_ctaw8]);
10135 if (ctx->write_sample_nm_cts) {
10136 write_sample_nm_cts_iter = &(ctx->write_sample_nm_cts[prev_copy_ct + cur_idx_start]);
10137 }
10138 for (uint32_t cur_idx = cur_idx_start; cur_idx != cur_idx_end; ++cur_idx) {
10139 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
10140 uintptr_t allele_idx_offset_base = variant_uidx * 2;
10141 if (allele_idx_offsets) {
10142 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
10143 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
10144 if (unlikely(cur_allele_ct > 4)) {
10145 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, kPglRetInconsistentInput);
10146 goto PhylipPhasedReadThread_err;
10147 }
10148 }
10149 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
10150 for (uint32_t aidx = 0; aidx != cur_allele_ct; ++aidx) {
10151 const char* cur_allele = cur_alleles[aidx];
10152 const uint32_t cur_nybble = allele_nybble_table[S_CAST(unsigned char, cur_allele[0])];
10153 if (unlikely((!cur_nybble) || cur_allele[1])) {
10154 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, kPglRetInconsistentInput);
10155 goto PhylipPhasedReadThread_err;
10156 }
10157 allele_nybbles[aidx] = cur_nybble;
10158 }
10159 PglErr reterr;
10160 if (cur_allele_ct == 2) {
10161 reterr = PgrGetP(sample_include, pssi, read_sample_ct, variant_uidx, pgrp, genovec, phasepresent, phaseinfo, &pgv.phasepresent_ct);
10162 } else {
10163 reterr = PgrGetMP(sample_include, pssi, read_sample_ct, variant_uidx, pgrp, &pgv);
10164 }
10165 if (unlikely(reterr)) {
10166 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
10167 goto PhylipPhasedReadThread_err;
10168 }
10169 ZeroTrailingNyps(read_sample_ct, genovec);
10170 STD_ARRAY_DECL(uint32_t, 4, genocounts);
10171 GenoarrCountFreqsUnsafe(genovec, read_sample_ct, genocounts);
10172 const uint32_t nybble0 = allele_nybbles[0];
10173 const uint32_t nybble1 = allele_nybbles[1];
10174 {
10175 const uint32_t allele0_table_idx = ctzu32(nybble0) + 4 * (nybble0 == 15);
10176 const uint32_t allele1_table_idx = ctzu32(nybble1) + 4 * (nybble1 == 15);
10177 const uint32_t table_idx = allele0_table_idx + 5 * allele1_table_idx;
10178 GenoarrLookup256x1bx4(genovec, genovec_to_nybblepair_tables[table_idx], read_sample_ct, vmaj_readbuf_iter);
10179 }
10180 uint32_t het_ct = genocounts[1];
10181 uint32_t missing_allele_present = (nybble0 == 15) || (nybble1 == 15);
10182 if (cur_allele_ct > 2) {
10183 unsigned char* nybblepairs = DowncastToUc(vmaj_readbuf_iter);
10184 const uint32_t patch_01_ct = pgv.patch_01_ct;
10185 uint32_t shifted_nybbles[4];
10186 shifted_nybbles[2] = allele_nybbles[2] << 4;
10187 missing_allele_present |= (allele_nybbles[2] == 15);
10188 if (cur_allele_ct == 4) {
10189 shifted_nybbles[3] = allele_nybbles[3] << 4;
10190 missing_allele_present |= (allele_nybbles[3] == 15);
10191 }
10192 if (patch_01_ct) {
10193 const uintptr_t* patch_01_set = pgv.patch_01_set;
10194 const AlleleCode* patch_01_vals = pgv.patch_01_vals;
10195 uintptr_t sample_widx = 0;
10196 uintptr_t patch_01_bits = patch_01_set[0];
10197 for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
10198 const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_widx, &patch_01_bits);
10199 const AlleleCode ac = patch_01_vals[uii];
10200 nybblepairs[sample_idx] = nybble0 | shifted_nybbles[ac];
10201 }
10202 }
10203 const uint32_t patch_10_ct = pgv.patch_10_ct;
10204 if (patch_10_ct) {
10205 const uintptr_t* patch_10_set = pgv.patch_10_set;
10206 const AlleleCode* patch_10_vals = pgv.patch_10_vals;
10207 uintptr_t sample_widx = 0;
10208 uintptr_t patch_10_bits = patch_10_set[0];
10209 for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
10210 const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_widx, &patch_10_bits);
10211 const AlleleCode ac0 = patch_10_vals[uii * 2];
10212 const AlleleCode ac1 = patch_10_vals[uii * 2 + 1];
10213 het_ct += (ac0 != ac1);
10214 nybblepairs[sample_idx] = allele_nybbles[ac0] | shifted_nybbles[ac1];
10215 }
10216 }
10217 }
10218 if (write_sample_nm_cts_iter) {
10219 uint32_t missing_ct;
10220 if (missing_allele_present) {
10221 missing_ct = CountNybble(vmaj_readbuf_iter, ~k0LU, read_sample_ct * 2);
10222 } else {
10223 missing_ct = genocounts[3] * 2;
10224 }
10225 *write_sample_nm_cts_iter += read_sample_ct * 2 - missing_ct;
10226 ++write_sample_nm_cts_iter;
10227 }
10228 const uint32_t phasepresent_ct = pgv.phasepresent_ct;
10229 if (unlikely(phasepresent_ct != het_ct)) {
10230 // another type of InconsistentInput
10231 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, kPglRetInternalUse1);
10232 goto PhylipPhasedReadThread_err;
10233 }
10234 if (phasepresent_ct) {
10235 for (uint32_t widx = 0; widx != read_sample_ctl; ++widx) {
10236 const uintptr_t phasepresent_word = phasepresent[widx];
10237 uintptr_t phaseinfo_word = phasepresent_word & phaseinfo[widx];
10238 if (phaseinfo_word) {
10239 unsigned char* cur_nybblepairs = DowncastToUc(vmaj_readbuf_iter);
10240 cur_nybblepairs = &(cur_nybblepairs[widx * kBitsPerWord]);
10241 do {
10242 const uint32_t sample_idx_lowbits = ctzw(phaseinfo_word);
10243 const uint32_t nybblepair = cur_nybblepairs[sample_idx_lowbits];
10244 cur_nybblepairs[sample_idx_lowbits] = (nybblepair << 4) | (nybblepair >> 4);
10245 phaseinfo_word &= phaseinfo_word - 1;
10246 } while (phaseinfo_word);
10247 }
10248 }
10249 }
10250 vmaj_readbuf_iter = &(vmaj_readbuf_iter[read_sample_ctaw8]);
10251 }
10252 prev_copy_ct += cur_block_copy_ct;
10253 while (0) {
10254 PhylipPhasedReadThread_err:
10255 UpdateU64IfSmaller(new_err_info, &ctx->err_info);
10256 }
10257 } while (!THREAD_BLOCK_FINISH(arg));
10258 THREAD_RETURN;
10259 }
10260
10261 typedef struct PhylipTransposeCtxStruct {
10262 const uintptr_t* variant_include;
10263 uint32_t variant_ct;
10264 uint32_t write_sample_ct;
10265
10266 const uintptr_t* vmaj_readbuf;
10267
10268 VecW** thread_vecaligned_bufs;
10269 uintptr_t** thread_smaj_nybble_bufs;
10270
10271 uint32_t sample_batch_size;
10272
10273 uintptr_t* smaj_writebufs[2];
10274 } PhylipTransposeCtx;
10275
10276 THREAD_FUNC_DECL PhylipTransposeWriteThread(void* raw_arg) {
10277 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
10278 const uintptr_t tidx = arg->tidx;
10279 PhylipTransposeCtx* ctx = S_CAST(PhylipTransposeCtx*, arg->sharedp->context);
10280
10281 const uint32_t variant_ct = ctx->variant_ct;
10282 const uintptr_t variant_batch_ct = DivUp(variant_ct, kPglNybbleTransposeBatch);
10283 const uintptr_t write_word_stride = RoundUpPow2(variant_ct, kCacheline) / kBytesPerWord;
10284 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
10285 const uintptr_t variant_batch_idx_start = (S_CAST(uint64_t, tidx) * variant_batch_ct) / calc_thread_ct;
10286 VecW* vecaligned_buf = ctx->thread_vecaligned_bufs[tidx];
10287 uintptr_t* smaj_nybble_buf = ctx->thread_smaj_nybble_bufs[tidx];
10288 uintptr_t variant_batch_idx_full_end = ((S_CAST(uint64_t, tidx) + 1) * variant_batch_ct) / calc_thread_ct;
10289 uint32_t variant_idx_end;
10290 if (tidx + 1 < calc_thread_ct) {
10291 variant_idx_end = variant_batch_idx_full_end * kPglNybbleTransposeBatch;
10292 } else {
10293 variant_idx_end = variant_ct;
10294 if (variant_ct % kPglNybbleTransposeBatch) {
10295 --variant_batch_idx_full_end;
10296 }
10297 }
10298 const uint32_t sample_ct = ctx->write_sample_ct;
10299 const uintptr_t sample_ctaw4 = NybbleCtToAlignedWordCt(sample_ct);
10300 const uintptr_t* vmaj_readbuf = ctx->vmaj_readbuf;
10301 uint32_t sample_widx = 0;
10302 uint32_t parity = 0;
10303 do {
10304 const uint32_t sample_batch_size = ctx->sample_batch_size;
10305 const uintptr_t* vmaj_readbuf_iter = &(vmaj_readbuf[variant_batch_idx_start * kPglNybbleTransposeBatch * sample_ctaw4 + sample_widx]);
10306 uintptr_t* smaj_writebuf_start = &(ctx->smaj_writebufs[parity][variant_batch_idx_start * kPglNybbleTransposeWords * 2]);
10307 uintptr_t* smaj_writebuf_iter = smaj_writebuf_start;
10308 uint32_t variant_batch_size = kPglNybbleTransposeBatch;
10309 for (uintptr_t variant_batch_idx = variant_batch_idx_start; ; ++variant_batch_idx) {
10310 if (variant_batch_idx >= variant_batch_idx_full_end) {
10311 if (variant_batch_idx * kPglNybbleTransposeBatch >= variant_idx_end) {
10312 break;
10313 }
10314 variant_batch_size = variant_idx_end - variant_batch_idx * kPglNybbleTransposeBatch;
10315 }
10316 TransposeNybbleblock(vmaj_readbuf_iter, sample_ctaw4, kPglNybbleTransposeWords, variant_batch_size, sample_batch_size, smaj_nybble_buf, vecaligned_buf);
10317 const uintptr_t* nybble_read_iter = smaj_nybble_buf;
10318 uintptr_t* ascii_write_iter = smaj_writebuf_iter;
10319 for (uint32_t uii = 0; uii != sample_batch_size; ++uii) {
10320 NybblesToIupac(nybble_read_iter, variant_batch_size, ascii_write_iter);
10321 nybble_read_iter = &(nybble_read_iter[kPglNybbleTransposeWords]);
10322 ascii_write_iter = &(ascii_write_iter[write_word_stride]);
10323 }
10324 smaj_writebuf_iter = &(smaj_writebuf_iter[kPglNybbleTransposeWords * 2]);
10325 vmaj_readbuf_iter = &(vmaj_readbuf_iter[variant_batch_size * sample_ctaw4]);
10326 }
10327 parity = 1 - parity;
10328 sample_widx += sample_batch_size / kBitsPerWordD4;
10329 } while (!THREAD_BLOCK_FINISH(arg));
10330 THREAD_RETURN;
10331 }
10332
10333 static_assert(kTextbufSize >= kMaxMediumLine + 2 * kMaxIdSlen + 385, "ExportPhylip() used-sites writer must be updated.");
10334 PglErr ExportPhylip(const uintptr_t* orig_sample_include, const SampleIdInfo* siip, const uintptr_t* sex_male_collapsed, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t export_phased, uint32_t export_used_sites, char input_missing_geno_char, uint32_t max_thread_ct, IdpasteFlags exportf_id_paste, char exportf_id_delim, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, char* outname, char* outname_end) {
10335 // Most similar to ExportPed().
10336 unsigned char* bigstack_mark = g_bigstack_base;
10337 FILE* outfile = nullptr;
10338 PglErr reterr = kPglRetSuccess;
10339 ThreadGroup read_tg;
10340 ThreadGroup transpose_tg;
10341 PreinitThreads(&read_tg);
10342 PreinitThreads(&transpose_tg);
10343 PhylipReadCtx read_ctx;
10344 PhylipTransposeCtx transpose_ctx;
10345 {
10346 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
10347 // 1. Fill genovec_to_nybble_tables, and perform initial validation if
10348 // applicable.
10349 const unsigned char acgtn_to_nybble[5] = {1, 2, 4, 8, 15};
10350 if (export_phased) {
10351 // Verify all data is diploid. In main loops, we also verify that all
10352 // data is phased.
10353 const uint32_t males_exist = !AllWordsAreZero(sex_male_collapsed, sample_ctl);
10354 if (unlikely((cip->haploid_mask[0] & 1) ||
10355 (males_exist && XymtIsNonempty(variant_include, cip, kChrOffsetX)) ||
10356 XymtIsNonempty(variant_include, cip, kChrOffsetY) ||
10357 XymtIsNonempty(variant_include, cip, kChrOffsetMT))) {
10358 logerrputs("Error: --export phylip-phased can only be used with all-diploid data.\n");
10359 goto ExportPhylip_ret_INCONSISTENT_INPUT;
10360 }
10361 uint32_t* genovec_to_nybblepair_iter;
10362 if (unlikely(bigstack_alloc_u32(21 * (kLookup256x1bx4Size / sizeof(int32_t)), &genovec_to_nybblepair_iter))) {
10363 goto ExportPhylip_ret_NOMEM;
10364 }
10365 for (uint32_t high_acgtn = 0; high_acgtn != 5; ++high_acgtn) {
10366 const uint32_t high_nybble = acgtn_to_nybble[high_acgtn];
10367 for (uint32_t low_acgtn = 0; low_acgtn != 5; ++low_acgtn) {
10368 const uint32_t table_idx = high_acgtn * 5 + low_acgtn;
10369 if ((low_acgtn == high_acgtn) && (low_acgtn != 4)) {
10370 read_ctx.genovec_to_nybble_tables[table_idx] = nullptr;
10371 continue;
10372 }
10373 const uint32_t low_nybble = acgtn_to_nybble[low_acgtn];
10374 genovec_to_nybblepair_iter[0] = low_nybble * 17;
10375 genovec_to_nybblepair_iter[1] = low_nybble | (high_nybble << 4);
10376 genovec_to_nybblepair_iter[2] = high_nybble * 17;
10377 genovec_to_nybblepair_iter[3] = 255;
10378 InitLookup256x1bx4(genovec_to_nybblepair_iter);
10379 read_ctx.genovec_to_nybble_tables[table_idx] = genovec_to_nybblepair_iter;
10380 genovec_to_nybblepair_iter = &(genovec_to_nybblepair_iter[kLookup256x1bx4Size / sizeof(int32_t)]);
10381 }
10382 }
10383 } else {
10384 #ifdef USE_SHUFFLE8
10385 // defensive
10386 for (uint32_t table_idx = 0; table_idx != 25; ++table_idx) {
10387 read_ctx.genovec_to_nybble_tables[table_idx] = nullptr;
10388 }
10389 #else
10390 uint16_t* genovec_to_nybble_iter;
10391 if (unlikely(bigstack_alloc_u16(21 * 256, &genovec_to_nybble_iter))) {
10392 goto ExportPhylip_ret_NOMEM;
10393 }
10394 for (uint32_t low_acgtn = 0; low_acgtn != 5; ++low_acgtn) {
10395 const uint32_t low_nybble = acgtn_to_nybble[low_acgtn];
10396 for (uint32_t high_acgtn = 0; high_acgtn != 5; ++high_acgtn) {
10397 const uint32_t table_idx = high_acgtn * 5 + low_acgtn;
10398 if ((low_acgtn == high_acgtn) && (low_acgtn != 4)) {
10399 read_ctx.genovec_to_nybble_tables[table_idx] = nullptr;
10400 continue;
10401 }
10402 const uint32_t high_nybble = acgtn_to_nybble[high_acgtn];
10403 InitLookup256x05bx4(low_nybble, low_nybble | high_nybble, high_nybble, 15, genovec_to_nybble_iter);
10404 read_ctx.genovec_to_nybble_tables[table_idx] = genovec_to_nybble_iter;
10405 genovec_to_nybble_iter = &(genovec_to_nybble_iter[256]);
10406 }
10407 }
10408 #endif
10409 }
10410 memset(read_ctx.allele_nybble_table, 0, 256);
10411 read_ctx.allele_nybble_table[S_CAST(unsigned char, 'A')] = 1;
10412 read_ctx.allele_nybble_table[S_CAST(unsigned char, 'a')] = 1;
10413 read_ctx.allele_nybble_table[S_CAST(unsigned char, 'C')] = 2;
10414 read_ctx.allele_nybble_table[S_CAST(unsigned char, 'c')] = 2;
10415 read_ctx.allele_nybble_table[S_CAST(unsigned char, 'G')] = 4;
10416 read_ctx.allele_nybble_table[S_CAST(unsigned char, 'g')] = 4;
10417 read_ctx.allele_nybble_table[S_CAST(unsigned char, 'T')] = 8;
10418 read_ctx.allele_nybble_table[S_CAST(unsigned char, 't')] = 8;
10419 read_ctx.allele_nybble_table[S_CAST(unsigned char, 'N')] = 15;
10420 read_ctx.allele_nybble_table[S_CAST(unsigned char, 'n')] = 15;
10421 read_ctx.allele_nybble_table[S_CAST(unsigned char, '.')] = 15;
10422 read_ctx.allele_nybble_table[S_CAST(unsigned char, input_missing_geno_char)] = 15;
10423 read_ctx.write_sample_nm_cts = nullptr;
10424 if (export_used_sites) {
10425 if (unlikely(bigstack_calloc_u32(variant_ct, &read_ctx.write_sample_nm_cts))) {
10426 goto ExportPhylip_ret_NOMEM;
10427 }
10428 }
10429
10430 char* exported_sample_ids;
10431 uintptr_t max_exported_sample_id_blen;
10432 if (unlikely(ExportIdpaste(orig_sample_include, siip, export_phased? "phylip-phased" : "phylip", nullptr, sample_ct, exportf_id_paste, exportf_id_delim, &max_exported_sample_id_blen, &exported_sample_ids))) {
10433 goto ExportPhylip_ret_NOMEM;
10434 }
10435 snprintf(outname_end, kMaxOutfnameExtBlen, ".phy");
10436 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
10437 goto ExportPhylip_ret_OPEN_FAIL;
10438 }
10439 // yes, it's trivial to allocate this on bigstack instead
10440 char* textbuf = g_textbuf;
10441 char* textbuf_line_start;
10442 char* write_id_stop;
10443 {
10444 char* write_iter = u32toa_x(sample_ct << export_phased, ' ', textbuf);
10445 write_iter = u32toa(variant_ct, write_iter);
10446 if (unlikely(fwrite_checked(textbuf, write_iter - textbuf, outfile))) {
10447 goto ExportPhylip_ret_WRITE_FAIL;
10448 }
10449 textbuf_line_start = textbuf;
10450 AppendBinaryEoln(&textbuf_line_start);
10451 // vcf2phylip.py pads second column to start after <max ID length>+3
10452 // characters. max_exported_sample_id_blen can be greater than
10453 // <max ID length>+1, so we need to determine true max ID length here.
10454 uint32_t max_id_slen = 0;
10455 const char* exported_sample_ids_iter = exported_sample_ids;
10456 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
10457 const uint32_t cur_id_slen = strlen(exported_sample_ids_iter);
10458 if (cur_id_slen > max_id_slen) {
10459 max_id_slen = cur_id_slen;
10460 }
10461 exported_sample_ids_iter = &(exported_sample_ids_iter[max_exported_sample_id_blen]);
10462 }
10463 // add 2 for export_phased, since we append _A and _B to the IDs
10464 write_id_stop = &(textbuf_line_start[max_id_slen + 2 * export_phased + 3]);
10465 }
10466
10467 const char id_delim = exportf_id_delim? exportf_id_delim : '_';
10468
10469 // * Read phase: main thread reads raw bytes with MultireadNonempty(),
10470 // while other thread(s) decode to 4-bit IUPAC
10471 // * Write phase: most threads transpose and then expand to ASCII, main
10472 // thread flushes ASCII IUPAC codes (and adds the tiny amount of other
10473 // text we need).
10474 const uint32_t max_allele_ct = pgfip->max_allele_ct;
10475 const uint32_t mhc_needed = (max_allele_ct > 2);
10476
10477 // todo: check when this saturates for each phase.
10478 uint32_t calc_thread_ct = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
10479 STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
10480 read_ctx.phasepresents = nullptr;
10481 read_ctx.phaseinfos = nullptr;
10482 read_ctx.thread_read_mhc = nullptr;
10483 uint32_t read_block_size;
10484 if (unlikely(PgenMtLoadInit(variant_include, sample_ct, variant_ct, bigstack_left() / 4, pgr_alloc_cacheline_ct, 0, 0, 0, pgfip, &calc_thread_ct, &read_ctx.genovecs, mhc_needed? (&read_ctx.thread_read_mhc) : nullptr, export_phased? (&read_ctx.phasepresents) : nullptr, export_phased? (&read_ctx.phaseinfos) : nullptr, nullptr, nullptr, nullptr, nullptr, &read_block_size, nullptr, main_loadbufs, &read_ctx.pgr_ptrs, &read_ctx.variant_uidx_starts))) {
10485 goto ExportPhylip_ret_NOMEM;
10486 }
10487 if (unlikely(SetThreadCt(calc_thread_ct, &read_tg))) {
10488 goto ExportPhylip_ret_NOMEM;
10489 }
10490 read_ctx.variant_include = variant_include;
10491 read_ctx.allele_idx_offsets = allele_idx_offsets;
10492 read_ctx.allele_storage = allele_storage;
10493 read_ctx.err_info = (~0LLU) << 32;
10494 if (export_phased) {
10495 SetThreadFuncAndData(PhylipPhasedReadThread, &read_ctx, &read_tg);
10496 } else {
10497 SetThreadFuncAndData(PhylipReadThread, &read_ctx, &read_tg);
10498 }
10499
10500 const uintptr_t variant_write_cacheline_ct = DivUp(variant_ct, kCacheline);
10501 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
10502 uintptr_t* sample_include;
10503 uint32_t* sample_include_cumulative_popcounts;
10504 if (unlikely(SetThreadCt(calc_thread_ct, &transpose_tg) ||
10505 bigstack_alloc_w(raw_sample_ctl, &sample_include) ||
10506 bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) ||
10507 bigstack_alloc_vp(calc_thread_ct, &transpose_ctx.thread_vecaligned_bufs) ||
10508 bigstack_alloc_wp(calc_thread_ct, &transpose_ctx.thread_smaj_nybble_bufs))) {
10509 goto ExportPhylip_ret_NOMEM;
10510 }
10511 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
10512 // PgenLoadMtInit() call succeeded with just 1/4 of workspace, so these
10513 // can't fail
10514 transpose_ctx.thread_vecaligned_bufs[tidx] = S_CAST(VecW*, bigstack_alloc_raw(kPglNybbleTransposeBufbytes));
10515 transpose_ctx.thread_smaj_nybble_bufs[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(kPglNybbleTransposeBufbytes));
10516 }
10517 // each of the two transpose-result buffers should use <= 1/6 of the
10518 // remaining workspace. (this is more than for ExportPed since
10519 // transpose-result buffers are 4x as large, while vmaj_readbuf is only
10520 // twice as large.)
10521 const uintptr_t smaj_writebuf_cachelines_avail = bigstack_left() / (kCacheline * 6);
10522 uint32_t write_sample_batch_size = kPglNybbleTransposeBatch;
10523 if (variant_write_cacheline_ct * kPglNybbleTransposeBatch > smaj_writebuf_cachelines_avail) {
10524 // Until the final iteration, TransposeNybbleblock must transpose at
10525 // least a word's worth of nybbles per variant at a time.
10526 write_sample_batch_size = RoundDownPow2(smaj_writebuf_cachelines_avail / variant_write_cacheline_ct, kBitsPerWordD4);
10527 if (unlikely(!write_sample_batch_size)) {
10528 goto ExportPhylip_ret_NOMEM;
10529 }
10530 }
10531 transpose_ctx.smaj_writebufs[0] = S_CAST(uintptr_t*, bigstack_alloc_raw(variant_write_cacheline_ct * kCacheline * write_sample_batch_size));
10532 transpose_ctx.smaj_writebufs[1] = S_CAST(uintptr_t*, bigstack_alloc_raw(variant_write_cacheline_ct * kCacheline * write_sample_batch_size));
10533
10534 const uintptr_t readbuf_vecs_avail = (bigstack_left() / kCacheline) * kVecsPerCacheline;
10535 if (unlikely(readbuf_vecs_avail < variant_ct)) {
10536 goto ExportPhylip_ret_NOMEM;
10537 }
10538 uintptr_t read_sample_ctv4 = readbuf_vecs_avail / variant_ct;
10539 uint32_t read_sample_ct;
10540 if (read_sample_ctv4 >= NybbleCtToVecCt(sample_ct)) {
10541 read_sample_ct = sample_ct;
10542 } else {
10543 read_sample_ct = read_sample_ctv4 * kNybblesPerVec;
10544 }
10545 uintptr_t read_sample_ctaw4 = NybbleCtToAlignedWordCt(read_sample_ct);
10546 uintptr_t* vmaj_readbuf = S_CAST(uintptr_t*, bigstack_alloc_raw_rd(variant_ct * read_sample_ctaw4 * kBytesPerWord));
10547 read_ctx.vmaj_readbuf = vmaj_readbuf;
10548 transpose_ctx.variant_include = variant_include;
10549 transpose_ctx.variant_ct = variant_ct;
10550 transpose_ctx.vmaj_readbuf = vmaj_readbuf;
10551 SetThreadFuncAndData(PhylipTransposeWriteThread, &transpose_ctx, &transpose_tg);
10552
10553 uint32_t sample_uidx_start = AdvTo1Bit(orig_sample_include, 0);
10554 const uintptr_t variant_ctaclw8 = variant_write_cacheline_ct * kWordsPerCacheline;
10555 const uint32_t pass_ct = 1 + (sample_ct - 1) / read_sample_ct;
10556 for (uint32_t pass_idx = 0; pass_idx != pass_ct; ++pass_idx) {
10557 memcpy(sample_include, orig_sample_include, raw_sample_ctl * sizeof(intptr_t));
10558 if (sample_uidx_start) {
10559 ClearBitsNz(0, sample_uidx_start, sample_include);
10560 }
10561 const uint32_t read_sample_idx_offset = pass_idx * read_sample_ct;
10562 uint32_t sample_uidx_end;
10563 if (pass_idx + 1 == pass_ct) {
10564 read_sample_ct = sample_ct - read_sample_idx_offset;
10565 read_sample_ctaw4 = NybbleCtToAlignedWordCt(read_sample_ct);
10566 sample_uidx_end = raw_sample_ct;
10567 } else {
10568 sample_uidx_end = FindNth1BitFrom(orig_sample_include, sample_uidx_start + 1, read_sample_ct);
10569 ClearBitsNz(sample_uidx_end, raw_sample_ct, sample_include);
10570 }
10571 FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts);
10572 read_ctx.sample_include = sample_include;
10573 read_ctx.sample_include_cumulative_popcounts = sample_include_cumulative_popcounts;
10574 read_ctx.sample_ct = read_sample_ct;
10575 const uint32_t write_sample_ct = read_sample_ct << export_phased;
10576 transpose_ctx.write_sample_ct = write_sample_ct;
10577 if (pass_idx) {
10578 pgfip->block_base = main_loadbufs[0];
10579 // er, don't need SetBaseAndOffset0?
10580 PgrSetBaseAndOffset0(main_loadbufs[0], calc_thread_ct, read_ctx.pgr_ptrs);
10581 }
10582 uint32_t parity = 0;
10583 uint32_t read_block_idx = 0;
10584 ReinitThreads(&read_tg);
10585 uint32_t pct = 0;
10586 uint32_t next_print_idx = variant_ct / 100;
10587 putc_unlocked('\r', stdout);
10588 printf("--export phylip%s pass %u/%u: loading... 0%%", export_phased? "-phased" : "", pass_idx + 1, pass_ct);
10589 fflush(stdout);
10590 for (uint32_t variant_idx = 0; ; ) {
10591 const uint32_t cur_block_write_ct = MultireadNonempty(variant_include, &read_tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr);
10592 if (unlikely(reterr)) {
10593 goto ExportPhylip_ret_PGR_FAIL;
10594 }
10595 if (variant_idx) {
10596 JoinThreads(&read_tg);
10597 reterr = S_CAST(PglErr, read_ctx.err_info);
10598 if (unlikely(reterr)) {
10599 const uint32_t variant_uidx = read_ctx.err_info >> 32;
10600 if (reterr == kPglRetInternalUse1) {
10601 logprintfww("\nError: --export phylip-phased: 0-based variant #%u is not fully phased.\n", variant_uidx);
10602 reterr = kPglRetInconsistentInput;
10603 } else if (reterr == kPglRetInconsistentInput) {
10604 logprintfww("\nError: --export phylip%s: 0-based variant #%u has allele code(s) outside {A,C,G,T,missing}. (Did you forget --snps-only?)\n", export_phased? "-phased" : "", variant_uidx);
10605 } else {
10606 PgenErrPrintNV(reterr, variant_uidx);
10607 }
10608 goto ExportPhylip_ret_1;
10609 }
10610 }
10611 if (!IsLastBlock(&read_tg)) {
10612 read_ctx.cur_block_write_ct = cur_block_write_ct;
10613 ComputeUidxStartPartition(variant_include, cur_block_write_ct, calc_thread_ct, read_block_idx * read_block_size, read_ctx.variant_uidx_starts);
10614 PgrCopyBaseAndOffset(pgfip, calc_thread_ct, read_ctx.pgr_ptrs);
10615 if (variant_idx + cur_block_write_ct == variant_ct) {
10616 DeclareLastThreadBlock(&read_tg);
10617 }
10618 if (unlikely(SpawnThreads(&read_tg))) {
10619 goto ExportPhylip_ret_THREAD_CREATE_FAIL;
10620 }
10621 }
10622 parity = 1 - parity;
10623 if (variant_idx == variant_ct) {
10624 break;
10625 }
10626 if (variant_idx >= next_print_idx) {
10627 if (pct > 10) {
10628 putc_unlocked('\b', stdout);
10629 }
10630 pct = (variant_idx * 100LLU) / variant_ct;
10631 printf("\b\b%u%%", pct++);
10632 fflush(stdout);
10633 next_print_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
10634 }
10635 ++read_block_idx;
10636 variant_idx += cur_block_write_ct;
10637 pgfip->block_base = main_loadbufs[parity];
10638 }
10639 // 2. Transpose and write.
10640 ReinitThreads(&transpose_tg);
10641 transpose_ctx.sample_batch_size = write_sample_batch_size;
10642 parity = 0;
10643 if (pct > 10) {
10644 fputs("\b \b", stdout);
10645 }
10646 fputs("\b\b\b\b\b\b\b\b\b\b\b\b\bwriting... 0%", stdout);
10647 fflush(stdout);
10648 pct = 0;
10649 uint32_t flush_write_sample_idx = 0;
10650 next_print_idx = write_sample_ct / 100;
10651 for (uint32_t flush_write_sample_idx_end = 0; ; ) {
10652 if (!IsLastBlock(&transpose_tg)) {
10653 if (flush_write_sample_idx_end + write_sample_batch_size >= write_sample_ct) {
10654 DeclareLastThreadBlock(&transpose_tg);
10655 transpose_ctx.sample_batch_size = write_sample_ct - flush_write_sample_idx_end;
10656 }
10657 if (unlikely(SpawnThreads(&transpose_tg))) {
10658 goto ExportPhylip_ret_THREAD_CREATE_FAIL;
10659 }
10660 }
10661 if (flush_write_sample_idx_end) {
10662 const uintptr_t* ascii_iupac_iter = transpose_ctx.smaj_writebufs[1 - parity];
10663 for (; flush_write_sample_idx != flush_write_sample_idx_end; ++flush_write_sample_idx) {
10664 const uint32_t orig_sample_idx = read_sample_idx_offset + (flush_write_sample_idx >> export_phased);
10665 char* write_iter = strcpya(textbuf_line_start, &(exported_sample_ids[orig_sample_idx * max_exported_sample_id_blen]));
10666 if (export_phased) {
10667 *write_iter++ = id_delim;
10668 *write_iter++ = 'A' + (flush_write_sample_idx % 2);
10669 }
10670 memset(write_iter, ' ', write_id_stop - write_iter);
10671 if (unlikely(fwrite_checked(textbuf, write_id_stop - textbuf, outfile) ||
10672 fwrite_checked(ascii_iupac_iter, variant_ct, outfile))) {
10673 goto ExportPhylip_ret_WRITE_FAIL;
10674 }
10675 ascii_iupac_iter = &(ascii_iupac_iter[variant_ctaclw8]);
10676 }
10677 if (flush_write_sample_idx_end == write_sample_ct) {
10678 break;
10679 }
10680 if (flush_write_sample_idx_end >= next_print_idx) {
10681 if (pct > 10) {
10682 putc_unlocked('\b', stdout);
10683 }
10684 pct = (flush_write_sample_idx_end * 100LLU) / write_sample_ct;
10685 printf("\b\b%u%%", pct++);
10686 fflush(stdout);
10687 next_print_idx = (pct * S_CAST(uint64_t, write_sample_ct)) / 100;
10688 }
10689 }
10690 JoinThreads(&transpose_tg);
10691 parity = 1 - parity;
10692 flush_write_sample_idx_end += write_sample_batch_size;
10693 if (flush_write_sample_idx_end > write_sample_ct) {
10694 flush_write_sample_idx_end = write_sample_ct;
10695 }
10696 }
10697 sample_uidx_start = sample_uidx_end;
10698 if (pct > 10) {
10699 fputs("\b \b", stdout);
10700 }
10701 }
10702
10703 #ifdef _WIN32
10704 if (unlikely((putc_unlocked('\r', outfile) == EOF))) {
10705 goto ExportPhylip_ret_WRITE_FAIL;
10706 }
10707 #endif
10708 if (unlikely((putc_unlocked('\n', outfile) == EOF) ||
10709 fclose_null(&outfile))) {
10710 goto ExportPhylip_ret_WRITE_FAIL;
10711 }
10712 fputs("\b\bdone.\n", stdout);
10713 logprintfww("--export phylip%s: %s written.\n", export_phased? "-phased" : "", outname);
10714
10715 if (export_used_sites) {
10716 snprintf(outname_end, kMaxOutfnameExtBlen, ".used_sites.tsv");
10717 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
10718 goto ExportPhylip_ret_OPEN_FAIL;
10719 }
10720 const uint32_t* write_sample_nm_cts = read_ctx.write_sample_nm_cts;
10721 char* writebuf_flush = &(textbuf[kMaxMediumLine]);
10722 char* write_iter = strcpya_k(textbuf, "#CHROM\tPOS\tNUM_SAMPLES" EOLN_STR);
10723 uint32_t chr_fo_idx = UINT32_MAX;
10724 uint32_t chr_end = 0;
10725 uint32_t chr_blen = 0;
10726 uint32_t min_ct = UINT32_MAX;
10727 char* chr_buf = &(writebuf_flush[kMaxIdSlen + 384]);
10728 uintptr_t variant_uidx_base = 0;
10729 uintptr_t variant_include_bits = variant_include[0];
10730 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
10731 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
10732 if (variant_uidx >= chr_end) {
10733 do {
10734 ++chr_fo_idx;
10735 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
10736 } while (variant_uidx >= chr_end);
10737 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
10738 char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
10739 *chr_name_end++ = '\t';
10740 chr_blen = chr_name_end - chr_buf;
10741 }
10742 write_iter = memcpya(write_iter, chr_buf, chr_blen);
10743 write_iter = u32toa_x(variant_bps[variant_uidx], '\t', write_iter);
10744 const uint32_t cur_ct = write_sample_nm_cts[variant_idx];
10745 if (cur_ct < min_ct) {
10746 min_ct = cur_ct;
10747 }
10748 write_iter = u32toa(cur_ct, write_iter);
10749 AppendBinaryEoln(&write_iter);
10750 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
10751 goto ExportPhylip_ret_WRITE_FAIL;
10752 }
10753 }
10754 if (unlikely(fclose_flush_null(writebuf_flush, write_iter, &outfile))) {
10755 goto ExportPhylip_ret_WRITE_FAIL;
10756 }
10757 logprintfww("--export phylip%s: %s written.\n", export_phased? "-phased" : "", outname);
10758 logprintf("Minimum non-N sample count across loci: %u/%u\n", min_ct, sample_ct << export_phased);
10759 }
10760 }
10761 while (0) {
10762 ExportPhylip_ret_NOMEM:
10763 reterr = kPglRetNomem;
10764 break;
10765 ExportPhylip_ret_OPEN_FAIL:
10766 reterr = kPglRetOpenFail;
10767 break;
10768 ExportPhylip_ret_PGR_FAIL:
10769 PgenErrPrintN(reterr);
10770 break;
10771 ExportPhylip_ret_WRITE_FAIL:
10772 reterr = kPglRetWriteFail;
10773 break;
10774 ExportPhylip_ret_INCONSISTENT_INPUT:
10775 reterr = kPglRetInconsistentInput;
10776 break;
10777 ExportPhylip_ret_THREAD_CREATE_FAIL:
10778 reterr = kPglRetThreadCreateFail;
10779 break;
10780 }
10781 ExportPhylip_ret_1:
10782 CleanupThreads(&transpose_tg);
10783 CleanupThreads(&read_tg);
10784 fclose_cond(outfile);
10785 pgfip->block_base = nullptr;
10786 BigstackReset(bigstack_mark);
10787 return reterr;
10788 }
10789
10790 PglErr Exportf(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 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 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 ExportfInfo* eip, const char* legacy_output_missing_pheno, const uint32_t* contig_lens, 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_variant_id_slen, uint32_t max_allele_slen, uint32_t max_filter_slen, uint32_t info_reload_slen, char input_missing_geno_char, char output_missing_geno_char, char legacy_output_missing_geno_char, uint32_t max_thread_ct, MakePlink2Flags make_plink2_flags, uintptr_t pgr_alloc_cacheline_ct, char* xheader, PgenFileInfo* pgfip, PgenReader* simple_pgrp, char* outname, char* outname_end) {
10791 unsigned char* bigstack_mark = g_bigstack_base;
10792 unsigned char* bigstack_end_mark = g_bigstack_end;
10793 PglErr reterr = kPglRetSuccess;
10794 {
10795 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
10796 const uint32_t sample_ctaw = BitCtToAlignedWordCt(sample_ct);
10797 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
10798 uint32_t* sample_include_cumulative_popcounts;
10799 uintptr_t* sex_male_collapsed;
10800 if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) ||
10801 bigstack_alloc_w(sample_ctaw, &sex_male_collapsed))) {
10802 goto Exportf_ret_NOMEM;
10803 }
10804 FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts);
10805 PgrSampleSubsetIndex pssi;
10806 PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi);
10807 CopyBitarrSubset(sex_male, sample_include, sample_ct, sex_male_collapsed);
10808 ZeroTrailingWords(sample_ctl, sex_male_collapsed);
10809 // possible todo: remove one of {sex_female_collapsed,
10810 // sex_nonfemale_collapsed}
10811 // unfortunately, the awkward sex_nonfemale is a slightly more convenient
10812 // representation (sex_nonfemale_cumulative_popcounts for chrY).
10813 uintptr_t* sex_female_collapsed = nullptr;
10814 ExportfFlags flags = eip->flags;
10815 if (flags & (kfExportfBcf | kfExportfBgen12 | kfExportfBgen13)) {
10816 if (unlikely(bigstack_alloc_w(sample_ctl, &sex_female_collapsed))) {
10817 goto Exportf_ret_NOMEM;
10818 }
10819 CopyBitarrSubset(sex_nm, sample_include, sample_ct, sex_female_collapsed);
10820 BitvecInvmask(sex_male_collapsed, sample_ctl, sex_female_collapsed);
10821 }
10822 uintptr_t* sex_nonfemale_collapsed = nullptr;
10823 if (flags & (kfExportfOxGen | kfExportfBgen11)) {
10824 uintptr_t* sex_nonfemale_tmp;
10825 if (unlikely(bigstack_alloc_w(sample_ctl, &sex_nonfemale_collapsed) ||
10826 bigstack_alloc_w(raw_sample_ctl, &sex_nonfemale_tmp))) {
10827 goto Exportf_ret_NOMEM;
10828 }
10829 AlignedBitarrOrnotCopy(sex_male, sex_nm, raw_sample_ct, sex_nonfemale_tmp);
10830 CopyBitarrSubset(sex_nonfemale_tmp, sample_include, sample_ct, sex_nonfemale_collapsed);
10831 BigstackReset(sex_nonfemale_tmp);
10832 }
10833 uint32_t* sample_missing_geno_cts = nullptr;
10834 if (flags & (kfExportfOxGen | kfExportfHaps | kfExportfHapsLegend | kfExportfBgen11 | kfExportfBgen12 | kfExportfBgen13)) {
10835 if (unlikely(bigstack_alloc_u32(sample_ct, &sample_missing_geno_cts))) {
10836 goto Exportf_ret_NOMEM;
10837 }
10838 }
10839 if (flags & (kfExportf01 | kfExportf12)) {
10840 const uint32_t is_12 = (flags / kfExportf12) & 1;
10841 if (unlikely((flags & (kfExportfTped | kfExportfPed | kfExportfCompound)) && ((legacy_output_missing_geno_char == '1') || (ctou32(legacy_output_missing_geno_char) == '0' + (2 * is_12))))) {
10842 // Could move enforcement of this to initial command-line parsing if it
10843 // turns out to be a common mistake.
10844 logerrputs("Error: --export '01'/'12' conflicts with the --output-missing-genotype setting.\n");
10845 goto Exportf_ret_INVALID_CMDLINE;
10846 }
10847 // yes, this could be time- and memory-optimized...
10848 uintptr_t global_allele_ct = raw_variant_ct * 2;
10849 if (allele_idx_offsets) {
10850 global_allele_ct = allele_idx_offsets[raw_variant_ct];
10851 }
10852 const char** subst_allele_storage;
10853 if (unlikely(bigstack_alloc_kcp(global_allele_ct, &subst_allele_storage))) {
10854 goto Exportf_ret_NOMEM;
10855 }
10856 // '0' or '1'
10857 const char* new_ref_allele = &(g_one_char_strs[96 + 2 * is_12]);
10858
10859 const char* new_alt_allele = &(new_ref_allele[2]);
10860 if (!allele_idx_offsets) {
10861 const char** subst_allele_storage_iter = subst_allele_storage;
10862 for (uint32_t variant_uidx = 0; variant_uidx != raw_variant_ct; ++variant_uidx) {
10863 *subst_allele_storage_iter++ = new_ref_allele;
10864 *subst_allele_storage_iter++ = new_alt_allele;
10865 }
10866 } else {
10867 uintptr_t variant_uidx_base = 0;
10868 uintptr_t cur_bits = variant_include[0];
10869 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
10870 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
10871 const uintptr_t allele_idx_offset_base = allele_idx_offsets[variant_uidx];
10872 const uintptr_t allele_idx_offset_end = allele_idx_offsets[variant_uidx + 1];
10873 if (allele_idx_offset_end != allele_idx_offset_base + 2) {
10874 // Could permit this with ALT2 being encoded as '2'/'3', ALT3 being
10875 // encoded as '3'/'4', etc. But let's not implement it
10876 // until/unless someone wants it.
10877 logerrprintf("Error: --export '01'/'12' cannot be used with multiallelic variants. (Contact\nus if you want ALT2 to be encoded as '%c', ALT3 to be encoded as '%c', etc.)\n", '2' + is_12, '3' + is_12);
10878 goto Exportf_ret_INCONSISTENT_INPUT;
10879 }
10880 subst_allele_storage[allele_idx_offset_base] = new_ref_allele;
10881 subst_allele_storage[allele_idx_offset_base + 1] = new_alt_allele;
10882 }
10883 }
10884 allele_storage = subst_allele_storage;
10885 }
10886 if (flags & (kfExportfTypemask - kfExportfIndMajorBed - kfExportfVcf - kfExportfBcf - kfExportfOxGen - kfExportfBgen11 - kfExportfBgen12 - kfExportfBgen13 - kfExportfHaps - kfExportfHapsLegend - kfExportfAv - kfExportfA - kfExportfAD - kfExportfTped - kfExportfPed - kfExportfPhylip - kfExportfPhylipPhased - kfExportfCompound)) {
10887 logerrputs("Error: Only VCF, BCF, oxford, bgen-1.x, haps, hapslegend, A, AD, Av, ped, tped,\ncompound-genotypes, phylip, phylip-phased, and ind-major-bed output have been\nimplemented so far.\n");
10888 reterr = kPglRetNotYetSupported;
10889 goto Exportf_ret_1;
10890 }
10891 const char exportf_delim = (flags & kfExportfSpaces)? ' ' : '\t';
10892 // Move this first, so we error out more quickly when any variants are
10893 // still multiallelic.
10894 if ((!(make_plink2_flags & kfMakeBim)) && (flags & kfExportfIndMajorBed)) {
10895 snprintf(outname_end, kMaxOutfnameExtBlen, ".bim");
10896 logprintfww5("Writing %s ... ", outname);
10897 fflush(stdout);
10898 reterr = WriteMapOrBim(outname, variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, nullptr, allele_permute, variant_cms, variant_ct, max_allele_slen, exportf_delim, output_missing_geno_char, 0, max_thread_ct);
10899 if (unlikely(reterr)) {
10900 goto Exportf_ret_1;
10901 }
10902 logputs("done.\n");
10903 }
10904
10905 const AlleleCode* export_allele = nullptr;
10906 const char** export_allele_missing = nullptr;
10907 uint32_t max_export_allele_slen = max_allele_slen;
10908 if ((flags & (kfExportfAv | kfExportfA | kfExportfAD)) && (allele_permute || eip->export_allele_fname)) {
10909 AlleleCode* new_export_allele;
10910 if (unlikely(bigstack_alloc_ac(raw_variant_ct, &new_export_allele))) {
10911 goto Exportf_ret_NOMEM;
10912 }
10913 if (allele_permute) {
10914 if (!allele_idx_offsets) {
10915 // possible todo: SIMD
10916 for (uint32_t variant_uidx = 0; variant_uidx != raw_variant_ct; ++variant_uidx) {
10917 new_export_allele[variant_uidx] = allele_permute[variant_uidx * 2];
10918 }
10919 } else {
10920 for (uint32_t variant_uidx = 0; variant_uidx != raw_variant_ct; ++variant_uidx) {
10921 new_export_allele[variant_uidx] = allele_permute[allele_idx_offsets[variant_uidx]];
10922 }
10923 }
10924 } else {
10925 memset(new_export_allele, 0, raw_variant_ct * sizeof(AlleleCode));
10926 }
10927 if (eip->export_allele_fname) {
10928 reterr = ExportAlleleLoad(eip->export_allele_fname, variant_include, variant_ids, allele_idx_offsets, allele_storage, raw_variant_ct, variant_ct, max_variant_id_slen, input_missing_geno_char, max_thread_ct, &max_export_allele_slen, new_export_allele, &export_allele_missing);
10929 if (unlikely(reterr)) {
10930 goto Exportf_ret_1;
10931 }
10932 }
10933 export_allele = new_export_allele;
10934 }
10935 if (flags & kfExportfAv) {
10936 // multiallelic ok
10937 snprintf(outname_end, kMaxOutfnameExtBlen, ".traw");
10938 reterr = Export012Vmaj(outname, sample_include, sample_include_cumulative_popcounts, piip->sii.sample_ids, variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, export_allele, export_allele_missing, variant_cms, sample_ct, piip->sii.max_sample_id_blen, variant_ct, max_export_allele_slen, exportf_delim, simple_pgrp);
10939 if (unlikely(reterr)) {
10940 goto Exportf_ret_1;
10941 }
10942 }
10943 if (flags & kfExportfIndMajorBed) {
10944 // multiallelic not ok, but already checked
10945 reterr = ExportIndMajorBed(sample_include, variant_include, allele_idx_offsets, allele_permute, raw_sample_ct, sample_ct, raw_variant_ct, variant_ct, max_thread_ct, pgr_alloc_cacheline_ct, pgfip, outname, outname_end);
10946 if (unlikely(reterr)) {
10947 goto Exportf_ret_1;
10948 }
10949 }
10950 if (flags & kfExportfOxGen) {
10951 // multiallelic really not ok
10952 reterr = ExportOxGen(sample_include, sample_include_cumulative_popcounts, sex_nonfemale_collapsed, variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, allele_permute, sample_ct, variant_ct, max_allele_slen, max_thread_ct, flags, simple_pgrp, outname, outname_end, sample_missing_geno_cts);
10953 if (unlikely(reterr)) {
10954 goto Exportf_ret_1;
10955 }
10956 }
10957 if (flags & (kfExportfHaps | kfExportfHapsLegend)) {
10958 // multiallelic not ok
10959 reterr = ExportOxHapslegend(sample_include, sample_include_cumulative_popcounts, sex_male_collapsed, variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, allele_permute, sample_ct, raw_variant_ct, variant_ct, max_allele_slen, max_thread_ct, flags, simple_pgrp, outname, outname_end);
10960 if (unlikely(reterr)) {
10961 goto Exportf_ret_1;
10962 }
10963 ZeroU32Arr(sample_ct, sample_missing_geno_cts);
10964 }
10965 const IdpasteFlags idpaste_flags = eip->idpaste_flags;
10966 const char id_delim = eip->id_delim;
10967 if (flags & kfExportfBgen11) {
10968 // multiallelic not ok
10969 assert(PopcountWords(sample_include, raw_sample_ctl) == sample_ct);
10970 snprintf(outname_end, kMaxOutfnameExtBlen, ".bgen");
10971 reterr = ExportBgen11(outname, sample_include, sample_include_cumulative_popcounts, sex_nonfemale_collapsed, variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, allele_permute, sample_ct, raw_variant_ct, variant_ct, max_allele_slen, max_thread_ct, flags, pgr_alloc_cacheline_ct, pgfip, sample_missing_geno_cts);
10972 if (unlikely(reterr)) {
10973 goto Exportf_ret_1;
10974 }
10975 } else if (flags & (kfExportfBgen12 | kfExportfBgen13)) {
10976 // multiallelic ok... in the future, anyway.
10977 snprintf(outname_end, kMaxOutfnameExtBlen, ".bgen");
10978 reterr = ExportBgen13(outname, sample_include, sample_include_cumulative_popcounts, &(piip->sii), sex_male_collapsed, sex_female_collapsed, variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, allele_permute, sample_ct, raw_variant_ct, variant_ct, max_allele_slen, max_thread_ct, flags, eip->bgen_bits, idpaste_flags, id_delim, pgr_alloc_cacheline_ct, pgfip, sample_missing_geno_cts);
10979 if (unlikely(reterr)) {
10980 goto Exportf_ret_1;
10981 }
10982 }
10983 if (flags & (kfExportfOxGen | kfExportfBgen11 | kfExportfBgen12 | kfExportfBgen13 | kfExportfHaps | kfExportfHapsLegend)) {
10984 snprintf(outname_end, kMaxOutfnameExtBlen, ".sample");
10985 uint32_t y_ct = 0;
10986 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
10987 if ((!IsI32Neg(y_code)) && IsSet(cip->chr_mask, y_code)) {
10988 y_ct = CountChrVariantsUnsafe(variant_include, cip, y_code);
10989 }
10990 assert(PopcountWords(sample_include, raw_sample_ctl) == sample_ct);
10991 if (flags & kfExportfSampleV2) {
10992 reterr = ExportOxSampleV2(outname, sample_include, piip, sample_missing_geno_cts, sex_nm, sex_male, pheno_cols, pheno_names, sample_ct, pheno_ct, max_pheno_name_blen, variant_ct, y_ct, idpaste_flags, id_delim);
10993 } else {
10994 reterr = ExportOxSample(outname, sample_include, piip->sii.sample_ids, sample_missing_geno_cts, sex_nm, sex_male, pheno_cols, pheno_names, sample_ct, piip->sii.max_sample_id_blen, pheno_ct, max_pheno_name_blen, variant_ct, y_ct);
10995 }
10996 if (unlikely(reterr)) {
10997 goto Exportf_ret_1;
10998 }
10999 }
11000 if (flags & kfExportfVcf) {
11001 // multiallelic ok
11002 reterr = ExportVcf(sample_include, sample_include_cumulative_popcounts, &(piip->sii), sex_male_collapsed, variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, allele_permute, pvar_qual_present, pvar_quals, pvar_filter_present, pvar_filter_npass, pvar_filter_storage, pvar_info_reload, contig_lens, xheader_blen, info_flags, sample_ct, raw_variant_ct, variant_ct, max_allele_slen, max_filter_slen, info_reload_slen, max_thread_ct, flags, eip->vcf_mode, idpaste_flags, id_delim, xheader, pgfip, simple_pgrp, outname, outname_end);
11003 if (unlikely(reterr)) {
11004 goto Exportf_ret_1;
11005 }
11006 }
11007 if (flags & kfExportfBcf) {
11008 reterr = ExportBcf(sample_include, sample_include_cumulative_popcounts, &(piip->sii), sex_male_collapsed, sex_female_collapsed, variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, allele_permute, pvar_qual_present, pvar_quals, pvar_filter_present, pvar_filter_npass, pvar_filter_storage, pvar_info_reload, contig_lens, xheader_blen, info_flags, sample_ct, raw_variant_ct, variant_ct, max_allele_slen, max_filter_slen, info_reload_slen, max_thread_ct, flags, eip->vcf_mode, idpaste_flags, id_delim, xheader, pgfip, simple_pgrp, outname, outname_end);
11009 if (unlikely(reterr)) {
11010 goto Exportf_ret_1;
11011 }
11012 }
11013
11014 if (flags & (kfExportfA | kfExportfAD)) {
11015 // multiallelic ok
11016 snprintf(outname_end, kMaxOutfnameExtBlen, ".raw");
11017 reterr = Export012Smaj(outname, sample_include, piip, sex_nm, sex_male, pheno_cols, variant_include, variant_ids, allele_idx_offsets, allele_storage, export_allele, export_allele_missing, legacy_output_missing_pheno, raw_sample_ct, sample_ct, pheno_ct, raw_variant_ct, variant_ct, max_export_allele_slen, (flags / kfExportfAD) & 1, (flags / kfExportfIncludeAlt) & 1, max_thread_ct, pgr_alloc_cacheline_ct, exportf_delim, pgfip);
11018 if (unlikely(reterr)) {
11019 goto Exportf_ret_1;
11020 }
11021 }
11022
11023 if (flags & kfExportfTped) {
11024 snprintf(outname_end, kMaxOutfnameExtBlen, ".tfam");
11025 logprintfww5("Writing %s ... ", outname);
11026 fflush(stdout);
11027 reterr = WriteFam(outname, sample_include, piip, sex_nm, sex_male, pheno_cols, nullptr, legacy_output_missing_pheno, sample_ct, pheno_ct, exportf_delim);
11028 if (unlikely(reterr)) {
11029 goto Exportf_ret_1;
11030 }
11031 logputs("done.\n");
11032
11033 snprintf(outname_end, kMaxOutfnameExtBlen, ".tped");
11034 reterr = ExportTped(outname, sample_include, sample_include_cumulative_popcounts, variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, variant_cms, sample_ct, variant_ct, max_allele_slen, exportf_delim, legacy_output_missing_geno_char, simple_pgrp);
11035 if (unlikely(reterr)) {
11036 goto Exportf_ret_1;
11037 }
11038 }
11039
11040 if (flags & (kfExportfPed | kfExportfCompound)) {
11041 snprintf(outname_end, kMaxOutfnameExtBlen, ".map");
11042 logprintfww5("Writing %s ... ", outname);
11043 fflush(stdout);
11044 reterr = WriteMapOrBim(outname, variant_include, cip, variant_bps, variant_ids, nullptr, nullptr, nullptr, nullptr, variant_cms, variant_ct, 0, exportf_delim, '\0', 0, max_thread_ct);
11045 if (unlikely(reterr)) {
11046 goto Exportf_ret_1;
11047 }
11048 logputs("done.\n");
11049
11050 snprintf(outname_end, kMaxOutfnameExtBlen, ".ped");
11051 reterr = ExportPed(outname, sample_include, piip, sex_nm, sex_male, pheno_cols, variant_include, allele_idx_offsets, allele_storage, legacy_output_missing_pheno, raw_sample_ct, sample_ct, pheno_ct, raw_variant_ct, variant_ct, max_allele_slen, (flags / kfExportfCompound) & 1, max_thread_ct, pgr_alloc_cacheline_ct, exportf_delim, legacy_output_missing_geno_char, pgfip);
11052 if (unlikely(reterr)) {
11053 goto Exportf_ret_1;
11054 }
11055 }
11056
11057 if (flags & (kfExportfPhylip | kfExportfPhylipPhased)) {
11058 reterr = ExportPhylip(sample_include, &(piip->sii), sex_male_collapsed, variant_include, cip, variant_bps, allele_idx_offsets, allele_storage, raw_sample_ct, sample_ct, raw_variant_ct, variant_ct, (flags / kfExportfPhylipPhased) & 1, (flags / kfExportfPhylipUsedSites) & 1, input_missing_geno_char, max_thread_ct, idpaste_flags, id_delim, pgr_alloc_cacheline_ct, pgfip, outname, outname_end);
11059 if (unlikely(reterr)) {
11060 goto Exportf_ret_1;
11061 }
11062 }
11063
11064 if ((!(make_plink2_flags & kfMakeFam)) && (flags & kfExportfIndMajorBed)) {
11065 snprintf(outname_end, kMaxOutfnameExtBlen, ".fam");
11066 logprintfww5("Writing %s ... ", outname);
11067 fflush(stdout);
11068 reterr = WriteFam(outname, sample_include, piip, sex_nm, sex_male, pheno_cols, nullptr, legacy_output_missing_pheno, sample_ct, pheno_ct, exportf_delim);
11069 if (unlikely(reterr)) {
11070 goto Exportf_ret_1;
11071 }
11072 logputs("done.\n");
11073 }
11074 }
11075 while (0) {
11076 Exportf_ret_NOMEM:
11077 reterr = kPglRetNomem;
11078 break;
11079 Exportf_ret_INVALID_CMDLINE:
11080 reterr = kPglRetInvalidCmdline;
11081 break;
11082 Exportf_ret_INCONSISTENT_INPUT:
11083 reterr = kPglRetInconsistentInput;
11084 break;
11085 }
11086 Exportf_ret_1:
11087 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
11088 return reterr;
11089 }
11090
11091 #ifdef __cplusplus
11092 } // namespace plink2
11093 #endif