Debian Codegraph @

plink2_import.cc

raw
1 // This file is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
2 // Christopher Chang.
3 //
4 // This program is free software: you can redistribute it and/or modify it
5 // under the terms of the GNU General Public License as published by the Free
6 // Software Foundation, either version 3 of the License, or (at your option)
7 // any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 // more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17
18 #include "include/pgenlib_write.h"
19 #include "plink2_compress_stream.h"
20 #include "plink2_import.h"
21 #include "plink2_import_legacy.h"
22 #include "plink2_psam.h"
23 #include "plink2_pvar.h"
24 #include "plink2_random.h"
25
26 #ifdef __cplusplus
27 namespace plink2 {
28 #endif
29
30 void InitPlink1Dosage(Plink1DosageInfo* plink1_dosage_info_ptr) {
31 plink1_dosage_info_ptr->flags = kfPlink1Dosage0;
32 STD_ARRAY_FILL0(plink1_dosage_info_ptr->skips);
33 plink1_dosage_info_ptr->chr_col_idx = UINT32_MAX;
34 plink1_dosage_info_ptr->pos_col_idx = UINT32_MAX;
35 plink1_dosage_info_ptr->id_delim = '\0';
36 }
37
38 void InitGenDummy(GenDummyInfo* gendummy_info_ptr) {
39 gendummy_info_ptr->flags = kfGenDummy0;
40 gendummy_info_ptr->pheno_ct = 1;
41 gendummy_info_ptr->geno_mfreq_ct = 0;
42 gendummy_info_ptr->geno_mfreqs = nullptr; // defensive
43 gendummy_info_ptr->pheno_mfreq = 0.0;
44 gendummy_info_ptr->phase_freq = 0.0;
45 gendummy_info_ptr->dosage_freq = 0.0;
46 }
47
48 void CleanupGenDummy(GenDummyInfo* gendummy_info_ptr) {
49 free_cond(gendummy_info_ptr->geno_mfreqs);
50 }
51
52
53 // Basic workflow for fully-powered import functions (VCF/BCF, BGEN-1.3):
54 // * Perform an initial scan of the file to count the number of variants we're
55 // actually importing, save allele counts of each of those variants, and
56 // determine maximum input and output record sizes (checking whether phase or
57 // dosage information is present in the process).
58 // * Rewind, shrink file-read buffer, set worker thread count, size and
59 // allocate file-parsing double-buffer, initialize .pgen writer.
60 // * Iterate through file again. On the first main loop iteration, the I/O
61 // thread just appends raw records to the first half of the double-buffer,
62 // spacing them so that the parsed results can be written back in-place. On
63 // the second iteration, the I/O thread appends raw records to the second
64 // half of the double-buffer while the worker threads replace the raw bytes
65 // in the first half with a parsed form. On subsequent iterations, the I/O
66 // thread uses the relevant SpgwAppend... functions to flush parsed data in
67 // its side of the double-buffer, then overwrites it with new raw records.
68 // This does not currently make sense for --make-pgen, since (unless a
69 // compute-heavy operation like --indiv-sort is involved) the worker threads
70 // usually wouldn't have enough to do.
71
72 // allele count determined from global allele_idx_offsets[] array
73 FLAGSET_DEF_START()
74 kfGparse0,
75 kfGparseNull = (1 << 0), // just create an all-missing record
76 kfGparseHphase = (1 << 1),
77 kfGparseDosage = (1 << 2),
78 kfGparseDphase = (1 << 3)
79 FLAGSET_DEF_END(GparseFlags);
80
81 typedef struct GparseReadBgenMetadataStruct {
82 uint32_t input_byte_ct;
83 uint32_t uncompressed_byte_ct;
84 } GparseReadBgenMetadata;
85
86 typedef struct GparseReadVcfMetadataStruct {
87 STD_ARRAY_DECL(uint32_t, 2, qual_field_idxs);
88 uint16_t gt_exists;
89 uint16_t qual_exists;
90 uint32_t dosage_field_idx;
91 uint32_t hds_field_idx;
92 uintptr_t line_idx; // for error reporting
93 } GparseReadVcfMetadata;
94
95 typedef struct GparseReadBcfMetadataStruct {
96 // [0] = GQ, [1] = DP
97 STD_ARRAY_DECL(uint32_t, 2, qual_vec_offsets);
98 uint32_t gt_vec_offset;
99 uint32_t dosage_vec_offset;
100 uint32_t hds_vec_offset;
101 uintptr_t rec_idx; // for error reporting
102 } GparseReadBcfMetadata;
103
104 // The "parsed form" is as follows (all arrays vector-aligned, vector counts in
105 // parentheses):
106 // genovec (sample_ctv2)
107 // iff allele_ct > 2 set:
108 // patch_01_set (sample_ctv)
109 // patch_01_vals (DivUp(sample_ct, kDosagePerVec))
110 // patch_10_set (sample_ctv)
111 // patch_10_vals (DivUp(sample_ct * 2, kDosagePerVec))
112 // iff kfGparseHphase set:
113 // phasepresent (sample_ctv)
114 // phaseinfo (sample_ctv)
115 // iff kfGparseDosage set:
116 // dosage_present (sample_ctv)
117 // dosage_main (DivUp(sample_ct, kDosagePerVec))
118 // iff allele_ct > 2:
119 // todo; probably want to exploit alternate size limit
120 // iff kfGparseDphase set:
121 // dphase_present (sample_ctv)
122 // dphase_delta (DivUp(sample_ct, kDosagePerVec))
123 // iff allele_ct > 2:
124 // todo; probably want to exploit alternate size limit
125
126 uint64_t GparseWriteByteCt(uint32_t sample_ct, uint32_t allele_ct, GparseFlags flags) {
127 const uint32_t is_multiallelic = (allele_ct > 2);
128 uint64_t vec_ct = NypCtToVecCt(sample_ct);
129 if ((flags & (kfGparseHphase | kfGparseDosage | kfGparseDphase)) || is_multiallelic) {
130 const uint32_t sample_ctv = BitCtToVecCt(sample_ct);
131 if (is_multiallelic) {
132 // patch_01_set, patch_10_set: sample_ctv each
133 // patch_01_vals: sample_ct AlleleCodes
134 // patch_10_vals: 2 * sample_ct AlleleCodes
135 vec_ct += 2 * sample_ctv + AlleleCodeCtToVecCt(sample_ct) + AlleleCodeCtToVecCt(sample_ct * 2);
136 }
137 if (flags & kfGparseHphase) {
138 vec_ct += 2 * sample_ctv;
139 }
140 if (flags & kfGparseDosage) {
141 const uint32_t dosage_ctv = DosageCtToVecCt(sample_ct);
142 uintptr_t vec_incr = sample_ctv + dosage_ctv;
143 if (is_multiallelic) {
144 // todo
145 // note that in VCF/BCF cases, we can compute an alternate upper bound
146 // based on input record size, and this can buy us a lot
147 logerrprintf("Error: GparseWriteByteCt multiallelic dosage size request.\n");
148 exit(S_CAST(int32_t, kPglRetInternalError));
149 }
150 vec_ct += vec_incr * (1 + ((flags / kfGparseDphase) & 1));
151 }
152 }
153 return vec_ct * kBytesPerVec;
154 }
155
156 typedef struct GparseWriteMetadataStruct {
157 uint32_t patch_01_ct;
158 uint32_t patch_10_ct;
159 uint32_t phasepresent_exists; // may want count later
160 uint32_t dosage_ct;
161 uint32_t multiallelic_dosage_ct;
162 uint32_t dphase_ct;
163 uint32_t multiallelic_dphase_ct;
164 } GparseWriteMetadata;
165
166 union GparseMetadata {
167 GparseReadVcfMetadata read_vcf;
168 GparseReadBcfMetadata read_bcf;
169 GparseReadBgenMetadata read_bgen;
170 GparseWriteMetadata write;
171 };
172
173 typedef struct GparseRecordStruct {
174 unsigned char* record_start; // vector-aligned
175 GparseFlags flags;
176 union GparseMetadata metadata;
177 } GparseRecord;
178
179 // returns genovec
180 uintptr_t* GparseGetPointers(unsigned char* record_start, uint32_t sample_ct, uint32_t allele_ct, GparseFlags flags, uintptr_t** patch_01_set_ptr, AlleleCode** patch_01_vals_ptr, uintptr_t** patch_10_set_ptr, AlleleCode** patch_10_vals_ptr, uintptr_t** phasepresent_ptr, uintptr_t** phaseinfo_ptr, uintptr_t** dosage_present_ptr, Dosage** dosage_main_ptr, uintptr_t** dphase_present_ptr, SDosage** dphase_delta_ptr) {
181 const uint32_t is_multiallelic = (allele_ct > 2);
182 uintptr_t* genovec = R_CAST(uintptr_t*, record_start);
183 if ((flags & (kfGparseHphase | kfGparseDosage | kfGparseDphase)) || is_multiallelic) {
184 uintptr_t* record_iter = &(genovec[NypCtToAlignedWordCt(sample_ct)]);
185 const uint32_t sample_ctaw = BitCtToAlignedWordCt(sample_ct);
186 if (is_multiallelic) {
187 *patch_01_set_ptr = record_iter;
188 record_iter = &(record_iter[sample_ctaw]);
189 *patch_01_vals_ptr = R_CAST(AlleleCode*, record_iter);
190 record_iter = &(record_iter[AlleleCodeCtToAlignedWordCt(sample_ct)]);
191 *patch_10_set_ptr = record_iter;
192 record_iter = &(record_iter[sample_ctaw]);
193 *patch_10_vals_ptr = R_CAST(AlleleCode*, record_iter);
194 record_iter = &(record_iter[kWordsPerVec * DivUp(2 * sample_ct, kAlleleCodesPerVec)]);
195 }
196 if (flags & kfGparseHphase) {
197 *phasepresent_ptr = record_iter;
198 record_iter = &(record_iter[sample_ctaw]);
199 *phaseinfo_ptr = record_iter;
200 record_iter = &(record_iter[sample_ctaw]);
201 }
202 if (flags & kfGparseDosage) {
203 const uint32_t dosage_ctaw = DosageCtToAlignedWordCt(sample_ct);
204 *dosage_present_ptr = record_iter;
205 record_iter = &(record_iter[sample_ctaw]);
206 *dosage_main_ptr = R_CAST(Dosage*, record_iter);
207 record_iter = &(record_iter[dosage_ctaw]);
208 if (is_multiallelic) {
209 // todo
210 }
211 if (flags & kfGparseDphase) {
212 *dphase_present_ptr = record_iter;
213 record_iter = &(record_iter[sample_ctaw]);
214 *dphase_delta_ptr = R_CAST(SDosage*, record_iter);
215 // record_iter = &(record_iter[dosage_ctaw]);
216 if (is_multiallelic) {
217 // todo
218 }
219 }
220 }
221 }
222 return genovec;
223 }
224
225 // Might want to change allele_idx_offsets parameter to
226 // block_allele_idx_offsets, to facilitate single-pass .bgen parsing.
227 PglErr GparseFlush(const GparseRecord* grp, const uintptr_t* allele_idx_offsets, uint32_t write_block_size, STPgenWriter* spgwp) {
228 PglErr reterr = kPglRetSuccess;
229 {
230 if (allele_idx_offsets) {
231 allele_idx_offsets = &(allele_idx_offsets[SpgwGetVidx(spgwp)]);
232 }
233 const uint32_t sample_ct = SpgwGetSampleCt(spgwp);
234 uint32_t allele_ct = 2;
235 uintptr_t* patch_01_set = nullptr;
236 AlleleCode* patch_01_vals = nullptr;
237 uintptr_t* patch_10_set = nullptr;
238 AlleleCode* patch_10_vals = nullptr;
239 uintptr_t* phasepresent = nullptr;
240 uintptr_t* phaseinfo = nullptr;
241 uintptr_t* dosage_present = nullptr;
242 Dosage* dosage_main = nullptr;
243 uintptr_t* dphase_present = nullptr;
244 SDosage* dphase_delta = nullptr;
245 // todo: multiallelic dosage buffers
246 for (uintptr_t write_block_vidx = 0; write_block_vidx != write_block_size; ++write_block_vidx) {
247 const GparseRecord* cur_gparse_rec = &(grp[write_block_vidx]);
248 const GparseFlags flags = cur_gparse_rec->flags;
249 if (allele_idx_offsets) {
250 allele_ct = allele_idx_offsets[write_block_vidx + 1] - allele_idx_offsets[write_block_vidx];
251 }
252 uintptr_t* genovec = GparseGetPointers(cur_gparse_rec->record_start, sample_ct, allele_ct, flags, &patch_01_set, &patch_01_vals, &patch_10_set, &patch_10_vals, &phasepresent, &phaseinfo, &dosage_present, &dosage_main, &dphase_present, &dphase_delta);
253 const GparseWriteMetadata* cur_gwmp = &(cur_gparse_rec->metadata.write);
254 if (!(flags & (kfGparseHphase | kfGparseDosage))) {
255 if (allele_ct == 2) {
256 if (unlikely(SpgwAppendBiallelicGenovec(genovec, spgwp))) {
257 goto GparseFlush_ret_WRITE_FAIL;
258 }
259 } else {
260 reterr = SpgwAppendMultiallelicSparse(genovec, patch_01_set, patch_01_vals, patch_10_set, patch_10_vals, allele_ct, cur_gwmp->patch_01_ct, cur_gwmp->patch_10_ct, spgwp);
261 if (unlikely(reterr)) {
262 goto GparseFlush_ret_1;
263 }
264 }
265 } else {
266 const uint32_t cur_dosage_ct = cur_gwmp->dosage_ct;
267 const uint32_t cur_dphase_ct = cur_gwmp->dphase_ct;
268 if (!cur_dphase_ct) {
269 if (!cur_dosage_ct) {
270 if (allele_ct == 2) {
271 if (!cur_gwmp->phasepresent_exists) {
272 if (unlikely(SpgwAppendBiallelicGenovec(genovec, spgwp))) {
273 goto GparseFlush_ret_WRITE_FAIL;
274 }
275 } else {
276 if (unlikely(SpgwAppendBiallelicGenovecHphase(genovec, phasepresent, phaseinfo, spgwp))) {
277 goto GparseFlush_ret_WRITE_FAIL;
278 }
279 }
280 } else {
281 if (!cur_gwmp->phasepresent_exists) {
282 reterr = SpgwAppendMultiallelicSparse(genovec, patch_01_set, patch_01_vals, patch_10_set, patch_10_vals, allele_ct, cur_gwmp->patch_01_ct, cur_gwmp->patch_10_ct, spgwp);
283 } else {
284 reterr = SpgwAppendMultiallelicGenovecHphase(genovec, patch_01_set, patch_01_vals, patch_10_set, patch_10_vals, phasepresent, phaseinfo, allele_ct, cur_gwmp->patch_01_ct, cur_gwmp->patch_10_ct, spgwp);
285 }
286 if (unlikely(reterr)) {
287 goto GparseFlush_ret_1;
288 }
289 }
290 } else {
291 if (!cur_gwmp->phasepresent_exists) {
292 reterr = SpgwAppendBiallelicGenovecDosage16(genovec, dosage_present, dosage_main, cur_dosage_ct, spgwp);
293 } else {
294 reterr = SpgwAppendBiallelicGenovecHphaseDosage16(genovec, phasepresent, phaseinfo, dosage_present, dosage_main, cur_dosage_ct, spgwp);
295 }
296 if (unlikely(reterr)) {
297 goto GparseFlush_ret_1;
298 }
299 }
300 } else {
301 reterr = SpgwAppendBiallelicGenovecDphase16(genovec, phasepresent, phaseinfo, dosage_present, dphase_present, dosage_main, dphase_delta, cur_dosage_ct, cur_dphase_ct, spgwp);
302 if (unlikely(reterr)) {
303 goto GparseFlush_ret_1;
304 }
305 }
306 }
307 }
308 }
309 while (0) {
310 GparseFlush_ret_WRITE_FAIL:
311 reterr = kPglRetWriteFail;
312 break;
313 }
314 GparseFlush_ret_1:
315 return reterr;
316 }
317
318
319 typedef struct ImportSampleIdContextStruct {
320 const char* const_fid;
321 uint32_t const_fid_slen;
322 uint32_t double_id;
323 uint32_t id_delim_sid;
324 uint32_t two_part_null_fid;
325 uint32_t two_part_null_sid;
326 uint32_t omit_fid_0;
327 char id_delim;
328 } ImportSampleIdContext;
329
330 void InitImportSampleIdContext(const char* const_fid, MiscFlags misc_flags, ImportFlags import_flags, char id_delim, ImportSampleIdContext* isicp) {
331 isicp->const_fid = nullptr;
332 isicp->const_fid_slen = 0;
333 if (const_fid && (!strequal_k_unsafe(const_fid, "0"))) {
334 isicp->const_fid_slen = strlen(const_fid);
335 isicp->const_fid = const_fid;
336 }
337 isicp->double_id = (import_flags / kfImportDoubleId) & 1;
338 isicp->id_delim_sid = (misc_flags / kfMiscIidSid) & 1;
339 isicp->two_part_null_fid = 0;
340 isicp->two_part_null_sid = 0;
341 isicp->omit_fid_0 = 0;
342 isicp->id_delim = id_delim;
343 }
344
345 PglErr ImportSampleId(const char* input_id_iter, const char* input_id_end, const ImportSampleIdContext* isicp, char** write_iterp) {
346 PglErr reterr = kPglRetSuccess;
347 {
348 const char id_delim = isicp->id_delim;
349 char* write_iter = *write_iterp;
350 if (id_delim) {
351 const char* first_delim = S_CAST(const char*, memchr(input_id_iter, ctou32(id_delim), input_id_end - input_id_iter));
352 if (unlikely(!first_delim)) {
353 snprintf(g_logbuf, kLogbufSize, "Error: No '%c' in sample ID.\n", id_delim);
354 goto ImportSampleId_ret_INCONSISTENT_INPUT_2;
355 }
356 if (unlikely(*input_id_iter == id_delim)) {
357 snprintf(g_logbuf, kLogbufSize, "Error: '%c' at beginning of sample ID.\n", id_delim);
358 goto ImportSampleId_ret_INCONSISTENT_INPUT_2;
359 }
360 if (unlikely(input_id_end[-1] == id_delim)) {
361 snprintf(g_logbuf, kLogbufSize, "Error: '%c' at end of sample ID.\n", id_delim);
362 goto ImportSampleId_ret_INCONSISTENT_INPUT_2;
363 }
364 const uint32_t first_part_slen = first_delim - input_id_iter;
365 if (unlikely(first_part_slen > kMaxIdSlen)) {
366 // strictly speaking, you could have e.g. a 20k char ID which
367 // splits into a valid pair with the right delimiter, but you're
368 // not supposed to have sample IDs anywhere near that length so
369 // I'll classify this as MalformedInput.
370 goto ImportSampleId_ret_MALFORMED_INPUT_LONG_ID;
371 }
372 const char* second_part_start = &(first_delim[1]);
373 const char* second_part_end = S_CAST(const char*, memchr(second_part_start, ctou32(id_delim), input_id_end - second_part_start));
374 const char* third_part_start = nullptr;
375 uint32_t third_part_slen = 0;
376 if (second_part_end) {
377 if (unlikely(second_part_start == second_part_end)) {
378 snprintf(g_logbuf, kLogbufSize, "Error: Consecutive instances of '%c' in sample ID.\n", id_delim);
379 goto ImportSampleId_ret_INCONSISTENT_INPUT_2;
380 }
381 third_part_start = &(second_part_end[1]);
382 third_part_slen = input_id_end - third_part_start;
383 if (unlikely(memchr(third_part_start, ctou32(id_delim), third_part_slen))) {
384 snprintf(g_logbuf, kLogbufSize, "Error: More than two instances of '%c' in sample ID.\n", id_delim);
385 goto ImportSampleId_ret_INCONSISTENT_INPUT_2;
386 }
387 if (unlikely(third_part_slen > kMaxIdSlen)) {
388 goto ImportSampleId_ret_MALFORMED_INPUT_LONG_ID;
389 }
390 } else {
391 second_part_end = input_id_end;
392 if (isicp->id_delim_sid) {
393 if (unlikely((first_part_slen == 1) && (*input_id_iter == '0'))) {
394 logerrputs("Error: Sample ID induces an invalid IID of '0'.\n");
395 goto ImportSampleId_ret_INCONSISTENT_INPUT;
396 }
397 if (isicp->two_part_null_fid) {
398 write_iter = strcpya_k(write_iter, "0\t");
399 }
400 }
401 }
402 if (!isicp->omit_fid_0) {
403 write_iter = memcpyax(write_iter, input_id_iter, first_part_slen, '\t');
404 }
405 const uint32_t second_part_slen = second_part_end - second_part_start;
406 if (unlikely((third_part_start || (!isicp->id_delim_sid)) && (second_part_slen == 1) && (*second_part_end == '0'))) {
407 logerrputs("Error: Sample ID induces an invalid IID of '0'.\n");
408 goto ImportSampleId_ret_INCONSISTENT_INPUT;
409 }
410 if (unlikely(second_part_slen > kMaxIdSlen)) {
411 goto ImportSampleId_ret_MALFORMED_INPUT_LONG_ID;
412 }
413 write_iter = memcpya(write_iter, second_part_start, second_part_slen);
414 if (third_part_start) {
415 *write_iter++ = '\t';
416 write_iter = memcpya(write_iter, third_part_start, third_part_slen);
417 } else if (isicp->two_part_null_sid) {
418 write_iter = strcpya_k(write_iter, "\t0");
419 }
420 } else {
421 const uint32_t token_slen = input_id_end - input_id_iter;
422 if (unlikely((*input_id_iter == '0') && (token_slen == 1))) {
423 logerrputs("Error: Sample ID cannot be '0'.\n");
424 goto ImportSampleId_ret_MALFORMED_INPUT;
425 }
426 if (unlikely(token_slen > kMaxIdSlen)) {
427 goto ImportSampleId_ret_MALFORMED_INPUT_LONG_ID;
428 }
429 if (isicp->double_id) {
430 write_iter = memcpyax(write_iter, input_id_iter, token_slen, '\t');
431 } else if (isicp->const_fid) {
432 write_iter = memcpyax(write_iter, isicp->const_fid, isicp->const_fid_slen, '\t');
433 }
434 write_iter = memcpya(write_iter, input_id_iter, token_slen);
435 }
436 *write_iterp = write_iter;
437 }
438 while (0) {
439 ImportSampleId_ret_MALFORMED_INPUT_LONG_ID:
440 logerrputs("Error: FIDs, IIDs, and SIDs are limited to " MAX_ID_SLEN_STR " characters.\n");
441 ImportSampleId_ret_MALFORMED_INPUT:
442 reterr = kPglRetMalformedInput;
443 break;
444 ImportSampleId_ret_INCONSISTENT_INPUT_2:
445 logerrputsb();
446 ImportSampleId_ret_INCONSISTENT_INPUT:
447 reterr = kPglRetInconsistentInput;
448 break;
449 }
450 return reterr;
451 }
452
453 PglErr ImportIidFromSampleId(const char* input_id_iter, const char* input_id_end, const ImportSampleIdContext* isicp, const char** iid_start_ptr, uint32_t* iid_slen_ptr) {
454 PglErr reterr = kPglRetSuccess;
455 {
456 const char id_delim = isicp->id_delim;
457 const char* iid_start = input_id_iter;
458 uint32_t iid_slen;
459 if (id_delim) {
460 const char* first_delim = S_CAST(const char*, memchr(input_id_iter, ctou32(id_delim), input_id_end - input_id_iter));
461 if (unlikely(!first_delim)) {
462 snprintf(g_logbuf, kLogbufSize, "Error: No '%c' in sample ID.\n", id_delim);
463 goto ImportIidFromSampleId_ret_INCONSISTENT_INPUT_2;
464 }
465 if (isicp->id_delim_sid && (!isicp->two_part_null_fid)) {
466 // only possible if there's never a third field
467 iid_slen = first_delim - input_id_iter;
468 } else {
469 const char* second_part_start = &(first_delim[1]);
470 const char* second_part_end = S_CAST(const char*, memchr(second_part_start, ctou32(id_delim), input_id_end - second_part_start));
471 if ((!isicp->id_delim_sid) || second_part_end) {
472 iid_start = second_part_start;
473 if (!second_part_end) {
474 second_part_end = input_id_end;
475 }
476 iid_slen = second_part_end - second_part_start;
477 } else {
478 iid_slen = first_delim - iid_start;
479 }
480 }
481 } else {
482 iid_slen = input_id_end - iid_start;
483 }
484 if (unlikely((iid_slen == 1) && (*iid_start == '0'))) {
485 logerrputs("Error: IID cannot be '0'.\n");
486 goto ImportIidFromSampleId_ret_MALFORMED_INPUT;
487 }
488 if (unlikely(iid_slen > kMaxIdSlen)) {
489 goto ImportIidFromSampleId_ret_MALFORMED_INPUT_LONG_ID;
490 }
491 *iid_start_ptr = iid_start;
492 *iid_slen_ptr = iid_slen;
493 }
494 while (0) {
495 ImportIidFromSampleId_ret_MALFORMED_INPUT_LONG_ID:
496 logerrputs("Error: FIDs, IIDs, and SIDs are limited to " MAX_ID_SLEN_STR " characters.\n");
497 ImportIidFromSampleId_ret_MALFORMED_INPUT:
498 reterr = kPglRetMalformedInput;
499 break;
500 ImportIidFromSampleId_ret_INCONSISTENT_INPUT_2:
501 logerrputsb();
502 reterr = kPglRetInconsistentInput;
503 break;
504 }
505 return reterr;
506 }
507
508 PglErr VcfSampleLine(const char* preexisting_psamname, const char* const_fid, MiscFlags misc_flags, ImportFlags import_flags, FamCol fam_cols, char id_delim, char idspace_to, char flag_char, char* sample_line_first_id, char* outname, char* outname_end, uint32_t* sample_ct_ptr) {
509 unsigned char* bigstack_mark = g_bigstack_base;
510 FILE* psamfile = nullptr;
511 uintptr_t line_idx = 0;
512 PglErr reterr = kPglRetSuccess;
513 TextStream psam_txs;
514 PreinitTextStream(&psam_txs);
515 {
516 ImportSampleIdContext isic;
517 InitImportSampleIdContext(const_fid, misc_flags, import_flags, id_delim, &isic);
518 uint32_t write_fid = 1;
519 uint32_t write_sid = 0;
520 // Alpha 2 changes:
521 // * --id-delim can no longer be used with --const-fid/--double-id. All
522 // samples must be multipart.
523 // * New default is --const-fid 0, which causes no FID column to be written
524 // at all.
525 if (id_delim) {
526 if (id_delim != ' ') {
527 char* sample_line_iter = strchrnul_n(sample_line_first_id, ' ');
528 if (*sample_line_iter == ' ') {
529 if (unlikely(!idspace_to)) {
530 logerrputs("Error: VCF/BCF2 sample ID contains space(s). Use --idspace-to to convert them\nto another character, or \"--id-delim ' '\" to interpret the spaces as FID/IID\nor IID/SID delimiters.\n");
531 goto VcfSampleLine_ret_INCONSISTENT_INPUT;
532 }
533 do {
534 *sample_line_iter = idspace_to;
535 sample_line_iter = strchrnul_n(&(sample_line_iter[1]), ' ');
536 } while (*sample_line_iter == ' ');
537 }
538 }
539 const char* sample_line_iter = sample_line_first_id;
540 uint32_t nonzero_first_field_observed = 0;
541 while (ctou32(sample_line_iter[0]) >= ' ') {
542 const char* token_end = strchrnul_n(sample_line_iter, '\t');
543 const char* first_delim = S_CAST(const char*, memchr(sample_line_iter, ctou32(id_delim), token_end - sample_line_iter));
544 if (unlikely(!first_delim)) {
545 snprintf(g_logbuf, kLogbufSize, "Error: No '%c' in sample ID.\n", id_delim);
546 goto VcfSampleLine_ret_INCONSISTENT_INPUT_2;
547 }
548 if (!nonzero_first_field_observed) {
549 nonzero_first_field_observed = (first_delim != &(sample_line_iter[1])) || (sample_line_iter[0] != '0');
550 }
551 sample_line_iter = &(first_delim[1]);
552 if (memchr(sample_line_iter, ctou32(id_delim), token_end - sample_line_iter)) {
553 write_fid = 1;
554 write_sid = 1;
555 if (!nonzero_first_field_observed) {
556 // bugfix (22 Feb 2018): this was != instead of ==
557 while (*token_end == '\t') {
558 sample_line_iter = &(token_end[1]);
559 token_end = strchrnul_n(sample_line_iter, '\t');
560 if ((sample_line_iter[0] != '0') || (sample_line_iter[1] != id_delim)) {
561 nonzero_first_field_observed = 1;
562 break;
563 }
564 }
565 }
566 break;
567 }
568 if (*token_end != '\t') {
569 if (isic.id_delim_sid) {
570 write_fid = 0;
571 write_sid = 1;
572 }
573 break;
574 }
575 sample_line_iter = &(token_end[1]);
576 }
577 if (!nonzero_first_field_observed) {
578 write_fid = 0;
579 isic.omit_fid_0 = 1;
580 }
581 } else if ((!isic.const_fid) && (!isic.double_id)) {
582 write_fid = 0;
583 }
584 const char* sample_line_iter = sample_line_first_id;
585 uint32_t sample_ct = 0;
586 if (!preexisting_psamname) {
587 snprintf(outname_end, kMaxOutfnameExtBlen, ".psam");
588 if (unlikely(fopen_checked(outname, FOPEN_WB, &psamfile))) {
589 goto VcfSampleLine_ret_OPEN_FAIL;
590 }
591 char* write_iter = g_textbuf;
592 char* textbuf_flush = &(write_iter[kMaxMediumLine]);
593 *write_iter++ = '#';
594 if (write_fid) {
595 write_iter = strcpya_k(write_iter, "FID\t");
596 }
597 write_iter = strcpya_k(write_iter, "IID");
598 if (write_sid) {
599 write_iter = strcpya_k(write_iter, "\tSID");
600 if (write_fid || isic.omit_fid_0) {
601 isic.two_part_null_fid = isic.id_delim_sid;
602 isic.two_part_null_sid = 1 - isic.id_delim_sid;
603 }
604 }
605 write_iter = strcpya_k(write_iter, "\tSEX");
606 AppendBinaryEoln(&write_iter);
607 while (ctou32(sample_line_iter[0]) >= ' ') {
608 ++sample_ct;
609 const char* token_end = NextPrespace(sample_line_iter);
610 reterr = ImportSampleId(sample_line_iter, token_end, &isic, &write_iter);
611 if (unlikely(reterr)) {
612 goto VcfSampleLine_ret_1;
613 }
614 // PAT/MAT/PHENO1 not required in .psam file
615 // SEX now included, so that --vcf + --out has the same effect as --vcf
616 // + --make-pgen + --out
617 write_iter = strcpya_k(write_iter, "\tNA");
618 AppendBinaryEoln(&write_iter);
619 if (unlikely(fwrite_ck(textbuf_flush, psamfile, &write_iter))) {
620 goto VcfSampleLine_ret_WRITE_FAIL;
621 }
622 if (*token_end != '\t') {
623 break;
624 }
625 sample_line_iter = &(token_end[1]);
626 }
627 if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &psamfile))) {
628 goto VcfSampleLine_ret_WRITE_FAIL;
629 }
630 } else {
631 // check consistency of IIDs between VCF and .psam file.
632 reterr = SizeAndInitTextStream(preexisting_psamname, bigstack_left(), 1, &psam_txs);
633 if (unlikely(reterr)) {
634 goto VcfSampleLine_ret_TSTREAM_FAIL;
635 }
636 uint32_t sample_line_eoln = IsEoln(sample_line_iter[0]);
637 char* psam_line_start;
638 do {
639 ++line_idx;
640 psam_line_start = TextGet(&psam_txs);
641 if (!psam_line_start) {
642 if (TextStreamErrcode2(&psam_txs, &reterr)) {
643 goto VcfSampleLine_ret_TSTREAM_FAIL;
644 }
645 if (unlikely(!sample_line_eoln)) {
646 snprintf(g_logbuf, kLogbufSize, "Error: --%ccf file contains more sample IDs than %s.\n", flag_char, preexisting_psamname);
647 goto VcfSampleLine_ret_INCONSISTENT_INPUT_WW;
648 }
649 *sample_ct_ptr = 0;
650 goto VcfSampleLine_ret_1;
651 }
652 } while ((psam_line_start[0] == '#') && (!tokequal_k(&(psam_line_start[1]), "FID")) && (!tokequal_k(&(psam_line_start[1]), "IID")));
653 uint32_t fid_exists;
654 if (psam_line_start[0] == '#') {
655 // only check for matching IIDs for now.
656 fid_exists = (psam_line_start[1] == 'F');
657 // bugfix (12 Apr 2018): forgot to skip this line
658 ++line_idx;
659 psam_line_start = TextGet(&psam_txs);
660 } else {
661 fid_exists = fam_cols & kfFamCol1;
662 }
663 for (; psam_line_start; ++line_idx, psam_line_start = TextGet(&psam_txs)) {
664 if (unlikely(psam_line_start[0] == '#')) {
665 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s starts with a '#'. (This is only permitted before the first nonheader line, and a #FID/IID header line is present it must denote the end of the header block.)\n", line_idx, preexisting_psamname);
666 goto VcfSampleLine_ret_MALFORMED_INPUT_WW;
667 }
668 const char* psam_iid_start = psam_line_start;
669 if (fid_exists) {
670 psam_iid_start = FirstNonTspace(CurTokenEnd(psam_iid_start));
671 if (unlikely(IsEolnKns(*psam_iid_start))) {
672 goto VcfSampleLine_ret_MISSING_TOKENS;
673 }
674 }
675 if (unlikely(sample_line_eoln)) {
676 snprintf(g_logbuf, kLogbufSize, "Error: --%ccf file contains fewer sample IDs than %s.\n", flag_char, preexisting_psamname);
677 goto VcfSampleLine_ret_INCONSISTENT_INPUT_WW;
678 }
679 ++sample_ct;
680 const char* sample_line_token_end = NextPrespace(sample_line_iter);
681 const char* sample_line_iid_start;
682 uint32_t sample_line_iid_slen;
683 reterr = ImportIidFromSampleId(sample_line_iter, sample_line_token_end, &isic, &sample_line_iid_start, &sample_line_iid_slen);
684 if (unlikely(reterr)) {
685 goto VcfSampleLine_ret_1;
686 }
687 if (unlikely(!memequal(sample_line_iid_start, psam_iid_start, sample_line_iid_slen) || (ctou32(psam_iid_start[sample_line_iid_slen]) > 32))) {
688 snprintf(g_logbuf, kLogbufSize, "Error: Mismatched IDs between --%ccf file and %s.\n", flag_char, preexisting_psamname);
689 goto VcfSampleLine_ret_INCONSISTENT_INPUT_WW;
690 }
691 sample_line_eoln = (*sample_line_token_end != '\t');
692 sample_line_iter = &(sample_line_token_end[1]);
693 }
694 if (unlikely(TextStreamErrcode2(&psam_txs, &reterr))) {
695 goto VcfSampleLine_ret_TSTREAM_FAIL;
696 }
697 if (unlikely(!sample_line_eoln)) {
698 snprintf(g_logbuf, kLogbufSize, "Error: --%ccf file contains more sample IDs than %s.\n", flag_char, preexisting_psamname);
699 goto VcfSampleLine_ret_INCONSISTENT_INPUT_WW;
700 }
701 }
702 *sample_ct_ptr = sample_ct;
703 }
704 while (0) {
705 VcfSampleLine_ret_OPEN_FAIL:
706 reterr = kPglRetOpenFail;
707 break;
708 VcfSampleLine_ret_TSTREAM_FAIL:
709 TextStreamErrPrint(preexisting_psamname, &psam_txs);
710 break;
711 VcfSampleLine_ret_WRITE_FAIL:
712 reterr = kPglRetWriteFail;
713 break;
714 VcfSampleLine_ret_MALFORMED_INPUT_WW:
715 WordWrapB(0);
716 logerrputsb();
717 reterr = kPglRetMalformedInput;
718 break;
719 VcfSampleLine_ret_MISSING_TOKENS:
720 logerrprintfww("Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, preexisting_psamname);
721 reterr = kPglRetMalformedInput;
722 break;
723 VcfSampleLine_ret_INCONSISTENT_INPUT_WW:
724 WordWrapB(0);
725 VcfSampleLine_ret_INCONSISTENT_INPUT_2:
726 logerrputsb();
727 VcfSampleLine_ret_INCONSISTENT_INPUT:
728 reterr = kPglRetInconsistentInput;
729 break;
730 }
731 VcfSampleLine_ret_1:
732 CleanupTextStream2(preexisting_psamname, &psam_txs, &reterr);
733 fclose_cond(psamfile);
734 BigstackReset(bigstack_mark);
735 return reterr;
736 }
737
738 uint32_t VcfIsHetShort(const char* first_gchar_ptr, VcfHalfCall vcf_half_call) {
739 // '.' == ascii 46, '0' == ascii 48
740 // if kVcfHalfCallReference, .|0 is not phased, but .|1 is
741 const uint32_t first_gchar = ctou32(first_gchar_ptr[0]);
742 const uint32_t second_gchar = ctou32(first_gchar_ptr[2]);
743 return (first_gchar != second_gchar) && (((first_gchar != 46) && (second_gchar != 46)) || ((vcf_half_call == kVcfHalfCallReference) && ((first_gchar > 48) || (second_gchar > 48))));
744 }
745
746 uint32_t VcfIsHetLong(const char* first_allele_idx_str_iter, const char* second_allele_idx_str_iter, VcfHalfCall vcf_half_call) {
747 uint32_t first_allele_idx = ctou32(*first_allele_idx_str_iter++);
748 uint32_t second_allele_idx = ctou32(*second_allele_idx_str_iter++);
749 if (first_allele_idx == 46) {
750 return (vcf_half_call == kVcfHalfCallReference) && (second_allele_idx > 48);
751 }
752 if (second_allele_idx == 46) {
753 return (vcf_half_call == kVcfHalfCallReference) && (first_allele_idx > 48);
754 }
755 first_allele_idx -= 48;
756 for (; ; ++first_allele_idx_str_iter) {
757 const uint32_t next_digit = ctou32(*first_allele_idx_str_iter) - 48;
758 if (next_digit >= 10) {
759 break;
760 }
761 first_allele_idx = first_allele_idx * 10 + next_digit;
762 }
763 second_allele_idx -= 48;
764 for (; ; ++second_allele_idx_str_iter) {
765 const uint32_t next_digit = ctou32(*second_allele_idx_str_iter) - 48;
766 if (next_digit >= 10) {
767 break;
768 }
769 second_allele_idx = second_allele_idx * 10 + next_digit;
770 }
771 return (first_allele_idx != second_allele_idx);
772 }
773
774 uint32_t GetVcfFormatPosition(const char* __restrict needle, const char* format_start, const char* format_end, uint32_t needle_slen) {
775 // no longer assumes first field is GT
776 const char* token_start = format_start;
777 for (uint32_t field_idx = 0; ; ++field_idx) {
778 const char* token_end = AdvToDelimOrEnd(token_start, format_end, ':');
779 if ((S_CAST(uintptr_t, token_end - token_start) == needle_slen) && memequal(token_start, needle, needle_slen)) {
780 return field_idx;
781 }
782 if (token_end == format_end) {
783 return UINT32_MAX;
784 }
785 token_start = &(token_end[1]);
786 }
787 }
788
789 uint32_t VcfQualScanInit1(const char* format_start, const char* format_end, int32_t vcf_min_gq, int32_t vcf_min_dp, int32_t vcf_max_dp, STD_ARRAY_REF(uint32_t, 2) qual_field_idxs) {
790 uint32_t qual_exists = 0;
791 qual_field_idxs[0] = UINT32_MAX;
792 qual_field_idxs[1] = UINT32_MAX;
793 if (vcf_min_gq >= 0) {
794 qual_field_idxs[0] = GetVcfFormatPosition("GQ", format_start, format_end, 2);
795 qual_exists = (qual_field_idxs[0] != UINT32_MAX);
796 }
797 if ((vcf_min_dp >= 0) || (vcf_max_dp != 0x7fffffff)) {
798 qual_field_idxs[1] = GetVcfFormatPosition("DP", format_start, format_end, 2);
799 if (qual_field_idxs[1] != UINT32_MAX) {
800 qual_exists = 1;
801 }
802 }
803 return qual_exists;
804 }
805
806 uint32_t VcfQualScanInit2(STD_ARRAY_KREF(uint32_t, 2) qual_field_idxs, STD_ARRAY_KREF(int32_t, 2) qual_mins, STD_ARRAY_KREF(int32_t, 2) qual_maxs, STD_ARRAY_REF(uint32_t, 2) qual_field_skips, STD_ARRAY_REF(int32_t, 2) qual_line_mins, STD_ARRAY_REF(int32_t, 2) qual_line_maxs) {
807 // handcoded for now, but can be switched to a std::sort call if necessary
808 const uint32_t gq_field_idx = qual_field_idxs[0];
809 uint32_t dp_field_idx = qual_field_idxs[1];
810 uint32_t qual_field_ct = 0;
811 if (dp_field_idx < gq_field_idx) {
812 qual_field_skips[0] = dp_field_idx;
813 qual_line_mins[0] = qual_mins[1];
814 qual_line_maxs[0] = qual_maxs[1];
815 qual_field_ct = 1;
816 dp_field_idx = UINT32_MAX;
817 }
818 if (gq_field_idx != UINT32_MAX) {
819 qual_field_skips[qual_field_ct] = gq_field_idx;
820 qual_line_mins[qual_field_ct] = qual_mins[0];
821 qual_line_maxs[qual_field_ct] = 0x7fffffff;
822 ++qual_field_ct;
823 if (dp_field_idx != UINT32_MAX) {
824 qual_field_skips[qual_field_ct] = dp_field_idx;
825 qual_line_mins[qual_field_ct] = qual_mins[1];
826 qual_line_maxs[qual_field_ct] = qual_maxs[1];
827 ++qual_field_ct;
828 }
829 }
830 if (qual_field_ct == 2) {
831 qual_field_skips[1] -= qual_field_skips[0];
832 }
833 return qual_field_ct;
834 }
835
836 // These values are constant over a single VCF line, and relevant to parsing
837 // inner loop(s). VcfImportBaseContext covers what's needed for dosageless
838 // import, while VcfImportContext covers the general case.
839 typedef struct VcfImportContextBaseStruct {
840 // constant across file
841 uint32_t sample_ct;
842 VcfHalfCall halfcall_mode;
843 uint32_t error_on_polyploid;
844
845 // line-specific
846 uint32_t gt_exists;
847 STD_ARRAY_DECL(uint32_t, 2, qual_field_skips);
848 STD_ARRAY_DECL(int32_t, 2, qual_line_mins);
849 STD_ARRAY_DECL(int32_t, 2, qual_line_maxs);
850 uint32_t qual_field_ct; // must be set to zero if no qual fields
851 } VcfImportBaseContext;
852
853 typedef struct VcfImportContext {
854 VcfImportBaseContext vibc;
855
856 // constant across file
857 uint32_t dosage_is_gp;
858 uint32_t dosage_erase_halfdist;
859 double import_dosage_certainty;
860
861 // line-specific
862 uint32_t dosage_field_idx;
863 uint32_t hds_field_idx;
864 } VcfImportContext;
865
866 // returns 1 if a quality check failed
867 // assumes either 1 or 2 qual fields, otherwise change this to a loop
868 uint32_t VcfCheckQuals(STD_ARRAY_KREF(uint32_t, 2) qual_field_skips, STD_ARRAY_KREF(int32_t, 2) qual_line_mins, STD_ARRAY_KREF(int32_t, 2) qual_line_maxs, const char* gtext_iter, const char* gtext_end, uint32_t qual_field_ct) {
869 const uint32_t skip0 = qual_field_skips[0]; // this can now be zero
870 if (skip0) {
871 gtext_iter = AdvToNthDelimChecked(gtext_iter, gtext_end, skip0, ':');
872 if (!gtext_iter) {
873 return 0;
874 }
875 ++gtext_iter;
876 }
877 int32_t ii;
878 if ((!ScanInt32(gtext_iter, &ii)) && ((ii < qual_line_mins[0]) || (ii > qual_line_maxs[0]))) {
879 return 1;
880 }
881 if (qual_field_ct == 1) {
882 return 0;
883 }
884 gtext_iter = AdvToNthDelimChecked(gtext_iter, gtext_end, qual_field_skips[1], ':');
885 if (!gtext_iter) {
886 return 0;
887 }
888 ++gtext_iter;
889 return (!ScanInt32(gtext_iter, &ii)) && ((ii < qual_line_mins[1]) || (ii > qual_line_maxs[1]));
890 }
891
892 // kDosageParseForceMissing = --import-dosage-certainty filter applied
893 ENUM_U31_DEF_START()
894 kDosageParseOk,
895 kDosageParsePolyploid,
896 kDosageParseMissing,
897 kDosageParseForceMissing
898 ENUM_U31_DEF_END(DosageParseResult);
899
900 BoolErr ParseVcfBiallelicGp(const char* gp_iter, uint32_t is_haploid, double import_dosage_certainty, DosageParseResult* dpr_ptr, double* alt_dosage_ptr) {
901 // P(0/0), P(0/1), P(1/1), etc.
902 // assumes dpr initialized to kDosageParseOk
903 double prob_0alt;
904 gp_iter = ScanadvDouble(gp_iter, &prob_0alt);
905 if (unlikely((!gp_iter) || (prob_0alt < 0.0) || (prob_0alt > 1.0) || (*gp_iter != ','))) {
906 return 1;
907 }
908 double prob_1alt;
909 gp_iter = ScanadvDouble(&(gp_iter[1]), &prob_1alt);
910 if (unlikely((!gp_iter) || (prob_1alt < 0.0) || (prob_1alt > 1.0))) {
911 return 1;
912 }
913 if (is_haploid) {
914 const double denom = prob_0alt + prob_1alt;
915 if (denom <= 2 * import_dosage_certainty) {
916 if ((prob_0alt <= import_dosage_certainty) && (prob_1alt <= import_dosage_certainty)) {
917 *dpr_ptr = kDosageParseForceMissing;
918 return 1;
919 }
920 }
921 *alt_dosage_ptr = 2 * prob_1alt / denom;
922 return 0;
923 }
924 double prob_2alt;
925 if (unlikely((*gp_iter != ',') || (!ScanadvDouble(&(gp_iter[1]), &prob_2alt)) || (prob_2alt < 0.0) || (prob_2alt > 1.0))) {
926 return 1;
927 }
928 const double denom = prob_0alt + prob_1alt + prob_2alt;
929 if (denom <= 3 * import_dosage_certainty) {
930 if ((prob_0alt <= import_dosage_certainty) && (prob_1alt <= import_dosage_certainty) && (prob_2alt <= import_dosage_certainty)) {
931 // force-missing
932 // ok to use <= since we multiplied by (1 - epsilon)
933 // during command-line parsing. this lets us avoid
934 // special-casing denom=0.
935 *dpr_ptr = kDosageParseForceMissing;
936 return 1; // not really an error
937 }
938 }
939 *alt_dosage_ptr = (prob_1alt + 2 * prob_2alt) / denom;
940 return 0;
941 }
942
943 BoolErr ParseVcfBiallelicDosage(const char* gtext_iter, const char* gtext_end, uint32_t dosage_field_idx, uint32_t is_haploid, uint32_t dosage_is_gp, double import_dosage_certainty, DosageParseResult* dpr_ptr, uint32_t* dosage_int_ptr) {
944 // assumes dosage_field_idx != UINT32_MAX
945 // assumes dpr initialized to kDosageParseOk
946 // returns 1 if missing OR parsing error. error: dpr still kDosageParseOk.
947 if (dosage_field_idx) {
948 gtext_iter = AdvToNthDelimChecked(gtext_iter, gtext_end, dosage_field_idx, ':');
949 if (!gtext_iter) {
950 *dpr_ptr = kDosageParseMissing;
951 return 1;
952 }
953 ++gtext_iter;
954 }
955 if ((gtext_iter[0] == '?') || ((gtext_iter[0] == '.') && (ctou32(gtext_iter[1]) - 48 >= 10))) {
956 // missing field (dot/'?' followed by non-digit)
957 // could enforce gtext_iter[1] == colon, comma, etc.?
958 *dpr_ptr = kDosageParseMissing;
959 return 1;
960 }
961 double alt_dosage;
962 if (dosage_is_gp) {
963 if (ParseVcfBiallelicGp(gtext_iter, is_haploid, import_dosage_certainty, dpr_ptr, &alt_dosage)) {
964 return 1;
965 }
966 } else {
967 if (unlikely((!ScanadvDouble(gtext_iter, &alt_dosage)) || (alt_dosage < 0.0))) {
968 return 1;
969 }
970 if (is_haploid) {
971 // possible todo: allow this to be suppressed (maybe upstream of this
972 // function); 1000 Genomes phase 1 haploid dosages are still on 0..2
973 // scale
974 // right now the best approach for importing those files is commenting
975 // out this line and recompiling...
976 if (import_dosage_certainty != 0.0) {
977 // quasi-bugfix (19 Feb 2019): dosage=DS import should respect
978 // --import-dosage-certainty
979 if (((1.0 - alt_dosage) <= import_dosage_certainty) && (alt_dosage <= import_dosage_certainty)) {
980 *dpr_ptr = kDosageParseForceMissing;
981 return 1;
982 }
983 }
984 alt_dosage *= 2;
985 } else {
986 if (import_dosage_certainty != 0.0) {
987 const double dist_from_1 = fabs(1.0 - alt_dosage);
988 if ((1.0 - dist_from_1 <= import_dosage_certainty) && (dist_from_1 <= import_dosage_certainty)) {
989 *dpr_ptr = kDosageParseForceMissing;
990 return 1;
991 }
992 }
993 }
994 if (unlikely(alt_dosage > 2.0)) {
995 return 1;
996 }
997 }
998 *dosage_int_ptr = S_CAST(int32_t, alt_dosage * kDosageMid + 0.5);
999 return 0;
1000 }
1001
1002 BoolErr ParseVcfBiallelicHds(const char* gtext_iter, const char* gtext_end, uint32_t dosage_field_idx, uint32_t hds_field_idx, uint32_t is_haploid, uint32_t dosage_is_gp, double import_dosage_certainty, DosageParseResult* dpr_ptr, uint32_t* dosage_int_ptr, int32_t* cur_dphase_delta_ptr, uint32_t* hds_valid_ptr) {
1003 // assumes dpr initialized to kDosageParseOk
1004 // assumes cur_dphase_delta initialized to 0
1005 // assumes hds_valid initialized to 0
1006 // assumes dosage_field_idx != UINT32_MAX and/or hds_field_idx != UINT32_MAX
1007 // returns 1 if missing OR parsing error. error: dpr still kDosageParseOk,
1008 // unless kDosageParsePolyploid.
1009
1010 if (hds_field_idx != UINT32_MAX) {
1011 // search for HDS first, then DS
1012 const char* hds_gtext_iter = gtext_iter;
1013 if (hds_field_idx) {
1014 hds_gtext_iter = AdvToNthDelimChecked(gtext_iter, gtext_end, hds_field_idx, ':');
1015 if (!hds_gtext_iter) {
1016 goto ParseVcfBiallelicHdsSkip;
1017 }
1018 ++hds_gtext_iter;
1019 }
1020 if ((hds_gtext_iter[0] != '?') && ((hds_gtext_iter[0] != '.') || (ctou32(hds_gtext_iter[1]) - 48 < 10))) {
1021 double dosage1;
1022 // tried implementing fast path for '0', '1', '0,0', '1,1'; only helped
1023 // ~10% in HDS-force case
1024 hds_gtext_iter = ScanadvDouble(hds_gtext_iter, &dosage1);
1025 if (unlikely((!hds_gtext_iter) || (dosage1 < 0.0) || (dosage1 > 1.0))) {
1026 return 1;
1027 }
1028 // if hds_valid and (cur_dphase_delta == 0), caller should override
1029 // hardcall-phase
1030 *hds_valid_ptr = 1;
1031 if (*hds_gtext_iter != ',') {
1032 if (import_dosage_certainty != 0.0) {
1033 if ((1.0 - dosage1 <= import_dosage_certainty) && (dosage1 <= import_dosage_certainty)) {
1034 *dpr_ptr = kDosageParseForceMissing;
1035 return 1;
1036 }
1037 }
1038 *dosage_int_ptr = S_CAST(int32_t, dosage1 * kDosageMax + 0.5);
1039 return 0;
1040 }
1041 ++hds_gtext_iter;
1042 // don't permit HDS half-calls
1043 double dosage2;
1044 hds_gtext_iter = ScanadvDouble(hds_gtext_iter, &dosage2);
1045 if (unlikely((!hds_gtext_iter) || (dosage2 < 0.0) || (dosage2 > 1.0))) {
1046 return 1;
1047 }
1048 if (unlikely(*hds_gtext_iter == ',')) {
1049 *dpr_ptr = kDosageParsePolyploid;
1050 return 1;
1051 }
1052 const double dosage_sum = dosage1 + dosage2;
1053 if (import_dosage_certainty != 0.0) {
1054 // Assume maximal het probability.
1055 const double dist_from_1 = fabs(1.0 - dosage_sum);
1056 if ((1.0 - dist_from_1 <= import_dosage_certainty) && (dist_from_1 <= import_dosage_certainty)) {
1057 *dpr_ptr = kDosageParseForceMissing;
1058 return 1;
1059 }
1060 }
1061
1062 // force this to be nonnegative, since static_cast<int32_t> rounds
1063 // negative numbers toward zero
1064 const double dosage_diffp1 = 1.0 + dosage1 - dosage2;
1065
1066 *dosage_int_ptr = S_CAST(int32_t, dosage_sum * kDosageMid + 0.5);
1067 *cur_dphase_delta_ptr = S_CAST(int32_t, dosage_diffp1 * kDosageMid + 0.5) - kDosageMid;
1068 return 0;
1069 }
1070 ParseVcfBiallelicHdsSkip:
1071 if (dosage_field_idx == UINT32_MAX) {
1072 *dpr_ptr = kDosageParseMissing;
1073 return 1;
1074 }
1075 }
1076 return ParseVcfBiallelicDosage(gtext_iter, gtext_end, dosage_field_idx, is_haploid, dosage_is_gp, import_dosage_certainty, dpr_ptr, dosage_int_ptr);
1077 }
1078
1079 ENUM_U31_DEF_START()
1080 kVcfParseOk,
1081 kVcfParseMissingTokens,
1082 kVcfParseInvalidGt,
1083 kVcfParseHalfCallError,
1084 kVcfParseInvalidDosage,
1085 kVcfParsePolyploidError
1086 ENUM_U31_DEF_END(VcfParseErr);
1087
1088 VcfParseErr VcfScanBiallelicHdsLine(const VcfImportContext* vicp, const char* format_end, uint32_t* phase_or_dosage_found_ptr, char** line_iter_ptr) {
1089 // Either just DS, or DS+HDS.
1090 // only need to find phase *or* dosage
1091 const uint32_t gt_exists = vicp->vibc.gt_exists;
1092 const uint32_t sample_ct = vicp->vibc.sample_ct;
1093 const uint32_t hds_field_idx = vicp->hds_field_idx;
1094 // special case: if there is no GT or HDS field, there can't be any phase
1095 // information; we're only here to check for a non-integer dosage. So if
1096 // there either (i) aren't any '.' characters, or (ii) every second character
1097 // is a '\t', we can early-exit.
1098 if ((!gt_exists) && (hds_field_idx == UINT32_MAX)) {
1099 const char* dot_or_lf_ptr = S_CAST(const char*, rawmemchr2(format_end, '.', '\n'));
1100 if (*dot_or_lf_ptr == '\n') {
1101 *line_iter_ptr = K_CAST(char*, dot_or_lf_ptr);
1102 return kVcfParseOk;
1103 }
1104 const char* lf_ptr = AdvToDelim(dot_or_lf_ptr, '\n');
1105 if (lf_ptr[-1] == '\r') {
1106 --lf_ptr;
1107 }
1108 const uintptr_t body_len = lf_ptr - format_end;
1109 if (body_len <= 2 * sample_ct) {
1110 if (unlikely(body_len < 2 * sample_ct)) {
1111 return kVcfParseMissingTokens;
1112 }
1113 // TODO: check for alternate tabs
1114 }
1115 }
1116 const VcfHalfCall halfcall_mode = vicp->vibc.halfcall_mode;
1117 const uint32_t error_on_polyploid = vicp->vibc.error_on_polyploid;
1118 STD_ARRAY_KREF(uint32_t, 2) qual_field_skips = vicp->vibc.qual_field_skips;
1119 STD_ARRAY_KREF(int32_t, 2) qual_line_mins = vicp->vibc.qual_line_mins;
1120 STD_ARRAY_KREF(int32_t, 2) qual_line_maxs = vicp->vibc.qual_line_maxs;
1121 const uint32_t qual_field_ct = vicp->vibc.qual_field_ct;
1122
1123 const uint32_t dosage_erase_halfdist = vicp->dosage_erase_halfdist;
1124 const double import_dosage_certainty = vicp->import_dosage_certainty;
1125 const uint32_t dosage_field_idx = vicp->dosage_field_idx;
1126
1127 const char* dosagescan_iter = format_end;
1128 uint32_t cur_gt_phased = 0;
1129 uint32_t is_haploid = 0;
1130 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1131 const char* cur_gtext_start = ++dosagescan_iter;
1132 const char* cur_gtext_end = FirstPrespace(dosagescan_iter);
1133 if (unlikely((*cur_gtext_end != '\t') && (sample_idx + 1 != sample_ct))) {
1134 return kVcfParseMissingTokens;
1135 }
1136 dosagescan_iter = cur_gtext_end;
1137 if (qual_field_ct && VcfCheckQuals(qual_field_skips, qual_line_mins, qual_line_maxs, cur_gtext_start, cur_gtext_end, qual_field_ct)) {
1138 continue;
1139 }
1140 if (gt_exists) {
1141 cur_gt_phased = (cur_gtext_start[1] == '|');
1142 is_haploid = (cur_gtext_start[1] != '/') && (!cur_gt_phased);
1143 }
1144 DosageParseResult dpr = kDosageParseOk;
1145 int32_t cur_dphase_delta = 0;
1146 uint32_t hds_valid = 0;
1147 uint32_t dosage_int;
1148 if (ParseVcfBiallelicHds(cur_gtext_start, cur_gtext_end, dosage_field_idx, hds_field_idx, is_haploid, 0, import_dosage_certainty, &dpr, &dosage_int, &cur_dphase_delta, &hds_valid)) {
1149 if (unlikely(!dpr)) {
1150 return kVcfParseInvalidDosage;
1151 }
1152 if (dpr == kDosageParsePolyploid) {
1153 if (unlikely(error_on_polyploid)) {
1154 return kVcfParsePolyploidError;
1155 }
1156 dpr = kDosageParseForceMissing;
1157 } else if ((dpr != kDosageParseForceMissing) && cur_gt_phased && VcfIsHetShort(cur_gtext_start, halfcall_mode)) {
1158 goto VcfScanBiallelicHdsLine_found;
1159 }
1160 } else if (cur_dphase_delta) {
1161 const uint32_t dphase_side1 = dosage_int + cur_dphase_delta;
1162 const uint32_t dphase_side2 = dosage_int - cur_dphase_delta;
1163 const uint32_t dphase_halfdist1 = DphaseHalfdist(dphase_side1);
1164 const uint32_t dphase_halfdist2 = DphaseHalfdist(dphase_side2);
1165 const uint32_t dphase_erase_halfdist = dosage_erase_halfdist + kDosage4th;
1166 if ((dphase_halfdist1 < dphase_erase_halfdist) ||
1167 (dphase_halfdist2 < dphase_erase_halfdist) ||
1168 (((dphase_side1 + kDosageMid) ^ (dphase_side2 + kDosageMid)) & kDosageMax)) {
1169 goto VcfScanBiallelicHdsLine_found;
1170 }
1171 } else {
1172 const uint32_t cur_halfdist = BiallelicDosageHalfdist(dosage_int);
1173 if ((cur_halfdist < dosage_erase_halfdist) ||
1174 ((!hds_valid) && cur_gt_phased && VcfIsHetShort(cur_gtext_start, halfcall_mode))) {
1175 goto VcfScanBiallelicHdsLine_found;
1176 }
1177 }
1178 }
1179 while (0) {
1180 VcfScanBiallelicHdsLine_found:
1181 *phase_or_dosage_found_ptr = 1;
1182 }
1183 *line_iter_ptr = K_CAST(char*, dosagescan_iter);
1184 return kVcfParseOk;
1185 }
1186
1187 // either HDS, or both dosage and phase flags set
1188 VcfParseErr VcfConvertPhasedBiallelicDosageLine(const VcfImportContext* vicp, const char* linebuf_iter, uintptr_t* genovec, uintptr_t* phasepresent, uintptr_t* phaseinfo, uintptr_t* dosage_present, uintptr_t* dphase_present, Dosage** dosage_main_iter_ptr, SDosage** dphase_delta_iter_ptr) {
1189 const uint32_t sample_ct = vicp->vibc.sample_ct;
1190 const uint32_t sample_ctl2_m1 = (sample_ct - 1) / kBitsPerWordD2;
1191 const VcfHalfCall halfcall_mode = vicp->vibc.halfcall_mode;
1192 const uint32_t error_on_polyploid = vicp->vibc.error_on_polyploid;
1193 const uint32_t gt_exists = vicp->vibc.gt_exists;
1194 STD_ARRAY_KREF(uint32_t, 2) qual_field_skips = vicp->vibc.qual_field_skips;
1195 STD_ARRAY_KREF(int32_t, 2) qual_line_mins = vicp->vibc.qual_line_mins;
1196 STD_ARRAY_KREF(int32_t, 2) qual_line_maxs = vicp->vibc.qual_line_maxs;
1197 const uint32_t qual_field_ct = vicp->vibc.qual_field_ct;
1198
1199 Halfword* phasepresent_alias = R_CAST(Halfword*, phasepresent);
1200 Halfword* phaseinfo_alias = R_CAST(Halfword*, phaseinfo);
1201 const uint32_t dosage_is_gp = vicp->dosage_is_gp;
1202 const uint32_t dosage_erase_halfdist = vicp->dosage_erase_halfdist;
1203 const uint32_t dphase_erase_halfdist = dosage_erase_halfdist + kDosage4th;
1204 const double import_dosage_certainty = vicp->import_dosage_certainty;
1205 const uint32_t dosage_field_idx = vicp->dosage_field_idx;
1206 const uint32_t hds_field_idx = vicp->hds_field_idx;
1207 Halfword* dosage_present_alias = R_CAST(Halfword*, dosage_present);
1208 Halfword* dphase_present_alias = R_CAST(Halfword*, dphase_present);
1209 Dosage* dosage_main_iter = *dosage_main_iter_ptr;
1210 SDosage* dphase_delta_iter = *dphase_delta_iter_ptr;
1211 uint32_t inner_loop_last = kBitsPerWordD2 - 1;
1212 uint32_t cur_gt_phased = 0;
1213 uint32_t is_haploid = 0;
1214 for (uint32_t widx = 0; ; ++widx) {
1215 if (widx >= sample_ctl2_m1) {
1216 if (widx > sample_ctl2_m1) {
1217 if (widx % 2) {
1218 phasepresent_alias[widx] = 0;
1219 // phaseinfo doesn't matter
1220 dosage_present_alias[widx] = 0;
1221 dphase_present_alias[widx] = 0;
1222 }
1223 break;
1224 }
1225 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
1226 }
1227 uintptr_t genovec_word = 0;
1228 uint32_t phasepresent_hw = 0;
1229 uint32_t phaseinfo_hw = 0;
1230 uint32_t dosage_present_hw = 0;
1231 uint32_t dphase_present_hw = 0;
1232 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
1233 const char* cur_gtext_end = FirstPrespace(linebuf_iter);
1234 if (unlikely((*cur_gtext_end != '\t') && ((sample_idx_lowbits != inner_loop_last) || (widx != sample_ctl2_m1)))) {
1235 return kVcfParseMissingTokens;
1236 }
1237 uintptr_t cur_geno = 3;
1238 if (!(qual_field_ct && VcfCheckQuals(qual_field_skips, qual_line_mins, qual_line_maxs, linebuf_iter, cur_gtext_end, qual_field_ct))) {
1239 // We now parse dosage first. Only care about the hardcall if
1240 // (i) there's no dosage, or
1241 // (ii) there's no phased dosage, and it's a phased het.
1242 if (gt_exists) {
1243 cur_gt_phased = (linebuf_iter[1] == '|');
1244 is_haploid = (linebuf_iter[1] != '/') && (!cur_gt_phased);
1245 }
1246 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
1247 DosageParseResult dpr = kDosageParseOk;
1248 int32_t cur_dphase_delta = 0;
1249 uint32_t hds_valid = 0;
1250 uint32_t dosage_int;
1251 if (!ParseVcfBiallelicHds(linebuf_iter, cur_gtext_end, dosage_field_idx, hds_field_idx, is_haploid, dosage_is_gp, import_dosage_certainty, &dpr, &dosage_int, &cur_dphase_delta, &hds_valid)) {
1252 if (hds_valid) {
1253 const uint32_t dphase_halfdist1 = DphaseHalfdist(dosage_int + cur_dphase_delta);
1254 const uint32_t dphase_halfdist2 = DphaseHalfdist(dosage_int - cur_dphase_delta);
1255 if ((dphase_halfdist1 < dphase_erase_halfdist) || (dphase_halfdist2 < dphase_erase_halfdist)) {
1256 // No need to fill cur_geno here, since it'll get corrected by
1257 // --hard-call-threshold.
1258 dosage_present_hw |= shifted_bit;
1259 *dosage_main_iter++ = dosage_int;
1260 if (cur_dphase_delta) {
1261 dphase_present_hw |= shifted_bit;
1262 *dphase_delta_iter++ = cur_dphase_delta;
1263 }
1264 } else {
1265 // Not saving dosage, since it's too close to an integer
1266 // (--dosage-erase-threshold). Just directly synthesize the
1267 // hardcall we need.
1268 cur_geno = (dosage_int + kDosage4th) / kDosageMid;
1269 if (cur_geno == 1) {
1270 // Since dphase_erase_halfdist >= 8193, dphase_halfdist1 and
1271 // dphase_halfdist2 are both in [0, 8191] or [24577, 32768], so
1272 // it's always appropriate to save hardcall-phase.
1273 phasepresent_hw |= shifted_bit;
1274 if (cur_dphase_delta > 0) {
1275 phaseinfo_hw |= shifted_bit;
1276 }
1277 }
1278 }
1279 goto VcfConvertPhasedBiallelicDosageLine_geno_done;
1280 }
1281 // defer handling of unphased dosage
1282 } else if (unlikely(!dpr)) {
1283 return kVcfParseInvalidDosage;
1284 } else if (dpr == kDosageParseForceMissing) {
1285 // bugfix (20 Feb 2019): if forced missing due to
1286 // --import-dosage-certainty, gt_exists must be ignored
1287 goto VcfConvertPhasedBiallelicDosageLine_geno_done;
1288 } else if (dpr == kDosageParsePolyploid) {
1289 if (unlikely(error_on_polyploid)) {
1290 return kVcfParsePolyploidError;
1291 }
1292 goto VcfConvertPhasedBiallelicDosageLine_geno_done;
1293 }
1294 if (gt_exists) {
1295 cur_geno = ctow(*linebuf_iter) - 48;
1296 // this nasty code should be spelled out in as few places as possible
1297 if (cur_geno <= 1) {
1298 if (is_haploid) {
1299 cur_geno *= 2;
1300 } else {
1301 const char polyploid_char = linebuf_iter[3];
1302 // Update (26 Sep 2023): "x/y/." is no longer treated as "x/y".
1303 // If someone's depending on that behavior, add another
1304 // --polyploid mode for it.
1305 if ((polyploid_char == '/') || (polyploid_char == '|')) {
1306 if (unlikely(error_on_polyploid)) {
1307 return kVcfParsePolyploidError;
1308 }
1309 cur_geno = 3;
1310 } else {
1311 const uintptr_t second_allele_idx = ctow(linebuf_iter[2]) - 48;
1312 if (second_allele_idx <= 1) {
1313 cur_geno += second_allele_idx;
1314 if (cur_gt_phased && (cur_geno == 1)) {
1315 phasepresent_hw |= shifted_bit;
1316 #ifdef USE_AVX2
1317 // See comment in VcfConvertPhasedBiallelicLine().
1318 if (!second_allele_idx) {
1319 // 1|0
1320 phaseinfo_hw |= shifted_bit;
1321 }
1322 #else
1323 phaseinfo_hw |= shifted_bit & (second_allele_idx - 1);
1324 #endif
1325 }
1326 } else if (unlikely(second_allele_idx != (~k0LU) * 2)) {
1327 // not '.'
1328 return kVcfParseInvalidGt;
1329 } else if (halfcall_mode == kVcfHalfCallMissing) {
1330 cur_geno = 3;
1331 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
1332 return kVcfParseHalfCallError;
1333 } else {
1334 // kVcfHalfCallHaploid, kVcfHalfCallReference
1335 cur_geno <<= halfcall_mode;
1336 }
1337 }
1338 }
1339 } else if (unlikely(cur_geno != (~k0LU) * 2)) {
1340 // not '.'
1341 return kVcfParseInvalidGt;
1342 } else if (halfcall_mode != kVcfHalfCallMissing) {
1343 const char second_allele_char = linebuf_iter[2];
1344 if ((second_allele_char != '.') && ((linebuf_iter[1] == '/') || (linebuf_iter[1] == '|'))) {
1345 cur_geno = ctow(second_allele_char) - 48;
1346 if (unlikely(cur_geno > 1)) {
1347 return kVcfParseInvalidGt;
1348 }
1349 if (unlikely(halfcall_mode == kVcfHalfCallError)) {
1350 return kVcfParseHalfCallError;
1351 }
1352 // kVcfHalfCallHaploid, kVcfHalfCallReference
1353 cur_geno <<= halfcall_mode;
1354 } else {
1355 cur_geno = 3;
1356 }
1357 } else {
1358 cur_geno = 3;
1359 }
1360 }
1361 if (!dpr) {
1362 // now actually handle the unphased dosage
1363 const uint32_t cur_halfdist = BiallelicDosageHalfdist(dosage_int);
1364 if (cur_halfdist < dosage_erase_halfdist) {
1365 // ok for cur_geno to be 'wrong' for now, since it'll get corrected
1366 // by --hard-call-threshold
1367 dosage_present_hw |= shifted_bit;
1368 *dosage_main_iter++ = dosage_int;
1369 } else {
1370 // Not saving dosage, since it's too close to an integer, except
1371 // possibly in the implicit-phased-dosage edge case.
1372 // If that integer actually conflicts with the hardcall, we must
1373 // override the hardcall.
1374 cur_geno = (dosage_int + kDosage4th) / kDosageMid;
1375 if (phasepresent_hw & shifted_bit) {
1376 if (cur_geno != 1) {
1377 // Hardcall-phase no longer applies.
1378 phasepresent_hw ^= shifted_bit;
1379 } else if (cur_halfdist * 2 < dphase_erase_halfdist) {
1380 // Implicit phased-dosage, e.g. 0|0.99. More stringent
1381 // dosage_erase_halfdist applies.
1382 dosage_present_hw |= shifted_bit;
1383 *dosage_main_iter++ = dosage_int;
1384 }
1385 }
1386 }
1387 }
1388 }
1389 VcfConvertPhasedBiallelicDosageLine_geno_done:
1390 genovec_word |= cur_geno << (2 * sample_idx_lowbits);
1391 linebuf_iter = &(cur_gtext_end[1]);
1392 }
1393 genovec[widx] = genovec_word;
1394 phasepresent_alias[widx] = phasepresent_hw;
1395 phaseinfo_alias[widx] = phaseinfo_hw;
1396 dosage_present_alias[widx] = dosage_present_hw;
1397 dphase_present_alias[widx] = dphase_present_hw;
1398 }
1399 *dosage_main_iter_ptr = dosage_main_iter;
1400 *dphase_delta_iter_ptr = dphase_delta_iter;
1401 return kVcfParseOk;
1402 }
1403
1404 // alt_ct < 10
1405 uintptr_t VcfScanShortallelicLine(const VcfImportBaseContext* vibcp, const char* format_end, char** line_iter_ptr) {
1406 // Just check for a phased het.
1407 const VcfHalfCall halfcall_mode = vibcp->halfcall_mode;
1408 STD_ARRAY_KREF(uint32_t, 2) qual_field_skips = vibcp->qual_field_skips;
1409 STD_ARRAY_KREF(int32_t, 2) qual_line_mins = vibcp->qual_line_mins;
1410 STD_ARRAY_KREF(int32_t, 2) qual_line_maxs = vibcp->qual_line_maxs;
1411 const uint32_t qual_field_ct = vibcp->qual_field_ct;
1412 const char* phasescan_iter = format_end;
1413 uintptr_t retval = 0;
1414 while (1) {
1415 // this should quickly fail if there are no phased hardcalls at all.
1416 if (incr_strchrnul_n_mov('|', &phasescan_iter)) {
1417 goto VcfScanShortallelicLine_no_phased_het;
1418 }
1419 if (phasescan_iter[-2] != '\t') {
1420 // at least one other FORMAT field uses the '|' character.
1421 // switch to iterating over tabs.
1422 break;
1423 }
1424 if (VcfIsHetShort(&(phasescan_iter[-1]), halfcall_mode)) {
1425 if ((!qual_field_ct) || (!VcfCheckQuals(qual_field_skips, qual_line_mins, qual_line_maxs, phasescan_iter, FirstPrespace(&(phasescan_iter[2])), qual_field_ct))) {
1426 goto VcfScanShortallelicLine_phased_het_found;
1427 }
1428 }
1429 if (incr_strchrnul_n_mov('\t', &phasescan_iter)) {
1430 goto VcfScanShortallelicLine_no_phased_het;
1431 }
1432 }
1433 while (!incr_strchrnul_n_mov('\t', &phasescan_iter)) {
1434 if ((phasescan_iter[2] != '|') || (!VcfIsHetShort(&(phasescan_iter[1]), halfcall_mode))) {
1435 continue;
1436 }
1437 if ((!qual_field_ct) || (!VcfCheckQuals(qual_field_skips, qual_line_mins, qual_line_maxs, phasescan_iter, FirstPrespace(&(phasescan_iter[4])), qual_field_ct))) {
1438 goto VcfScanShortallelicLine_phased_het_found;
1439 }
1440 }
1441 while (0) {
1442 VcfScanShortallelicLine_phased_het_found:
1443 retval = 1;
1444 }
1445 VcfScanShortallelicLine_no_phased_het:
1446 *line_iter_ptr = K_CAST(char*, phasescan_iter);
1447 return retval;
1448 }
1449
1450 VcfParseErr VcfConvertUnphasedBiallelicLine(const VcfImportBaseContext* vibcp, const char* linebuf_iter, uintptr_t* genovec) {
1451 const uint32_t sample_ct = vibcp->sample_ct;
1452 const uint32_t sample_ctl2_m1 = (sample_ct - 1) / kBitsPerWordD2;
1453 const VcfHalfCall halfcall_mode = vibcp->halfcall_mode;
1454 const uint32_t error_on_polyploid = vibcp->error_on_polyploid;
1455 STD_ARRAY_KREF(uint32_t, 2) qual_field_skips = vibcp->qual_field_skips;
1456 STD_ARRAY_KREF(int32_t, 2) qual_line_mins = vibcp->qual_line_mins;
1457 STD_ARRAY_KREF(int32_t, 2) qual_line_maxs = vibcp->qual_line_maxs;
1458 const uint32_t qual_field_ct = vibcp->qual_field_ct;
1459
1460 uint32_t inner_loop_last = kBitsPerWordD2 - 1;
1461 for (uint32_t widx = 0; ; ++widx) {
1462 if (widx >= sample_ctl2_m1) {
1463 if (widx > sample_ctl2_m1) {
1464 break;
1465 }
1466 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
1467 }
1468 uintptr_t genovec_word = 0;
1469 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
1470 const char* cur_gtext_end = FirstPrespace(linebuf_iter);
1471 if (unlikely((*cur_gtext_end != '\t') && ((sample_idx_lowbits != inner_loop_last) || (widx != sample_ctl2_m1)))) {
1472 return kVcfParseMissingTokens;
1473 }
1474 uintptr_t cur_geno;
1475 if (qual_field_ct && VcfCheckQuals(qual_field_skips, qual_line_mins, qual_line_maxs, linebuf_iter, cur_gtext_end, qual_field_ct)) {
1476 // skipping polyploid check for now
1477 cur_geno = 3;
1478 } else {
1479 // Still must check for '|', since phasing_flags bit is unset when all
1480 // entries are e.g. 0|0. We just don't bother distinguishing it from
1481 // '/'.
1482 const uint32_t is_haploid = (linebuf_iter[1] != '/') && (linebuf_iter[1] != '|');
1483 cur_geno = ctow(*linebuf_iter) - 48;
1484 if (cur_geno <= 1) {
1485 if (is_haploid) {
1486 cur_geno *= 2;
1487 } else {
1488 const char polyploid_char = linebuf_iter[3];
1489 if ((polyploid_char == '/') || (polyploid_char == '|')) {
1490 if (unlikely(error_on_polyploid)) {
1491 return kVcfParsePolyploidError;
1492 }
1493 cur_geno = 3;
1494 } else {
1495 // bugfix (26 Jul 2018): this needs to be ctow, not ctou32
1496 const uintptr_t second_allele_idx = ctow(linebuf_iter[2]) - 48;
1497 if (second_allele_idx <= 1) {
1498 cur_geno += second_allele_idx;
1499 } else if (unlikely(second_allele_idx != (~k0LU) * 2)) {
1500 // not '.'
1501 return kVcfParseInvalidGt;
1502 } else if (halfcall_mode == kVcfHalfCallMissing) {
1503 cur_geno = 3;
1504 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
1505 return kVcfParseHalfCallError;
1506 } else {
1507 // kVcfHalfCallHaploid, kVcfHalfCallReference
1508 cur_geno <<= halfcall_mode;
1509 }
1510 }
1511 }
1512 } else {
1513 if (unlikely(cur_geno != (~k0LU) * 2)) {
1514 // not '.'
1515 return kVcfParseInvalidGt;
1516 }
1517 cur_geno = 3;
1518 if (!is_haploid) {
1519 // ./x
1520 const char polyploid_char = linebuf_iter[3];
1521 if ((polyploid_char == '/') || (polyploid_char == '|')) {
1522 if (unlikely(error_on_polyploid)) {
1523 return kVcfParsePolyploidError;
1524 }
1525 // could perform InvalidGt check?
1526 } else {
1527 const char second_allele_char = linebuf_iter[2];
1528 if ((second_allele_char != '.') && (halfcall_mode != kVcfHalfCallMissing)) {
1529 cur_geno = ctow(second_allele_char) - 48;
1530 if (unlikely(cur_geno > 1)) {
1531 return kVcfParseInvalidGt;
1532 }
1533 if (unlikely(halfcall_mode == kVcfHalfCallError)) {
1534 return kVcfParseHalfCallError;
1535 }
1536 // kVcfHalfCallHaploid, kVcfHalfCallReference
1537 cur_geno <<= halfcall_mode;
1538 }
1539 }
1540 }
1541 }
1542 }
1543 genovec_word |= cur_geno << (2 * sample_idx_lowbits);
1544 linebuf_iter = &(cur_gtext_end[1]);
1545 }
1546 genovec[widx] = genovec_word;
1547 }
1548 return kVcfParseOk;
1549 }
1550
1551 VcfParseErr VcfConvertUnphasedMultiallelicLine(const VcfImportBaseContext* vibcp, const char* linebuf_iter, uintptr_t allele_ct, uint32_t* __restrict patch_01_ctp, uint32_t* __restrict patch_10_ctp, uintptr_t* __restrict genovec, uintptr_t* __restrict patch_01_set, AlleleCode* __restrict patch_01_vals, uintptr_t* __restrict patch_10_set, AlleleCode* __restrict patch_10_vals) {
1552 const uint32_t sample_ct = vibcp->sample_ct;
1553 const uint32_t sample_ctl2_m1 = (sample_ct - 1) / kBitsPerWordD2;
1554 const VcfHalfCall halfcall_mode = vibcp->halfcall_mode;
1555 const uint32_t error_on_polyploid = vibcp->error_on_polyploid;
1556 STD_ARRAY_KREF(uint32_t, 2) qual_field_skips = vibcp->qual_field_skips;
1557 STD_ARRAY_KREF(int32_t, 2) qual_line_mins = vibcp->qual_line_mins;
1558 STD_ARRAY_KREF(int32_t, 2) qual_line_maxs = vibcp->qual_line_maxs;
1559 const uint32_t qual_field_ct = vibcp->qual_field_ct;
1560 Halfword* patch_01_set_alias = R_CAST(Halfword*, patch_01_set);
1561 Halfword* patch_10_set_alias = R_CAST(Halfword*, patch_10_set);
1562 AlleleCode* patch_01_vals_iter = patch_01_vals;
1563 AlleleCode* patch_10_vals_iter = patch_10_vals;
1564
1565 uint32_t inner_loop_last = kBitsPerWordD2 - 1;
1566 for (uint32_t widx = 0; ; ++widx) {
1567 if (widx >= sample_ctl2_m1) {
1568 if (widx > sample_ctl2_m1) {
1569 if (widx % 2) {
1570 // might not need this, but lets play it safe
1571 patch_01_set_alias[widx] = 0;
1572 patch_10_set_alias[widx] = 0;
1573 }
1574 break;
1575 }
1576 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
1577 }
1578 uintptr_t genovec_word = 0;
1579 uint32_t patch_01_hw = 0;
1580 uint32_t patch_10_hw = 0;
1581 if (allele_ct <= 10) {
1582 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
1583 const char* cur_gtext_end = FirstPrespace(linebuf_iter);
1584 if (unlikely((*cur_gtext_end != '\t') && ((sample_idx_lowbits != inner_loop_last) || (widx != sample_ctl2_m1)))) {
1585 return kVcfParseMissingTokens;
1586 }
1587 uintptr_t cur_geno;
1588 if (qual_field_ct && VcfCheckQuals(qual_field_skips, qual_line_mins, qual_line_maxs, linebuf_iter, cur_gtext_end, qual_field_ct)) {
1589 // skipping polyploid check for now
1590 cur_geno = 3;
1591 } else {
1592 const uint32_t is_haploid = (linebuf_iter[1] != '/') && (linebuf_iter[1] != '|');
1593 cur_geno = ctow(*linebuf_iter) - 48;
1594 if (cur_geno < allele_ct) {
1595 if (is_haploid) {
1596 if (cur_geno <= 1) {
1597 cur_geno *= 2;
1598 } else {
1599 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
1600 patch_10_hw |= shifted_bit;
1601 *patch_10_vals_iter++ = cur_geno;
1602 *patch_10_vals_iter++ = cur_geno;
1603 cur_geno = 2;
1604 }
1605 } else {
1606 const char polyploid_char = linebuf_iter[3];
1607 if ((polyploid_char == '/') || (polyploid_char == '|')) {
1608 if (unlikely(error_on_polyploid)) {
1609 return kVcfParsePolyploidError;
1610 }
1611 cur_geno = 3;
1612 } else {
1613 uintptr_t second_allele_idx = ctow(linebuf_iter[2]) - 48;
1614 if (second_allele_idx < allele_ct) {
1615 if (cur_geno <= 1) {
1616 if (second_allele_idx <= 1) {
1617 cur_geno += second_allele_idx;
1618 } else {
1619 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
1620 if (!cur_geno) {
1621 patch_01_hw |= shifted_bit;
1622 *patch_01_vals_iter++ = second_allele_idx;
1623 } else {
1624 patch_10_hw |= shifted_bit;
1625 *patch_10_vals_iter++ = 1;
1626 *patch_10_vals_iter++ = second_allele_idx;
1627 }
1628 ++cur_geno;
1629 }
1630 } else {
1631 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
1632 if (!second_allele_idx) {
1633 patch_01_hw |= shifted_bit;
1634 *patch_01_vals_iter++ = cur_geno;
1635 cur_geno = 1;
1636 } else {
1637 patch_10_hw |= shifted_bit;
1638 if (second_allele_idx < cur_geno) {
1639 // this is not explicitly disallowed, but should almost
1640 // never happen
1641 const uintptr_t ulii = cur_geno;
1642 cur_geno = second_allele_idx;
1643 second_allele_idx = ulii;
1644 }
1645 *patch_10_vals_iter++ = cur_geno;
1646 *patch_10_vals_iter++ = second_allele_idx;
1647 cur_geno = 2;
1648 }
1649 }
1650 } else {
1651 // second_allele_idx >= allele_ct
1652 if (unlikely(second_allele_idx != (~k0LU) * 2)) {
1653 // not '.'
1654 return kVcfParseInvalidGt;
1655 }
1656 if (halfcall_mode == kVcfHalfCallMissing) {
1657 cur_geno = 3;
1658 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
1659 return kVcfParseHalfCallError;
1660 } else {
1661 // kVcfHalfCallHaploid, kVcfHalfCallReference
1662 if (cur_geno <= 1) {
1663 cur_geno <<= halfcall_mode;
1664 } else {
1665 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
1666 if (halfcall_mode == kVcfHalfCallReference) {
1667 patch_01_hw |= shifted_bit;
1668 *patch_01_vals_iter++ = cur_geno;
1669 cur_geno = 1;
1670 } else {
1671 patch_10_hw |= shifted_bit;
1672 *patch_10_vals_iter++ = cur_geno;
1673 *patch_10_vals_iter++ = cur_geno;
1674 cur_geno = 2;
1675 }
1676 }
1677 }
1678 }
1679 }
1680 }
1681 } else if (unlikely(cur_geno != (~k0LU) * 2)) {
1682 // not '.'
1683 return kVcfParseInvalidGt;
1684 } else {
1685 cur_geno = 3;
1686 if (!is_haploid) {
1687 // ./x
1688 const char polyploid_char = linebuf_iter[3];
1689 if ((polyploid_char == '/') || (polyploid_char == '|')) {
1690 if (unlikely(error_on_polyploid)) {
1691 return kVcfParsePolyploidError;
1692 }
1693 // could perform InvalidGt check?
1694 } else {
1695 const char second_allele_char = linebuf_iter[2];
1696 if ((second_allele_char != '.') && (halfcall_mode != kVcfHalfCallMissing)) {
1697 cur_geno = ctow(second_allele_char) - 48;
1698 if (unlikely(cur_geno >= allele_ct)) {
1699 return kVcfParseInvalidGt;
1700 }
1701 if (unlikely(halfcall_mode == kVcfHalfCallError)) {
1702 return kVcfParseHalfCallError;
1703 }
1704 // kVcfHalfCallHaploid, kVcfHalfCallReference
1705 if (cur_geno <= 1) {
1706 cur_geno <<= halfcall_mode;
1707 } else {
1708 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
1709 if (halfcall_mode == kVcfHalfCallReference) {
1710 patch_01_hw |= shifted_bit;
1711 *patch_01_vals_iter++ = cur_geno;
1712 cur_geno = 1;
1713 } else {
1714 patch_10_hw |= shifted_bit;
1715 *patch_10_vals_iter++ = cur_geno;
1716 *patch_10_vals_iter++ = cur_geno;
1717 cur_geno = 2;
1718 }
1719 }
1720 }
1721 }
1722 }
1723 }
1724 }
1725 genovec_word |= cur_geno << (2 * sample_idx_lowbits);
1726 linebuf_iter = &(cur_gtext_end[1]);
1727 }
1728 } else {
1729 // allele_ct > 10
1730 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
1731 const char* cur_gtext_end = FirstPrespace(linebuf_iter);
1732 if (unlikely((*cur_gtext_end != '\t') && ((sample_idx_lowbits != inner_loop_last) || (widx != sample_ctl2_m1)))) {
1733 return kVcfParseMissingTokens;
1734 }
1735 uintptr_t cur_geno;
1736 if (qual_field_ct && VcfCheckQuals(qual_field_skips, qual_line_mins, qual_line_maxs, linebuf_iter, cur_gtext_end, qual_field_ct)) {
1737 // skipping polyploid check for now
1738 cur_geno = 3;
1739 } else {
1740 cur_geno = ctow(*linebuf_iter) - 48;
1741 if (cur_geno < 10) {
1742 const char* gt_first_nondigit = &(linebuf_iter[1]);
1743 uintptr_t next_digit;
1744 for (; ; ++gt_first_nondigit) {
1745 next_digit = ctow(*gt_first_nondigit) - 48;
1746 if (next_digit >= 10) {
1747 break;
1748 }
1749 cur_geno = cur_geno * 10 + next_digit;
1750 if (cur_geno >= allele_ct) {
1751 return kVcfParseInvalidGt;
1752 }
1753 }
1754 // '/' = ascii 47, '|' = ascii 124 (i.e. 48 + 76)
1755 const uint32_t is_haploid = (next_digit != (~k0LU)) && (next_digit != 76);
1756 if (is_haploid) {
1757 if (cur_geno <= 1) {
1758 cur_geno *= 2;
1759 } else {
1760 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
1761 patch_10_hw |= shifted_bit;
1762 *patch_10_vals_iter++ = cur_geno;
1763 *patch_10_vals_iter++ = cur_geno;
1764 cur_geno = 2;
1765 }
1766 } else {
1767 const char* second_allele_iter = &(gt_first_nondigit[1]);
1768 uintptr_t second_allele_idx = ctow(*second_allele_iter++) - 48;
1769 if (second_allele_idx < 10) {
1770 for (; ; ++second_allele_iter) {
1771 next_digit = ctow(*second_allele_iter) - 48;
1772 if (next_digit >= 10) {
1773 break;
1774 }
1775 second_allele_idx = second_allele_idx * 10 + next_digit;
1776 if (second_allele_idx >= allele_ct) {
1777 return kVcfParseInvalidGt;
1778 }
1779 }
1780 if ((next_digit == ~k0LU) || (next_digit == 76)) {
1781 if (unlikely(error_on_polyploid)) {
1782 return kVcfParsePolyploidError;
1783 }
1784 cur_geno = 3;
1785 } else if (cur_geno <= 1) {
1786 if (second_allele_idx <= 1) {
1787 cur_geno += second_allele_idx;
1788 } else {
1789 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
1790 if (!cur_geno) {
1791 patch_01_hw |= shifted_bit;
1792 *patch_01_vals_iter++ = second_allele_idx;
1793 } else {
1794 patch_10_hw |= shifted_bit;
1795 *patch_10_vals_iter++ = 1;
1796 *patch_10_vals_iter++ = second_allele_idx;
1797 }
1798 ++cur_geno;
1799 }
1800 } else {
1801 // first_allele_idx == cur_geno >= 2
1802 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
1803 if (!second_allele_idx) {
1804 patch_01_hw |= shifted_bit;
1805 *patch_01_vals_iter++ = cur_geno;
1806 cur_geno = 1;
1807 } else {
1808 patch_10_hw |= shifted_bit;
1809 if (second_allele_idx < cur_geno) {
1810 const uintptr_t ulii = cur_geno;
1811 cur_geno = second_allele_idx;
1812 second_allele_idx = ulii;
1813 }
1814 *patch_10_vals_iter++ = cur_geno;
1815 *patch_10_vals_iter++ = second_allele_idx;
1816 cur_geno = 2;
1817 }
1818 }
1819 } else if (unlikely(second_allele_idx != (~k0LU) * 2)) {
1820 // not '.'
1821 return kVcfParseInvalidGt;
1822 } else {
1823 const char polyploid_char = *second_allele_iter;
1824 if ((polyploid_char == '/') || (polyploid_char == '|')) {
1825 if (unlikely(error_on_polyploid)) {
1826 return kVcfParsePolyploidError;
1827 }
1828 cur_geno = 3;
1829 } else if (halfcall_mode == kVcfHalfCallMissing) {
1830 cur_geno = 3;
1831 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
1832 return kVcfParseHalfCallError;
1833 } else {
1834 // kVcfHalfCallHaploid, kVcfHalfCallReference
1835 if (cur_geno <= 1) {
1836 cur_geno <<= halfcall_mode;
1837 } else {
1838 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
1839 if (halfcall_mode == kVcfHalfCallReference) {
1840 patch_01_hw |= shifted_bit;
1841 *patch_01_vals_iter++ = cur_geno;
1842 cur_geno = 1;
1843 } else {
1844 patch_10_hw |= shifted_bit;
1845 *patch_10_vals_iter++ = cur_geno;
1846 *patch_10_vals_iter++ = cur_geno;
1847 cur_geno = 2;
1848 }
1849 }
1850 }
1851 }
1852 }
1853 } else if (unlikely(cur_geno != (~k0LU) * 2)) {
1854 // not '.'
1855 return kVcfParseInvalidGt;
1856 } else {
1857 cur_geno = 3;
1858 const uint32_t is_haploid = (linebuf_iter[1] != '/') && (linebuf_iter[1] != '|');
1859 if (!is_haploid) {
1860 const char second_allele_first_char = linebuf_iter[2];
1861 if (second_allele_first_char == '.') {
1862 if (error_on_polyploid) {
1863 const char polyploid_char = linebuf_iter[3];
1864 if (unlikely((polyploid_char == '/') || (polyploid_char == '|'))) {
1865 return kVcfParsePolyploidError;
1866 }
1867 }
1868 } else {
1869 // don't check halfcall_mode == kVcfHalfCallMissing yet because
1870 // we want error_on_polyploid to work
1871 cur_geno = ctow(second_allele_first_char) - 48;
1872 if (unlikely(cur_geno >= 10)) {
1873 return kVcfParseInvalidGt;
1874 }
1875 uintptr_t next_digit;
1876 for (const char* second_allele_iter = &(linebuf_iter[3]); ; ++second_allele_iter) {
1877 next_digit = ctow(*second_allele_iter) - 48;
1878 if (next_digit >= 10) {
1879 break;
1880 }
1881 cur_geno = cur_geno * 10 + next_digit;
1882 if (unlikely(cur_geno >= allele_ct)) {
1883 return kVcfParseInvalidGt;
1884 }
1885 }
1886 if ((next_digit == ~k0LU) || (next_digit == 76)) {
1887 if (unlikely(error_on_polyploid)) {
1888 return kVcfParsePolyploidError;
1889 }
1890 cur_geno = 3;
1891 } else if (halfcall_mode != kVcfHalfCallMissing) {
1892 if (unlikely(halfcall_mode == kVcfHalfCallError)) {
1893 return kVcfParseHalfCallError;
1894 }
1895 // kVcfHalfCallHaploid, kVcfHalfCallReference
1896 if (cur_geno <= 1) {
1897 cur_geno <<= halfcall_mode;
1898 } else {
1899 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
1900 if (halfcall_mode == kVcfHalfCallReference) {
1901 patch_01_hw |= shifted_bit;
1902 *patch_01_vals_iter++ = cur_geno;
1903 cur_geno = 1;
1904 } else {
1905 patch_10_hw |= shifted_bit;
1906 *patch_10_vals_iter++ = cur_geno;
1907 *patch_10_vals_iter++ = cur_geno;
1908 cur_geno = 2;
1909 }
1910 }
1911 } else {
1912 // bugfix (3 Feb 2024)
1913 cur_geno = 3;
1914 }
1915 }
1916 }
1917 }
1918 }
1919 genovec_word |= cur_geno << (2 * sample_idx_lowbits);
1920 linebuf_iter = &(cur_gtext_end[1]);
1921 }
1922 }
1923 genovec[widx] = genovec_word;
1924 patch_01_set_alias[widx] = patch_01_hw;
1925 patch_10_set_alias[widx] = patch_10_hw;
1926 }
1927 *patch_01_ctp = patch_01_vals_iter - patch_01_vals;
1928 *patch_10_ctp = S_CAST(uintptr_t, patch_10_vals_iter - patch_10_vals) / 2;
1929 return kVcfParseOk;
1930 }
1931
1932 VcfParseErr VcfConvertPhasedBiallelicLine(const VcfImportBaseContext* vibcp, const char* linebuf_iter, uintptr_t* genovec, uintptr_t* phasepresent, uintptr_t* phaseinfo) {
1933 const uint32_t sample_ct = vibcp->sample_ct;
1934 const uint32_t sample_ctl2_m1 = (sample_ct - 1) / kBitsPerWordD2;
1935 const VcfHalfCall halfcall_mode = vibcp->halfcall_mode;
1936 const uint32_t error_on_polyploid = vibcp->error_on_polyploid;
1937 STD_ARRAY_KREF(uint32_t, 2) qual_field_skips = vibcp->qual_field_skips;
1938 STD_ARRAY_KREF(int32_t, 2) qual_line_mins = vibcp->qual_line_mins;
1939 STD_ARRAY_KREF(int32_t, 2) qual_line_maxs = vibcp->qual_line_maxs;
1940 const uint32_t qual_field_ct = vibcp->qual_field_ct;
1941 Halfword* phasepresent_alias = R_CAST(Halfword*, phasepresent);
1942 Halfword* phaseinfo_alias = R_CAST(Halfword*, phaseinfo);
1943
1944 uint32_t inner_loop_last = kBitsPerWordD2 - 1;
1945 for (uint32_t widx = 0; ; ++widx) {
1946 if (widx >= sample_ctl2_m1) {
1947 if (widx > sample_ctl2_m1) {
1948 if (widx % 2) {
1949 // might not need this, but lets play it safe
1950 phasepresent_alias[widx] = 0;
1951 }
1952 break;
1953 }
1954 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
1955 }
1956 uintptr_t genovec_word = 0;
1957 uint32_t phasepresent_hw = 0;
1958 uint32_t phaseinfo_hw = 0;
1959 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
1960 const char* cur_gtext_end = FirstPrespace(linebuf_iter);
1961 if (unlikely((*cur_gtext_end != '\t') && ((sample_idx_lowbits != inner_loop_last) || (widx != sample_ctl2_m1)))) {
1962 return kVcfParseMissingTokens;
1963 }
1964 uintptr_t cur_geno;
1965 if (qual_field_ct && VcfCheckQuals(qual_field_skips, qual_line_mins, qual_line_maxs, linebuf_iter, cur_gtext_end, qual_field_ct)) {
1966 // skipping polyploid check for now
1967 cur_geno = 3;
1968 } else {
1969 const uint32_t is_phased = (linebuf_iter[1] == '|');
1970 const uint32_t is_haploid = (!is_phased) && (linebuf_iter[1] != '/');
1971 cur_geno = ctow(*linebuf_iter) - 48;
1972 if (cur_geno <= 1) {
1973 if (is_haploid) {
1974 cur_geno *= 2;
1975 } else {
1976 const char polyploid_char = linebuf_iter[3];
1977 if ((polyploid_char == '/') || (polyploid_char == '|')) {
1978 if (unlikely(error_on_polyploid)) {
1979 return kVcfParsePolyploidError;
1980 }
1981 cur_geno = 3;
1982 } else {
1983 const uintptr_t second_allele_idx = ctow(linebuf_iter[2]) - 48;
1984 if (second_allele_idx <= 1) {
1985 cur_geno += second_allele_idx;
1986 if (is_phased && (cur_geno == 1)) {
1987 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
1988 phasepresent_hw |= shifted_bit;
1989 #ifdef USE_AVX2
1990 // compiler seems to automatically handle this well iff it
1991 // has access to BMI/BMI2 instructions, at least on my main
1992 // dev Mac
1993 if (!second_allele_idx) {
1994 // 1|0
1995 phaseinfo_hw |= shifted_bit;
1996 }
1997 #else
1998 phaseinfo_hw |= shifted_bit & (second_allele_idx - 1);
1999 #endif
2000 }
2001 } else if (unlikely(second_allele_idx != (~k0LU) * 2)) {
2002 // not '.'
2003 return kVcfParseInvalidGt;
2004 } else if (halfcall_mode == kVcfHalfCallMissing) {
2005 cur_geno = 3;
2006 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
2007 return kVcfParseHalfCallError;
2008 } else {
2009 // kVcfHalfCallHaploid, kVcfHalfCallReference
2010 if (is_phased && (halfcall_mode == kVcfHalfCallReference) && (cur_geno == 1)) {
2011 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
2012 phasepresent_hw |= shifted_bit;
2013 phaseinfo_hw |= shifted_bit;
2014 } else {
2015 cur_geno <<= halfcall_mode;
2016 }
2017 }
2018 }
2019 }
2020 } else if (unlikely(cur_geno != (~k0LU) * 2)) {
2021 // not '.'
2022 return kVcfParseInvalidGt;
2023 } else {
2024 cur_geno = 3;
2025 if (!is_haploid) {
2026 // ./x
2027 const char second_allele_char = linebuf_iter[2];
2028 const char polyploid_char = linebuf_iter[3];
2029 if ((polyploid_char == '/') || (polyploid_char == '|')) {
2030 if (unlikely(error_on_polyploid)) {
2031 return kVcfParsePolyploidError;
2032 }
2033 // could perform InvalidGt check?
2034 } else if ((second_allele_char != '.') && (halfcall_mode != kVcfHalfCallMissing)) {
2035 cur_geno = ctow(second_allele_char) - 48;
2036 if (unlikely(cur_geno > 1)) {
2037 return kVcfParseInvalidGt;
2038 }
2039 if (unlikely(halfcall_mode == kVcfHalfCallError)) {
2040 return kVcfParseHalfCallError;
2041 }
2042 // kVcfHalfCallHaploid, kVcfHalfCallReference
2043 if (is_phased && (halfcall_mode == kVcfHalfCallReference) && (cur_geno == 1)) {
2044 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
2045 phasepresent_hw |= shifted_bit;
2046 } else {
2047 cur_geno <<= halfcall_mode;
2048 }
2049 }
2050 }
2051 }
2052 }
2053 genovec_word |= cur_geno << (2 * sample_idx_lowbits);
2054 linebuf_iter = &(cur_gtext_end[1]);
2055 }
2056 genovec[widx] = genovec_word;
2057 phasepresent_alias[widx] = phasepresent_hw;
2058 phaseinfo_alias[widx] = phaseinfo_hw;
2059 }
2060 return kVcfParseOk;
2061 }
2062
2063 // todo: try merging this with VcfConvertUnphasedMultiallelicLine, most of the
2064 // code is duplicated
2065 VcfParseErr VcfConvertPhasedMultiallelicLine(const VcfImportBaseContext* vibcp, const char* linebuf_iter, uintptr_t allele_ct, uint32_t* __restrict patch_01_ctp, uint32_t* __restrict patch_10_ctp, uintptr_t* __restrict genovec, uintptr_t* __restrict patch_01_set, AlleleCode* __restrict patch_01_vals, uintptr_t* __restrict patch_10_set, AlleleCode* __restrict patch_10_vals, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo) {
2066 const uint32_t sample_ct = vibcp->sample_ct;
2067 const uint32_t sample_ctl2_m1 = (sample_ct - 1) / kBitsPerWordD2;
2068 const VcfHalfCall halfcall_mode = vibcp->halfcall_mode;
2069 const uint32_t error_on_polyploid = vibcp->error_on_polyploid;
2070 STD_ARRAY_KREF(uint32_t, 2) qual_field_skips = vibcp->qual_field_skips;
2071 STD_ARRAY_KREF(int32_t, 2) qual_line_mins = vibcp->qual_line_mins;
2072 STD_ARRAY_KREF(int32_t, 2) qual_line_maxs = vibcp->qual_line_maxs;
2073 const uint32_t qual_field_ct = vibcp->qual_field_ct;
2074 Halfword* patch_01_set_alias = R_CAST(Halfword*, patch_01_set);
2075 Halfword* patch_10_set_alias = R_CAST(Halfword*, patch_10_set);
2076 AlleleCode* patch_01_vals_iter = patch_01_vals;
2077 AlleleCode* patch_10_vals_iter = patch_10_vals;
2078 Halfword* phasepresent_alias = R_CAST(Halfword*, phasepresent);
2079 Halfword* phaseinfo_alias = R_CAST(Halfword*, phaseinfo);
2080
2081 uint32_t inner_loop_last = kBitsPerWordD2 - 1;
2082 for (uint32_t widx = 0; ; ++widx) {
2083 if (widx >= sample_ctl2_m1) {
2084 if (widx > sample_ctl2_m1) {
2085 if (widx % 2) {
2086 // might not need this, but lets play it safe
2087 patch_01_set_alias[widx] = 0;
2088 patch_10_set_alias[widx] = 0;
2089 phasepresent_alias[widx] = 0;
2090 // phaseinfo doesn't matter
2091 }
2092 break;
2093 }
2094 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
2095 }
2096 uintptr_t genovec_word = 0;
2097 uint32_t patch_01_hw = 0;
2098 uint32_t patch_10_hw = 0;
2099 uint32_t phasepresent_hw = 0;
2100 uint32_t phaseinfo_hw = 0;
2101 uint32_t shifted_bit = 1;
2102 if (allele_ct <= 10) {
2103 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
2104 const char* cur_gtext_end = FirstPrespace(linebuf_iter);
2105 if (unlikely((*cur_gtext_end != '\t') && ((sample_idx_lowbits != inner_loop_last) || (widx != sample_ctl2_m1)))) {
2106 return kVcfParseMissingTokens;
2107 }
2108 uintptr_t cur_geno;
2109 if (qual_field_ct && VcfCheckQuals(qual_field_skips, qual_line_mins, qual_line_maxs, linebuf_iter, cur_gtext_end, qual_field_ct)) {
2110 // skipping polyploid check for now
2111 cur_geno = 3;
2112 } else {
2113 const uint32_t is_phased = (linebuf_iter[1] == '|');
2114 const uint32_t is_haploid = (!is_phased) && (linebuf_iter[1] != '/');
2115 cur_geno = ctow(*linebuf_iter) - 48;
2116 if (cur_geno < allele_ct) {
2117 if (is_haploid) {
2118 if (cur_geno <= 1) {
2119 cur_geno *= 2;
2120 } else {
2121 patch_10_hw |= shifted_bit;
2122 *patch_10_vals_iter++ = cur_geno;
2123 *patch_10_vals_iter++ = cur_geno;
2124 cur_geno = 2;
2125 }
2126 } else {
2127 const char polyploid_char = linebuf_iter[3];
2128 if ((polyploid_char == '/') || (polyploid_char == '|')) {
2129 if (unlikely(error_on_polyploid)) {
2130 return kVcfParsePolyploidError;
2131 }
2132 cur_geno = 3;
2133 } else {
2134 uintptr_t second_allele_idx = ctow(linebuf_iter[2]) - 48;
2135 if (second_allele_idx < allele_ct) {
2136 if (cur_geno <= 1) {
2137 if (is_phased && (cur_geno != second_allele_idx)) {
2138 phasepresent_hw |= shifted_bit;
2139 if (!second_allele_idx) {
2140 // has to be 1|0 here, since cur_geno <= 1
2141 phaseinfo_hw |= shifted_bit;
2142 }
2143 }
2144 if (second_allele_idx <= 1) {
2145 cur_geno += second_allele_idx;
2146 } else {
2147 if (!cur_geno) {
2148 patch_01_hw |= shifted_bit;
2149 *patch_01_vals_iter++ = second_allele_idx;
2150 } else {
2151 patch_10_hw |= shifted_bit;
2152 *patch_10_vals_iter++ = 1;
2153 *patch_10_vals_iter++ = second_allele_idx;
2154 }
2155 ++cur_geno;
2156 }
2157 } else {
2158 // first_allele_idx == cur_geno >= 2
2159 if (is_phased && (cur_geno != second_allele_idx)) {
2160 phasepresent_hw |= shifted_bit;
2161 if (second_allele_idx < cur_geno) {
2162 phaseinfo_hw |= shifted_bit;
2163 }
2164 }
2165 if (!second_allele_idx) {
2166 patch_01_hw |= shifted_bit;
2167 *patch_01_vals_iter++ = cur_geno;
2168 cur_geno = 1;
2169 } else {
2170 patch_10_hw |= shifted_bit;
2171 if (second_allele_idx < cur_geno) {
2172 const uintptr_t ulii = cur_geno;
2173 cur_geno = second_allele_idx;
2174 second_allele_idx = ulii;
2175 }
2176 *patch_10_vals_iter++ = cur_geno;
2177 *patch_10_vals_iter++ = second_allele_idx;
2178 cur_geno = 2;
2179 }
2180 }
2181 } else {
2182 // second_allele_idx >= allele_ct
2183 if (unlikely(second_allele_idx != (~k0LU) * 2)) {
2184 // not '.'
2185 return kVcfParseInvalidGt;
2186 }
2187 if (halfcall_mode == kVcfHalfCallMissing) {
2188 cur_geno = 3;
2189 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
2190 return kVcfParseHalfCallError;
2191 } else {
2192 // kVcfHalfCallHaploid, kVcfHalfCallReference
2193 if (cur_geno <= 1) {
2194 if (is_phased && (halfcall_mode == kVcfHalfCallReference) && cur_geno) {
2195 phasepresent_hw |= shifted_bit;
2196 phaseinfo_hw |= shifted_bit;
2197 } else {
2198 cur_geno <<= halfcall_mode;
2199 }
2200 } else if (halfcall_mode == kVcfHalfCallReference) {
2201 if (is_phased) {
2202 phasepresent_hw |= shifted_bit;
2203 phaseinfo_hw |= shifted_bit;
2204 }
2205 patch_01_hw |= shifted_bit;
2206 *patch_01_vals_iter++ = cur_geno;
2207 cur_geno = 1;
2208 } else {
2209 patch_10_hw |= shifted_bit;
2210 *patch_10_vals_iter++ = cur_geno;
2211 *patch_10_vals_iter++ = cur_geno;
2212 cur_geno = 2;
2213 }
2214 }
2215 }
2216 }
2217 }
2218 } else if (unlikely(cur_geno != (~k0LU) * 2)) {
2219 // not '.'
2220 return kVcfParseInvalidGt;
2221 } else {
2222 cur_geno = 3;
2223 if (!is_haploid) {
2224 const char polyploid_char = linebuf_iter[3];
2225 if ((polyploid_char == '/') || (polyploid_char == '|')) {
2226 if (unlikely(error_on_polyploid)) {
2227 return kVcfParsePolyploidError;
2228 }
2229 // could perform InvalidGt check?
2230 } else {
2231 const char second_allele_char = linebuf_iter[2];
2232 if ((second_allele_char != '.') && (halfcall_mode != kVcfHalfCallMissing)) {
2233 cur_geno = ctow(second_allele_char) - 48;
2234 if (unlikely(cur_geno >= allele_ct)) {
2235 return kVcfParseInvalidGt;
2236 }
2237 if (unlikely(halfcall_mode == kVcfHalfCallError)) {
2238 return kVcfParseHalfCallError;
2239 }
2240 if (is_phased && (halfcall_mode == kVcfHalfCallReference) && cur_geno) {
2241 phasepresent_hw |= shifted_bit;
2242 }
2243 // kVcfHalfCallHaploid, kVcfHalfCallReference
2244 if (cur_geno <= 1) {
2245 cur_geno <<= halfcall_mode;
2246 } else {
2247 if (halfcall_mode == kVcfHalfCallReference) {
2248 patch_01_hw |= shifted_bit;
2249 *patch_01_vals_iter++ = cur_geno;
2250 cur_geno = 1;
2251 } else {
2252 patch_10_hw |= shifted_bit;
2253 *patch_10_vals_iter++ = cur_geno;
2254 *patch_10_vals_iter++ = cur_geno;
2255 cur_geno = 2;
2256 }
2257 }
2258 }
2259 }
2260 }
2261 }
2262 }
2263 genovec_word |= cur_geno << (2 * sample_idx_lowbits);
2264 shifted_bit *= 2;
2265 linebuf_iter = &(cur_gtext_end[1]);
2266 }
2267 } else {
2268 // allele_ct > 10
2269 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
2270 const char* cur_gtext_end = FirstPrespace(linebuf_iter);
2271 if (unlikely((*cur_gtext_end != '\t') && ((sample_idx_lowbits != inner_loop_last) || (widx != sample_ctl2_m1)))) {
2272 return kVcfParseMissingTokens;
2273 }
2274 uintptr_t cur_geno;
2275 if (qual_field_ct && VcfCheckQuals(qual_field_skips, qual_line_mins, qual_line_maxs, linebuf_iter, cur_gtext_end, qual_field_ct)) {
2276 // skipping polyploid check for now
2277 cur_geno = 3;
2278 } else {
2279 cur_geno = ctow(*linebuf_iter) - 48;
2280 if (cur_geno < 10) {
2281 const char* gt_first_nondigit = &(linebuf_iter[1]);
2282 uintptr_t next_digit;
2283 for (; ; ++gt_first_nondigit) {
2284 next_digit = ctow(*gt_first_nondigit) - 48;
2285 if (next_digit >= 10) {
2286 break;
2287 }
2288 cur_geno = cur_geno * 10 + next_digit;
2289 if (cur_geno >= allele_ct) {
2290 return kVcfParseInvalidGt;
2291 }
2292 }
2293 // '/' = ascii 47, '|' = ascii 124 (i.e. 48 + 76)
2294 const uint32_t is_phased = (next_digit == 76);
2295 const uint32_t is_haploid = (!is_phased) && (next_digit != (~k0LU));
2296 if (is_haploid) {
2297 if (cur_geno <= 1) {
2298 cur_geno *= 2;
2299 } else {
2300 patch_10_hw |= shifted_bit;
2301 *patch_10_vals_iter++ = cur_geno;
2302 *patch_10_vals_iter++ = cur_geno;
2303 cur_geno = 2;
2304 }
2305 } else {
2306 const char* second_allele_iter = &(gt_first_nondigit[1]);
2307 uintptr_t second_allele_idx = ctow(*second_allele_iter++) - 48;
2308 if (second_allele_idx < 10) {
2309 for (; ; ++second_allele_iter) {
2310 next_digit = ctow(*second_allele_iter) - 48;
2311 if (next_digit >= 10) {
2312 break;
2313 }
2314 second_allele_idx = second_allele_idx * 10 + next_digit;
2315 if (second_allele_idx >= allele_ct) {
2316 return kVcfParseInvalidGt;
2317 }
2318 }
2319 if ((next_digit == ~k0LU) || (next_digit == 76)) {
2320 if (unlikely(error_on_polyploid)) {
2321 return kVcfParsePolyploidError;
2322 }
2323 cur_geno = 3;
2324 } else if (cur_geno <= 1) {
2325 if (is_phased && (cur_geno != second_allele_idx)) {
2326 phasepresent_hw |= shifted_bit;
2327 if (!second_allele_idx) {
2328 // has to be 1|0 here, since cur_geno <= 1
2329 phaseinfo_hw |= shifted_bit;
2330 }
2331 }
2332 if (second_allele_idx <= 1) {
2333 cur_geno += second_allele_idx;
2334 } else {
2335 if (!cur_geno) {
2336 patch_01_hw |= shifted_bit;
2337 *patch_01_vals_iter++ = second_allele_idx;
2338 } else {
2339 patch_10_hw |= shifted_bit;
2340 *patch_10_vals_iter++ = 1;
2341 *patch_10_vals_iter++ = second_allele_idx;
2342 }
2343 ++cur_geno;
2344 }
2345 } else {
2346 // first_allele_idx == cur_geno >= 2
2347 if (is_phased && (cur_geno != second_allele_idx)) {
2348 phasepresent_hw |= shifted_bit;
2349 if (second_allele_idx < cur_geno) {
2350 phaseinfo_hw |= shifted_bit;
2351 }
2352 }
2353 if (!second_allele_idx) {
2354 patch_01_hw |= shifted_bit;
2355 *patch_01_vals_iter++ = cur_geno;
2356 cur_geno = 1;
2357 } else {
2358 patch_10_hw |= shifted_bit;
2359 if (second_allele_idx < cur_geno) {
2360 const uintptr_t ulii = cur_geno;
2361 cur_geno = second_allele_idx;
2362 second_allele_idx = ulii;
2363 }
2364 *patch_10_vals_iter++ = cur_geno;
2365 *patch_10_vals_iter++ = second_allele_idx;
2366 cur_geno = 2;
2367 }
2368 }
2369 } else if (unlikely(second_allele_idx != (~k0LU) * 2)) {
2370 // not '.'
2371 return kVcfParseInvalidGt;
2372 } else {
2373 const char polyploid_char = *second_allele_iter;
2374 if ((polyploid_char == '/') || (polyploid_char == '|')) {
2375 if (unlikely(error_on_polyploid)) {
2376 return kVcfParsePolyploidError;
2377 }
2378 cur_geno = 3;
2379 } else if (halfcall_mode == kVcfHalfCallMissing) {
2380 cur_geno = 3;
2381 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
2382 return kVcfParseHalfCallError;
2383 } else {
2384 // kVcfHalfCallHaploid, kVcfHalfCallReference
2385 if (cur_geno <= 1) {
2386 if (is_phased && (halfcall_mode == kVcfHalfCallReference) && cur_geno) {
2387 phasepresent_hw |= shifted_bit;
2388 phaseinfo_hw |= shifted_bit;
2389 } else {
2390 cur_geno <<= halfcall_mode;
2391 }
2392 } else if (halfcall_mode == kVcfHalfCallReference) {
2393 if (is_phased) {
2394 phasepresent_hw |= shifted_bit;
2395 phaseinfo_hw |= shifted_bit;
2396 }
2397 patch_01_hw |= shifted_bit;
2398 *patch_01_vals_iter++ = cur_geno;
2399 cur_geno = 1;
2400 } else {
2401 patch_10_hw |= shifted_bit;
2402 *patch_10_vals_iter++ = cur_geno;
2403 *patch_10_vals_iter++ = cur_geno;
2404 cur_geno = 2;
2405 }
2406 }
2407 }
2408 }
2409 } else if (unlikely(cur_geno != (~k0LU) * 2)) {
2410 // not '.'
2411 return kVcfParseInvalidGt;
2412 } else {
2413 cur_geno = 3;
2414 const uint32_t is_haploid = (linebuf_iter[1] != '/') && (linebuf_iter[1] != '|');
2415 if (!is_haploid) {
2416 const char second_allele_first_char = linebuf_iter[2];
2417 if (second_allele_first_char == '.') {
2418 if (error_on_polyploid) {
2419 const char polyploid_char = linebuf_iter[3];
2420 if (unlikely((polyploid_char == '/') || (polyploid_char == '|'))) {
2421 return kVcfParsePolyploidError;
2422 }
2423 }
2424 } else {
2425 // don't check halfcall_mode == kVcfHalfCallMissing yet because
2426 // we want error_on_polyploid to work
2427 cur_geno = ctow(second_allele_first_char) - 48;
2428 if (unlikely(cur_geno >= 10)) {
2429 return kVcfParseInvalidGt;
2430 }
2431 uintptr_t next_digit;
2432 for (const char* second_allele_iter = &(linebuf_iter[3]); ; ++second_allele_iter) {
2433 next_digit = ctow(*second_allele_iter) - 48;
2434 if (next_digit >= 10) {
2435 break;
2436 }
2437 cur_geno = cur_geno * 10 + next_digit;
2438 if (cur_geno >= allele_ct) {
2439 return kVcfParseInvalidGt;
2440 }
2441 }
2442 if ((next_digit == ~k0LU) || (next_digit == 76)) {
2443 if (unlikely(error_on_polyploid)) {
2444 return kVcfParsePolyploidError;
2445 }
2446 cur_geno = 3;
2447 } else if (halfcall_mode != kVcfHalfCallMissing) {
2448 if (unlikely(halfcall_mode == kVcfHalfCallError)) {
2449 return kVcfParseHalfCallError;
2450 }
2451 if ((linebuf_iter[1] == '|') && (halfcall_mode == kVcfHalfCallReference) && cur_geno) {
2452 phasepresent_hw |= shifted_bit;
2453 }
2454 // kVcfHalfCallHaploid, kVcfHalfCallReference
2455 if (cur_geno <= 1) {
2456 cur_geno <<= halfcall_mode;
2457 } else {
2458 if (halfcall_mode == kVcfHalfCallReference) {
2459 patch_01_hw |= shifted_bit;
2460 *patch_01_vals_iter++ = cur_geno;
2461 cur_geno = 1;
2462 } else {
2463 patch_10_hw |= shifted_bit;
2464 *patch_10_vals_iter++ = cur_geno;
2465 *patch_10_vals_iter++ = cur_geno;
2466 cur_geno = 2;
2467 }
2468 }
2469 } else {
2470 // bugfix (3 Feb 2024)
2471 cur_geno = 3;
2472 }
2473 }
2474 }
2475 }
2476 }
2477 genovec_word |= cur_geno << (2 * sample_idx_lowbits);
2478 shifted_bit *= 2;
2479 linebuf_iter = &(cur_gtext_end[1]);
2480 }
2481 }
2482 genovec[widx] = genovec_word;
2483 patch_01_set_alias[widx] = patch_01_hw;
2484 patch_10_set_alias[widx] = patch_10_hw;
2485 phasepresent_alias[widx] = phasepresent_hw;
2486 phaseinfo_alias[widx] = phaseinfo_hw;
2487 }
2488 *patch_01_ctp = patch_01_vals_iter - patch_01_vals;
2489 *patch_10_ctp = S_CAST(uintptr_t, patch_10_vals_iter - patch_10_vals) / 2;
2490 return kVcfParseOk;
2491 }
2492
2493 uintptr_t VcfScanLongallelicLine(const VcfImportBaseContext* vibcp, const char* format_end, char** line_iter_ptr) {
2494 const VcfHalfCall halfcall_mode = vibcp->halfcall_mode;
2495 STD_ARRAY_KREF(uint32_t, 2) qual_field_skips = vibcp->qual_field_skips;
2496 STD_ARRAY_KREF(int32_t, 2) qual_line_mins = vibcp->qual_line_mins;
2497 STD_ARRAY_KREF(int32_t, 2) qual_line_maxs = vibcp->qual_line_maxs;
2498 const uint32_t qual_field_ct = vibcp->qual_field_ct;
2499 const char* phasescan_iter = format_end;
2500 uintptr_t retval = 0;
2501 while (1) {
2502 const char* next_vbar = phasescan_iter;
2503 // this should quickly fail if there are no phased hardcalls at all.
2504 if (strchrnul_n_mov('|', &next_vbar)) {
2505 goto VcfScanLongallelicLine_no_phased_het;
2506 }
2507 phasescan_iter = &(next_vbar[-1]);
2508 unsigned char ucc = *phasescan_iter;
2509 if (ucc == '.') {
2510 --phasescan_iter;
2511 } else {
2512 while (IsDigit(ucc)) {
2513 ucc = *(--phasescan_iter);
2514 }
2515 }
2516 if (*phasescan_iter != '\t') {
2517 // at least one other FORMAT field uses the '|' character.
2518 // switch to iterating over tabs.
2519 break;
2520 }
2521 if (VcfIsHetLong(&(phasescan_iter[1]), &(next_vbar[1]), halfcall_mode)) {
2522 if ((!qual_field_ct) || (!VcfCheckQuals(qual_field_skips, qual_line_mins, qual_line_maxs, phasescan_iter, FirstPrespace(&(next_vbar[2])), qual_field_ct))) {
2523 goto VcfScanLongallelicLine_phased_het_found;
2524 }
2525 }
2526 if (incr_strchrnul_n_mov('\t', &phasescan_iter)) {
2527 goto VcfScanLongallelicLine_no_phased_het;
2528 }
2529 }
2530 while (!incr_strchrnul_n_mov('\t', &phasescan_iter)) {
2531 const char* next_vbar = &(phasescan_iter[1]);
2532 while (IsDigit(*next_vbar)) {
2533 ++next_vbar;
2534 }
2535 if ((*next_vbar != '|') || (!VcfIsHetLong(&(phasescan_iter[1]), &(next_vbar[1]), halfcall_mode))) {
2536 continue;
2537 }
2538 if ((!qual_field_ct) || (!VcfCheckQuals(qual_field_skips, qual_line_mins, qual_line_maxs, phasescan_iter, FirstPrespace(&(next_vbar[2])), qual_field_ct))) {
2539 goto VcfScanLongallelicLine_phased_het_found;
2540 }
2541 }
2542 while (0) {
2543 VcfScanLongallelicLine_phased_het_found:
2544 retval = 1;
2545 }
2546 VcfScanLongallelicLine_no_phased_het:
2547 *line_iter_ptr = K_CAST(char*, phasescan_iter);
2548 return retval;
2549 }
2550
2551 typedef struct VcfGenoToPgenCtxStruct {
2552 uint32_t sample_ct;
2553 uint32_t hard_call_halfdist;
2554 uint32_t dosage_erase_halfdist;
2555 double import_dosage_certainty;
2556 VcfHalfCall halfcall_mode;
2557 uint32_t error_on_polyploid;
2558 uint32_t dosage_is_gp;
2559 STD_ARRAY_DECL(int32_t, 2, qual_mins);
2560 STD_ARRAY_DECL(int32_t, 2, qual_maxs);
2561
2562 unsigned char** thread_wkspaces;
2563
2564 uint32_t* thread_bidxs[2];
2565 GparseRecord* gparse[2];
2566 const uintptr_t* block_allele_idx_offsets[2];
2567
2568 // PglErr set by main thread
2569 VcfParseErr* vcf_parse_errs;
2570 uintptr_t* err_line_idxs;
2571 uint32_t parse_failed;
2572 } VcfGenoToPgenCtx;
2573
2574 THREAD_FUNC_DECL VcfGenoToPgenThread(void* raw_arg) {
2575 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
2576 const uintptr_t tidx = arg->tidx;
2577 VcfGenoToPgenCtx* ctx = S_CAST(VcfGenoToPgenCtx*, arg->sharedp->context);
2578
2579 VcfImportContext vic;
2580 const uint32_t sample_ct = ctx->sample_ct;
2581 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
2582 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
2583 vic.vibc.sample_ct = sample_ct;
2584 vic.vibc.halfcall_mode = ctx->halfcall_mode;
2585 vic.vibc.error_on_polyploid = ctx->error_on_polyploid;
2586 vic.dosage_is_gp = ctx->dosage_is_gp;
2587 vic.dosage_erase_halfdist = ctx->dosage_erase_halfdist;
2588 vic.import_dosage_certainty = ctx->import_dosage_certainty;
2589 const uint32_t hard_call_halfdist = ctx->hard_call_halfdist;
2590 STD_ARRAY_DECL(int32_t, 2, qual_mins);
2591 STD_ARRAY_DECL(int32_t, 2, qual_maxs);
2592 STD_ARRAY_COPY(ctx->qual_mins, 2, qual_mins);
2593 STD_ARRAY_COPY(ctx->qual_maxs, 2, qual_maxs);
2594 unsigned char* thread_wkspace = ctx->thread_wkspaces[tidx];
2595 uintptr_t* patch_01_set = nullptr;
2596 AlleleCode* patch_01_vals = nullptr;
2597 uintptr_t* patch_10_set = nullptr;
2598 AlleleCode* patch_10_vals = nullptr;
2599 uintptr_t* phasepresent = nullptr;
2600 uintptr_t* phaseinfo = nullptr;
2601 uintptr_t* dosage_present = nullptr;
2602 Dosage* dosage_main = nullptr;
2603 uintptr_t* dphase_present = nullptr;
2604 SDosage* dphase_delta = nullptr;
2605 SDosage* tmp_dphase_delta = R_CAST(SDosage*, thread_wkspace);
2606 thread_wkspace = &(thread_wkspace[RoundUpPow2(sample_ct * sizeof(SDosage), kBytesPerVec)]);
2607 uintptr_t* write_patch_01_set = nullptr;
2608 AlleleCode* write_patch_01_vals = nullptr;
2609 uintptr_t* write_patch_10_set = nullptr;
2610 AlleleCode* write_patch_10_vals = nullptr;
2611 uintptr_t* write_phasepresent = nullptr;
2612 uintptr_t* write_phaseinfo = nullptr;
2613 uintptr_t* write_dosage_present = nullptr;
2614 Dosage* write_dosage_main = nullptr;
2615 uintptr_t* write_dphase_present = nullptr;
2616 SDosage* write_dphase_delta = nullptr;
2617 uint32_t cur_allele_ct = 2;
2618 uint32_t parity = 0;
2619 VcfParseErr vcf_parse_err = kVcfParseOk;
2620 uintptr_t line_idx = 0;
2621 do {
2622 const uintptr_t* block_allele_idx_offsets = ctx->block_allele_idx_offsets[parity];
2623 const uint32_t bidx_end = ctx->thread_bidxs[parity][tidx + 1];
2624 GparseRecord* cur_gparse = ctx->gparse[parity];
2625
2626 for (uint32_t bidx = ctx->thread_bidxs[parity][tidx]; bidx != bidx_end; ++bidx) {
2627 GparseRecord* grp = &(cur_gparse[bidx]);
2628 uint32_t patch_01_ct = 0;
2629 uint32_t patch_10_ct = 0;
2630 uint32_t cur_phasepresent_exists = 0;
2631 uint32_t dosage_ct = 0;
2632 uint32_t dphase_ct = 0;
2633 GparseFlags gparse_flags = grp->flags;
2634 if (gparse_flags == kfGparseNull) {
2635 SetAllBits(2 * sample_ct, R_CAST(uintptr_t*, grp->record_start));
2636 } else {
2637 if (block_allele_idx_offsets) {
2638 cur_allele_ct = block_allele_idx_offsets[bidx + 1] - block_allele_idx_offsets[bidx];
2639 }
2640 uintptr_t* genovec = GparseGetPointers(thread_wkspace, sample_ct, cur_allele_ct, gparse_flags, &patch_01_set, &patch_01_vals, &patch_10_set, &patch_10_vals, &phasepresent, &phaseinfo, &dosage_present, &dosage_main, &dphase_present, &dphase_delta);
2641 uintptr_t* write_genovec = GparseGetPointers(grp->record_start, sample_ct, cur_allele_ct, gparse_flags, &write_patch_01_set, &write_patch_01_vals, &write_patch_10_set, &write_patch_10_vals, &write_phasepresent, &write_phaseinfo, &write_dosage_present, &write_dosage_main, &write_dphase_present, &write_dphase_delta);
2642 char* genotext_start = R_CAST(char*, grp->record_start);
2643 ++genotext_start;
2644 uint32_t qual_field_ct = grp->metadata.read_vcf.qual_exists;
2645 if (qual_field_ct) {
2646 qual_field_ct = VcfQualScanInit2(grp->metadata.read_vcf.qual_field_idxs, qual_mins, qual_maxs, vic.vibc.qual_field_skips, vic.vibc.qual_line_mins, vic.vibc.qual_line_maxs);
2647 }
2648 vic.vibc.gt_exists = grp->metadata.read_vcf.gt_exists;
2649 vic.vibc.qual_field_ct = qual_field_ct;
2650 vic.dosage_field_idx = grp->metadata.read_vcf.dosage_field_idx;
2651 vic.hds_field_idx = grp->metadata.read_vcf.hds_field_idx;
2652 if ((vic.hds_field_idx == UINT32_MAX) && (vic.dosage_field_idx == UINT32_MAX)) {
2653 if (!(gparse_flags & kfGparseHphase)) {
2654 if (cur_allele_ct == 2) {
2655 vcf_parse_err = VcfConvertUnphasedBiallelicLine(&(vic.vibc), genotext_start, genovec);
2656 } else {
2657 vcf_parse_err = VcfConvertUnphasedMultiallelicLine(&(vic.vibc), genotext_start, cur_allele_ct, &patch_01_ct, &patch_10_ct, genovec, patch_01_set, patch_01_vals, patch_10_set, patch_10_vals);
2658 }
2659 } else {
2660 if (cur_allele_ct == 2) {
2661 vcf_parse_err = VcfConvertPhasedBiallelicLine(&(vic.vibc), genotext_start, genovec, phasepresent, phaseinfo);
2662 } else {
2663 vcf_parse_err = VcfConvertPhasedMultiallelicLine(&(vic.vibc), genotext_start, cur_allele_ct, &patch_01_ct, &patch_10_ct, genovec, patch_01_set, patch_01_vals, patch_10_set, patch_10_vals, phasepresent, phaseinfo);
2664 }
2665 cur_phasepresent_exists = !AllWordsAreZero(phasepresent, sample_ctl);
2666 }
2667 if (unlikely(vcf_parse_err)) {
2668 line_idx = grp->metadata.read_vcf.line_idx;
2669 goto VcfGenoToPgenThread_malformed;
2670 }
2671 } else {
2672 Dosage* dosage_main_iter = dosage_main;
2673 SDosage* dphase_delta_iter = dphase_delta;
2674 if (cur_allele_ct == 2) {
2675 vcf_parse_err = VcfConvertPhasedBiallelicDosageLine(&vic, genotext_start, genovec, phasepresent, phaseinfo, dosage_present, dphase_present, &dosage_main_iter, &dphase_delta_iter);
2676 } else {
2677 // multiallelic dosage: shouldn't be possible to get here yet
2678 exit(S_CAST(int32_t, kPglRetInternalError));
2679 }
2680 if (unlikely(vcf_parse_err)) {
2681 line_idx = grp->metadata.read_vcf.line_idx;
2682 goto VcfGenoToPgenThread_malformed;
2683 }
2684 dosage_ct = dosage_main_iter - dosage_main;
2685 if (dosage_ct) {
2686 dphase_ct = ApplyHardCallThreshPhased(dosage_present, dosage_main, dosage_ct, hard_call_halfdist, genovec, phasepresent, phaseinfo, dphase_present, dphase_delta, tmp_dphase_delta);
2687 memcpy(write_dosage_present, dosage_present, sample_ctl * sizeof(intptr_t));
2688 memcpy(write_dosage_main, dosage_main, dosage_ct * sizeof(Dosage));
2689 if (dphase_ct) {
2690 memcpy(write_dphase_present, dphase_present, sample_ctl * sizeof(intptr_t));
2691 memcpy(write_dphase_delta, dphase_delta, dphase_ct * sizeof(SDosage));
2692 }
2693 }
2694 cur_phasepresent_exists = !AllWordsAreZero(phasepresent, sample_ctl);
2695 }
2696 memcpy(write_genovec, genovec, sample_ctl2 * sizeof(intptr_t));
2697 if (patch_01_ct) {
2698 memcpy(write_patch_01_set, patch_01_set, sample_ctl * sizeof(intptr_t));
2699 memcpy(write_patch_01_vals, patch_01_vals, patch_01_ct * sizeof(AlleleCode));
2700 }
2701 if (patch_10_ct) {
2702 memcpy(write_patch_10_set, patch_10_set, sample_ctl * sizeof(intptr_t));
2703 memcpy(write_patch_10_vals, patch_10_vals, patch_10_ct * sizeof(AlleleCode) * 2);
2704 }
2705 if (cur_phasepresent_exists || dphase_ct) {
2706 memcpy(write_phasepresent, phasepresent, sample_ctl * sizeof(intptr_t));
2707 memcpy(write_phaseinfo, phaseinfo, sample_ctl * sizeof(intptr_t));
2708 }
2709 }
2710
2711 grp->metadata.write.patch_01_ct = patch_01_ct;
2712 grp->metadata.write.patch_10_ct = patch_10_ct;
2713 grp->metadata.write.phasepresent_exists = cur_phasepresent_exists;
2714 grp->metadata.write.dosage_ct = dosage_ct;
2715 grp->metadata.write.multiallelic_dosage_ct = 0;
2716 grp->metadata.write.dphase_ct = dphase_ct;
2717 grp->metadata.write.multiallelic_dphase_ct = 0;
2718 }
2719 while (0) {
2720 VcfGenoToPgenThread_malformed:
2721 ctx->vcf_parse_errs[tidx] = vcf_parse_err;
2722 ctx->err_line_idxs[tidx] = line_idx;
2723 ctx->parse_failed = 1;
2724 break;
2725 }
2726 parity = 1 - parity;
2727 } while (!THREAD_BLOCK_FINISH(arg));
2728 THREAD_RETURN;
2729 }
2730
2731 static const char kGpText[] = "GP";
2732
2733 // pgen_generated and psam_generated assumed to be initialized to 1.
2734 static_assert(!kVcfHalfCallReference, "VcfToPgen() assumes kVcfHalfCallReference == 0.");
2735 static_assert(kVcfHalfCallHaploid == 1, "VcfToPgen() assumes kVcfHalfCallHaploid == 1.");
2736 PglErr VcfToPgen(const char* vcfname, const char* preexisting_psamname, const char* const_fid, const char* dosage_import_field, MiscFlags misc_flags, ImportFlags import_flags, uint32_t no_samples_ok, uint32_t is_update_or_impute_sex, uint32_t is_splitpar, uint32_t hard_call_thresh, uint32_t dosage_erase_thresh, double import_dosage_certainty, char id_delim, char idspace_to, int32_t vcf_min_gq, int32_t vcf_min_dp, int32_t vcf_max_dp, VcfHalfCall halfcall_mode, FamCol fam_cols, uint32_t import_max_allele_ct, uint32_t max_thread_ct, char* outname, char* outname_end, ChrInfo* cip, uint32_t* pgen_generated_ptr, uint32_t* psam_generated_ptr) {
2737 // Performs a 2-pass load. Probably staying that way after sequential writer
2738 // is implemented since header lines are a pain.
2739 //
2740 // preexisting_psamname should be nullptr if no such file was specified.
2741 unsigned char* bigstack_mark = g_bigstack_base;
2742 unsigned char* bigstack_end_mark = g_bigstack_end;
2743 char* pvar_cswritep = nullptr;
2744 uintptr_t line_idx = 1;
2745 const uint32_t half_call_explicit_error = (halfcall_mode == kVcfHalfCallError);
2746 PglErr reterr = kPglRetSuccess;
2747 VcfParseErr vcf_parse_err = kVcfParseOk;
2748 CompressStreamState pvar_css;
2749 PreinitCstream(&pvar_css);
2750 ThreadGroup tg;
2751 PreinitThreads(&tg);
2752 VcfGenoToPgenCtx ctx;
2753 TextStream vcf_txs;
2754 STPgenWriter spgw;
2755 PreinitTextStream(&vcf_txs);
2756 PreinitSpgw(&spgw);
2757 {
2758 uint32_t max_line_blen;
2759 if (StandardizeMaxLineBlen(bigstack_left() / 4, &max_line_blen)) {
2760 goto VcfToPgen_ret_NOMEM;
2761 }
2762 // probable todo: if chromosome filter specified, take advantage of an
2763 // index file with the standard extension if it's present. (The index
2764 // reader can be very simple since *only* chromosome filters are supported
2765 // by import functions.) Do the same for .bgen and .bcf files.
2766
2767 reterr = ForceNonFifo(vcfname);
2768 if (unlikely(reterr)) {
2769 if (reterr == kPglRetOpenFail) {
2770 const uint32_t slen = strlen(vcfname);
2771 if ((!StrEndsWith(vcfname, ".vcf", slen)) &&
2772 (!StrEndsWith(vcfname, ".vcf.gz", slen))) {
2773 logerrprintfww("Error: Failed to open %s : %s. (--vcf expects a complete filename; did you forget '.vcf' at the end?)\n", vcfname, strerror(errno));
2774 } else {
2775 logerrprintfww(kErrprintfFopen, vcfname, strerror(errno));
2776 }
2777 } else {
2778 logerrprintfww(kErrprintfRewind, vcfname);
2779 }
2780 goto VcfToPgen_ret_1;
2781 }
2782 reterr = InitTextStreamEx(vcfname, 1, kMaxLongLine, max_line_blen, ClipU32(max_thread_ct - 1, 1, 4), &vcf_txs);
2783 if (unlikely(reterr)) {
2784 goto VcfToPgen_ret_TSTREAM_FAIL;
2785 }
2786 const uint32_t prohibit_extra_chr = (misc_flags / kfMiscProhibitExtraChr) & 1;
2787 uint32_t dosage_import_field_slen = 0;
2788
2789 // == 2 when searched for and found in header
2790 // then becomes a boolean
2791 uint32_t format_hds_search = 0;
2792
2793 uint32_t unforced_gp = 0;
2794 if (dosage_import_field) {
2795 dosage_import_field_slen = strlen(dosage_import_field);
2796 ctx.dosage_is_gp = 0;
2797 if (strequal_k(dosage_import_field, "HDS", dosage_import_field_slen)) {
2798 format_hds_search = 1;
2799 // special case: search for DS and HDS
2800 dosage_import_field = &(dosage_import_field[1]);
2801 dosage_import_field_slen = 2;
2802 } else if (strequal_k(dosage_import_field, "GP-force", dosage_import_field_slen)) {
2803 dosage_import_field = kGpText;
2804 dosage_import_field_slen = 2;
2805 ctx.dosage_is_gp = 1;
2806 } else if (strequal_k(dosage_import_field, "GP", dosage_import_field_slen)) {
2807 unforced_gp = (import_dosage_certainty == 0.0);
2808 // bugfix (20 Aug 2018): forgot to initialize dosage_is_gp
2809 ctx.dosage_is_gp = 1;
2810 }
2811 }
2812
2813 ctx.qual_mins[0] = vcf_min_gq;
2814 ctx.qual_mins[1] = vcf_min_dp;
2815 ctx.qual_maxs[0] = 0x7fffffff;
2816 ctx.qual_maxs[1] = vcf_max_dp;
2817 VcfImportContext vic;
2818 // sample_ct set later
2819 if (halfcall_mode == kVcfHalfCallDefault) {
2820 halfcall_mode = kVcfHalfCallError;
2821 }
2822 ctx.halfcall_mode = halfcall_mode; // bugfix (28 Nov 2019)
2823 ctx.error_on_polyploid = !(import_flags & kfImportPolyploidMissing);
2824 vic.vibc.halfcall_mode = halfcall_mode;
2825 vic.vibc.error_on_polyploid = ctx.error_on_polyploid;
2826
2827 vic.dosage_is_gp = ctx.dosage_is_gp;
2828
2829 // always positive
2830 vic.dosage_erase_halfdist = kDosage4th - dosage_erase_thresh;
2831
2832 vic.import_dosage_certainty = import_dosage_certainty;
2833
2834 vic.dosage_field_idx = UINT32_MAX;
2835 vic.hds_field_idx = UINT32_MAX;
2836
2837 max_line_blen = 1; // Now means "max_observed_line_blen".
2838 uint32_t format_gt_exists = 0;
2839 uint32_t format_gq_relevant = 0;
2840 uint32_t format_dp_relevant = 0;
2841 uint32_t format_dosage_relevant = 0;
2842 uint32_t info_pr_exists = 0;
2843 uint32_t info_pr_nonflag_exists = 0;
2844 uint32_t info_nonpr_exists = 0;
2845 uint32_t chrset_exists = 0;
2846 char* line_iter = TextLineEnd(&vcf_txs);
2847 char* prev_line_start;
2848 for (; ; ++line_idx) {
2849 // don't tolerate leading spaces
2850 reterr = TextNextLineUnsafe(&vcf_txs, &line_iter);
2851 if (unlikely(reterr)) {
2852 if (reterr == kPglRetEof) {
2853 logerrputs("Error: No #CHROM header line or variant records in --vcf file.\n");
2854 goto VcfToPgen_ret_MALFORMED_INPUT;
2855 }
2856 goto VcfToPgen_ret_TSTREAM_FAIL;
2857 }
2858 prev_line_start = line_iter;
2859 if (unlikely(*line_iter != '#')) {
2860 if ((line_idx == 1) && memequal_sk(line_iter, "BCF")) {
2861 // this is more informative than "missing header line"...
2862 if (line_iter[3] == 2) {
2863 snprintf(g_logbuf, kLogbufSize, "Error: %s appears to be a BCF2 file. Try --bcf instead of --vcf.\n", vcfname);
2864 goto VcfToPgen_ret_MALFORMED_INPUT_WW;
2865 }
2866 if (line_iter[3] == 4) {
2867 snprintf(g_logbuf, kLogbufSize, "Error: %s appears to be a BCF1 file. Use 'bcftools view' to convert it to a PLINK-readable VCF.\n", vcfname);
2868 goto VcfToPgen_ret_MALFORMED_INPUT_WW;
2869 }
2870 }
2871 logerrputs("Error: No #CHROM header line in --vcf file.\n");
2872 goto VcfToPgen_ret_MALFORMED_INPUT;
2873 }
2874 if (line_iter[1] != '#') {
2875 break;
2876 }
2877 // Recognized header lines:
2878 // ##fileformat: discard (regenerate; todo: conditionally error out)
2879 // ##fileDate: discard (regenerate)
2880 // ##source: discard (regenerate)
2881 // ##contig: conditionally keep
2882 // ##INFO: note presence of INFO/PR, note presence of at least one non-PR
2883 // field, keep data (though, if INFO/PR is the *only* field,
2884 // omit it from the .pvar for consistency with --make-pgen
2885 // default)
2886 // update (8 Sep 2017): nonflag INFO/PR is noted, and not treated
2887 // specially unless provisional-reference INFO/PR output would
2888 // conflict with it
2889 // ##FORMAT: note presence of FORMAT/GT and FORMAT/GP, discard
2890 // (regenerate)
2891 // ##chrSet: if recognized, perform consistency check and/or update
2892 // chr_info
2893 //
2894 // Everything else (##FILTER, ##reference, etc.) is passed through
2895 // unchanged. FILTER values in the VCF body do not have to be mentioned
2896 // in the header (since only BCF, not VCF, spec requires that).
2897 //
2898 // Because of how ##contig is handled (we only keep the lines which
2899 // correspond to chromosomes/contigs actually present in the VCF, and not
2900 // filtered out), we wait until the second pass to write the .pvar.
2901 if (StrStartsWithUnsafe(&(line_iter[2]), "chrSet=<")) {
2902 if (unlikely(chrset_exists)) {
2903 logerrputs("Error: Multiple ##chrSet header lines in --vcf file.\n");
2904 goto VcfToPgen_ret_MALFORMED_INPUT;
2905 }
2906 chrset_exists = 1;
2907 // .pvar loader will print a warning if necessary
2908 reterr = ReadChrsetHeaderLine(&(line_iter[2 + strlen("chrSet=<")]), "--vcf file", misc_flags, line_idx, cip);
2909 if (unlikely(reterr)) {
2910 goto VcfToPgen_ret_1;
2911 }
2912 } else if (StrStartsWithUnsafe(&(line_iter[2]), "FORMAT=<")) {
2913 line_iter = &(line_iter[2 + strlen("FORMAT=<")]);
2914 char* idval;
2915 uint32_t id_slen;
2916 if (unlikely(HkvlineId(&line_iter, &idval, &id_slen))) {
2917 goto VcfToPgen_ret_MALFORMED_HEADER_LINE;
2918 }
2919 char* numstr;
2920 char* typestr;
2921 uint32_t num_slen;
2922 uint32_t type_slen;
2923 if (unlikely(HkvlineNumType(line_iter, &numstr, &num_slen, &typestr, &type_slen))) {
2924 goto VcfToPgen_ret_MALFORMED_HEADER_LINE;
2925 }
2926 if (strequal_k(idval, "GT", id_slen)) {
2927 if (unlikely(format_gt_exists)) {
2928 logerrputs("Error: Duplicate FORMAT/GT header line in --vcf file.\n");
2929 goto VcfToPgen_ret_MALFORMED_INPUT;
2930 }
2931 if (unlikely((!strequal_k(numstr, "1", num_slen)) || (!strequal_k(typestr, "String", type_slen)))) {
2932 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of --vcf file does not have expected FORMAT/GT format.\n", line_idx);
2933 goto VcfToPgen_ret_MALFORMED_INPUT_WW;
2934 }
2935 // bugfix (21 Nov 2023)
2936 format_gt_exists = 1;
2937 } else if ((vcf_min_gq != -1) && strequal_k(idval, "GQ", id_slen)) {
2938 if (unlikely(format_gq_relevant)) {
2939 logerrputs("Error: Duplicate FORMAT/GQ header line in --vcf file.\n");
2940 goto VcfToPgen_ret_MALFORMED_INPUT;
2941 }
2942 if (unlikely(!strequal_k(numstr, "1", num_slen))) {
2943 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of --vcf file does not have expected FORMAT/GQ format.\n", line_idx);
2944 goto VcfToPgen_ret_MALFORMED_INPUT_WW;
2945 }
2946 format_gq_relevant = 1;
2947 } else if (((vcf_min_dp != -1) || (vcf_max_dp != 0x7fffffff)) && strequal_k(idval, "DP", id_slen)) {
2948 if (unlikely(format_dp_relevant)) {
2949 logerrputs("Error: Duplicate FORMAT/DP header line in --vcf file.\n");
2950 goto VcfToPgen_ret_MALFORMED_INPUT;
2951 }
2952 if (unlikely(!strequal_k(numstr, "1", num_slen))) {
2953 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of --vcf file does not have expected FORMAT/DP format.\n", line_idx);
2954 }
2955 format_dp_relevant = 1;
2956 } else if (dosage_import_field) {
2957 if ((id_slen == dosage_import_field_slen) && memequal(idval, dosage_import_field, id_slen)) {
2958 if (unlikely(format_dosage_relevant)) {
2959 snprintf(g_logbuf, kLogbufSize, "Error: Duplicate FORMAT/%s header line in --vcf file.\n", dosage_import_field);
2960 goto VcfToPgen_ret_MALFORMED_INPUT_WW;
2961 }
2962 format_dosage_relevant = 1;
2963 } else if (format_hds_search && strequal_k(idval, "HDS", id_slen)) {
2964 if (unlikely(format_hds_search == 2)) {
2965 logerrputs("Error: Duplicate FORMAT/HDS header line in --vcf file.\n");
2966 goto VcfToPgen_ret_MALFORMED_INPUT;
2967 }
2968 format_hds_search = 2;
2969 } else if (unforced_gp && strequal_k(idval, "DS", id_slen)) {
2970 logerrputs("Error: --vcf dosage=GP specified, but --import-dosage-certainty was not and\nFORMAT/DS header line is present.\nSince " PROG_NAME_STR " collapses genotype probabilities down to dosages (even when\nperforming simple operations like \"" PROG_NAME_STR " --vcf ... --export bgen-1.2 ...\"),\n'dosage=GP' almost never makes sense in this situation. Either change it to\n'dosage=DS' (if dosages are good enough for your analysis), or use another\nprogram to work with the genotype probabilities.\nThere is one notable exception to the preceding recommendation: you are writing\na script to process VCF files that are guaranteed to have FORMAT/GP, but may or\nmay not have FORMAT/DS. You can use 'dosage=GP-force' to suppress this error\nin that situation.\n");
2971 goto VcfToPgen_ret_INCONSISTENT_INPUT;
2972 }
2973 }
2974 } else if (StrStartsWithUnsafe(&(line_iter[2]), "INFO=<")) {
2975 line_iter = &(line_iter[2 + strlen("INFO=<")]);
2976 char* idval;
2977 uint32_t id_slen;
2978 if (unlikely(HkvlineId(&line_iter, &idval, &id_slen))) {
2979 goto VcfToPgen_ret_MALFORMED_HEADER_LINE;
2980 }
2981 if (strequal_k(idval, "PR", id_slen)) {
2982 if (unlikely(info_pr_exists || info_pr_nonflag_exists)) {
2983 logerrputs("Error: Duplicate INFO/PR header line in --vcf file.\n");
2984 goto VcfToPgen_ret_MALFORMED_INPUT;
2985 }
2986 char* typestr;
2987 uint32_t type_slen;
2988 if (unlikely(HkvlineFind(line_iter, "Type", &typestr, &type_slen))) {
2989 goto VcfToPgen_ret_MALFORMED_HEADER_LINE;
2990 }
2991 info_pr_nonflag_exists = !strequal_k(typestr, "Flag", type_slen);
2992 info_pr_exists = 1 - info_pr_nonflag_exists;
2993 if (info_pr_nonflag_exists) {
2994 logerrprintfww("Warning: Header line %" PRIuPTR " of --vcf file has an unexpected definition of INFO/PR. This interferes with a few merge and liftover operations.\n", line_idx);
2995 }
2996 } else {
2997 info_nonpr_exists = 1;
2998 }
2999 }
3000 line_iter = AdvPastDelim(line_iter, '\n');
3001 const uint32_t prev_line_blen = line_iter - prev_line_start;
3002 if (prev_line_blen > max_line_blen) {
3003 max_line_blen = prev_line_blen;
3004 }
3005 }
3006 const uint32_t ref_n_missing = (import_flags / kfImportVcfRefNMissing) & 1;
3007 if (unlikely(ref_n_missing && (!info_pr_exists))) {
3008 logerrputs("Error: --vcf-ref-n-missing was specified, but the VCF does not have the\nINFO/PR header line that should be present in any .ped-derived VCF.\n");
3009 goto VcfToPgen_ret_INCONSISTENT_INPUT;
3010 }
3011 const uint32_t require_gt = (import_flags / kfImportVcfRequireGt) & 1;
3012 if (unlikely((!format_gt_exists) && require_gt)) {
3013 logerrputs("Error: No FORMAT/GT key found in --vcf file header, when --vcf-require-gt was\nspecified.\n(If this header line is actually present, but with extra spaces or unusual\nfield ordering, standardize the header with e.g. bcftools.)\n");
3014 goto VcfToPgen_ret_INCONSISTENT_INPUT;
3015 }
3016 if ((!format_gq_relevant) && (vcf_min_gq != -1)) {
3017 logerrputs("Warning: No FORMAT/GQ key found in --vcf file header. --vcf-min-gq ignored.\n(If this header line is actually present, but with extra spaces or unusual\nfield ordering, standardize the header with e.g. bcftools.)\n");
3018 vcf_min_gq = -1;
3019 }
3020 if ((!format_dp_relevant) && ((vcf_max_dp != 0x7fffffff) || (vcf_min_dp != -1))) {
3021 logerrputs("Warning: No FORMAT/DP key found in --vcf file header. --vcf-{max,min}-dp\nignored.\n(If this header line is actually present, but with extra spaces or unusual\nfield ordering, standardize the header with e.g. bcftools.)\n");
3022 vcf_max_dp = 0x7fffffff;
3023 vcf_min_dp = -1;
3024 }
3025 const uint32_t format_gq_or_dp_relevant = format_gq_relevant || format_dp_relevant;
3026 if (format_hds_search) {
3027 --format_hds_search;
3028 if (!format_hds_search) {
3029 if (!format_dosage_relevant) {
3030 logerrputs("Warning: No FORMAT/DS or /HDS key found in --vcf file header. Dosages will not\nbe imported.\n(If these header line(s) are actually present, but with extra spaces or unusual\nfield ordering, standardize the header with e.g. bcftools.)\n");
3031 } else {
3032 // since we did find FORMAT/DS, trailing parenthetical is very
3033 // unlikely to be relevant
3034 logerrputs("Warning: No FORMAT/HDS key found in --vcf file header. Dosages will be imported\n(from FORMAT/DS), but phase information will be limited or absent.\n");
3035 }
3036 }
3037 } else if ((!format_dosage_relevant) && dosage_import_field) {
3038 logerrprintfww("Warning: No FORMAT/%s key found in --vcf file header. Dosages will not be imported. (If this header line is actually present, but with extra spaces or unusual field ordering, standardize the header with e.g. bcftools.)\n", dosage_import_field);
3039 }
3040 FinalizeChrset(misc_flags, cip);
3041 // don't call FinalizeChrInfo here, since this may be followed by --pmerge,
3042 // etc.
3043
3044 if (unlikely(!StrStartsWithUnsafe(line_iter, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO"))) {
3045 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of --vcf file does not have expected field sequence after #CHROM.\n", line_idx);
3046 goto VcfToPgen_ret_MALFORMED_INPUT_WW;
3047 }
3048 char* linebuf_iter = &(line_iter[strlen("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO")]);
3049 uint32_t sample_ct = 0;
3050 if (StrStartsWithUnsafe(linebuf_iter, "\tFORMAT\t")) {
3051 reterr = VcfSampleLine(preexisting_psamname, const_fid, misc_flags, import_flags, fam_cols, id_delim, idspace_to, 'v', &(linebuf_iter[strlen("\tFORMAT\t")]), outname, outname_end, &sample_ct);
3052 if (unlikely(reterr)) {
3053 goto VcfToPgen_ret_1;
3054 }
3055 }
3056 if (unlikely((!sample_ct) && (!no_samples_ok))) {
3057 logerrputs("Error: No samples in --vcf file. (This is only permitted when you haven't\nspecified another operation which requires genotype or sample information.)\n");
3058 goto VcfToPgen_ret_DEGENERATE_DATA;
3059 }
3060 vic.vibc.sample_ct = sample_ct;
3061 // bugfix (5 Jun 2018): must initialize qual_field_ct to zero
3062 vic.vibc.qual_field_ct = 0;
3063
3064 uint32_t variant_ct = 0;
3065 uintptr_t max_variant_ct = bigstack_left() / sizeof(intptr_t);
3066 if (info_pr_exists) {
3067 // nonref_flags
3068 max_variant_ct -= BitCtToAlignedWordCt(max_variant_ct) * kWordsPerVec;
3069 }
3070 #ifdef __LP64__
3071 if (max_variant_ct > kPglMaxVariantCt) {
3072 max_variant_ct = kPglMaxVariantCt;
3073 }
3074 #endif
3075 uintptr_t base_chr_present[kChrExcludeWords];
3076 ZeroWArr(kChrExcludeWords, base_chr_present);
3077
3078 const uintptr_t header_line_ct = line_idx;
3079 const uint32_t max_variant_ctaw = BitCtToAlignedWordCt(max_variant_ct);
3080 // don't need dosage_flags or dphase_flags; dosage overrides GT so slow
3081 // parse needed
3082 uintptr_t* nonref_flags = nullptr;
3083 if (info_pr_exists) {
3084 nonref_flags = S_CAST(uintptr_t*, bigstack_alloc_raw_rd(max_variant_ctaw * sizeof(intptr_t)));
3085 }
3086 uintptr_t* nonref_flags_iter = nonref_flags;
3087 uintptr_t* allele_idx_offsets = R_CAST(uintptr_t*, g_bigstack_base);
3088 uintptr_t max_postformat_blen = 1; // starting from tab at end of FORMAT
3089 uintptr_t variant_skip_ct = 0;
3090 uintptr_t nonref_word = 0;
3091 uintptr_t allele_idx_end = 0;
3092 uint32_t max_alt_ct = 1;
3093 uint32_t max_allele_slen = 1;
3094 uint32_t max_qualfilterinfo_slen = 6;
3095 uint32_t phase_or_dosage_found = 0;
3096 uint32_t not_single_sample_no_nonvar = (sample_ct != 1) || format_dosage_relevant || format_hds_search || (import_flags & kfImportVcfAllowNoNonvar);
3097 uint32_t nonvar_nonmissing_ct = 0;
3098
3099 while (1) {
3100 ++line_idx;
3101 line_iter = AdvPastDelim(line_iter, '\n');
3102 const uint32_t prev_line_blen = line_iter - prev_line_start;
3103 if (prev_line_blen > max_line_blen) {
3104 max_line_blen = prev_line_blen;
3105 }
3106 reterr = TextNextLineUnsafe(&vcf_txs, &line_iter);
3107 if (reterr) {
3108 if (likely(reterr == kPglRetEof)) {
3109 // reterr = kPglRetSuccess;
3110 break;
3111 }
3112 goto VcfToPgen_ret_TSTREAM_FAIL;
3113 }
3114 prev_line_start = line_iter;
3115 // we were previously tolerating trailing newlines here, but there wasn't
3116 // a good reason for doing so.
3117 if (unlikely(ctou32(*line_iter) <= 32)) {
3118 if ((*line_iter == ' ') || (*line_iter == '\t')) {
3119 snprintf(g_logbuf, kLogbufSize, "Error: Leading space or tab on line %" PRIuPTR " of --vcf file.\n", line_idx);
3120 goto VcfToPgen_ret_MALFORMED_INPUT_2N;
3121 }
3122 goto VcfToPgen_ret_MISSING_TOKENS;
3123 }
3124 linebuf_iter = line_iter;
3125 char* chr_code_end = NextPrespace(line_iter);
3126 if (unlikely(*chr_code_end != '\t')) {
3127 goto VcfToPgen_ret_MISSING_TOKENS;
3128 }
3129 // QUAL/FILTER enforcement is now postponed till .pvar loading. only
3130 // other things we do during the scanning pass are (i) count alt alleles,
3131 // and (ii) check whether any phased genotype calls are present.
3132
3133 char* pos_end = NextPrespace(chr_code_end);
3134 if (unlikely(*pos_end != '\t')) {
3135 goto VcfToPgen_ret_MISSING_TOKENS;
3136 }
3137
3138 // may as well check ID length here
3139 // postpone POS validation till second pass so we only have to parse it
3140 // once
3141 char* id_end = NextPrespace(pos_end);
3142 if (unlikely(*id_end != '\t')) {
3143 goto VcfToPgen_ret_MISSING_TOKENS;
3144 }
3145 if (unlikely(S_CAST(uintptr_t, id_end - pos_end) > kMaxIdBlen)) {
3146 snprintf(g_logbuf, kLogbufSize, "Error: Invalid ID on line %" PRIuPTR " of --vcf file (max " MAX_ID_SLEN_STR " chars).\n", line_idx);
3147 goto VcfToPgen_ret_MALFORMED_INPUT_WWN;
3148 }
3149
3150 // note REF length
3151 char* ref_allele_start = &(id_end[1]);
3152 linebuf_iter = FirstPrespace(ref_allele_start);
3153 if (unlikely(*linebuf_iter != '\t')) {
3154 goto VcfToPgen_ret_MISSING_TOKENS;
3155 }
3156 uint32_t cur_max_allele_slen = linebuf_iter - ref_allele_start;
3157 if (unlikely(memchr(ref_allele_start, ',', cur_max_allele_slen) != nullptr)) {
3158 snprintf(g_logbuf, kLogbufSize, "Error: Invalid REF allele on line %" PRIuPTR " of --vcf file.\n", line_idx);
3159 goto VcfToPgen_ret_MALFORMED_INPUT_WWN;
3160 }
3161
3162 uint32_t alt_ct = 1;
3163 unsigned char ucc;
3164 // treat ALT=. as if it were an actual allele for now
3165 for (; ; ++alt_ct) {
3166 char* cur_allele_start = ++linebuf_iter;
3167 ucc = *linebuf_iter;
3168 if (unlikely((ucc <= ',') && (ucc != '*'))) {
3169 snprintf(g_logbuf, kLogbufSize, "Error: Invalid alternate allele on line %" PRIuPTR " of --vcf file.\n", line_idx);
3170 goto VcfToPgen_ret_MALFORMED_INPUT_2N;
3171 }
3172 do {
3173 ucc = *(++linebuf_iter);
3174 // allow GATK 3.4 <*:DEL> symbolic allele
3175 } while ((ucc > ',') || (ucc == '*'));
3176 const uint32_t cur_allele_slen = linebuf_iter - cur_allele_start;
3177 if (cur_allele_slen > cur_max_allele_slen) {
3178 cur_max_allele_slen = cur_allele_slen;
3179 }
3180 if (ucc != ',') {
3181 break;
3182 }
3183 }
3184
3185 if (unlikely(ucc != '\t')) {
3186 snprintf(g_logbuf, kLogbufSize, "Error: Malformed ALT field on line %" PRIuPTR " of --vcf file.\n", line_idx);
3187 goto VcfToPgen_ret_MALFORMED_INPUT_2N;
3188 }
3189 if (alt_ct > max_alt_ct) {
3190 if (alt_ct >= import_max_allele_ct) {
3191 ++variant_skip_ct;
3192 line_iter = linebuf_iter;
3193 continue;
3194 }
3195 max_alt_ct = alt_ct;
3196 }
3197
3198 // skip QUAL, FILTER
3199 char* qual_start_m1 = linebuf_iter;
3200 for (uint32_t uii = 0; uii != 2; ++uii) {
3201 linebuf_iter = NextPrespace(linebuf_iter);
3202 if (unlikely(*linebuf_iter != '\t')) {
3203 goto VcfToPgen_ret_MISSING_TOKENS;
3204 }
3205 }
3206
3207 // --vcf-require-gt
3208 char* info_start = &(linebuf_iter[1]);
3209 char* info_end = FirstPrespace(info_start);
3210 if (sample_ct) {
3211 if (unlikely(*info_end != '\t')) {
3212 goto VcfToPgen_ret_MISSING_TOKENS;
3213 }
3214 linebuf_iter = &(info_end[1]);
3215 vic.vibc.gt_exists = memequal_sk(linebuf_iter, "GT") && ((linebuf_iter[2] == ':') || (linebuf_iter[2] == '\t'));
3216 if (require_gt && (!vic.vibc.gt_exists)) {
3217 ++variant_skip_ct;
3218 line_iter = linebuf_iter;
3219 continue;
3220 }
3221 }
3222 const uint32_t cur_qualfilterinfo_slen = info_end - qual_start_m1;
3223
3224 // all converters *do* respect chromosome filters
3225 // wait till this point to apply it, since we don't want to
3226 // add a contig name to the hash table unless at least one variant on
3227 // that contig wasn't filtered out for other reasons.
3228 uint32_t cur_chr_code;
3229 reterr = GetOrAddChrCodeDestructive("--vcf file", line_idx, prohibit_extra_chr, line_iter, chr_code_end, cip, &cur_chr_code);
3230 if (unlikely(reterr)) {
3231 goto VcfToPgen_ret_1;
3232 }
3233 if (!IsSet(cip->chr_mask, cur_chr_code)) {
3234 ++variant_skip_ct;
3235 line_iter = info_end;
3236 continue;
3237 }
3238 if (cur_max_allele_slen > max_allele_slen) {
3239 max_allele_slen = cur_max_allele_slen;
3240 }
3241 if (cur_qualfilterinfo_slen > max_qualfilterinfo_slen) {
3242 max_qualfilterinfo_slen = cur_qualfilterinfo_slen;
3243 }
3244 if (cur_chr_code <= cip->max_code) {
3245 SetBit(cur_chr_code, base_chr_present);
3246 }
3247
3248 allele_idx_offsets[variant_ct] = allele_idx_end;
3249 allele_idx_end += alt_ct + 1;
3250 const uint32_t variant_idx_lowbits = variant_ct % kBitsPerWord;
3251 if (info_pr_exists) {
3252 if (PrInInfo(info_end - info_start, info_start)) {
3253 nonref_word |= k1LU << variant_idx_lowbits;
3254 }
3255 if (variant_idx_lowbits == (kBitsPerWord - 1)) {
3256 *nonref_flags_iter++ = nonref_word;
3257 nonref_word = 0;
3258 }
3259 }
3260 if (sample_ct) {
3261 // linebuf_iter currently points to beginning of FORMAT field
3262 const char* format_end = FirstPrespace(linebuf_iter);
3263 if (unlikely(*format_end != '\t')) {
3264 goto VcfToPgen_ret_MISSING_TOKENS;
3265 }
3266 if (phase_or_dosage_found && not_single_sample_no_nonvar) {
3267 goto VcfToPgen_linescan_done;
3268 }
3269
3270 if (format_dosage_relevant) {
3271 vic.dosage_field_idx = GetVcfFormatPosition(dosage_import_field, linebuf_iter, format_end, dosage_import_field_slen);
3272 }
3273 if (format_hds_search) {
3274 // theoretically possible for HDS to be in VCF header without
3275 // accompanying DS
3276 vic.hds_field_idx = GetVcfFormatPosition("HDS", linebuf_iter, format_end, 3);
3277 }
3278 if (format_gq_or_dp_relevant) {
3279 STD_ARRAY_DECL(uint32_t, 2, qual_field_idxs);
3280 uint32_t qual_field_ct = VcfQualScanInit1(linebuf_iter, format_end, vcf_min_gq, vcf_min_dp, vcf_max_dp, qual_field_idxs);
3281 // bugfix (5 Jun 2018): must initialize qual_field_ct to zero
3282 vic.vibc.qual_field_ct = 0;
3283 if (qual_field_ct) {
3284 vic.vibc.qual_field_ct = VcfQualScanInit2(qual_field_idxs, ctx.qual_mins, ctx.qual_maxs, vic.vibc.qual_field_skips, vic.vibc.qual_line_mins, vic.vibc.qual_line_maxs);
3285 }
3286 }
3287
3288 // Check if there's at least one phased het call, and/or at least one
3289 // relevant dosage.
3290 // If there's only one sample, maybe also check whether the VCF has any
3291 // hom-REF calls at all.
3292 // Don't bother multithreading this since it's trivial.
3293 if ((vic.hds_field_idx != UINT32_MAX) || (vic.dosage_field_idx != UINT32_MAX)) {
3294 if (alt_ct == 1) {
3295 vcf_parse_err = VcfScanBiallelicHdsLine(&vic, format_end, &phase_or_dosage_found, &line_iter);
3296 } else {
3297 putc_unlocked('\n', stdout);
3298 logerrputs("Error: --vcf multiallelic dosage import is under development.\n");
3299 reterr = kPglRetNotYetSupported;
3300 goto VcfToPgen_ret_1;
3301 }
3302 if (unlikely(vcf_parse_err)) {
3303 goto VcfToPgen_ret_PARSE;
3304 }
3305 } else {
3306 if (!vic.vibc.gt_exists) {
3307 goto VcfToPgen_linescan_done;
3308 }
3309 if (!not_single_sample_no_nonvar) {
3310 if (format_end[1] == '0') {
3311 const char cc = format_end[2];
3312 not_single_sample_no_nonvar = (((cc == '/') || (cc == '|')) && (format_end[3] == '0')) || (cc == ':') || (cc == '\t');
3313 }
3314 // This can miss ./0 and the like, but that should practically
3315 // never matter.
3316 nonvar_nonmissing_ct += (format_end[1] != '.');
3317 }
3318 if (!phase_or_dosage_found) {
3319 if (alt_ct < 10) {
3320 phase_or_dosage_found = VcfScanShortallelicLine(&(vic.vibc), format_end, &line_iter);
3321 } else {
3322 phase_or_dosage_found = VcfScanLongallelicLine(&(vic.vibc), format_end, &line_iter);
3323 }
3324 }
3325 }
3326 VcfToPgen_linescan_done:
3327 line_iter = AdvToDelim(line_iter, '\n');
3328 const uint32_t cur_postformat_slen = line_iter - format_end;
3329 if (cur_postformat_slen >= max_postformat_blen) {
3330 max_postformat_blen = cur_postformat_slen + 1;
3331 }
3332 }
3333 if (unlikely(variant_ct++ == max_variant_ct)) {
3334 #ifdef __LP64__
3335 if (variant_ct == kPglMaxVariantCt) {
3336 putc_unlocked('\n', stdout);
3337 logerrputs("Error: " PROG_NAME_STR " does not support more than 2^31 - 3 variants. We recommend using\nother software for very deep studies of small numbers of genomes.\n");
3338 goto VcfToPgen_ret_MALFORMED_INPUT;
3339 }
3340 #endif
3341 goto VcfToPgen_ret_NOMEM;
3342 }
3343 if (!(variant_ct % 1000)) {
3344 printf("\r--vcf: %uk variants scanned.", variant_ct / 1000);
3345 fflush(stdout);
3346 }
3347 }
3348 if (variant_ct % kBitsPerWord) {
3349 if (nonref_flags_iter) {
3350 *nonref_flags_iter = nonref_word;
3351 }
3352 } else if (unlikely(!variant_ct)) {
3353 logerrputs("Error: No variants in --vcf file.\n");
3354 goto VcfToPgen_ret_DEGENERATE_DATA;
3355 }
3356
3357 putc_unlocked('\r', stdout);
3358 if (!variant_skip_ct) {
3359 logprintf("--vcf: %u variant%s scanned.\n", variant_ct, (variant_ct == 1)? "" : "s");
3360 } else {
3361 logprintf("--vcf: %u variant%s scanned (%" PRIuPTR " skipped).\n", variant_ct, (variant_ct == 1)? "" : "s", variant_skip_ct);
3362 }
3363 if ((!not_single_sample_no_nonvar) && (nonvar_nonmissing_ct >= 1000)) {
3364 logerrputs("Warning: All genotypes contain at least one ALT allele; this implies the VCF\nwas incorrectly generated. You probably need to backtrack and e.g. rerun GATK\nGenotypeGVCFs with the --include-non-variant-sites flag added.\n");
3365 }
3366
3367 if (allele_idx_end > 2 * variant_ct) {
3368 allele_idx_offsets[variant_ct] = allele_idx_end;
3369 BigstackFinalizeW(allele_idx_offsets, variant_ct + 1);
3370 } else {
3371 allele_idx_offsets = nullptr;
3372 }
3373
3374 // Close file, then reopen with a smaller line-load buffer and (if bgzf)
3375 // reduce decompression thread count. 2 is good in the simplest cases
3376 // (no GQ/DP filter, no dosage), otherwise limit to 1.
3377 uint32_t decompress_thread_ct = 1;
3378 uint32_t calc_thread_ct;
3379 {
3380 if ((vcf_min_gq != -1) || (vcf_min_dp != -1) || (phase_or_dosage_found && (format_dosage_relevant || format_hds_search))) {
3381 // "are lines expensive to parse?" will add a multiallelic condition
3382 // to the disjunction soon
3383 // this is based on a bunch of DS-force measurements
3384 calc_thread_ct = 1 + (sample_ct > 5) + (sample_ct > 12) + (sample_ct > 32) + (sample_ct > 512);
3385 } else {
3386 if (TextIsMt(&vcf_txs) && (max_thread_ct > 1)) {
3387 decompress_thread_ct = 2;
3388 }
3389 // this seems to saturate around 3 threads.
3390 calc_thread_ct = 1 + (sample_ct > 40) + (sample_ct > 320);
3391 }
3392 if (unlikely(CleanupTextStream2(vcfname, &vcf_txs, &reterr))) {
3393 goto VcfToPgen_ret_1;
3394 }
3395 BigstackEndReset(bigstack_end_mark);
3396 reterr = InitTextStreamEx(vcfname, 1, kMaxLongLine, MAXV(max_line_blen, kTextStreamBlenFast), decompress_thread_ct, &vcf_txs);
3397 if (unlikely(reterr)) {
3398 goto VcfToPgen_ret_TSTREAM_FAIL;
3399 }
3400 if (calc_thread_ct + decompress_thread_ct > max_thread_ct) {
3401 calc_thread_ct = MAXV(1, max_thread_ct - decompress_thread_ct);
3402 }
3403 }
3404
3405 const uint32_t variant_ctl = BitCtToWordCt(variant_ct);
3406 PgenGlobalFlags phase_dosage_gflags = kfPgenGlobal0;
3407 GparseFlags gparse_flags = kfGparse0; // yeah, this is a bit redundant
3408 // bugfix (22 Jun 2018): if dosage= was specified, we need to reserve
3409 // phasepresent/dosage_present buffers for each variant even when we know
3410 // they'll be irrelevant, since they're needed during conversion.
3411 if (phase_or_dosage_found || format_hds_search || format_dosage_relevant) {
3412 if ((!format_hds_search) && (!format_dosage_relevant)) {
3413 // TODO: if phase_or_dosage_found is false, why do we still have to set
3414 // phase_dosage_gflags here? with this behavior, what was the point of
3415 // scanning the lines in the first pass?
3416 phase_dosage_gflags = kfPgenGlobalHardcallPhasePresent;
3417 gparse_flags = kfGparseHphase;
3418 } else {
3419 // thanks to automatic --hard-call-threshold, we may need to save
3420 // dosage-phase even when there's no HDS field
3421 phase_dosage_gflags = kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent;
3422 gparse_flags = kfGparseHphase | kfGparseDosage | kfGparseDphase;
3423 }
3424 }
3425 uint32_t nonref_flags_storage = 1;
3426 if (nonref_flags) {
3427 const uint32_t variant_ctl_m1 = variant_ctl - 1;
3428 const uintptr_t last_nonref_flags_word = nonref_flags[variant_ctl_m1];
3429 if (!last_nonref_flags_word) {
3430 for (uint32_t widx = 0; widx != variant_ctl_m1; ++widx) {
3431 if (nonref_flags[widx]) {
3432 nonref_flags_storage = 3;
3433 break;
3434 }
3435 }
3436 } else if (!((~last_nonref_flags_word) << ((-variant_ct) & (kBitsPerWord - 1)))) {
3437 nonref_flags_storage = 2;
3438 for (uint32_t widx = 0; widx != variant_ctl_m1; ++widx) {
3439 if (~nonref_flags[widx]) {
3440 nonref_flags_storage = 3;
3441 break;
3442 }
3443 }
3444 } else {
3445 nonref_flags_storage = 3;
3446 }
3447 if (nonref_flags_storage != 3) {
3448 // yeah, we may now have a temporary "memory leak" here (if
3449 // multiallelic variants are present, and thus allele_idx_offsets[]
3450 // must be kept around), but this array is typically only 1/64 the size
3451 // of allele_idx_offsets[].
3452 if (!allele_idx_offsets) {
3453 BigstackReset(nonref_flags);
3454 }
3455 nonref_flags = nullptr;
3456 }
3457 }
3458 snprintf(outname_end, kMaxOutfnameExtBlen, ".pvar");
3459 const uint32_t output_zst = ((import_flags & (kfImportKeepAutoconv | kfImportKeepAutoconvVzs)) != kfImportKeepAutoconv);
3460 if (output_zst) {
3461 snprintf(&(outname_end[5]), kMaxOutfnameExtBlen - 5, ".zst");
3462 }
3463 const uintptr_t overflow_buf_size = kCompressStreamBlock + MAXV(2 * max_allele_slen + max_qualfilterinfo_slen + kMaxIdSlen + 32, kCompressStreamBlock);
3464 reterr = InitCstreamAlloc(outname, 0, output_zst, sample_ct? 1 : MAXV(1, max_thread_ct - decompress_thread_ct), overflow_buf_size, &pvar_css, &pvar_cswritep);
3465 if (unlikely(reterr)) {
3466 goto VcfToPgen_ret_1;
3467 }
3468 for (line_idx = 1, line_iter = TextLineEnd(&vcf_txs); ; ++line_idx, line_iter = AdvPastDelim(line_iter, '\n')) {
3469 reterr = TextNextLineUnsafe(&vcf_txs, &line_iter);
3470 if (unlikely(reterr)) {
3471 goto VcfToPgen_ret_TSTREAM_FAIL;
3472 }
3473 if (line_idx == header_line_ct) {
3474 break;
3475 }
3476 // chrSet skipped here since we call AppendChrsetLine after this loop
3477 if (StrStartsWithUnsafe(line_iter, "##fileformat=") || StrStartsWithUnsafe(line_iter, "##fileDate=") || StrStartsWithUnsafe(line_iter, "##source=") || StrStartsWithUnsafe(line_iter, "##FORMAT=") || StrStartsWithUnsafe(line_iter, "##chrSet=")) {
3478 continue;
3479 }
3480 if (StrStartsWithUnsafe(line_iter, "##contig=<ID=")) {
3481 char* contig_name_start = &(line_iter[strlen("##contig=<ID=")]);
3482 char* contig_name_end = strchrnul_n(contig_name_start, ',');
3483 if (*contig_name_end != ',') {
3484 contig_name_end = Memrchr(contig_name_start, '>', contig_name_end - contig_name_start);
3485 if (unlikely(!contig_name_end)) {
3486 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of --vcf file does not have expected ##contig format.\n", line_idx);
3487 goto VcfToPgen_ret_MALFORMED_INPUT_WW;
3488 }
3489 }
3490 const uint32_t cur_chr_code = GetChrCodeCounted(cip, contig_name_end - contig_name_start, contig_name_start);
3491 if (IsI32Neg(cur_chr_code)) {
3492 continue;
3493 }
3494 if (cur_chr_code <= cip->max_code) {
3495 if (!IsSet(base_chr_present, cur_chr_code)) {
3496 continue;
3497 }
3498 } else {
3499 if (!IsSet(cip->chr_mask, cur_chr_code)) {
3500 continue;
3501 }
3502 }
3503 // Note that, when --output-chr is specified, we don't update the
3504 // ##contig header line chromosome code in the .pvar file, since
3505 // ##contig is not an explicit part of the .pvar specification, it's
3506 // just another blob of text as far as the main body of plink2 is
3507 // concerned. However, the codes are brought in sync during VCF/BCF
3508 // export.
3509 }
3510 // force OS-appropriate eoln
3511 char* line_last = AdvToDelim(line_iter, '\n');
3512 #ifdef _WIN32
3513 if (line_last[-1] == '\r') {
3514 --line_last;
3515 }
3516 // NOT safe to use AppendBinaryEoln here.
3517 if (unlikely(CsputsStd(line_iter, line_last - line_iter, &pvar_css, &pvar_cswritep))) {
3518 goto VcfToPgen_ret_WRITE_FAIL;
3519 }
3520 pvar_cswritep = strcpya_k(pvar_cswritep, "\r\n");
3521 #else
3522 char* line_write_end;
3523 if (line_last[-1] == '\r') {
3524 line_write_end = line_last;
3525 line_last[-1] = '\n';
3526 } else {
3527 line_write_end = &(line_last[1]);
3528 }
3529 if (unlikely(CsputsStd(line_iter, line_write_end - line_iter, &pvar_css, &pvar_cswritep))) {
3530 goto VcfToPgen_ret_WRITE_FAIL;
3531 }
3532 #endif
3533 line_iter = line_last;
3534 }
3535 if (cip->chrset_source) {
3536 AppendChrsetLine(cip, &pvar_cswritep);
3537 }
3538 pvar_cswritep = strcpya_k(pvar_cswritep, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER");
3539 if (info_nonpr_exists) {
3540 pvar_cswritep = strcpya_k(pvar_cswritep, "\tINFO");
3541 }
3542 AppendBinaryEoln(&pvar_cswritep);
3543 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
3544 goto VcfToPgen_ret_WRITE_FAIL;
3545 }
3546 if (max_alt_ct > kPglMaxAltAlleleCt) {
3547 logerrprintfww("Error: VCF file has a variant with %u ALT alleles; this build of " PROG_NAME_STR " is limited to " PGL_MAX_ALT_ALLELE_CT_STR ". (You can use \"--import-max-alleles " PGL_MAX_ALLELE_CT_STR "\" to filter out such variants.)\n", max_alt_ct);
3548 reterr = kPglRetNotYetSupported;
3549 goto VcfToPgen_ret_1;
3550 }
3551 const uint32_t max_allele_ct = max_alt_ct + 1;
3552 // may as well have a functional progress meter in no-samples case
3553 uint32_t main_block_size = MINV(65536, variant_ct);
3554 uint32_t per_thread_block_limit = main_block_size;
3555 uint32_t cur_thread_block_vidx_limit = 1;
3556 uintptr_t per_thread_byte_limit = 0;
3557 unsigned char* geno_bufs[2];
3558 // defensive
3559 geno_bufs[0] = nullptr;
3560 geno_bufs[1] = nullptr;
3561 if (hard_call_thresh == UINT32_MAX) {
3562 hard_call_thresh = kDosageMid / 10;
3563 }
3564 const uint32_t hard_call_halfdist = kDosage4th - hard_call_thresh;
3565 if (sample_ct) {
3566 snprintf(outname_end, kMaxOutfnameExtBlen, ".pgen");
3567 uintptr_t spgw_alloc_cacheline_ct;
3568 uint32_t max_vrec_len;
3569 reterr = SpgwInitPhase1(outname, allele_idx_offsets, nonref_flags, variant_ct, sample_ct, max_allele_ct, kPgenWriteBackwardSeek, phase_dosage_gflags, nonref_flags_storage, &spgw, &spgw_alloc_cacheline_ct, &max_vrec_len);
3570 if (unlikely(reterr)) {
3571 if (reterr == kPglRetOpenFail) {
3572 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
3573 }
3574 goto VcfToPgen_ret_1;
3575 }
3576 unsigned char* spgw_alloc;
3577 if (unlikely(bigstack_alloc_uc(spgw_alloc_cacheline_ct * kCacheline, &spgw_alloc))) {
3578 goto VcfToPgen_ret_NOMEM;
3579 }
3580 SpgwInitPhase2(max_vrec_len, &spgw, spgw_alloc);
3581
3582 if (unlikely(bigstack_alloc_ucp(calc_thread_ct, &ctx.thread_wkspaces) ||
3583 bigstack_alloc_u32(calc_thread_ct + 1, &(ctx.thread_bidxs[0])) ||
3584 bigstack_alloc_u32(calc_thread_ct + 1, &(ctx.thread_bidxs[1])) ||
3585 bigstack_calloc_w(calc_thread_ct, &ctx.err_line_idxs))) {
3586 goto VcfToPgen_ret_NOMEM;
3587 }
3588 ctx.vcf_parse_errs = S_CAST(VcfParseErr*, bigstack_alloc_raw_rd(calc_thread_ct * sizeof(VcfParseErr)));
3589 if (unlikely(!ctx.vcf_parse_errs)) {
3590 goto VcfToPgen_ret_NOMEM;
3591 }
3592 ctx.sample_ct = sample_ct;
3593 ctx.hard_call_halfdist = hard_call_halfdist;
3594 ctx.dosage_erase_halfdist = vic.dosage_erase_halfdist;
3595 ctx.import_dosage_certainty = import_dosage_certainty;
3596 ctx.parse_failed = 0;
3597 // defensive
3598 ctx.gparse[0] = nullptr;
3599 ctx.gparse[1] = nullptr;
3600 ctx.block_allele_idx_offsets[0] = nullptr;
3601 ctx.block_allele_idx_offsets[1] = nullptr;
3602 // Finished with all other memory allocations, so all remaining workspace
3603 // can be spent on multithreaded parsing. Spend up to 1/6 on
3604 // g_thread_wkspaces (tune this fraction later).
3605 // Probable todo: factor out common parts with bgen-1.3 initialization
3606 // into separate function(s).
3607 uint64_t max_write_byte_ct = GparseWriteByteCt(sample_ct, max_allele_ct, gparse_flags);
3608 // always allocate tmp_dphase_delta for now
3609 uint64_t thread_wkspace_cl_ct = DivUp(max_write_byte_ct + sample_ct * sizeof(SDosage), kCacheline);
3610 uintptr_t cachelines_avail = bigstack_left() / (6 * kCacheline);
3611 if (calc_thread_ct * thread_wkspace_cl_ct > cachelines_avail) {
3612 if (unlikely(thread_wkspace_cl_ct > cachelines_avail)) {
3613 goto VcfToPgen_ret_NOMEM;
3614 }
3615 calc_thread_ct = cachelines_avail / thread_wkspace_cl_ct;
3616 }
3617 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
3618 ctx.thread_wkspaces[tidx] = S_CAST(unsigned char*, bigstack_alloc_raw(thread_wkspace_cl_ct * kCacheline));
3619 ctx.vcf_parse_errs[tidx] = kVcfParseOk;
3620 }
3621
3622 // be pessimistic re: rounding
3623 cachelines_avail = (bigstack_left() / kCacheline) - 4;
3624 const uint64_t max_bytes_req_per_variant = sizeof(GparseRecord) + MAXV(max_postformat_blen, max_write_byte_ct) + calc_thread_ct;
3625 if (unlikely(cachelines_avail * kCacheline < 2 * max_bytes_req_per_variant)) {
3626 goto VcfToPgen_ret_NOMEM;
3627 }
3628 // use worst-case gparse_flags since lines will usually be similar
3629 uintptr_t min_bytes_req_per_variant = sizeof(GparseRecord) + GparseWriteByteCt(sample_ct, 2, gparse_flags);
3630 main_block_size = (cachelines_avail * kCacheline) / (min_bytes_req_per_variant * 2);
3631 // this is arbitrary, there's no connection to kPglVblockSize
3632 if (main_block_size > 65536) {
3633 main_block_size = 65536;
3634 }
3635 // divide by 2 for better parallelism in small-variant-count case
3636 // round up per_thread_block_limit so we only have two blocks
3637 if (main_block_size > DivUp(variant_ct, 2)) {
3638 main_block_size = DivUp(variant_ct, 2) + calc_thread_ct - 1;
3639 }
3640 // may as well guarantee divisibility
3641 per_thread_block_limit = main_block_size / calc_thread_ct;
3642 main_block_size = per_thread_block_limit * calc_thread_ct;
3643 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
3644 goto VcfToPgen_ret_NOMEM;
3645 }
3646 ctx.gparse[0] = S_CAST(GparseRecord*, bigstack_alloc_raw_rd(main_block_size * sizeof(GparseRecord)));
3647 ctx.gparse[1] = S_CAST(GparseRecord*, bigstack_alloc_raw_rd(main_block_size * sizeof(GparseRecord)));
3648 SetThreadFuncAndData(VcfGenoToPgenThread, &ctx, &tg);
3649 cachelines_avail = bigstack_left() / (kCacheline * 2);
3650 geno_bufs[0] = S_CAST(unsigned char*, bigstack_alloc_raw(cachelines_avail * kCacheline));
3651 geno_bufs[1] = S_CAST(unsigned char*, bigstack_alloc_raw(cachelines_avail * kCacheline));
3652 // This is only used for comparison purposes, so it is unnecessary to
3653 // round it down to a multiple of kBytesPerVec even though every actual
3654 // record will be vector-aligned.
3655 per_thread_byte_limit = (cachelines_avail * kCacheline) / calc_thread_ct;
3656 }
3657
3658 const uint32_t can_fail_on_ds_only = strequal_k(dosage_import_field, "DS", dosage_import_field_slen) && (!require_gt);
3659 uint32_t fail_on_ds_only = 0;
3660
3661 // If --lax-chrx-import wasn't specified, we now error out when all of the
3662 // following conditions hold:
3663 // 1. At least one sample is present.
3664 // 2a. Either no .fam/.psam or --update-sex file was provided and there's
3665 // at least one chrX variant, or
3666 // 2b. The basic chromosome set is default/human, --split-par wasn't
3667 // specified, and there's a variant in the intersection of the b37 and
3668 // b38 PARs.
3669 //
3670 // Without this error, it's way too easy for users to process chrX
3671 // incorrectly without realizing it, especially since VCF files directly
3672 // encode ploidy information and it's not immediately obvious why plink2
3673 // fails to read that.
3674 //
3675 // If --lax-chrx-import wasn't specified, and conditions (1) and (2a) hold,
3676 // we can error out immediately.
3677 // If conditions (1) holds, (2a) doesn't hold, and (2b) might hold, we
3678 // initialize par_warn_code, and in the main loop we error out if we
3679 // encounter a chrX POS in the intersection of the b37 and b38 PARs.
3680
3681 // Could also require the .fam/.psam to contain non-NA sex information?
3682 // But this should already be enough to address the main footgun.
3683 const uint32_t sex_info_avail = preexisting_psamname || is_update_or_impute_sex;
3684 uint32_t par_warn_code = UINT32_MAX;
3685 if ((!(import_flags & kfImportLaxChrX)) && sample_ct) {
3686 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
3687 if ((!IsI32Neg(x_code)) && IsSet(base_chr_present, x_code)) {
3688 if (unlikely(!sex_info_avail)) {
3689 logerrputs("Error: chrX is present in the input file, but no sex information was provided;\nrerun this import with --psam or --update-sex. --split-par may also be\nappropriate.\n");
3690 goto VcfToPgen_ret_INCONSISTENT_INPUT;
3691 } else if (IsHumanChrset(cip) && (!is_splitpar)) {
3692 par_warn_code = x_code;
3693 }
3694 }
3695 }
3696
3697 // Main workflow:
3698 // 1. Set n=0, load genotype data for first main_block_size variants
3699 // while writing .pvar
3700 //
3701 // 2. Spawn threads processing batch n genotype data
3702 // 3. If n>0, write results for block (n-1)
3703 // 4. Increment n by 1
3704 // 5. Load/write-.pvar for batch (n+1) unless eof
3705 // 6. Join threads
3706 // 7. Goto step 2 unless eof
3707 //
3708 // 8. Write results for last block
3709 uint32_t prev_block_write_ct = 0;
3710 uint32_t genotext_byte_ct = 0;
3711 uintptr_t record_byte_ct = 0;
3712 uint32_t allele_ct = 0;
3713 uint32_t* thread_bidxs = nullptr;
3714 GparseRecord* cur_gparse = nullptr;
3715 unsigned char* geno_buf_iter = nullptr;
3716 unsigned char* cur_thread_byte_stop = nullptr;
3717 uint32_t parity = 0;
3718 for (uint32_t vidx_start = 0; ; ) {
3719 uint32_t cur_block_write_ct = 0;
3720 if (!IsLastBlock(&tg)) {
3721 const uint32_t block_vidx_limit = variant_ct - vidx_start;
3722 cur_thread_block_vidx_limit = MINV(block_vidx_limit, per_thread_block_limit);
3723 uint32_t cur_thread_fill_idx = 0;
3724 if (sample_ct) {
3725 thread_bidxs = ctx.thread_bidxs[parity];
3726 cur_gparse = ctx.gparse[parity];
3727 if (allele_idx_offsets) {
3728 ctx.block_allele_idx_offsets[parity] = &(allele_idx_offsets[vidx_start]);
3729 }
3730 geno_buf_iter = geno_bufs[parity];
3731 cur_thread_byte_stop = &(geno_buf_iter[per_thread_byte_limit]);
3732 thread_bidxs[0] = 0;
3733 }
3734 uint32_t block_vidx = 0;
3735 GparseRecord* grp;
3736 if (!genotext_byte_ct) {
3737 goto VcfToPgen_load_start;
3738 }
3739 // we may stop before main_block_size due to insufficient space in
3740 // geno_bufs[parity]. if so, we copy over the post-FORMAT part of the
3741 // current line before proceeding.
3742 while (1) {
3743 grp = &(cur_gparse[block_vidx]);
3744 grp->record_start = geno_buf_iter;
3745 grp->flags = gparse_flags;
3746 STD_ARRAY_COPY(vic.vibc.qual_field_skips, 2, grp->metadata.read_vcf.qual_field_idxs);
3747 grp->metadata.read_vcf.gt_exists = vic.vibc.gt_exists;
3748 grp->metadata.read_vcf.qual_exists = vic.vibc.qual_field_ct;
3749 grp->metadata.read_vcf.dosage_field_idx = vic.dosage_field_idx;
3750 grp->metadata.read_vcf.hds_field_idx = vic.hds_field_idx;
3751 grp->metadata.read_vcf.line_idx = line_idx;
3752 if (gparse_flags != kfGparseNull) {
3753 memcpy(geno_buf_iter, linebuf_iter, genotext_byte_ct);
3754 }
3755 geno_buf_iter = &(geno_buf_iter[record_byte_ct]);
3756 ++block_vidx;
3757
3758 // true iff this is the last variant we're keeping in the entire
3759 // file
3760 if (block_vidx == block_vidx_limit) {
3761 for (; cur_thread_fill_idx != calc_thread_ct; ) {
3762 // save endpoint for current thread, and tell any leftover
3763 // threads to do nothing
3764 thread_bidxs[++cur_thread_fill_idx] = block_vidx;
3765 }
3766 break;
3767 }
3768 VcfToPgen_load_start:
3769 ++line_idx;
3770 line_iter = AdvPastDelim(line_iter, '\n');
3771 // In principle, it shouldn't be necessary to check the exact value
3772 // of reterr, but this may be useful for bug investigation.
3773 reterr = TextNextLineUnsafe(&vcf_txs, &line_iter);
3774 if (unlikely(reterr)) {
3775 goto VcfToPgen_ret_TSTREAM_FAIL;
3776 }
3777
3778 // 1. check if we skip this variant. chromosome filter,
3779 // import_max_allele_ct, and require_gt can cause this.
3780 char* chr_code_end = AdvToDelim(line_iter, '\t');
3781 uint32_t chr_code_base = GetChrCodeRaw(line_iter);
3782 if (chr_code_base == UINT32_MAX) {
3783 // skip hash table lookup if we know we aren't skipping the variant
3784 if (variant_skip_ct) {
3785 *chr_code_end = '\0';
3786 // can't overread, nonstd_names not in main workspace
3787 const uint32_t chr_code = IdHtableFind(line_iter, TO_CONSTCPCONSTP(cip->nonstd_names), cip->nonstd_id_htable, chr_code_end - line_iter, kChrHtableSize);
3788 if ((chr_code == UINT32_MAX) || (!IsSet(cip->chr_mask, chr_code))) {
3789 line_iter = chr_code_end;
3790 goto VcfToPgen_load_start;
3791 }
3792 *chr_code_end = '\t';
3793 }
3794 if (can_fail_on_ds_only) {
3795 fail_on_ds_only = cip->haploid_mask[0] & 1;
3796 }
3797 } else {
3798 if (chr_code_base >= kMaxContigs) {
3799 chr_code_base = cip->xymt_codes[chr_code_base - kMaxContigs];
3800 }
3801 if (IsI32Neg(chr_code_base) || (!IsSet(base_chr_present, chr_code_base))) {
3802 assert(variant_skip_ct);
3803 line_iter = chr_code_end;
3804 goto VcfToPgen_load_start;
3805 }
3806 if (can_fail_on_ds_only) {
3807 fail_on_ds_only = IsSet(cip->haploid_mask, chr_code_base);
3808 }
3809 }
3810 // chr_code_base is now a proper numeric chromosome index for
3811 // non-contigs, and UINT32_MAX if it's a contig name
3812 char* pos_str = &(chr_code_end[1]);
3813 char* pos_str_end = AdvToDelim(pos_str, '\t');
3814 // copy ID, REF verbatim...
3815 linebuf_iter = AdvToNthDelim(&(pos_str_end[1]), 2, '\t');
3816 if (ref_n_missing && memequal_sk(&(linebuf_iter[-2]), "\tN")) {
3817 // ...unless --vcf-ref-n-missing applies.
3818 linebuf_iter[-1] = '.';
3819 }
3820
3821 // ALT, QUAL, FILTER, INFO
3822 char* alt_start = &(linebuf_iter[1]);
3823 char* alt_end = AdvToDelim(alt_start, '\t');
3824 if ((import_max_allele_ct < 0x7ffffffe) && variant_skip_ct) {
3825 const uint32_t alt_ct = 1 + CountByte(alt_start, ',', alt_end - alt_start);
3826 if (alt_ct >= import_max_allele_ct) {
3827 line_iter = alt_end;
3828 goto VcfToPgen_load_start;
3829 }
3830 }
3831 char* filter_end = AdvToNthDelim(&(alt_end[1]), 2, '\t');
3832 char* format_start = nullptr;
3833 char* info_end;
3834 if (sample_ct) {
3835 info_end = AdvToDelim(&(filter_end[1]), '\t');
3836 format_start = &(info_end[1]);
3837 vic.vibc.gt_exists = memequal_sk(format_start, "GT") && ((format_start[2] == ':') || (format_start[2] == '\t'));
3838 if (require_gt && (!vic.vibc.gt_exists)) {
3839 line_iter = format_start;
3840 goto VcfToPgen_load_start;
3841 }
3842 } else {
3843 info_end = NextPrespace(filter_end);
3844 }
3845 // No variant-skipping past this point; safe to start writing to
3846 // pvar_cswritep.
3847
3848 // make sure POS starts with an integer, apply --output-chr setting
3849 uint32_t cur_bp;
3850 if (unlikely(ScanUintDefcap(pos_str, &cur_bp))) {
3851 snprintf(g_logbuf, kLogbufSize, "Error: Invalid POS on line %" PRIuPTR " of --vcf file.\n", line_idx);
3852 goto VcfToPgen_ret_MALFORMED_INPUT_2N;
3853 }
3854
3855 if (chr_code_base == UINT32_MAX) {
3856 pvar_cswritep = memcpya(pvar_cswritep, line_iter, chr_code_end - line_iter);
3857 } else {
3858 if (par_warn_code == chr_code_base) {
3859 if (unlikely((cur_bp <= kPAR1IntersectionLast) || (cur_bp >= kPAR2IntersectionFirst))) {
3860 putc_unlocked('\n', stdout);
3861 logerrputs("Error: Human chrX pseudoautosomal variant(s) appear to be present in the input\nVCF, but --split-par was not specified.\n");
3862 goto VcfToPgen_ret_INCONSISTENT_INPUT;
3863 }
3864 }
3865 pvar_cswritep = chrtoa(cip, chr_code_base, pvar_cswritep);
3866 }
3867 *pvar_cswritep++ = '\t';
3868 pvar_cswritep = u32toa(cur_bp, pvar_cswritep);
3869
3870 // first copy includes both REF and ALT1
3871 char* copy_start = pos_str_end;
3872 uint32_t alt_ct;
3873 for (alt_ct = 1; ; ++alt_ct) {
3874 ++linebuf_iter;
3875 unsigned char ucc;
3876 do {
3877 ucc = *(++linebuf_iter);
3878 // allow GATK 3.4 <*:DEL> symbolic allele
3879 } while ((ucc > ',') || (ucc == '*'));
3880 pvar_cswritep = memcpya(pvar_cswritep, copy_start, linebuf_iter - copy_start);
3881 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
3882 goto VcfToPgen_ret_WRITE_FAIL;
3883 }
3884 if (ucc != ',') {
3885 break;
3886 }
3887 copy_start = linebuf_iter;
3888 }
3889
3890 if (info_nonpr_exists) {
3891 // VCF specification permits whitespace in INFO field, while PVAR
3892 // does not. Check for whitespace and error out if necessary.
3893 if (unlikely(memchr(filter_end, ' ', info_end - filter_end))) {
3894 snprintf(g_logbuf, kLogbufSize, "Error: INFO field on line %" PRIuPTR " of --vcf file contains a space; this cannot be imported by " PROG_NAME_STR ". Remove or reformat the field before reattempting import.\n", line_idx);
3895 goto VcfToPgen_ret_MALFORMED_INPUT_WWN;
3896 }
3897 pvar_cswritep = memcpya(pvar_cswritep, linebuf_iter, info_end - linebuf_iter);
3898 } else {
3899 pvar_cswritep = memcpya(pvar_cswritep, linebuf_iter, filter_end - linebuf_iter);
3900 }
3901 AppendBinaryEoln(&pvar_cswritep);
3902 if (!sample_ct) {
3903 if (++block_vidx == cur_thread_block_vidx_limit) {
3904 break;
3905 }
3906 line_iter = info_end;
3907 goto VcfToPgen_load_start;
3908 }
3909 if ((!vic.vibc.gt_exists) && (!format_dosage_relevant) && (!format_hds_search)) {
3910 line_iter = AdvToDelim(format_start, '\n');
3911 if (unlikely(CountByte(format_start, '\t', line_iter - format_start) != sample_ct)) {
3912 goto VcfToPgen_ret_MISSING_TOKENS;
3913 }
3914 gparse_flags = kfGparseNull;
3915 genotext_byte_ct = 1;
3916 } else {
3917 linebuf_iter = AdvToDelim(format_start, '\t');
3918 if (format_gq_or_dp_relevant) {
3919 vic.vibc.qual_field_ct = VcfQualScanInit1(format_start, linebuf_iter, vcf_min_gq, vcf_min_dp, vcf_max_dp, vic.vibc.qual_field_skips);
3920 }
3921 if ((!phase_or_dosage_found) && (!format_dosage_relevant) && (!format_hds_search)) {
3922 gparse_flags = kfGparse0;
3923 } else {
3924 if (format_dosage_relevant) {
3925 vic.dosage_field_idx = GetVcfFormatPosition(dosage_import_field, format_start, linebuf_iter, dosage_import_field_slen);
3926 }
3927 if (format_hds_search) {
3928 vic.hds_field_idx = GetVcfFormatPosition("HDS", format_start, linebuf_iter, 3);
3929 }
3930 if (unlikely(fail_on_ds_only && (!vic.vibc.gt_exists) && (vic.dosage_field_idx != UINT32_MAX) && (vic.hds_field_idx == UINT32_MAX))) {
3931 // could allow the chrX all-female case, but let's keep this
3932 // simple for now
3933 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --vcf file is for a chrX, chrM, or fully-haploid variant, and has a DS field without a companion GT field to clarify whether each DS value is on a 0..1 or 0..2 scale. This cannot be imported by " PROG_NAME_STR "; please e.g. regenerate the file with GT present.\n", line_idx);
3934 goto VcfToPgen_ret_MALFORMED_INPUT_WWN;
3935 }
3936 gparse_flags = ((vic.dosage_field_idx != UINT32_MAX) || (vic.hds_field_idx != UINT32_MAX))? (kfGparseHphase | kfGparseDosage | kfGparseDphase) : kfGparseHphase;
3937 }
3938 line_iter = AdvToDelim(linebuf_iter, '\n');
3939 genotext_byte_ct = 1 + S_CAST(uintptr_t, line_iter - linebuf_iter);
3940 }
3941 allele_ct = alt_ct + 1;
3942 const uintptr_t write_byte_ct_limit = GparseWriteByteCt(sample_ct, allele_ct, gparse_flags);
3943 record_byte_ct = MAXV(RoundUpPow2(genotext_byte_ct, kBytesPerVec), write_byte_ct_limit);
3944
3945 if ((block_vidx == cur_thread_block_vidx_limit) || (S_CAST(uintptr_t, cur_thread_byte_stop - geno_buf_iter) < record_byte_ct)) {
3946 thread_bidxs[++cur_thread_fill_idx] = block_vidx;
3947 if (cur_thread_fill_idx == calc_thread_ct) {
3948 break;
3949 }
3950 cur_thread_byte_stop = &(cur_thread_byte_stop[per_thread_byte_limit]);
3951 cur_thread_block_vidx_limit = MINV(cur_thread_block_vidx_limit + per_thread_block_limit, block_vidx_limit);
3952 }
3953 }
3954 cur_block_write_ct = block_vidx;
3955 }
3956 if (sample_ct) {
3957 if (vidx_start) {
3958 JoinThreads(&tg);
3959 if (unlikely(ctx.parse_failed)) {
3960 goto VcfToPgen_ret_THREAD_PARSE;
3961 }
3962 }
3963 if (!IsLastBlock(&tg)) {
3964 if (vidx_start + cur_block_write_ct == variant_ct) {
3965 DeclareLastThreadBlock(&tg);
3966 }
3967 if (unlikely(SpawnThreads(&tg))) {
3968 goto VcfToPgen_ret_THREAD_CREATE_FAIL;
3969 }
3970 }
3971 parity = 1 - parity;
3972 if (vidx_start) {
3973 // write *previous* block results
3974 reterr = GparseFlush(ctx.gparse[parity], allele_idx_offsets, prev_block_write_ct, &spgw);
3975 if (unlikely(reterr)) {
3976 goto VcfToPgen_ret_1;
3977 }
3978 }
3979 } else if (vidx_start + cur_block_write_ct == variant_ct) {
3980 break;
3981 }
3982 if (vidx_start == variant_ct) {
3983 break;
3984 }
3985 if (vidx_start) {
3986 printf("\r--vcf: %uk variants converted.", vidx_start / 1000);
3987 if (vidx_start <= main_block_size) {
3988 fputs(" \b\b\b\b", stdout);
3989 }
3990 fflush(stdout);
3991 }
3992 vidx_start += cur_block_write_ct;
3993 prev_block_write_ct = cur_block_write_ct;
3994 }
3995 if (unlikely(CswriteCloseNull(&pvar_css, pvar_cswritep))) {
3996 goto VcfToPgen_ret_WRITE_FAIL;
3997 }
3998 if (sample_ct) {
3999 reterr = SpgwFinish(&spgw);
4000 if (unlikely(reterr)) {
4001 goto VcfToPgen_ret_1;
4002 }
4003 }
4004 putc_unlocked('\r', stdout);
4005 char* write_iter = strcpya_k(g_logbuf, "--vcf: ");
4006 const uint32_t outname_base_slen = outname_end - outname;
4007 if (sample_ct) {
4008 write_iter = memcpya(write_iter, outname, outname_base_slen + 5);
4009 write_iter = strcpya_k(write_iter, " + ");
4010 } else {
4011 *pgen_generated_ptr = 0;
4012 }
4013 write_iter = memcpya(write_iter, outname, outname_base_slen);
4014 write_iter = strcpya_k(write_iter, ".pvar");
4015 if (output_zst) {
4016 write_iter = strcpya_k(write_iter, ".zst");
4017 }
4018 if (sample_ct && (!preexisting_psamname)) {
4019 write_iter = strcpya_k(write_iter, " + ");
4020 write_iter = memcpya(write_iter, outname, outname_base_slen);
4021 write_iter = strcpya_k(write_iter, ".psam");
4022 } else {
4023 *psam_generated_ptr = 0;
4024 }
4025 write_iter = strcpya_k(write_iter, " written");
4026 if (!sample_ct) {
4027 write_iter = strcpya_k(write_iter, " (no samples present)");
4028 }
4029 strcpy_k(write_iter, ".\n");
4030 WordWrapB(0);
4031 logputsb();
4032 }
4033 while (0) {
4034 VcfToPgen_ret_NOMEM:
4035 reterr = kPglRetNomem;
4036 break;
4037 VcfToPgen_ret_WRITE_FAIL:
4038 reterr = kPglRetWriteFail;
4039 break;
4040 VcfToPgen_ret_TSTREAM_FAIL:
4041 putc_unlocked('\n', stdout);
4042 TextStreamErrPrint("--vcf file", &vcf_txs);
4043 break;
4044 VcfToPgen_ret_THREAD_PARSE:
4045 {
4046 // Doesn't really cost us anything to report the first error if multiple
4047 // converter threads error out in the same block, though we can't
4048 // generally guarantee that we'll report the first error in the file.
4049 for (uint32_t tidx = 0; ; ++tidx) {
4050 vcf_parse_err = ctx.vcf_parse_errs[tidx];
4051 if (vcf_parse_err) {
4052 line_idx = ctx.err_line_idxs[tidx];
4053 break;
4054 }
4055 }
4056 }
4057 VcfToPgen_ret_PARSE:
4058 if (vcf_parse_err == kVcfParseInvalidGt) {
4059 putc_unlocked('\n', stdout);
4060 logerrprintf("Error: Line %" PRIuPTR " of --vcf file has an invalid GT field.\n", line_idx);
4061 reterr = kPglRetMalformedInput;
4062 break;
4063 } else if (vcf_parse_err == kVcfParseHalfCallError) {
4064 putc_unlocked('\n', stdout);
4065 logerrprintf("Error: Line %" PRIuPTR " of --vcf file has a GT half-call.\n", line_idx);
4066 if (!half_call_explicit_error) {
4067 logerrputs("Use --vcf-half-call to specify how these should be processed.\n");
4068 }
4069 reterr = kPglRetMalformedInput;
4070 break;
4071 } else if (vcf_parse_err == kVcfParseInvalidDosage) {
4072 // probable todo: distinguish HDS errors (right now, it just prints
4073 // "invalid DS field" on all HDS errors).
4074 putc_unlocked('\n', stdout);
4075 logerrprintfww("Error: Line %" PRIuPTR " of --vcf file has an invalid %s field.\n", line_idx, dosage_import_field);
4076 reterr = kPglRetInconsistentInput;
4077 break;
4078 } else if (vcf_parse_err == kVcfParsePolyploidError) {
4079 putc_unlocked('\n', stdout);
4080 logerrprintfww("Error: Line %" PRIuPTR " of --vcf file has a polyploid genotype.%s\n", line_idx, (import_flags & kfImportPolyploidExplicitError)? "" : " (Use '--polyploid-mode missing' to treat these as missing values.)");
4081 reterr = kPglRetInconsistentInput;
4082 break;
4083 }
4084 VcfToPgen_ret_MISSING_TOKENS:
4085 putc_unlocked('\n', stdout);
4086 logerrprintf("Error: Line %" PRIuPTR " of --vcf file has fewer tokens than expected.\n", line_idx);
4087 reterr = kPglRetMalformedInput;
4088 break;
4089 VcfToPgen_ret_MALFORMED_INPUT_2N:
4090 putc_unlocked('\n', stdout);
4091 logerrputsb();
4092 VcfToPgen_ret_MALFORMED_INPUT:
4093 reterr = kPglRetMalformedInput;
4094 break;
4095 VcfToPgen_ret_MALFORMED_HEADER_LINE:
4096 logerrprintf("Error: Header line %" PRIuPTR " of --vcf file is malformed.\n", line_idx);
4097 reterr = kPglRetMalformedInput;
4098 break;
4099 VcfToPgen_ret_MALFORMED_INPUT_WWN:
4100 putc_unlocked('\n', stdout);
4101 VcfToPgen_ret_MALFORMED_INPUT_WW:
4102 WordWrapB(0);
4103 logerrputsb();
4104 reterr = kPglRetMalformedInput;
4105 break;
4106 VcfToPgen_ret_INCONSISTENT_INPUT:
4107 reterr = kPglRetInconsistentInput;
4108 break;
4109 VcfToPgen_ret_THREAD_CREATE_FAIL:
4110 reterr = kPglRetThreadCreateFail;
4111 break;
4112 VcfToPgen_ret_DEGENERATE_DATA:
4113 reterr = kPglRetDegenerateData;
4114 break;
4115 }
4116 VcfToPgen_ret_1:
4117 CleanupSpgw(&spgw, &reterr);
4118 CleanupThreads(&tg);
4119 CleanupTextStream2("--vcf file", &vcf_txs, &reterr);
4120 CswriteCloseCond(&pvar_css, pvar_cswritep);
4121 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
4122 return reterr;
4123 }
4124
4125 PglErr BcfHeaderLineIdxCheck(const char* line_iter, uint32_t header_line_idx) {
4126 while (1) {
4127 const char* tag_start = &(line_iter[1]);
4128 if (unlikely(memequal_sk(tag_start, "IDX="))) {
4129 // Although this is text, it's not supposed to be human-edited, so we
4130 // deliberately discourage spec-conforming behavior that's different from
4131 // bcftools's straightforward approach of always putting IDX= at the end.
4132 logerrprintfww("Error: Line %u in BCF text header block has IDX= in the center instead of the end of the line; this is not currently supported by " PROG_NAME_STR ". Contact us if you need this to work.\n", header_line_idx);
4133 return kPglRetNotYetSupported;
4134 }
4135 line_iter = AdvPastDelim(tag_start, '=');
4136 if (*line_iter != '"') {
4137 line_iter = strchrnul_n(line_iter, ',');
4138 if (*line_iter == ',') {
4139 continue;
4140 }
4141 return kPglRetSuccess;
4142 }
4143 // Need to worry about backslash-escaped characters.
4144 ++line_iter;
4145 while (1) {
4146 line_iter = strchrnul2_n(line_iter, '\\', '"');
4147 const char cc = *line_iter;
4148 if (cc == '"') {
4149 break;
4150 }
4151 if (unlikely((cc == '\n') || (line_iter[1] == '\n'))) {
4152 goto BcfHeaderLineIdxCheck_FAIL;
4153 }
4154 line_iter = &(line_iter[2]);
4155 }
4156 ++line_iter;
4157 const char cc = *line_iter;
4158 if (cc == ',') {
4159 continue;
4160 }
4161 // bugfix (19 Feb 2020)
4162 if (likely(cc == '>')) {
4163 return kPglRetSuccess;
4164 }
4165 break;
4166 }
4167 BcfHeaderLineIdxCheck_FAIL:
4168 logerrprintf("Error: Line %u in BCF text header block is malformed.\n", header_line_idx);
4169 return kPglRetMalformedInput;
4170 }
4171
4172 // Caller's responsibility to check for overread and nonnegativity.
4173 BoolErr ScanBcfTypedInt(const unsigned char** vrec_iterp, uint32_t* uint_ptr) {
4174 const unsigned char* vrec_iter = *vrec_iterp;
4175 const uint32_t type_descriptor_byte = *vrec_iter++;
4176 int32_t ii;
4177 if (type_descriptor_byte == 0x11) {
4178 ii = *R_CAST(const int8_t*, vrec_iter);
4179 ++vrec_iter;
4180 } else if (type_descriptor_byte == 0x12) {
4181 ii = *R_CAST(const int16_t*, vrec_iter);
4182 vrec_iter = &(vrec_iter[2]);
4183 } else if (likely(type_descriptor_byte == 0x13)) {
4184 ii = *R_CAST(const int32_t*, vrec_iter);
4185 vrec_iter = &(vrec_iter[4]);
4186 } else {
4187 return 1;
4188 }
4189 *vrec_iterp = vrec_iter;
4190 *uint_ptr = ii;
4191 return 0;
4192 }
4193
4194 // value_type guaranteed to be in 0..15, but otherwise unvalidated. value_ct
4195 // not validated.
4196 static inline BoolErr ScanBcfType(const unsigned char** vrec_iterp, uint32_t* value_type_ptr, uint32_t* value_ct_ptr) {
4197 const uint32_t type_descriptor_byte = **vrec_iterp;
4198 *vrec_iterp += 1;
4199 *value_type_ptr = type_descriptor_byte & 0xf;
4200 *value_ct_ptr = type_descriptor_byte >> 4;
4201 if (*value_ct_ptr != 15) {
4202 return 0;
4203 }
4204 return ScanBcfTypedInt(vrec_iterp, value_ct_ptr);
4205 }
4206
4207 static inline BoolErr ScanBcfTypeAligned(const unsigned char** vrec_iterp, uint32_t* value_type_ptr, uint32_t* value_ct_ptr) {
4208 const uint32_t type_descriptor_byte = **vrec_iterp;
4209 *value_type_ptr = type_descriptor_byte & 0xf;
4210 *value_ct_ptr = type_descriptor_byte >> 4;
4211 if (*value_ct_ptr != 15) {
4212 *vrec_iterp += kBytesPerVec;
4213 return 0;
4214 }
4215 #ifdef __LP64__
4216 const unsigned char* vrec_iter_tmp = *vrec_iterp;
4217 ++vrec_iter_tmp;
4218 *vrec_iterp += kBytesPerVec;
4219 // bugfix (5 Apr 2023): this was not scanning the correct value. Previously
4220 // unnoticed since it would only come up for very high ploidy.
4221 return ScanBcfTypedInt(&vrec_iter_tmp, value_ct_ptr);
4222 #else
4223 *vrec_iterp += 1;
4224 BoolErr ret_boolerr = ScanBcfTypedInt(vrec_iterp, value_ct_ptr);
4225 AlignKUcToVec(vrec_iterp);
4226 return ret_boolerr;
4227 #endif
4228 }
4229
4230 // Check overread within this function, since it can be long enough for integer
4231 // overflow, etc.
4232 BoolErr ScanBcfTypedString(const unsigned char* vrec_end, const unsigned char** vrec_iterp, const char** string_startp, uint32_t* slen_ptr) {
4233 const unsigned char* vrec_iter = *vrec_iterp;
4234 const uint32_t type_descriptor_byte = *vrec_iter++;
4235 if (unlikely((type_descriptor_byte & 0xf) != 7)) {
4236 return 1;
4237 }
4238 uint32_t slen = type_descriptor_byte >> 4;
4239 if (slen == 15) {
4240 if (unlikely(ScanBcfTypedInt(&vrec_iter, &slen) || (S_CAST(int32_t, slen) < 15))) {
4241 return 1;
4242 }
4243 }
4244 if (unlikely(S_CAST(intptr_t, vrec_end - vrec_iter) < S_CAST(intptr_t, slen))) {
4245 return 1;
4246 }
4247 *string_startp = R_CAST(const char*, vrec_iter);
4248 *vrec_iterp = &(vrec_iter[slen]);
4249 *slen_ptr = slen;
4250 return 0;
4251 }
4252
4253 // Unlike the VCF case, everything in BcfImportContext is constant across the
4254 // file. Variation in FORMAT field presence and order is dealt with before the
4255 // handoff to BcfGenoToPgenThread, and UINT32_MAX offset values are used to
4256 // indicate missing fields.
4257 typedef struct BcfImportBaseContextStruct {
4258 uint32_t sample_ct;
4259 VcfHalfCall halfcall_mode;
4260 uint32_t error_on_polyploid;
4261 // [0] = GQ, [1] = DP
4262 STD_ARRAY_DECL(int32_t, 2, qual_mins);
4263 STD_ARRAY_DECL(int32_t, 2, qual_maxs);
4264 #ifdef USE_AVX2
4265 unsigned char biallelic_gt_lookup[32];
4266 #else
4267 unsigned char biallelic_gt_lookup[16];
4268 #endif
4269 } BcfImportBaseContext;
4270
4271 typedef struct BcfImportContextStruct {
4272 BcfImportBaseContext bibc;
4273 uint32_t dosage_is_gp;
4274 uint32_t dosage_erase_halfdist;
4275 double import_dosage_certainty;
4276 } BcfImportContext;
4277
4278 ENUM_U31_DEF_START()
4279 kBcfParseOk,
4280 kBcfParseMalformedGeneric,
4281 kBcfParseHalfCallError,
4282 kBcfParseInvalidDosage,
4283 kBcfParsePolyploidError,
4284 kBcfParseWideGt,
4285 kBcfParseFloatDp,
4286 kBcfParseNonfloatDosage
4287 ENUM_U31_DEF_END(BcfParseErr);
4288
4289 // Sets genovec bits to 0b11 whenever GQ/DP doesn't pass. (Caller should pass
4290 // in a separate array if they need to distinguish between ordinary genovec
4291 // missingness vs. missingness due to this filter.)
4292 BcfParseErr BcfParseGqDpMain(const unsigned char* qual_main, uint32_t sample_ct, uint32_t qual_min, uint32_t qual_max, uint32_t qual_value_type, uintptr_t* genovec) {
4293 // need to support int8, int16, int32, and float.
4294 #ifndef __LP64__
4295 const uint32_t word_ct_m1 = (sample_ct - 1) / kBitsPerWordD2;
4296 uint32_t loop_len = kBitsPerWordD2;
4297 #endif
4298 if (qual_value_type == 1) {
4299 // int8
4300 #ifdef __LP64__
4301 const uint32_t fullvec_ct = sample_ct / kBytesPerVec;
4302 Vec4thUint* genovec_alias = R_CAST(Vec4thUint*, genovec);
4303 #endif
4304 if (qual_max >= 0x7f) {
4305 // Usual case: safe to skip qual_max comparisons.
4306 // Subtract 1 with wraparound, and then check for < -1, since we need
4307 // 0x80 (missing) to always pass.
4308 const int8_t effective_qual_min_m1 = (qual_min >= 0x80)? 0x7f : (S_CAST(int8_t, qual_min) - 1);
4309 #ifdef __LP64__
4310 const VecUc* qual_alias = R_CAST(const VecUc*, qual_main);
4311 const VecUc all1 = vecuc_set1(0xff);
4312 const VecI8 min_m1_vec = veci8_set1(effective_qual_min_m1);
4313 for (uint32_t vidx = 0; vidx != fullvec_ct; ++vidx) {
4314 // don't start with VecI8, since we start with a wraparound
4315 // subtraction.
4316 const VecUc vv = vecuc_loadu(&(qual_alias[vidx]));
4317 const VecI8 vv_m1 = R_CAST(VecI8, vv + all1);
4318 VecI8 fail_vec = (min_m1_vec > vv_m1);
4319 fail_vec = veci8_permute0xd8_if_avx2(fail_vec);
4320 const VecI8 fail_vec_lo = veci8_unpacklo8(fail_vec, fail_vec);
4321 const VecI8 fail_vec_hi = veci8_unpackhi8(fail_vec, fail_vec);
4322 // todo: better ARM implementation
4323 const Vec4thUint fail_bits_lo = veci8_movemask(fail_vec_lo);
4324 const Vec4thUint fail_bits_hi = veci8_movemask(fail_vec_hi);
4325 genovec_alias[vidx] |= fail_bits_lo | (fail_bits_hi << kBytesPerVec);
4326 }
4327 const uint32_t remainder = sample_ct % kBytesPerVec;
4328 if (remainder) {
4329 const unsigned char* trailing_start = &(qual_main[fullvec_ct * kBytesPerVec]);
4330 Vec4thUint fail_bits = 0;
4331 for (uint32_t uii = 0; uii != remainder; ++uii) {
4332 const int8_t cur_qual_m1 = S_CAST(int8_t, trailing_start[uii] - 1);
4333 if (effective_qual_min_m1 > cur_qual_m1) {
4334 fail_bits |= (3 * k1LU) << (2 * uii);
4335 }
4336 }
4337 genovec_alias[fullvec_ct] |= fail_bits;
4338 }
4339 #else
4340 const unsigned char* qual_iter = qual_main;
4341 for (uint32_t widx = 0; ; ++widx) {
4342 if (widx >= word_ct_m1) {
4343 if (widx > word_ct_m1) {
4344 break;
4345 }
4346 loop_len = ModNz(sample_ct, kBitsPerWordD2);
4347 }
4348 uintptr_t geno_word = genovec[widx];
4349 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
4350 const int8_t cur_qual_m1 = S_CAST(int8_t, qual_iter[sample_idx_lowbits] - 1);
4351 if (effective_qual_min_m1 > cur_qual_m1) {
4352 geno_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
4353 }
4354 }
4355 qual_iter = &(qual_iter[kBitsPerWordD2]);
4356 genovec[widx] = geno_word;
4357 }
4358 #endif
4359 } else {
4360 // Two comparisons required, and we need to special-case the missing
4361 // value.
4362 // (There is currently no case where we enforce a maximum but not a
4363 // minimum. Even when --vcf-max-dp is specified without --vcf-min-dp, a
4364 // minimum depth of zero is always enforced, and we're scanning a vector
4365 // of signed values.)
4366 #ifdef __LP64__
4367 const VecI8* qual_alias = R_CAST(const VecI8*, qual_main);
4368 const VecI8 min_vec = veci8_set1(qual_min);
4369 const VecI8 max_vec = veci8_set1(qual_max);
4370 const VecI8 missing_vec = veci8_set1(0x80);
4371 for (uint32_t vidx = 0; vidx != fullvec_ct; ++vidx) {
4372 const VecI8 vv = veci8_loadu(&(qual_alias[vidx]));
4373 const VecI8 fail_or_missing_vec = (min_vec > vv) | (max_vec < vv);
4374 const VecI8 cur_missing_vec = (vv == missing_vec);
4375 VecI8 fail_vec = veci8_and_notfirst(cur_missing_vec, fail_or_missing_vec);
4376 fail_vec = veci8_permute0xd8_if_avx2(fail_vec);
4377 const VecI8 fail_vec_lo = veci8_unpacklo8(fail_vec, fail_vec);
4378 const VecI8 fail_vec_hi = veci8_unpackhi8(fail_vec, fail_vec);
4379 const Vec4thUint fail_bits_lo = veci8_movemask(fail_vec_lo);
4380 const Vec4thUint fail_bits_hi = veci8_movemask(fail_vec_hi);
4381 genovec_alias[vidx] |= fail_bits_lo | (fail_bits_hi << kBytesPerVec);
4382 }
4383 const uint32_t remainder = sample_ct % kBytesPerVec;
4384 if (remainder) {
4385 const int8_t* trailing_start = R_CAST(const int8_t*, &(qual_main[fullvec_ct * kBytesPerVec]));
4386 const int8_t qual_min_i8 = S_CAST(int8_t, qual_min);
4387 const int8_t qual_max_i8 = S_CAST(int8_t, qual_max);
4388 Vec4thUint fail_bits = 0;
4389 for (uint32_t uii = 0; uii != remainder; ++uii) {
4390 const int8_t cur_qual = trailing_start[uii];
4391 if (((qual_min_i8 > cur_qual) || (qual_max_i8 < cur_qual)) && (cur_qual != -128)) {
4392 fail_bits |= (3 * k1LU) << (2 * uii);
4393 }
4394 }
4395 genovec_alias[fullvec_ct] |= fail_bits;
4396 }
4397 #else
4398 const int8_t* qual_iter = R_CAST(const int8_t*, qual_main);
4399 const int8_t qual_min_i8 = S_CAST(int8_t, qual_min);
4400 const int8_t qual_max_i8 = S_CAST(int8_t, qual_max);
4401 for (uint32_t widx = 0; ; ++widx) {
4402 if (widx >= word_ct_m1) {
4403 if (widx > word_ct_m1) {
4404 break;
4405 }
4406 loop_len = ModNz(sample_ct, kBitsPerWordD2);
4407 }
4408 uintptr_t geno_word = genovec[widx];
4409 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
4410 const int8_t cur_qual = qual_iter[sample_idx_lowbits];
4411 if (((qual_min_i8 > cur_qual) || (qual_max_i8 < cur_qual)) && (cur_qual != -128)) {
4412 geno_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
4413 }
4414 }
4415 qual_iter = &(qual_iter[kBitsPerWordD2]);
4416 genovec[widx] = geno_word;
4417 }
4418 #endif
4419 }
4420 } else if (qual_value_type == 2) {
4421 // int16
4422 #ifdef __LP64__
4423 const uint32_t fullvec_ct = sample_ct / kInt16PerVec;
4424 Vec8thUint* genovec_alias = R_CAST(Vec8thUint*, genovec);
4425 #endif
4426 if (qual_max >= 0x7fff) {
4427 const int16_t effective_qual_min_m1 = (qual_min >= 0x8000)? 0x7fff : (S_CAST(int16_t, qual_min) - 1);
4428 #ifdef __LP64__
4429 const VecU16* qual_alias = R_CAST(const VecU16*, qual_main);
4430 const VecU16 all1 = vecu16_set1(0xffff);
4431 const VecI16 min_m1_vec = veci16_set1(effective_qual_min_m1);
4432 for (uint32_t vidx = 0; vidx != fullvec_ct; ++vidx) {
4433 const VecU16 vv = vecu16_loadu(&(qual_alias[vidx]));
4434 const VecI16 vv_m1 = R_CAST(VecI16, vv + all1);
4435 const VecI16 fail_vec = (min_m1_vec > vv_m1);
4436 const Vec8thUint fail_bits = veci16_movemask(fail_vec);
4437 genovec_alias[vidx] |= fail_bits;
4438 }
4439 const uint32_t remainder = sample_ct % kInt16PerVec;
4440 if (remainder) {
4441 const uint16_t* trailing_start = R_CAST(const uint16_t*, &(qual_main[fullvec_ct * kInt16PerVec]));
4442 Vec8thUint fail_bits = 0;
4443 for (uint32_t uii = 0; uii != remainder; ++uii) {
4444 const int16_t cur_qual_m1 = S_CAST(int16_t, trailing_start[uii]);
4445 if (effective_qual_min_m1 > cur_qual_m1) {
4446 fail_bits |= 3U << (2 * uii);
4447 }
4448 }
4449 genovec_alias[fullvec_ct] |= fail_bits;
4450 }
4451 #else
4452 const uint16_t* qual_iter = R_CAST(const uint16_t*, qual_main);
4453 for (uint32_t widx = 0; ; ++widx) {
4454 if (widx >= word_ct_m1) {
4455 if (widx > word_ct_m1) {
4456 break;
4457 }
4458 loop_len = ModNz(sample_ct, kBitsPerWordD2);
4459 }
4460 uintptr_t geno_word = genovec[widx];
4461 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
4462 const int16_t cur_qual_m1 = S_CAST(int16_t, qual_iter[sample_idx_lowbits] - 1);
4463 if (effective_qual_min_m1 > cur_qual_m1) {
4464 geno_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
4465 }
4466 }
4467 qual_iter = &(qual_iter[kBitsPerWordD2]);
4468 genovec[widx] = geno_word;
4469 }
4470 #endif
4471 } else {
4472 // Two comparisons required, and we need to special-case the missing
4473 // value.
4474 #ifdef __LP64__
4475 const VecI16* qual_alias = R_CAST(const VecI16*, qual_main);
4476 const VecI16 min_vec = veci16_set1(qual_min);
4477 const VecI16 max_vec = veci16_set1(qual_max);
4478 const VecI16 missing_vec = veci16_set1(0x8000);
4479 for (uint32_t vidx = 0; vidx != fullvec_ct; ++vidx) {
4480 const VecI16 vv = veci16_loadu(&(qual_alias[vidx]));
4481 const VecI16 fail_or_missing_vec = (min_vec > vv) | (max_vec < vv);
4482 const VecI16 cur_missing_vec = (vv == missing_vec);
4483 const VecI16 fail_vec = veci16_and_notfirst(cur_missing_vec, fail_or_missing_vec);
4484 const Vec8thUint fail_bits = veci16_movemask(fail_vec);
4485 genovec_alias[vidx] |= fail_bits;
4486 }
4487 const uint32_t remainder = sample_ct % kInt16PerVec;
4488 if (remainder) {
4489 const int16_t* trailing_start = R_CAST(const int16_t*, &(qual_main[fullvec_ct * kInt16PerVec]));
4490 const int16_t qual_min_i16 = S_CAST(int16_t, qual_min);
4491 const int16_t qual_max_i16 = S_CAST(int16_t, qual_max);
4492 Vec8thUint fail_bits = 0;
4493 for (uint32_t uii = 0; uii != remainder; ++uii) {
4494 const int16_t cur_qual = trailing_start[uii];
4495 if (((qual_min_i16 > cur_qual) || (qual_max_i16 < cur_qual)) && (cur_qual != -32768)) {
4496 fail_bits |= 3U << (2 * uii);
4497 }
4498 }
4499 genovec_alias[fullvec_ct] |= fail_bits;
4500 }
4501 #else
4502 const int16_t* qual_iter = R_CAST(const int16_t*, qual_main);
4503 const int16_t qual_min_i16 = S_CAST(int16_t, qual_min);
4504 const int16_t qual_max_i16 = S_CAST(int16_t, qual_max);
4505 for (uint32_t widx = 0; ; ++widx) {
4506 if (widx >= word_ct_m1) {
4507 if (widx > word_ct_m1) {
4508 break;
4509 }
4510 loop_len = ModNz(sample_ct, kBitsPerWordD2);
4511 }
4512 uintptr_t geno_word = genovec[widx];
4513 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
4514 const int16_t cur_qual = qual_iter[sample_idx_lowbits];
4515 if (((qual_min_i16 > cur_qual) || (qual_max_i16 < cur_qual)) && (cur_qual != -32768)) {
4516 geno_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
4517 }
4518 }
4519 qual_iter = &(qual_iter[kBitsPerWordD2]);
4520 genovec[widx] = geno_word;
4521 }
4522 #endif
4523 }
4524 } else if (unlikely((qual_value_type == 5) && (qual_max != 0x7fffffff))) {
4525 // Leave out the two-comparison float subcase for now, it's messier and
4526 // floating-point DP is unlikely.
4527 return kBcfParseFloatDp;
4528 } else if ((qual_value_type == 3) || ((qual_value_type == 5) && (!qual_min))) {
4529 // int32, or float qual_min == 0.
4530 #ifdef __LP64__
4531 const uint32_t fullvec_ct = sample_ct / kInt32PerVec;
4532 Vec16thUint* genovec_alias = R_CAST(Vec16thUint*, genovec);
4533 #endif
4534 if (qual_max == 0x7fffffff) {
4535 const int32_t qual_min_m1 = S_CAST(int32_t, qual_min) - 1;
4536 #ifdef __LP64__
4537 const VecU32* qual_alias = R_CAST(const VecU32*, qual_main);
4538 const VecU32 all1 = vecu32_set1(UINT32_MAX);
4539 const VecI32 min_m1_vec = veci32_set1(qual_min_m1);
4540 for (uint32_t vidx = 0; vidx != fullvec_ct; ++vidx) {
4541 const VecU32 vv = vecu32_loadu(&(qual_alias[vidx]));
4542 const VecI32 vv_m1 = R_CAST(VecI32, vv + all1);
4543 const VecI32 fail_vec = (min_m1_vec > vv_m1);
4544 # ifdef USE_AVX2
4545 const Vec16thUint fail_bits = _pext_u32(veci32_movemask(fail_vec), 0x33333333);
4546 # else
4547 const __m128i vec_packed = _mm_packs_epi16(R_CAST(__m128i, fail_vec), R_CAST(__m128i, fail_vec));
4548 // unwanted high bits get truncated here.
4549 const Vec16thUint fail_bits = _mm_movemask_epi8(vec_packed);
4550 # endif
4551 genovec_alias[vidx] |= fail_bits;
4552 }
4553 const uint32_t remainder = sample_ct % kInt32PerVec;
4554 if (remainder) {
4555 const uint32_t* trailing_start = R_CAST(const uint32_t*, &(qual_main[fullvec_ct * kInt32PerVec]));
4556 Vec16thUint fail_bits = 0;
4557 for (uint32_t uii = 0; uii != remainder; ++uii) {
4558 const int32_t cur_qual_m1 = S_CAST(int32_t, trailing_start[uii] - 1);
4559 if (qual_min_m1 > cur_qual_m1) {
4560 fail_bits |= 3U << (2 * uii);
4561 }
4562 }
4563 genovec_alias[fullvec_ct] |= fail_bits;
4564 }
4565 #else
4566 const uint32_t* qual_iter = R_CAST(const uint32_t*, qual_main);
4567 for (uint32_t widx = 0; ; ++widx) {
4568 if (widx >= word_ct_m1) {
4569 if (widx > word_ct_m1) {
4570 break;
4571 }
4572 loop_len = ModNz(sample_ct, kBitsPerWordD2);
4573 }
4574 uintptr_t geno_word = genovec[widx];
4575 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
4576 const int32_t cur_qual_m1 = S_CAST(int32_t, qual_iter[sample_idx_lowbits] - 1);
4577 if (qual_min_m1 > cur_qual_m1) {
4578 geno_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
4579 }
4580 }
4581 qual_iter = &(qual_iter[kBitsPerWordD2]);
4582 genovec[widx] = geno_word;
4583 }
4584 #endif
4585 } else {
4586 // Two comparisons required, and we need to special-case the missing
4587 // value.
4588 #ifdef __LP64__
4589 const VecI32* qual_alias = R_CAST(const VecI32*, qual_main);
4590 const VecI32 min_vec = veci32_set1(qual_min);
4591 const VecI32 max_vec = veci32_set1(qual_max);
4592 const VecI32 missing_vec = veci32_set1(0x80000000);
4593 for (uint32_t vidx = 0; vidx != fullvec_ct; ++vidx) {
4594 const VecI32 vv = veci32_loadu(&(qual_alias[vidx]));
4595 const VecI32 fail_or_missing_vec = (min_vec > vv) | (max_vec < vv);
4596 const VecI32 cur_missing_vec = (vv == missing_vec);
4597 const VecI32 fail_vec = veci32_and_notfirst(cur_missing_vec, fail_or_missing_vec);
4598 # ifdef USE_AVX2
4599 const Vec16thUint fail_bits = _pext_u32(veci32_movemask(fail_vec), 0x33333333);
4600 # else
4601 const __m128i vec_packed = _mm_packs_epi16(R_CAST(__m128i, fail_vec), R_CAST(__m128i, fail_vec));
4602 const Vec16thUint fail_bits = _mm_movemask_epi8(vec_packed);
4603 # endif
4604 genovec_alias[vidx] |= fail_bits;
4605 }
4606 const uint32_t remainder = sample_ct % kInt32PerVec;
4607 if (remainder) {
4608 const int32_t* trailing_start = R_CAST(const int32_t*, &(qual_main[fullvec_ct * kInt32PerVec]));
4609 const int32_t qual_min_i32 = S_CAST(int32_t, qual_min);
4610 const int32_t qual_max_i32 = S_CAST(int32_t, qual_max);
4611 Vec16thUint fail_bits = 0;
4612 for (uint32_t uii = 0; uii != remainder; ++uii) {
4613 const int32_t cur_qual = trailing_start[uii];
4614 // see https://stackoverflow.com/questions/9941261/warning-this-decimal-constant-is-unsigned-only-in-iso-c90
4615 if (((qual_min_i32 > cur_qual) || (qual_max_i32 < cur_qual)) && (cur_qual != (-2147483647 - 1))) {
4616 fail_bits |= 3U << (2 * uii);
4617 }
4618 }
4619 genovec_alias[fullvec_ct] |= fail_bits;
4620 }
4621 #else
4622 const int32_t* qual_iter = R_CAST(const int32_t*, qual_main);
4623 const int32_t qual_min_i32 = S_CAST(int32_t, qual_min);
4624 const int32_t qual_max_i32 = S_CAST(int32_t, qual_max);
4625 for (uint32_t widx = 0; ; ++widx) {
4626 if (widx >= word_ct_m1) {
4627 if (widx > word_ct_m1) {
4628 break;
4629 }
4630 loop_len = ModNz(sample_ct, kBitsPerWordD2);
4631 }
4632 uintptr_t geno_word = genovec[widx];
4633 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
4634 const int32_t cur_qual = qual_iter[sample_idx_lowbits];
4635 if (((qual_min_i32 > cur_qual) || (qual_max_i32 < cur_qual)) && (cur_qual != (-2147483647 - 1))) {
4636 geno_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
4637 }
4638 }
4639 qual_iter = &(qual_iter[kBitsPerWordD2]);
4640 genovec[widx] = geno_word;
4641 }
4642 #endif
4643 }
4644 } else if (likely(qual_value_type == 5)) {
4645 // float, qual_min > 0.
4646 // 0x80000000 does not pass in this case.
4647 if (qual_value_type == 5) {
4648 // Still more efficient to perform the comparison in integer-space, since
4649 // we treat all NaN values (0x7f800000...0x7fffffff) as passing.
4650
4651 // Convert to the appropriate floating-point bit pattern, rounding up.
4652 const uint32_t orig_qual_min = qual_min;
4653 const float fxx = S_CAST(float, qual_min);
4654 memcpy(&qual_min, &fxx, 4);
4655 if (orig_qual_min > 0x1000000) {
4656 // We need to add 1 to qual_min iff high_bit_idx > low_bit_idx + 23.
4657 const uint32_t high_bit_idx = bsru32(orig_qual_min);
4658 const uint32_t low_bit_idx = ctzu32(orig_qual_min);
4659 qual_min += (high_bit_idx > (low_bit_idx + 23));
4660 }
4661 }
4662 #ifdef __LP64__
4663 const uint32_t fullvec_ct = sample_ct / kInt32PerVec;
4664 Vec16thUint* genovec_alias = R_CAST(Vec16thUint*, genovec);
4665 const VecI32* qual_alias = R_CAST(const VecI32*, qual_main);
4666 const VecI32 min_vec = veci32_set1(qual_min);
4667 for (uint32_t vidx = 0; vidx != fullvec_ct; ++vidx) {
4668 const VecI32 vv = veci32_loadu(&(qual_alias[vidx]));
4669 const VecI32 fail_vec = (min_vec > vv);
4670 # ifdef USE_AVX2
4671 const Vec16thUint fail_bits = _pext_u32(veci32_movemask(fail_vec), 0x33333333);
4672 # else
4673 const __m128i vec_packed = _mm_packs_epi16(R_CAST(__m128i, fail_vec), R_CAST(__m128i, fail_vec));
4674 // unwanted high bits get truncated here.
4675 const Vec16thUint fail_bits = _mm_movemask_epi8(vec_packed);
4676 # endif
4677 genovec_alias[vidx] |= fail_bits;
4678 }
4679 const uint32_t remainder = sample_ct % kInt32PerVec;
4680 if (remainder) {
4681 const int32_t* trailing_start = R_CAST(const int32_t*, &(qual_main[fullvec_ct * kInt32PerVec]));
4682 const int32_t qual_min_i32 = S_CAST(int32_t, qual_min);
4683 Vec16thUint fail_bits = 0;
4684 for (uint32_t uii = 0; uii != remainder; ++uii) {
4685 if (qual_min_i32 > trailing_start[uii]) {
4686 fail_bits |= 3U << (2 * uii);
4687 }
4688 }
4689 genovec_alias[fullvec_ct] |= fail_bits;
4690 }
4691 #else
4692 const int32_t* qual_iter = R_CAST(const int32_t*, qual_main);
4693 const int32_t qual_min_i32 = S_CAST(int32_t, qual_min);
4694 for (uint32_t widx = 0; ; ++widx) {
4695 if (widx >= word_ct_m1) {
4696 if (widx > word_ct_m1) {
4697 break;
4698 }
4699 loop_len = ModNz(sample_ct, kBitsPerWordD2);
4700 }
4701 uintptr_t geno_word = genovec[widx];
4702 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
4703 if (qual_min_i32 > qual_iter[sample_idx_lowbits]) {
4704 geno_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
4705 }
4706 }
4707 qual_iter = &(qual_iter[kBitsPerWordD2]);
4708 genovec[widx] = geno_word;
4709 }
4710 #endif
4711 } else {
4712 return kBcfParseMalformedGeneric;
4713 }
4714 return kBcfParseOk;
4715 }
4716
4717 BcfParseErr BcfParseGqDpUnaligned(const unsigned char* qual_type_start, uint32_t sample_ct, uint32_t qual_min, uint32_t qual_max, uintptr_t* genovec) {
4718 const unsigned char* qual_iter = qual_type_start;
4719 uint32_t qual_value_type;
4720 uint32_t qual_value_ct;
4721 if (unlikely(ScanBcfType(&qual_iter, &qual_value_type, &qual_value_ct) || (qual_value_ct > 1))) {
4722 return kBcfParseMalformedGeneric;
4723 }
4724 if (!qual_value_ct) {
4725 return kBcfParseOk;
4726 }
4727 return BcfParseGqDpMain(qual_iter, sample_ct, qual_min, qual_max, qual_value_type, genovec);
4728 }
4729
4730 BcfParseErr BcfParseGqDpAligned(const unsigned char* qual_type_start, uint32_t sample_ct, uint32_t qual_min, uint32_t qual_max, uintptr_t* genovec) {
4731 const unsigned char* qual_iter = qual_type_start;
4732 uint32_t qual_value_type;
4733 uint32_t qual_value_ct;
4734 if (unlikely(ScanBcfTypeAligned(&qual_iter, &qual_value_type, &qual_value_ct) || (qual_value_ct > 1))) {
4735 return kBcfParseMalformedGeneric;
4736 }
4737 if (!qual_value_ct) {
4738 return kBcfParseOk;
4739 }
4740 return BcfParseGqDpMain(qual_iter, sample_ct, qual_min, qual_max, qual_value_type, genovec);
4741 }
4742
4743 static_assert(kPglMaxAlleleCt == 255, "BcfScanGt() needs to be updated.");
4744 BcfParseErr BcfScanGt(const BcfImportContext* bicp, const unsigned char* gt_start, const unsigned char** qual_starts, uint32_t* phase_or_dosage_found_ptr, uintptr_t* invfound_nypbuf) {
4745 // Just check for a phased het.
4746 const unsigned char* gt_main = gt_start;
4747 // Note that generic validation was already performed on these vectors. We
4748 // just need to verify that e.g. GT values are int8/int16, and GQ/DP values
4749 // aren't characters.
4750 uint32_t gt_value_type;
4751 uint32_t gt_value_ct;
4752 if (unlikely(ScanBcfType(&gt_main, &gt_value_type, &gt_value_ct) || (gt_value_type > 2))) {
4753 return (gt_value_type == 3)? kBcfParseWideGt : kBcfParseMalformedGeneric;
4754 }
4755 if (gt_value_ct < 2) {
4756 // ploidy 0 or 1, phased genotypes are impossible
4757 return kBcfParseOk;
4758 }
4759 if (unlikely((gt_value_ct > 2) && bicp->bibc.error_on_polyploid)) {
4760 return kBcfParsePolyploidError;
4761 }
4762 const uint32_t sample_ct = bicp->bibc.sample_ct;
4763 #ifdef __LP64__
4764 // Our search is over once we see a phased heterozygous call. Usually, if
4765 // one exists at all, a filter-passing call will be present within the first
4766 // few variants; the important case to optimize is no-phased-genotypes,
4767 // all-diploid.
4768 // So, in the 64-bit diploid case, we perform a pre-scan for a set bottom bit
4769 // in all of the second-genotype-values in each pair. If none exist, there
4770 // can't be any phased (or haploid/0-ploid) genotypes, and we can move on to
4771 // the next variant.
4772 // (Initially tried to make this an exhaustive scan, but then realized
4773 // halfcalls and SIMD don't get along that well.)
4774 if (gt_value_ct == 2) {
4775 if (gt_value_type == 1) {
4776 // int8
4777 if (sample_ct >= kInt16PerVec) {
4778 const uint32_t vec_ct_m1 = (sample_ct - 1) / kInt16PerVec;
4779 const VecU16* gt_alias = R_CAST(const VecU16*, gt_main);
4780 VecU16 found = vecu16_setzero();
4781 for (uint32_t vidx = 0; vidx != vec_ct_m1; ++vidx) {
4782 const VecU16 vv = vecu16_loadu(&(gt_alias[vidx]));
4783 found = found | vv;
4784 }
4785 const VecU16 last_vec = vecu16_loadu(&(gt_main[(sample_ct - kInt16PerVec) * 2]));
4786 found = found | last_vec;
4787 if (!vecu16_movemask(vecu16_srli(found, 1))) {
4788 // No phased (or haploid) genotypes at all.
4789 return kBcfParseOk;
4790 }
4791 }
4792 } else {
4793 // int16
4794 if (sample_ct >= kInt32PerVec) {
4795 const uint32_t vec_ct_m1 = (sample_ct - 1) / kInt32PerVec;
4796 const VecU32* gt_alias = R_CAST(const VecU32*, gt_main);
4797 VecU32 found = vecu32_setzero();
4798 for (uint32_t vidx = 0; vidx != vec_ct_m1; ++vidx) {
4799 const VecU32 vv = vecu32_loadu(&(gt_alias[vidx]));
4800 found = found | vv;
4801 }
4802 const VecU32 last_vec = vecu32_loadu(&(gt_main[(sample_ct - kInt32PerVec) * 4]));
4803 found = found | last_vec;
4804 if (!(vecu32_movemask(vecu32_srli(found, 1)) & 0x22222222U)) {
4805 return kBcfParseOk;
4806 }
4807 }
4808 }
4809 }
4810 #endif
4811 const VcfHalfCall halfcall_mode = bicp->bibc.halfcall_mode;
4812 if ((!qual_starts[0]) && (!qual_starts[1])) {
4813 // No gq/dp check, so we can exit as soon as we find a match.
4814 if (gt_value_type == 1) {
4815 // int8
4816 if (gt_value_ct == 2) {
4817 // Usual case.
4818 // Low bit of each second byte is set iff the genotype is either phased
4819 // or non-diploid (0x81 "END_OF_VECTOR").
4820 const unsigned char* second_byte_stop = &(gt_main[sample_ct * 2 + 1]);
4821 for (const unsigned char* second_byte_iter = &(gt_main[1]); second_byte_iter != second_byte_stop; second_byte_iter = &(second_byte_iter[2])) {
4822 const uint32_t second_byte = *second_byte_iter;
4823 if ((second_byte & 0x81) == 1) {
4824 // phased
4825 const uint32_t first_allele_idx_p1 = second_byte_iter[-1] >> 1;
4826 const uint32_t second_allele_idx_p1 = second_byte >> 1;
4827 if (first_allele_idx_p1 != second_allele_idx_p1) {
4828 // phased het or halfcall
4829 // (or malformed, false positive ok there)
4830 if (first_allele_idx_p1 && second_allele_idx_p1) {
4831 *phase_or_dosage_found_ptr = 1;
4832 return kBcfParseOk;
4833 }
4834 if (halfcall_mode == kVcfHalfCallReference) {
4835 if (first_allele_idx_p1 + second_allele_idx_p1 != 1) {
4836 *phase_or_dosage_found_ptr = 1;
4837 return kBcfParseOk;
4838 }
4839 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
4840 return kBcfParseHalfCallError;
4841 }
4842 }
4843 }
4844 }
4845 } else {
4846 // Ploidy > 2 treated as missing.
4847 // possible todo: Add SIMD code for the triploid case (advance 15 or 30
4848 // bytes on each iteration, etc.), since it does realistically come up
4849 // in large datasets, and it only takes one triploid sample to force
4850 // this code path to be taken for all samples.
4851 // (Tetraploidy is much rarer than triploidy.)
4852 const unsigned char* second_byte_stop = &(gt_main[sample_ct * gt_value_type + 1]);
4853 for (const unsigned char* second_byte_iter = &(gt_main[1]); second_byte_iter != second_byte_stop; second_byte_iter = &(second_byte_iter[gt_value_type])) {
4854 uint16_t second_and_third_bytes;
4855 memcpy(&second_and_third_bytes, second_byte_iter, 2);
4856 if ((second_and_third_bytes & 0x8181) == 0x8101) {
4857 // phased diploid
4858 const uint32_t first_allele_idx_p1 = second_byte_iter[-1] >> 1;
4859 const uint32_t second_allele_idx_p1 = (second_and_third_bytes & 0xff) >> 1;
4860 if (first_allele_idx_p1 != second_allele_idx_p1) {
4861 // phased het or halfcall
4862 if (first_allele_idx_p1 && second_allele_idx_p1) {
4863 *phase_or_dosage_found_ptr = 1;
4864 return kBcfParseOk;
4865 }
4866 if (halfcall_mode == kVcfHalfCallReference) {
4867 if (first_allele_idx_p1 + second_allele_idx_p1 != 1) {
4868 *phase_or_dosage_found_ptr = 1;
4869 return kBcfParseOk;
4870 }
4871 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
4872 return kBcfParseHalfCallError;
4873 }
4874 }
4875 }
4876 }
4877 }
4878 } else {
4879 // int16
4880 if (gt_value_ct == 2) {
4881 const uint16_t* second_u16_stop = R_CAST(const uint16_t*, &(gt_main[sample_ct * 4 + 2]));
4882 for (const uint16_t* second_u16_iter = R_CAST(const uint16_t*, &(gt_main[2])); second_u16_iter != second_u16_stop; second_u16_iter = &(second_u16_iter[2])) {
4883 const uint32_t second_u16 = *second_u16_iter;
4884 if ((second_u16 & 0x8001) == 1) {
4885 // phased
4886 const uint32_t first_allele_idx_p1 = second_u16_iter[-1] >> 1;
4887 const uint32_t second_allele_idx_p1 = second_u16 >> 1;
4888 if (first_allele_idx_p1 != second_allele_idx_p1) {
4889 // phased het or halfcall
4890 if (first_allele_idx_p1 && second_allele_idx_p1) {
4891 *phase_or_dosage_found_ptr = 1;
4892 return kBcfParseOk;
4893 }
4894 if (halfcall_mode == kVcfHalfCallReference) {
4895 if (first_allele_idx_p1 + second_allele_idx_p1 != 1) {
4896 *phase_or_dosage_found_ptr = 1;
4897 return kBcfParseOk;
4898 }
4899 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
4900 return kBcfParseHalfCallError;
4901 }
4902 }
4903 }
4904 }
4905 } else {
4906 // ploidy > 2
4907 const uint16_t* second_u16_stop = R_CAST(const uint16_t*, &(gt_main[sample_ct * 2 * gt_value_type + 2]));
4908 for (const uint16_t* second_u16_iter = R_CAST(const uint16_t*, &(gt_main[2])); second_u16_iter != second_u16_stop; second_u16_iter = &(second_u16_iter[gt_value_type])) {
4909 uint32_t second_and_third_u16s;
4910 memcpy(&second_and_third_u16s, second_u16_iter, 4);
4911 if ((second_and_third_u16s & 0x80018001U) == 0x80010001U) {
4912 // phased diploid
4913 const uint32_t first_allele_idx_p1 = second_u16_iter[-1] >> 1;
4914 const uint32_t second_allele_idx_p1 = (second_and_third_u16s & 0xffff) >> 1;
4915 if (first_allele_idx_p1 != second_allele_idx_p1) {
4916 // phased het or halfcall
4917 if (first_allele_idx_p1 && second_allele_idx_p1) {
4918 *phase_or_dosage_found_ptr = 1;
4919 return kBcfParseOk;
4920 }
4921 if (halfcall_mode == kVcfHalfCallReference) {
4922 if (first_allele_idx_p1 + second_allele_idx_p1 != 1) {
4923 *phase_or_dosage_found_ptr = 1;
4924 return kBcfParseOk;
4925 }
4926 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
4927 return kBcfParseHalfCallError;
4928 }
4929 }
4930 }
4931 }
4932 }
4933 }
4934 return kBcfParseOk;
4935 }
4936 // We clear a bit when we find a phase/dosage we're keeping; then
4937 // BcfParseGqDpUnaligned() sets it iff the GQ or DP filter fails for that
4938 // sample; if any clear bits remain at the end, we're done with our scan.
4939 SetAllBits(sample_ct * 2, invfound_nypbuf);
4940 if (gt_value_type == 1) {
4941 if (gt_value_ct == 2) {
4942 const unsigned char* second_byte_start = &(gt_main[1]);
4943 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
4944 const uint32_t second_byte = second_byte_start[sample_idx * 2];
4945 if ((second_byte & 0x81) == 1) {
4946 // phased
4947 const uint32_t first_allele_idx_p1 = second_byte_start[sample_idx * 2 - 1] >> 1;
4948 const uint32_t second_allele_idx_p1 = second_byte >> 1;
4949 if (first_allele_idx_p1 != second_allele_idx_p1) {
4950 // phased het or halfcall
4951 if (first_allele_idx_p1 && second_allele_idx_p1) {
4952 ClearBit(sample_idx * 2, invfound_nypbuf);
4953 } else if (halfcall_mode == kVcfHalfCallReference) {
4954 if (first_allele_idx_p1 + second_allele_idx_p1 != 1) {
4955 ClearBit(sample_idx * 2, invfound_nypbuf);
4956 }
4957 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
4958 return kBcfParseHalfCallError;
4959 }
4960 }
4961 }
4962 }
4963 } else {
4964 // ploidy > 2
4965 const unsigned char* second_byte_iter = &(gt_main[1]);
4966 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx, second_byte_iter = &(second_byte_iter[gt_value_type])) {
4967 uint16_t second_and_third_bytes;
4968 memcpy(&second_and_third_bytes, second_byte_iter, 2);
4969 if ((second_and_third_bytes & 0x8181) == 0x8101) {
4970 // phased diploid
4971 const uint32_t first_allele_idx_p1 = second_byte_iter[-1] >> 1;
4972 const uint32_t second_allele_idx_p1 = (second_and_third_bytes & 0xff) >> 1;
4973 if (first_allele_idx_p1 != second_allele_idx_p1) {
4974 // phased het or halfcall
4975 if (first_allele_idx_p1 && second_allele_idx_p1) {
4976 ClearBit(sample_idx * 2, invfound_nypbuf);
4977 } else if (halfcall_mode == kVcfHalfCallReference) {
4978 if (first_allele_idx_p1 + second_allele_idx_p1 != 1) {
4979 ClearBit(sample_idx * 2, invfound_nypbuf);
4980 }
4981 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
4982 return kBcfParseHalfCallError;
4983 }
4984 }
4985 }
4986 }
4987 }
4988 } else {
4989 // int16
4990 if (gt_value_ct == 2) {
4991 const uint16_t* second_u16_start = R_CAST(const uint16_t*, &(gt_main[2]));
4992 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
4993 const uint32_t second_u16 = second_u16_start[sample_idx * 2];
4994 if ((second_u16 & 0x8001) == 1) {
4995 // phased
4996 const uint32_t first_allele_idx_p1 = second_u16_start[sample_idx * 2 - 1] >> 1;
4997 const uint32_t second_allele_idx_p1 = second_u16 >> 1;
4998 if (first_allele_idx_p1 != second_allele_idx_p1) {
4999 // phased het or halfcall
5000 if (first_allele_idx_p1 && second_allele_idx_p1) {
5001 ClearBit(sample_idx * 2, invfound_nypbuf);
5002 } else if (halfcall_mode == kVcfHalfCallReference) {
5003 if (first_allele_idx_p1 + second_allele_idx_p1 != 1) {
5004 ClearBit(sample_idx * 2, invfound_nypbuf);
5005 }
5006 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
5007 return kBcfParseHalfCallError;
5008 }
5009 }
5010 }
5011 }
5012 } else {
5013 // ploidy > 2
5014 const uint16_t* second_u16_iter = R_CAST(const uint16_t*, &(gt_main[2]));
5015 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx, second_u16_iter = &(second_u16_iter[gt_value_type])) {
5016 uint32_t second_and_third_u16s;
5017 memcpy(&second_and_third_u16s, second_u16_iter, 4);
5018 if ((second_and_third_u16s & 0x80018001U) == 0x80010001U) {
5019 // phased diploid
5020 const uint32_t first_allele_idx_p1 = second_u16_iter[-1] >> 1;
5021 const uint32_t second_allele_idx_p1 = (second_and_third_u16s & 0xffff) >> 1;
5022 if (first_allele_idx_p1 != second_allele_idx_p1) {
5023 // phased het or halfcall
5024 if (first_allele_idx_p1 && second_allele_idx_p1) {
5025 ClearBit(sample_idx * 2, invfound_nypbuf);
5026 } else if (halfcall_mode == kVcfHalfCallReference) {
5027 if (first_allele_idx_p1 + second_allele_idx_p1 != 1) {
5028 ClearBit(sample_idx * 2, invfound_nypbuf);
5029 }
5030 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
5031 return kBcfParseHalfCallError;
5032 }
5033 }
5034 }
5035 }
5036 }
5037 }
5038 if (AllBitsAreOne(invfound_nypbuf, sample_ct * 2)) {
5039 return kBcfParseOk;
5040 }
5041 for (uint32_t qual_idx = 0; qual_idx != 2; ++qual_idx) {
5042 if (!qual_starts[qual_idx]) {
5043 continue;
5044 }
5045 BcfParseErr bcf_parse_err = BcfParseGqDpUnaligned(qual_starts[qual_idx], sample_ct, bicp->bibc.qual_mins[qual_idx], bicp->bibc.qual_maxs[qual_idx], invfound_nypbuf);
5046 if (bcf_parse_err != kBcfParseOk) {
5047 return bcf_parse_err;
5048 }
5049 if (AllBitsAreOne(invfound_nypbuf, sample_ct * 2)) {
5050 return kBcfParseOk;
5051 }
5052 }
5053 *phase_or_dosage_found_ptr = 1;
5054 return kBcfParseOk;
5055 }
5056
5057 // Dosage parsing is messy enough that we stick as closely as possible to the
5058 // VCF logic, instead of trying to vectorize.
5059 BoolErr ParseBcfBiallelicGp(const float* cur_gp_start, uint32_t is_haploid, double import_dosage_certainty, DosageParseResult* dpr_ptr, double* alt_dosage_ptr) {
5060 // See ParseVcfBiallelicGp().
5061 // P(0/0), P(0/1), P(1/1), etc.
5062 // assumes dpr initialized to kDosageParseOk
5063 // assumes *gp_iter is not missing
5064 // returns 1 if missing OR parsing error. error: dpr still kDosageParseOk
5065 const float prob_0altf = cur_gp_start[0];
5066 if (unlikely((prob_0altf < S_CAST(float, 0.0)) || (prob_0altf > S_CAST(float, 1.0)))) {
5067 return 1;
5068 }
5069 const float prob_1altf = cur_gp_start[1];
5070 // second predicate written to be true on NaN
5071 if (unlikely((prob_1altf < S_CAST(float, 0.0)) || (!(prob_1altf <= S_CAST(float, 1.0))))) {
5072 return 1;
5073 }
5074 const double prob_0alt = S_CAST(double, prob_0altf);
5075 const double prob_1alt = S_CAST(double, prob_1altf);
5076 if (is_haploid) {
5077 const double denom = prob_0alt + prob_1alt;
5078 if (denom <= 2 * import_dosage_certainty) {
5079 if ((prob_0alt <= import_dosage_certainty) && (prob_1alt <= import_dosage_certainty)) {
5080 *dpr_ptr = kDosageParseForceMissing;
5081 return 1;
5082 }
5083 }
5084 *alt_dosage_ptr = 2 * prob_1alt / denom;
5085 return 0;
5086 }
5087 const float prob_2altf = cur_gp_start[2];
5088 if (unlikely((prob_2altf < S_CAST(float, 0.0)) || (!(prob_2altf <= S_CAST(float, 1.0))))) {
5089 return 1;
5090 }
5091 const double prob_2alt = S_CAST(double, prob_2altf);
5092 const double denom = prob_0alt + prob_1alt + prob_2alt;
5093 if (denom <= 3 * import_dosage_certainty) {
5094 if ((prob_0alt <= import_dosage_certainty) && (prob_1alt <= import_dosage_certainty) && (prob_2alt <= import_dosage_certainty)) {
5095 // force-missing
5096 // ok to use <= since we multiplied by (1 - epsilon)
5097 // during command-line parsing. this lets us avoid
5098 // special-casing denom=0.
5099 *dpr_ptr = kDosageParseForceMissing;
5100 return 1; // not really an error
5101 }
5102 }
5103 *alt_dosage_ptr = (prob_1alt + 2 * prob_2alt) / denom;
5104 return 0;
5105 }
5106
5107 BoolErr ParseBcfBiallelicDosage(const float* cur_dosage_start, uint32_t is_haploid_or_0ploid, uint32_t dosage_is_gp, double import_dosage_certainty, DosageParseResult* dpr_ptr, uint32_t* dosage_int_ptr) {
5108 // See ParseVcfBiallelicDosage().
5109 // assumes dpr initialized to kDosageParseOk
5110 // returns 1 if missing OR parsing error. error: dpr still kDosageParseOk.
5111 int32_t first_bits;
5112 memcpy(&first_bits, cur_dosage_start, 4);
5113 if (first_bits > 0x7f800000) {
5114 // ploidy-0, regular missing call, or NaN.
5115 *dpr_ptr = kDosageParseMissing;
5116 return 1;
5117 }
5118 double alt_dosage;
5119 if (dosage_is_gp) {
5120 if (ParseBcfBiallelicGp(cur_dosage_start, is_haploid_or_0ploid, import_dosage_certainty, dpr_ptr, &alt_dosage)) {
5121 return 1;
5122 }
5123 } else {
5124 alt_dosage = S_CAST(double, *cur_dosage_start);
5125 if (unlikely(alt_dosage < 0.0)) {
5126 return 1;
5127 }
5128 if (is_haploid_or_0ploid) {
5129 // possible todo: allow this to be suppressed (maybe upstream of this
5130 // function); 1000 Genomes phase 1 haploid dosages are still on 0..2
5131 // scale
5132 // right now the best approach for importing those files is commenting
5133 // out this line and recompiling...
5134 if (import_dosage_certainty != 0.0) {
5135 // quasi-bugfix (19 Feb 2019): dosage=DS import should respect
5136 // --import-dosage-certainty
5137 if (((1.0 - alt_dosage) <= import_dosage_certainty) && (alt_dosage <= import_dosage_certainty)) {
5138 *dpr_ptr = kDosageParseForceMissing;
5139 return 1;
5140 }
5141 }
5142 alt_dosage *= 2;
5143 } else {
5144 if (import_dosage_certainty != 0.0) {
5145 const double dist_from_1 = fabs(1.0 - alt_dosage);
5146 if ((1.0 - dist_from_1 <= import_dosage_certainty) && (dist_from_1 <= import_dosage_certainty)) {
5147 *dpr_ptr = kDosageParseForceMissing;
5148 return 1;
5149 }
5150 }
5151 }
5152 if (unlikely(alt_dosage > 2.0)) {
5153 return 1;
5154 }
5155 }
5156 *dosage_int_ptr = S_CAST(int32_t, alt_dosage * kDosageMid + 0.5);
5157 return 0;
5158 }
5159
5160 BoolErr ParseBcfBiallelicHds(const float* dosage_main, const unsigned char* hds_main, uint32_t dosage_value_ct, uint32_t hds_value_ct, uint32_t sample_idx, uint32_t is_haploid_or_0ploid, uint32_t dosage_is_gp, double import_dosage_certainty, DosageParseResult* dpr_ptr, uint32_t* dosage_int_ptr, int32_t* cur_dphase_delta_ptr, uint32_t* hds_valid_ptr) {
5161 // See ParseVcfBiallelicHds().
5162 // assumes dpr initialized to kDosageParseOk
5163 // assumes cur_dphase_delta initialized to 0
5164 // assumes hds_valid initialized to 0
5165 // assumes dosage_main != nullptr and/or hds_main != nullptr
5166 // returns 1 if missing OR parsing error. error: dpr still kDosageParseOk.
5167 if (hds_main) {
5168 const unsigned char* cur_hds_start = &(hds_main[sample_idx * hds_value_ct * sizeof(float)]);
5169 // search for HDS first, then DS
5170 int32_t first_bits;
5171 memcpy(&first_bits, cur_hds_start, 4);
5172 if (first_bits <= 0x7f800000) {
5173 float fxx;
5174 CopyFromUnalignedF(&fxx, cur_hds_start);
5175 double dosage1 = S_CAST(double, fxx);
5176 if (unlikely((dosage1 < 0.0) || (dosage1 > 1.0))) {
5177 return 1;
5178 }
5179 // if hds_valid and (cur_dphase_delta == 0), caller should override
5180 // hardcall-phase
5181 *hds_valid_ptr = 1;
5182 int32_t second_bits;
5183 CopyFromUnalignedOffsetI32(&second_bits, cur_hds_start, 1);
5184 if (second_bits > 0x7f800000) {
5185 // haploid ok, half-call not ok
5186 // 0x7f800002 == END_OF_VECTOR
5187 if (unlikely(second_bits != 0x7f800002)) {
5188 return 1;
5189 }
5190 if (import_dosage_certainty != 0.0) {
5191 if ((1.0 - dosage1 <= import_dosage_certainty) && (dosage1 <= import_dosage_certainty)) {
5192 *dpr_ptr = kDosageParseForceMissing;
5193 return 1;
5194 }
5195 }
5196 *dosage_int_ptr = S_CAST(int32_t, dosage1 * kDosageMax + 0.5);
5197 return 0;
5198 }
5199 CopyFromUnalignedOffsetF(&fxx, cur_hds_start, 1);
5200 double dosage2 = S_CAST(double, fxx);
5201 if (unlikely((dosage2 < 0.0) || (dosage2 > 1.0))) {
5202 return 1;
5203 }
5204 const double dosage_sum = dosage1 + dosage2;
5205 if (import_dosage_certainty != 0.0) {
5206 // Assume maximal het probability.
5207 const double dist_from_1 = fabs(1.0 - dosage_sum);
5208 if ((1.0 - dist_from_1 <= import_dosage_certainty) && (dist_from_1 <= import_dosage_certainty)) {
5209 *dpr_ptr = kDosageParseForceMissing;
5210 return 1;
5211 }
5212 }
5213
5214 // force this to be nonnegative, since static_cast<int32_t> rounds
5215 // negative numbers toward zero
5216 const double dosage_diffp1 = 1.0 + dosage1 - dosage2;
5217
5218 *dosage_int_ptr = S_CAST(int32_t, dosage_sum * kDosageMid + 0.5);
5219 *cur_dphase_delta_ptr = S_CAST(int32_t, dosage_diffp1 * kDosageMid + 0.5) - kDosageMid;
5220 return 0;
5221 }
5222 if (!dosage_main) {
5223 *dpr_ptr = kDosageParseMissing;
5224 return 1;
5225 }
5226 }
5227 const float* cur_dosage_start = &(dosage_main[sample_idx * dosage_value_ct]);
5228 return ParseBcfBiallelicDosage(cur_dosage_start, is_haploid_or_0ploid, dosage_is_gp, import_dosage_certainty, dpr_ptr, dosage_int_ptr);
5229 }
5230
5231 uint32_t BcfGtIsPhasedHet(uint32_t gt_first, uint32_t gt_second, uint32_t gt_high_bit, VcfHalfCall halfcall_mode) {
5232 if (!(gt_second & 1)) {
5233 return 0;
5234 }
5235 const uint32_t first_allele_idx_p1 = (gt_first & (~gt_high_bit)) >> 1;
5236 const uint32_t second_allele_idx_p1 = (gt_second & (~gt_high_bit)) >> 1;
5237 if (first_allele_idx_p1 == second_allele_idx_p1) {
5238 return 0;
5239 }
5240 return (first_allele_idx_p1 && second_allele_idx_p1) || ((halfcall_mode == kVcfHalfCallReference) && (first_allele_idx_p1 + second_allele_idx_p1 != 1));
5241 }
5242
5243 BcfParseErr BcfScanBiallelicHds(const BcfImportContext* bicp, const unsigned char* gt_start, const unsigned char** qual_starts, const unsigned char* dosage_start, const unsigned char* hds_start, uint32_t* phase_or_dosage_found_ptr, uintptr_t* __restrict invfound_nypbuf) {
5244 // See VcfScanBiallelicHdsLine().
5245 // DS+HDS
5246 // Only need to find phase *or* dosage. We can expect this to happen
5247 // quickly (when we don't, it's essentially user error), so (unlike scanning
5248 // GT for a phased call) there's little point in spending much effort on
5249 // optimizing this.
5250 const unsigned char* hds_main = nullptr;
5251 uint32_t hds_value_ct = 0;
5252 if (hds_start) {
5253 const unsigned char* hds_main_raw = hds_start;
5254 uint32_t hds_value_type;
5255 if (unlikely(ScanBcfType(&hds_main_raw, &hds_value_type, &hds_value_ct))) {
5256 return kBcfParseMalformedGeneric;
5257 }
5258 if (unlikely(hds_value_type != 5)) {
5259 return kBcfParseNonfloatDosage;
5260 }
5261 if (hds_value_ct) {
5262 if (unlikely((hds_value_ct > 2) && bicp->bibc.error_on_polyploid)) {
5263 return kBcfParsePolyploidError;
5264 }
5265 hds_main = hds_main_raw;
5266 }
5267 }
5268 const float* dosage_main = nullptr;
5269 uint32_t dosage_value_ct = 0;
5270 if (dosage_start) {
5271 const unsigned char* dosage_main_raw = dosage_start;
5272 uint32_t dosage_value_type;
5273 if (unlikely(ScanBcfType(&dosage_main_raw, &dosage_value_type, &dosage_value_ct))) {
5274 return kBcfParseMalformedGeneric;
5275 }
5276 if (unlikely(dosage_value_type != 5)) {
5277 return kBcfParseNonfloatDosage;
5278 }
5279 if (dosage_value_ct) {
5280 dosage_main = R_CAST(const float*, dosage_main_raw);
5281 }
5282 }
5283 if ((!hds_value_ct) && (!dosage_value_ct)) {
5284 if (!gt_start) {
5285 // everything missing
5286 return kBcfParseOk;
5287 }
5288 return BcfScanGt(bicp, gt_start, qual_starts, phase_or_dosage_found_ptr, invfound_nypbuf);
5289 }
5290 const uint32_t sample_ct = bicp->bibc.sample_ct;
5291 ZeroWArr(NypCtToWordCt(sample_ct), invfound_nypbuf);
5292 for (uint32_t qual_idx = 0; qual_idx != 2; ++qual_idx) {
5293 if (!qual_starts[qual_idx]) {
5294 continue;
5295 }
5296 BcfParseErr bcf_parse_err = BcfParseGqDpUnaligned(qual_starts[qual_idx], sample_ct, bicp->bibc.qual_mins[qual_idx], bicp->bibc.qual_maxs[qual_idx], invfound_nypbuf);
5297 if (bcf_parse_err != kBcfParseOk) {
5298 return bcf_parse_err;
5299 }
5300 if (AllBitsAreOne(invfound_nypbuf, sample_ct * 2)) {
5301 return kBcfParseOk;
5302 }
5303 }
5304 const unsigned char* gt_main = gt_start;
5305 uint32_t gt_value_type = 0;
5306 uint32_t gt_value_ct = 0;
5307 if (gt_main) {
5308 if (unlikely(ScanBcfType(&gt_main, &gt_value_type, &gt_value_ct) || (gt_value_type > 3))) {
5309 return kBcfParseMalformedGeneric;
5310 }
5311 if (unlikely(gt_value_type > 1)) {
5312 return kBcfParseWideGt;
5313 }
5314 if (unlikely((gt_value_ct > 2) && bicp->bibc.error_on_polyploid)) {
5315 return kBcfParsePolyploidError;
5316 }
5317 }
5318 const uint32_t dosage_is_gp = bicp->dosage_is_gp;
5319 const uint32_t dosage_erase_halfdist = bicp->dosage_erase_halfdist;
5320 const double import_dosage_certainty = bicp->import_dosage_certainty;
5321 const VcfHalfCall halfcall_mode = bicp->bibc.halfcall_mode;
5322 uint32_t gt_first = 0;
5323 uint32_t gt_second = 0;
5324 uint32_t is_haploid_or_0ploid = (gt_value_ct == 1);
5325 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
5326 if (IsSet(invfound_nypbuf, sample_idx * 2)) {
5327 continue;
5328 }
5329 if (gt_value_ct > 1) {
5330 // no need to look at gt_first in haploid case.
5331 // only int8 supported, since variant is biallelic
5332 gt_first = gt_main[sample_idx * gt_value_ct];
5333 gt_second = gt_main[sample_idx * gt_value_ct + 1];
5334 is_haploid_or_0ploid = gt_second >> 7;
5335 }
5336 DosageParseResult dpr = kDosageParseOk;
5337 int32_t cur_dphase_delta = 0;
5338 uint32_t hds_valid = 0;
5339 uint32_t dosage_int;
5340 if (ParseBcfBiallelicHds(dosage_main, hds_main, dosage_value_ct, hds_value_ct, sample_idx, is_haploid_or_0ploid, dosage_is_gp, import_dosage_certainty, &dpr, &dosage_int, &cur_dphase_delta, &hds_valid)) {
5341 if (unlikely(!dpr)) {
5342 return kBcfParseInvalidDosage;
5343 }
5344 // if dpr != kDosageParseForceMissing, DS and HDS are missing.
5345 if ((dpr != kDosageParseForceMissing) && BcfGtIsPhasedHet(gt_first, gt_second, 0x80, halfcall_mode)) {
5346 *phase_or_dosage_found_ptr = 1;
5347 return kBcfParseOk;
5348 }
5349 } else if (cur_dphase_delta) {
5350 const uint32_t dphase_side1 = dosage_int + cur_dphase_delta;
5351 const uint32_t dphase_side2 = dosage_int - cur_dphase_delta;
5352 const uint32_t dphase_halfdist1 = DphaseHalfdist(dphase_side1);
5353 const uint32_t dphase_halfdist2 = DphaseHalfdist(dphase_side2);
5354 const uint32_t dphase_erase_halfdist = dosage_erase_halfdist + kDosage4th;
5355 if ((dphase_halfdist1 < dphase_erase_halfdist) ||
5356 (dphase_halfdist2 < dphase_erase_halfdist) ||
5357 (((dphase_side1 + kDosageMid) ^ (dphase_side2 + kDosageMid)) & kDosageMax)) {
5358 *phase_or_dosage_found_ptr = 1;
5359 return kBcfParseOk;
5360 }
5361 } else {
5362 const uint32_t cur_halfdist = BiallelicDosageHalfdist(dosage_int);
5363 if ((cur_halfdist < dosage_erase_halfdist) ||
5364 ((!hds_valid) && BcfGtIsPhasedHet(gt_first, gt_second, 0x80, halfcall_mode))) {
5365 *phase_or_dosage_found_ptr = 1;
5366 return kBcfParseOk;
5367 }
5368 }
5369 }
5370 return kBcfParseOk;
5371 }
5372
5373 void BcfConvertBiallelicHaploidGt(const unsigned char* gt_main, uint32_t sample_ct, uintptr_t* __restrict genovec) {
5374 // Haploid, single byte per genotype.
5375 // 0 -> 3
5376 // 2 -> 0
5377 // 4 -> 2
5378 // 0x81 -> 3
5379 // Other values invalid, but we don't promise exhaustive error-checking, we
5380 // just need to (i) not blow up and (ii) try to have consistent behavior
5381 // between build types.
5382 // single-byte values, subtract 2 with wraparound, MIN(result, 3) works.
5383 #ifdef __LP64__
5384 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
5385 genovec[sample_ctl2 - 1] = 0;
5386 // overread ok since we perform no error detection
5387 const uint32_t vec_ct = DivUp(sample_ct, kBytesPerVec);
5388 const VecUc* gt_alias = R_CAST(const VecUc*, gt_main);
5389 Vec4thUint* genovec_alias = R_CAST(Vec4thUint*, genovec);
5390 const VecUc neg2 = vecuc_set1(0xfe);
5391 const VecUc three = vecuc_set1(3);
5392 const VecW zero = vecw_setzero();
5393 for (uint32_t vidx = 0; vidx != vec_ct; ++vidx) {
5394 const VecUc bcf_bytes = vecuc_loadu(&(gt_alias[vidx]));
5395 const VecUc bcf_bytes_m2 = bcf_bytes + neg2;
5396 VecUc converted_bytes = vecuc_min(bcf_bytes_m2, three);
5397 // Now gather bits 0,1,8,9,... via movemask.
5398 // todo: better ARM implementation
5399 converted_bytes = vecuc_permute0xd8_if_avx2(converted_bytes);
5400 VecW vec_lo = vecw_unpacklo8(R_CAST(VecW, converted_bytes), zero);
5401 VecW vec_hi = vecw_unpackhi8(R_CAST(VecW, converted_bytes), zero);
5402 vec_lo = vecw_slli(vec_lo, 7) | vecw_slli(vec_lo, 14);
5403 vec_hi = vecw_slli(vec_hi, 7) | vecw_slli(vec_hi, 14);
5404 const Vec4thUint lo_bits = vecw_movemask(vec_lo);
5405 const Vec4thUint hi_bits = vecw_movemask(vec_hi);
5406 genovec_alias[vidx] = lo_bits | (hi_bits << kBytesPerVec);
5407 }
5408 // Zero out the garbage at the end.
5409 const uint32_t inv_remainder = (-sample_ct) & (kBytesPerVec - 1);
5410 genovec_alias[vec_ct - 1] &= (~S_CAST(Vec4thUint, 0)) >> (2 * inv_remainder);
5411 #else
5412 const unsigned char* gt_iter = gt_main;
5413 const uint32_t word_ct_m1 = (sample_ct - 1) / kBitsPerWordD2;
5414 uint32_t loop_len = kBitsPerWordD2;
5415 for (uint32_t widx = 0; ; ++widx) {
5416 if (widx >= word_ct_m1) {
5417 if (widx > word_ct_m1) {
5418 break;
5419 }
5420 loop_len = ModNz(sample_ct, kBitsPerWordD2);
5421 }
5422 uintptr_t geno_word = 0;
5423 // possible todo: benchmark this vs. the forward loop, with and without
5424 // sparse-optimization
5425 for (uint32_t sample_idx_lowbits = loop_len; sample_idx_lowbits; ) {
5426 --sample_idx_lowbits;
5427 unsigned char raw_val_m2 = gt_iter[sample_idx_lowbits] - 2;
5428 if (raw_val_m2 > 3) {
5429 raw_val_m2 = 3;
5430 }
5431 geno_word |= raw_val_m2;
5432 geno_word = geno_word << 2;
5433 }
5434 genovec[widx] = geno_word;
5435 gt_iter = &(gt_iter[kBitsPerWordD2]);
5436 }
5437 #endif
5438 }
5439
5440 BcfParseErr BcfApplyGqDpFilters(const BcfImportBaseContext* bibcp, const GparseReadBcfMetadata* metap, const unsigned char* record_start, uintptr_t* __restrict genovec) {
5441 if ((metap->qual_vec_offsets[0] != UINT32_MAX) || (metap->qual_vec_offsets[1] != UINT32_MAX)) {
5442 const uint32_t sample_ct = bibcp->sample_ct;
5443 for (uint32_t qual_idx = 0; qual_idx != 2; ++qual_idx) {
5444 const uint32_t vec_offset = metap->qual_vec_offsets[qual_idx];
5445 if (vec_offset == UINT32_MAX) {
5446 continue;
5447 }
5448 const unsigned char* qual_start = &(record_start[vec_offset * S_CAST(uintptr_t, kBytesPerVec)]);
5449 BcfParseErr bcf_parse_err = BcfParseGqDpAligned(qual_start, sample_ct, bibcp->qual_mins[qual_idx], bibcp->qual_maxs[qual_idx], genovec);
5450 if (bcf_parse_err != kBcfParseOk) {
5451 return bcf_parse_err;
5452 }
5453 }
5454 }
5455 return kBcfParseOk;
5456 }
5457
5458 // GT present, dosage/HDS not present, phase known to be irrelevant.
5459 BcfParseErr BcfConvertUnphasedBiallelic(const BcfImportBaseContext* bibcp, const GparseReadBcfMetadata* metap, unsigned char* record_start, uintptr_t* __restrict genovec) {
5460 unsigned char* gt_type_start = &(record_start[metap->gt_vec_offset * S_CAST(uintptr_t, kBytesPerVec)]);
5461 const unsigned char* gt_main = gt_type_start;
5462 // this was partially validated in first pass
5463 uint32_t value_type;
5464 uint32_t value_ct;
5465 ScanBcfTypeAligned(&gt_main, &value_type, &value_ct);
5466 if (unlikely(value_type != 1)) {
5467 return (value_type <= 3)? kBcfParseWideGt : kBcfParseMalformedGeneric;
5468 }
5469 const uint32_t sample_ct = bibcp->sample_ct;
5470 // value_ct guaranteed to be positive
5471 if (value_ct == 1) {
5472 BcfConvertBiallelicHaploidGt(gt_main, sample_ct, genovec);
5473 } else {
5474 const unsigned char* biallelic_gt_lookup = bibcp->biallelic_gt_lookup;
5475 #ifdef USE_SHUFFLE8
5476 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
5477 genovec[sample_ctl2 - 1] = 0;
5478 #else
5479 const uint32_t word_ct_m1 = (sample_ct - 1) / kBitsPerWordD2;
5480 uint32_t loop_len = kBitsPerWordD2;
5481 #endif
5482 if (value_ct == 2) {
5483 // Regular diploid.
5484 // Possibly phased, we ignore that since the prescan told us no phased
5485 // calls are hets.
5486 // After right-shifting, the four cases for each byte are 0, 1, 2, and
5487 // 0x40. This adds up to 16 cases for the byte pair, which works nicely
5488 // with _mm{256}_shuffle_epi8() parallel-lookup. Conveniently, all
5489 // missing, haploid, and non-error half-call handling logic can be
5490 // encoded in the table.
5491 // As for erroring out on half-calls, that's handled by setting the
5492 // relevant table entries to 4 instead of 0..3.
5493 #ifdef USE_SHUFFLE8
5494 const uint32_t vec_ct = DivUp(sample_ct, kInt16PerVec);
5495 const uint32_t inv_remainder = (-sample_ct) & (kInt16PerVec - 1);
5496 if (inv_remainder) {
5497 // Set all past-the-end bytes to 2. This causes trailing genovec bits
5498 // to be zero, and doesn't create a half_call_error_bit2_vec false
5499 // positive.
5500 // (yes, it's a bit silly to use gt_type_start instead of gt_main
5501 // here...)
5502 memset(&(gt_type_start[kBytesPerVec + sample_ct * 2]), 2, 2 * inv_remainder);
5503 }
5504 const VecU16* gt_alias = R_CAST(const VecU16*, gt_main);
5505 Vec8thUint* genovec_alias = R_CAST(Vec8thUint*, genovec);
5506
5507 const VecU16 hibit_mask = vecu16_set1(0x7f7f);
5508 const VecU16 three = vecu16_set1(0x303);
5509 const VecU16 mask_000f = vecu16_set1(0xf);
5510 const VecU16 lookup_vec = vecu16_loadu(biallelic_gt_lookup);
5511 VecU16 half_call_error_bit2_vec = vecu16_setzero();
5512 for (uint32_t vidx = 0; vidx != vec_ct; ++vidx) {
5513 const VecU16 bcf_bytes = vecu16_loadu(&(gt_alias[vidx]));
5514 const VecU16 shifted_bytes = vecu16_srli(bcf_bytes, 1) & hibit_mask;
5515 const VecU16 capped_bytes = vecu16_min8(shifted_bytes, three);
5516 const VecU16 ready_for_lookup = (capped_bytes | vecu16_srli(capped_bytes, 6)) & mask_000f;
5517 const VecU16 lookup_result = vecu16_shuffle8(lookup_vec, ready_for_lookup) & mask_000f;
5518 half_call_error_bit2_vec |= lookup_result;
5519 // todo: better ARM implementation
5520 const VecU16 ready_for_movemask = vecu16_slli(lookup_result, 7) | vecu16_slli(lookup_result, 14);
5521 const Vec8thUint geno_bits = vecu16_movemask(ready_for_movemask);
5522 genovec_alias[vidx] = geno_bits;
5523 }
5524 half_call_error_bit2_vec = vecu16_slli(half_call_error_bit2_vec, 5);
5525 if (unlikely(vecu16_movemask(half_call_error_bit2_vec))) {
5526 return kBcfParseHalfCallError;
5527 }
5528 #else
5529 // todo: benchmark explicit vectorization of SSE2; I suspect that, with
5530 // no parallel-lookup operation, it would usually be worse than this
5531 // simple sparse-optimization.
5532 const uint16_t* gt_iter = R_CAST(const uint16_t*, gt_main);
5533 uintptr_t half_call_error_bit2 = 0;
5534 for (uint32_t widx = 0; ; ++widx) {
5535 if (widx >= word_ct_m1) {
5536 if (widx > word_ct_m1) {
5537 break;
5538 }
5539 loop_len = ModNz(sample_ct, kBitsPerWordD2);
5540 }
5541 uintptr_t geno_word = 0;
5542 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
5543 const uint32_t phaseless_val = gt_iter[sample_idx_lowbits] & 0xfefe;
5544 if (phaseless_val == 0x202) {
5545 continue;
5546 }
5547 uint32_t first_allele_idx_p1 = (phaseless_val & 0xff) >> 1;
5548 uint32_t second_allele_idx_p1 = phaseless_val >> 9;
5549 if (first_allele_idx_p1 > 3) {
5550 first_allele_idx_p1 = 3;
5551 }
5552 if (second_allele_idx_p1 > 3) {
5553 second_allele_idx_p1 = 3;
5554 }
5555 const uintptr_t result = biallelic_gt_lookup[first_allele_idx_p1 + second_allele_idx_p1 * 4];
5556 half_call_error_bit2 |= result;
5557 geno_word |= result << (2 * sample_idx_lowbits);
5558 }
5559 genovec[widx] = geno_word;
5560 gt_iter = &(gt_iter[kBitsPerWordD2]);
5561 }
5562 if (unlikely(half_call_error_bit2 & 4)) {
5563 return kBcfParseHalfCallError;
5564 }
5565 #endif
5566 } else {
5567 // triploid, etc.
5568 if (unlikely(bibcp->error_on_polyploid)) {
5569 return kBcfParsePolyploidError;
5570 }
5571 #ifdef USE_SHUFFLE8
5572 const uint32_t word_ct_m1 = (sample_ct - 1) / kBitsPerWordD2;
5573 uint32_t loop_len = kBitsPerWordD2;
5574 #endif
5575 const unsigned char* gt_iter = gt_main;
5576 uintptr_t half_call_error_bit2 = 0;
5577 for (uint32_t widx = 0; ; ++widx) {
5578 if (widx >= word_ct_m1) {
5579 if (widx > word_ct_m1) {
5580 break;
5581 }
5582 loop_len = ModNz(sample_ct, kBitsPerWordD2);
5583 }
5584 uintptr_t geno_word = 0;
5585 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
5586 // may overread 1 byte
5587 uint32_t phaseless_val;
5588 memcpy(&phaseless_val, gt_iter, 4);
5589 gt_iter = &(gt_iter[value_ct]);
5590 phaseless_val &= 0xfffefe;
5591 if (phaseless_val == 0x810202) {
5592 continue;
5593 }
5594 uintptr_t result;
5595 if ((phaseless_val & 0x810000) != 0x810000) {
5596 // triploid+ (or malformed)
5597 result = 3;
5598 } else {
5599 unsigned char first_allele_idx_p1 = phaseless_val >> 1;
5600 unsigned char second_allele_idx_p1 = (phaseless_val >> 9) & 0x7f;
5601 if (first_allele_idx_p1 > 3) {
5602 first_allele_idx_p1 = 3;
5603 }
5604 if (second_allele_idx_p1 > 3) {
5605 second_allele_idx_p1 = 3;
5606 }
5607 result = biallelic_gt_lookup[first_allele_idx_p1 + second_allele_idx_p1 * 4];
5608 half_call_error_bit2 |= result;
5609 }
5610 geno_word |= result << (2 * sample_idx_lowbits);
5611 }
5612 genovec[widx] = geno_word;
5613 }
5614 if (unlikely(half_call_error_bit2 & 4)) {
5615 return kBcfParseHalfCallError;
5616 }
5617 }
5618 }
5619 return BcfApplyGqDpFilters(bibcp, metap, record_start, genovec);
5620 }
5621
5622 static_assert(sizeof(AlleleCode) == 1, "BcfConvertMultiallelicHaploidInt8Gt() needs to be updated.");
5623 // genovec assumed to be initialized by BcfApplyGqDpFilters()
5624 void BcfConvertMultiallelicHaploidInt8Gt(const unsigned char* gt_main, uint32_t sample_ct, uint32_t allele_ct, uintptr_t* __restrict genovec, Halfword* __restrict patch_10_set_alias, AlleleCode** patch_10_iterp) {
5625 const unsigned char* gt_iter = gt_main;
5626 const uint32_t word_ct_m1 = (sample_ct - 1) / kBitsPerWordD2;
5627 DoubleAlleleCode* patch_10_vals_alias = R_CAST(DoubleAlleleCode*, *patch_10_iterp);
5628 DoubleAlleleCode* patch_10_iter = patch_10_vals_alias;
5629 uint32_t loop_len = kBitsPerWordD2;
5630 for (uint32_t widx = 0; ; ++widx) {
5631 if (widx >= word_ct_m1) {
5632 if (widx > word_ct_m1) {
5633 break;
5634 }
5635 loop_len = ModNz(sample_ct, kBitsPerWordD2);
5636 }
5637 const uintptr_t gq_dp_fail_word = genovec[widx];
5638 uintptr_t geno_word = 0;
5639 uint32_t patch_10_set_hw = 0;
5640 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
5641 const unsigned char raw_val_m2 = gt_iter[sample_idx_lowbits] - 2;
5642 if ((!raw_val_m2) || ((gq_dp_fail_word >> (2 * sample_idx_lowbits)) & 1)) {
5643 continue;
5644 }
5645 const uint32_t allele_idx = raw_val_m2 >> 1;
5646 uintptr_t result;
5647 if (allele_idx >= allele_ct) {
5648 // missing and END_OF_VECTOR wind up here
5649 result = 3;
5650 } else {
5651 result = 2;
5652 // note that allele_idx == 0 is possible with malformed raw_val == 3,
5653 // we don't handle it "correctly" but we do need to avoid blowing up
5654 if (allele_idx >= 2) {
5655 patch_10_set_hw |= 1U << sample_idx_lowbits;
5656 *patch_10_iter++ = allele_idx * 0x101;
5657 }
5658 }
5659 geno_word |= result << (2 * sample_idx_lowbits);
5660 }
5661 genovec[widx] = geno_word | gq_dp_fail_word;
5662 patch_10_set_alias[widx] = patch_10_set_hw;
5663 gt_iter = &(gt_iter[kBitsPerWordD2]);
5664 }
5665 *patch_10_iterp = R_CAST(AlleleCode*, patch_10_iter);
5666 }
5667
5668 static_assert(sizeof(AlleleCode) == 1, "BcfConvertMultiallelicHaploidInt8Gt() needs to be updated.");
5669 // genovec assumed to be initialized by BcfApplyGqDpFilters()
5670 void BcfConvertMultiallelicHaploidInt16Gt(const unsigned char* gt_main, uint32_t sample_ct, uint32_t allele_ct, uintptr_t* __restrict genovec, Halfword* __restrict patch_10_set_alias, AlleleCode** patch_10_iterp) {
5671 const uint16_t* gt_iter = R_CAST(const uint16_t*, gt_main);
5672 const uint32_t word_ct_m1 = (sample_ct - 1) / kBitsPerWordD2;
5673 DoubleAlleleCode* patch_10_vals_alias = R_CAST(DoubleAlleleCode*, *patch_10_iterp);
5674 DoubleAlleleCode* patch_10_iter = patch_10_vals_alias;
5675 uint32_t loop_len = kBitsPerWordD2;
5676 for (uint32_t widx = 0; ; ++widx) {
5677 if (widx >= word_ct_m1) {
5678 if (widx > word_ct_m1) {
5679 break;
5680 }
5681 loop_len = ModNz(sample_ct, kBitsPerWordD2);
5682 }
5683 const uintptr_t gq_dp_fail_word = genovec[widx];
5684 uintptr_t geno_word = 0;
5685 uint32_t patch_10_set_hw = 0;
5686 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
5687 // intentional underflow
5688 const uint32_t raw_val_m2 = S_CAST(uint32_t, gt_iter[sample_idx_lowbits]) - 2;
5689 if ((!raw_val_m2) || ((gq_dp_fail_word >> (2 * sample_idx_lowbits)) & 1)) {
5690 continue;
5691 }
5692 const uint32_t allele_idx = raw_val_m2 >> 1;
5693 uintptr_t result;
5694 if (allele_idx >= allele_ct) {
5695 result = 3;
5696 } else {
5697 result = 2;
5698 if (allele_idx >= 2) {
5699 patch_10_set_hw |= 1U << sample_idx_lowbits;
5700 *patch_10_iter++ = allele_idx * 0x101;
5701 }
5702 }
5703 geno_word |= result << (2 * sample_idx_lowbits);
5704 }
5705 genovec[widx] = geno_word | gq_dp_fail_word;
5706 patch_10_set_alias[widx] = patch_10_set_hw;
5707 gt_iter = &(gt_iter[kBitsPerWordD2]);
5708 }
5709 *patch_10_iterp = R_CAST(AlleleCode*, patch_10_iter);
5710 }
5711
5712 BcfParseErr BcfConvertUnphasedMultiallelic(const BcfImportBaseContext* bibcp, const GparseReadBcfMetadata* metap, const unsigned char* record_start, uint32_t allele_ct, uint32_t* __restrict patch_01_ctp, uint32_t* __restrict patch_10_ctp, uintptr_t* __restrict genovec, uintptr_t* __restrict patch_01_set, AlleleCode* __restrict patch_01_vals, uintptr_t* __restrict patch_10_set, AlleleCode* __restrict patch_10_vals) {
5713 const uint32_t sample_ct = bibcp->sample_ct;
5714 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
5715 ZeroWArr(sample_ctl2, genovec);
5716 BcfParseErr bcf_parse_err = BcfApplyGqDpFilters(bibcp, metap, record_start, genovec);
5717 if (unlikely(bcf_parse_err != kBcfParseOk)) {
5718 return bcf_parse_err;
5719 }
5720 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
5721 const uint32_t word_ct_m1 = (sample_ct - 1) / kBitsPerWordD2;
5722 patch_01_set[sample_ctl - 1] = 0;
5723 patch_10_set[sample_ctl - 1] = 0;
5724 Halfword* patch_01_set_alias = R_CAST(Halfword*, patch_01_set);
5725 Halfword* patch_10_set_alias = R_CAST(Halfword*, patch_10_set);
5726 const VcfHalfCall halfcall_mode = bibcp->halfcall_mode;
5727 AlleleCode* patch_01_iter = patch_01_vals;
5728 AlleleCode* patch_10_iter = patch_10_vals;
5729 uint32_t loop_len = kBitsPerWordD2;
5730 const unsigned char* gt_main = &(record_start[metap->gt_vec_offset * S_CAST(uintptr_t, kBytesPerVec)]);
5731 uint32_t value_type;
5732 uint32_t value_ct;
5733 ScanBcfTypeAligned(&gt_main, &value_type, &value_ct);
5734 if (value_type == 1) {
5735 // int8
5736 if (allele_ct >= 64) {
5737 // don't misinterpret END_OF_VECTOR
5738 allele_ct = 63;
5739 }
5740 if (value_ct == 1) {
5741 ZeroWArr(sample_ctl, patch_01_set);
5742 BcfConvertMultiallelicHaploidInt8Gt(gt_main, sample_ct, allele_ct, genovec, patch_10_set_alias, &patch_10_iter);
5743 } else if (value_ct == 2) {
5744 const uint16_t* gt_iter = R_CAST(const uint16_t*, gt_main);
5745 for (uint32_t widx = 0; ; ++widx) {
5746 if (widx >= word_ct_m1) {
5747 if (widx > word_ct_m1) {
5748 break;
5749 }
5750 loop_len = ModNz(sample_ct, kBitsPerWordD2);
5751 }
5752 const uintptr_t gq_dp_fail_word = genovec[widx];
5753 uintptr_t geno_word = 0;
5754 uint32_t patch_01_set_hw = 0;
5755 uint32_t patch_10_set_hw = 0;
5756 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
5757 const uint32_t phaseless_val = gt_iter[sample_idx_lowbits] & 0xfefe;
5758 if ((phaseless_val == 0x202) || ((gq_dp_fail_word >> (2 * sample_idx_lowbits)) & 1)) {
5759 continue;
5760 }
5761 const uint32_t shifted_phaseless_val = phaseless_val >> 1;
5762 uint32_t first_allele_idx_p1 = shifted_phaseless_val & 0xff;
5763 uintptr_t result;
5764 if (first_allele_idx_p1 > allele_ct) {
5765 // assume end-of-vector
5766 result = 3;
5767 } else {
5768 uint32_t second_allele_idx_p1 = shifted_phaseless_val >> 8;
5769 const uint32_t cur_bit = 1U << sample_idx_lowbits;
5770 if (second_allele_idx_p1 > allele_ct) {
5771 // haploid
5772 if (!first_allele_idx_p1) {
5773 result = 3;
5774 } else {
5775 const uint32_t first_allele_idx = first_allele_idx_p1 - 1;
5776 if (first_allele_idx < 2) {
5777 result = first_allele_idx * 2;
5778 } else {
5779 result = 2;
5780 patch_10_set_hw |= cur_bit;
5781 *patch_10_iter++ = first_allele_idx;
5782 *patch_10_iter++ = first_allele_idx;
5783 }
5784 }
5785 } else {
5786 // diploid
5787 if (second_allele_idx_p1 < first_allele_idx_p1) {
5788 const uint32_t uii = first_allele_idx_p1;
5789 first_allele_idx_p1 = second_allele_idx_p1;
5790 second_allele_idx_p1 = uii;
5791 }
5792 if (!first_allele_idx_p1) {
5793 // missing or half-call
5794 if ((!second_allele_idx_p1) || (halfcall_mode == kVcfHalfCallMissing)) {
5795 result = 3;
5796 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
5797 return kBcfParseHalfCallError;
5798 } else {
5799 const uint32_t second_allele_idx = second_allele_idx_p1 - 1;
5800 if (second_allele_idx < 2) {
5801 // kVcfHalfCallHaploid, kVcfHalfCallReference
5802 result = second_allele_idx << halfcall_mode;
5803 } else if (halfcall_mode == kVcfHalfCallReference) {
5804 result = 1;
5805 patch_01_set_hw |= cur_bit;
5806 *patch_01_iter++ = second_allele_idx;
5807 } else {
5808 result = 2;
5809 patch_10_set_hw |= cur_bit;
5810 *patch_10_iter++ = second_allele_idx;
5811 *patch_10_iter++ = second_allele_idx;
5812 }
5813 }
5814 } else if (first_allele_idx_p1 == 1) {
5815 // note that we've handled the second_allele_idx_p1 == 0 and ==
5816 // 1 cases earlier
5817 result = 1;
5818 if (second_allele_idx_p1 > 2) {
5819 patch_01_set_hw |= cur_bit;
5820 *patch_01_iter++ = second_allele_idx_p1 - 1;
5821 }
5822 } else {
5823 result = 2;
5824 if (second_allele_idx_p1 > 2) {
5825 patch_10_set_hw |= cur_bit;
5826 *patch_10_iter++ = first_allele_idx_p1 - 1;
5827 *patch_10_iter++ = second_allele_idx_p1 - 1;
5828 }
5829 }
5830 }
5831 }
5832 geno_word |= result << (2 * sample_idx_lowbits);
5833 }
5834 genovec[widx] = geno_word | gq_dp_fail_word;
5835 patch_01_set_alias[widx] = patch_01_set_hw;
5836 patch_10_set_alias[widx] = patch_10_set_hw;
5837 gt_iter = &(gt_iter[kBitsPerWordD2]);
5838 }
5839 } else {
5840 const unsigned char* gt_iter = gt_main;
5841 for (uint32_t widx = 0; ; ++widx) {
5842 if (widx >= word_ct_m1) {
5843 if (widx > word_ct_m1) {
5844 break;
5845 }
5846 loop_len = ModNz(sample_ct, kBitsPerWordD2);
5847 }
5848 const uintptr_t gq_dp_fail_word = genovec[widx];
5849 uintptr_t geno_word = 0;
5850 uint32_t patch_01_set_hw = 0;
5851 uint32_t patch_10_set_hw = 0;
5852 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
5853 // may overread 1 byte
5854 uint32_t phaseless_val;
5855 memcpy(&phaseless_val, gt_iter, 4);
5856 gt_iter = &(gt_iter[value_ct]);
5857 phaseless_val &= 0xfffefe;
5858 if ((phaseless_val == 0x810202) || ((gq_dp_fail_word >> (2 * sample_idx_lowbits)) & 1)) {
5859 continue;
5860 }
5861 uintptr_t result;
5862 if ((phaseless_val & 0x810000) != 0x810000) {
5863 // triploid+ (or malformed)
5864 result = 3;
5865 } else {
5866 phaseless_val &= 0xffff;
5867 const uint32_t shifted_phaseless_val = phaseless_val >> 1;
5868 // rest of this is identical to diploid case
5869 // todo: try making this a static inline function (didn't start
5870 // with that since the function would have 10+ parameters, many of
5871 // which may not be touched on a given function call)
5872 uint32_t first_allele_idx_p1 = shifted_phaseless_val;
5873 if (first_allele_idx_p1 > allele_ct) {
5874 // assume end-of-vector
5875 result = 3;
5876 } else {
5877 uint32_t second_allele_idx_p1 = shifted_phaseless_val >> 8;
5878 const uint32_t cur_bit = 1U << sample_idx_lowbits;
5879 if (second_allele_idx_p1 > allele_ct) {
5880 // haploid
5881 if (!first_allele_idx_p1) {
5882 result = 3;
5883 } else {
5884 const uint32_t first_allele_idx = first_allele_idx_p1 - 1;
5885 if (first_allele_idx < 2) {
5886 result = first_allele_idx * 2;
5887 } else {
5888 result = 2;
5889 patch_10_set_hw |= cur_bit;
5890 *patch_10_iter++ = first_allele_idx;
5891 *patch_10_iter++ = first_allele_idx;
5892 }
5893 }
5894 } else {
5895 // diploid
5896 if (second_allele_idx_p1 < first_allele_idx_p1) {
5897 const uint32_t uii = first_allele_idx_p1;
5898 first_allele_idx_p1 = second_allele_idx_p1;
5899 second_allele_idx_p1 = uii;
5900 }
5901 if (!first_allele_idx_p1) {
5902 // missing or half-call
5903 if ((!second_allele_idx_p1) || (halfcall_mode == kVcfHalfCallMissing)) {
5904 result = 3;
5905 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
5906 return kBcfParseHalfCallError;
5907 } else {
5908 const uint32_t second_allele_idx = second_allele_idx_p1 - 1;
5909 if (second_allele_idx < 2) {
5910 // kVcfHalfCallHaploid, kVcfHalfCallReference
5911 result = second_allele_idx << halfcall_mode;
5912 } else if (halfcall_mode == kVcfHalfCallReference) {
5913 result = 1;
5914 patch_01_set_hw |= cur_bit;
5915 *patch_01_iter++ = second_allele_idx;
5916 } else {
5917 result = 2;
5918 patch_10_set_hw |= cur_bit;
5919 *patch_10_iter++ = second_allele_idx;
5920 *patch_10_iter++ = second_allele_idx;
5921 }
5922 }
5923 } else if (first_allele_idx_p1 == 1) {
5924 result = 1;
5925 if (second_allele_idx_p1 > 2) {
5926 patch_01_set_hw |= cur_bit;
5927 *patch_01_iter++ = second_allele_idx_p1 - 1;
5928 }
5929 } else {
5930 result = 2;
5931 if (second_allele_idx_p1 > 2) {
5932 patch_10_set_hw |= cur_bit;
5933 *patch_10_iter++ = first_allele_idx_p1 - 1;
5934 *patch_10_iter++ = second_allele_idx_p1 - 1;
5935 }
5936 }
5937 }
5938 }
5939 }
5940 geno_word |= result << (2 * sample_idx_lowbits);
5941 }
5942 genovec[widx] = geno_word | gq_dp_fail_word;
5943 patch_01_set_alias[widx] = patch_01_set_hw;
5944 patch_10_set_alias[widx] = patch_10_set_hw;
5945 }
5946 }
5947 } else if (likely(value_type == 2)) {
5948 // int16
5949 if (value_ct == 1) {
5950 BcfConvertMultiallelicHaploidInt16Gt(gt_main, sample_ct, allele_ct, genovec, patch_10_set_alias, &patch_10_iter);
5951 } else if (value_ct == 2) {
5952 const uint32_t* gt_iter = R_CAST(const uint32_t*, gt_main);
5953 for (uint32_t widx = 0; ; ++widx) {
5954 if (widx >= word_ct_m1) {
5955 if (widx > word_ct_m1) {
5956 break;
5957 }
5958 loop_len = ModNz(sample_ct, kBitsPerWordD2);
5959 }
5960 const uintptr_t gq_dp_fail_word = genovec[widx];
5961 uintptr_t geno_word = 0;
5962 uint32_t patch_01_set_hw = 0;
5963 uint32_t patch_10_set_hw = 0;
5964 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
5965 const uint32_t phaseless_val = gt_iter[sample_idx_lowbits] & 0xfffefffeU;
5966 if ((phaseless_val == 0x20002) || ((gq_dp_fail_word >> (2 * sample_idx_lowbits)) & 1)) {
5967 continue;
5968 }
5969 const uint32_t shifted_phaseless_val = phaseless_val >> 1;
5970 uint32_t first_allele_idx_p1 = shifted_phaseless_val & 0xffff;
5971 uintptr_t result;
5972 if (first_allele_idx_p1 > allele_ct) {
5973 // assume end-of-vector
5974 result = 3;
5975 } else {
5976 uint32_t second_allele_idx_p1 = shifted_phaseless_val >> 16;
5977 const uint32_t cur_bit = 1U << sample_idx_lowbits;
5978 if (second_allele_idx_p1 > allele_ct) {
5979 // haploid
5980 if (!first_allele_idx_p1) {
5981 result = 3;
5982 } else {
5983 const uint32_t first_allele_idx = first_allele_idx_p1 - 1;
5984 if (first_allele_idx < 2) {
5985 result = first_allele_idx * 2;
5986 } else {
5987 result = 2;
5988 patch_10_set_hw |= cur_bit;
5989 *patch_10_iter++ = first_allele_idx;
5990 *patch_10_iter++ = first_allele_idx;
5991 }
5992 }
5993 } else {
5994 // diploid
5995 if (second_allele_idx_p1 < first_allele_idx_p1) {
5996 const uint32_t uii = first_allele_idx_p1;
5997 first_allele_idx_p1 = second_allele_idx_p1;
5998 second_allele_idx_p1 = uii;
5999 }
6000 if (!first_allele_idx_p1) {
6001 // missing or half-call
6002 if ((!second_allele_idx_p1) || (halfcall_mode == kVcfHalfCallMissing)) {
6003 result = 3;
6004 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
6005 return kBcfParseHalfCallError;
6006 } else {
6007 const uint32_t second_allele_idx = second_allele_idx_p1 - 1;
6008 if (second_allele_idx < 2) {
6009 // kVcfHalfCallHaploid, kVcfHalfCallReference
6010 result = second_allele_idx << halfcall_mode;
6011 } else if (halfcall_mode == kVcfHalfCallReference) {
6012 result = 1;
6013 patch_01_set_hw |= cur_bit;
6014 *patch_01_iter++ = second_allele_idx;
6015 } else {
6016 result = 2;
6017 patch_10_set_hw |= cur_bit;
6018 *patch_10_iter++ = second_allele_idx;
6019 *patch_10_iter++ = second_allele_idx;
6020 }
6021 }
6022 } else if (first_allele_idx_p1 == 1) {
6023 // note that we've handled the second_allele_idx_p1 == 0 and ==
6024 // 1 cases earlier
6025 result = 1;
6026 if (second_allele_idx_p1 > 2) {
6027 patch_01_set_hw |= cur_bit;
6028 *patch_01_iter++ = second_allele_idx_p1 - 1;
6029 }
6030 } else {
6031 result = 2;
6032 if (second_allele_idx_p1 > 2) {
6033 patch_10_set_hw |= cur_bit;
6034 *patch_10_iter++ = first_allele_idx_p1 - 1;
6035 *patch_10_iter++ = second_allele_idx_p1 - 1;
6036 }
6037 }
6038 }
6039 }
6040 geno_word |= result << (2 * sample_idx_lowbits);
6041 }
6042 genovec[widx] = geno_word | gq_dp_fail_word;
6043 patch_01_set_alias[widx] = patch_01_set_hw;
6044 patch_10_set_alias[widx] = patch_10_set_hw;
6045 gt_iter = &(gt_iter[kBitsPerWordD2]);
6046 }
6047 } else {
6048 const uint16_t* gt_iter = R_CAST(const uint16_t*, gt_main);
6049 for (uint32_t widx = 0; ; ++widx) {
6050 if (widx >= word_ct_m1) {
6051 if (widx > word_ct_m1) {
6052 break;
6053 }
6054 loop_len = ModNz(sample_ct, kBitsPerWordD2);
6055 }
6056 const uintptr_t gq_dp_fail_word = genovec[widx];
6057 uintptr_t geno_word = 0;
6058 uint32_t patch_01_set_hw = 0;
6059 uint32_t patch_10_set_hw = 0;
6060 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
6061 // may overread 2 bytes
6062 uint64_t phaseless_val;
6063 memcpy(&phaseless_val, gt_iter, 8);
6064 gt_iter = &(gt_iter[value_ct]);
6065 phaseless_val &= 0xfffffffefffeLLU;
6066 if ((phaseless_val == 0x800100020002LLU) || ((gq_dp_fail_word >> (2 * sample_idx_lowbits)) & 1)) {
6067 continue;
6068 }
6069 uintptr_t result;
6070 if ((phaseless_val & 0x800100000000LLU) != 0x800100000000LLU) {
6071 // triploid+ (or malformed)
6072 result = 3;
6073 } else {
6074 const uint32_t shifted_phaseless_val = S_CAST(uint32_t, phaseless_val) >> 1;
6075 // rest of this is identical to diploid case
6076 uint32_t first_allele_idx_p1 = shifted_phaseless_val & 0xffff;
6077 if (first_allele_idx_p1 > allele_ct) {
6078 // assume end-of-vector
6079 result = 3;
6080 } else {
6081 uint32_t second_allele_idx_p1 = shifted_phaseless_val >> 16;
6082 const uint32_t cur_bit = 1U << sample_idx_lowbits;
6083 if (second_allele_idx_p1 > allele_ct) {
6084 // haploid
6085 if (!first_allele_idx_p1) {
6086 result = 3;
6087 } else {
6088 const uint32_t first_allele_idx = first_allele_idx_p1 - 1;
6089 if (first_allele_idx < 2) {
6090 result = first_allele_idx * 2;
6091 } else {
6092 result = 2;
6093 patch_10_set_hw |= cur_bit;
6094 *patch_10_iter++ = first_allele_idx;
6095 *patch_10_iter++ = first_allele_idx;
6096 }
6097 }
6098 } else {
6099 // diploid
6100 if (second_allele_idx_p1 < first_allele_idx_p1) {
6101 const uint32_t uii = first_allele_idx_p1;
6102 first_allele_idx_p1 = second_allele_idx_p1;
6103 second_allele_idx_p1 = uii;
6104 }
6105 if (!first_allele_idx_p1) {
6106 // missing or half-call
6107 if ((!second_allele_idx_p1) || (halfcall_mode == kVcfHalfCallMissing)) {
6108 result = 3;
6109 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
6110 return kBcfParseHalfCallError;
6111 } else {
6112 const uint32_t second_allele_idx = second_allele_idx_p1 - 1;
6113 if (second_allele_idx < 2) {
6114 // kVcfHalfCallHaploid, kVcfHalfCallReference
6115 result = second_allele_idx << halfcall_mode;
6116 } else if (halfcall_mode == kVcfHalfCallReference) {
6117 result = 1;
6118 patch_01_set_hw |= cur_bit;
6119 *patch_01_iter++ = second_allele_idx;
6120 } else {
6121 result = 2;
6122 patch_10_set_hw |= cur_bit;
6123 *patch_10_iter++ = second_allele_idx;
6124 *patch_10_iter++ = second_allele_idx;
6125 }
6126 }
6127 } else if (first_allele_idx_p1 == 1) {
6128 result = 1;
6129 if (second_allele_idx_p1 > 2) {
6130 patch_01_set_hw |= cur_bit;
6131 *patch_01_iter++ = second_allele_idx_p1 - 1;
6132 }
6133 } else {
6134 result = 2;
6135 if (second_allele_idx_p1 > 2) {
6136 patch_10_set_hw |= cur_bit;
6137 *patch_10_iter++ = first_allele_idx_p1 - 1;
6138 *patch_10_iter++ = second_allele_idx_p1 - 1;
6139 }
6140 }
6141 }
6142 }
6143 }
6144 geno_word |= result << (2 * sample_idx_lowbits);
6145 }
6146 genovec[widx] = geno_word | gq_dp_fail_word;
6147 patch_01_set_alias[widx] = patch_01_set_hw;
6148 patch_10_set_alias[widx] = patch_10_set_hw;
6149 }
6150 }
6151 } else {
6152 return (value_type == 3)? kBcfParseWideGt : kBcfParseMalformedGeneric;
6153 }
6154 *patch_01_ctp = patch_01_iter - patch_01_vals;
6155 *patch_10_ctp = S_CAST(uintptr_t, patch_10_iter - patch_10_vals) / 2;
6156 return kBcfParseOk;
6157 }
6158
6159 // GT present, phase matters, dosage/HDS not present.
6160 BcfParseErr BcfConvertPhasedBiallelic(const BcfImportBaseContext* bibcp, const GparseReadBcfMetadata* metap, unsigned char* record_start, uintptr_t* __restrict genovec, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo) {
6161 unsigned char* gt_type_start = &(record_start[metap->gt_vec_offset * S_CAST(uintptr_t, kBytesPerVec)]);
6162 const unsigned char* gt_main = gt_type_start;
6163 // this was partially validated in first pass
6164 uint32_t value_type;
6165 uint32_t value_ct;
6166 ScanBcfTypeAligned(&gt_main, &value_type, &value_ct);
6167 if (unlikely(value_type != 1)) {
6168 return (value_type <= 3)? kBcfParseWideGt : kBcfParseMalformedGeneric;
6169 }
6170 const uint32_t sample_ct = bibcp->sample_ct;
6171 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
6172 if (value_ct == 1) {
6173 ZeroWArr(sample_ctl, phasepresent);
6174 BcfConvertBiallelicHaploidGt(gt_main, sample_ct, genovec);
6175 } else {
6176 phasepresent[sample_ctl - 1] = 0;
6177 phaseinfo[sample_ctl - 1] = 0;
6178 const unsigned char* biallelic_gt_lookup = bibcp->biallelic_gt_lookup;
6179 #ifdef USE_SHUFFLE8
6180 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
6181 genovec[sample_ctl2 - 1] = 0;
6182 #else
6183 const uint32_t word_ct_m1 = (sample_ct - 1) / kBitsPerWordD2;
6184 uint32_t loop_len = kBitsPerWordD2;
6185 #endif
6186 if (value_ct == 2) {
6187 // Regular diploid.
6188 // Additional requirements beyond unphased case:
6189 // - Extract original bit 8 (low bit of second genotype value). No need
6190 // to do anything else (verify non-END_OF_VECTOR or het status) with
6191 // it, here, that's taken care of after the GQ/DP filter.
6192 // - Extract original bit 9 (since the variant is biallelic, this bit
6193 // should only be set when the second genotype value is 0, i.e. if the
6194 // genotype is a phased het, it's 1|0).
6195 #ifdef USE_SHUFFLE8
6196 const uint32_t vec_ct = DivUp(sample_ct, kInt16PerVec);
6197 const uint32_t inv_remainder = (-sample_ct) & (kInt16PerVec - 1);
6198 if (inv_remainder) {
6199 // Set all past-the-end bytes to 2. This causes trailing genovec and
6200 // phasepresent bits to be zero, and doesn't create a
6201 // half_call_error_bit2_vec false positive.
6202 memset(&(gt_type_start[kBytesPerVec + sample_ct * 2]), 2, 2 * inv_remainder);
6203 }
6204 const VecU16* gt_alias = R_CAST(const VecU16*, gt_main);
6205 Vec8thUint* genovec_alias = R_CAST(Vec8thUint*, genovec);
6206 Vec16thUint* phasepresent_alias = R_CAST(Vec16thUint*, phasepresent);
6207 Vec16thUint* phaseinfo_alias = R_CAST(Vec16thUint*, phaseinfo);
6208
6209 const VecU16 hibit_mask = vecu16_set1(0x7f7f);
6210 const VecU16 three = vecu16_set1(0x303);
6211 const VecU16 mask_000f = vecu16_set1(0xf);
6212 # ifndef USE_AVX2
6213 const VecU16 gather_even = vecu16_setr8(0, 2, 4, 6, 8, 10, 12, 14,
6214 -1, -1, -1, -1, -1, -1, -1, -1);
6215 # endif
6216 const VecU16 lookup_vec = vecu16_loadu(biallelic_gt_lookup);
6217 VecU16 half_call_error_bit2_vec = vecu16_setzero();
6218 for (uint32_t vidx = 0; vidx != vec_ct; ++vidx) {
6219 const VecU16 bcf_bytes = vecu16_loadu(&(gt_alias[vidx]));
6220 const VecU16 shifted_unmasked_bytes = vecu16_srli(bcf_bytes, 1);
6221 const VecU16 bit9s_at_bit7 = vecu16_srli(bcf_bytes, 2);
6222 # ifdef USE_AVX2
6223 const Vec16thUint cur_phasepresent = _pext_u32(vecu16_movemask(shifted_unmasked_bytes), 0x55555555);
6224 const Vec16thUint cur_phaseinfo = _pext_u32(vecu16_movemask(bit9s_at_bit7), 0x55555555);
6225 # else
6226 // todo: better ARM implementation
6227 const VecU16 phasepresent_vec = vecu16_shuffle8(shifted_unmasked_bytes, gather_even);
6228 const VecU16 phaseinfo_vec = vecu16_shuffle8(bit9s_at_bit7, gather_even);
6229 const Vec16thUint cur_phasepresent = vecu16_movemask(phasepresent_vec);
6230 const Vec16thUint cur_phaseinfo = vecu16_movemask(phaseinfo_vec);
6231 # endif
6232 phasepresent_alias[vidx] = cur_phasepresent;
6233 phaseinfo_alias[vidx] = cur_phaseinfo;
6234
6235 const VecU16 shifted_bytes = shifted_unmasked_bytes & hibit_mask;
6236 const VecU16 capped_bytes = vecu16_min8(shifted_bytes, three);
6237 const VecU16 ready_for_lookup = (capped_bytes | vecu16_srli(capped_bytes, 6)) & mask_000f;
6238 const VecU16 lookup_result = vecu16_shuffle8(lookup_vec, ready_for_lookup) & mask_000f;
6239 half_call_error_bit2_vec |= lookup_result;
6240 const VecU16 ready_for_movemask = vecu16_slli(lookup_result, 7) | vecu16_slli(lookup_result, 14);
6241 const Vec8thUint geno_bits = vecu16_movemask(ready_for_movemask);
6242 genovec_alias[vidx] = geno_bits;
6243 }
6244 half_call_error_bit2_vec = vecu16_slli(half_call_error_bit2_vec, 5);
6245 if (unlikely(vecu16_movemask(half_call_error_bit2_vec))) {
6246 return kBcfParseHalfCallError;
6247 }
6248 #else
6249 // todo: benchmark explicit vectorization of SSE2
6250 const uint16_t* gt_iter = R_CAST(const uint16_t*, gt_main);
6251 Halfword* phasepresent_alias = R_CAST(Halfword*, phasepresent);
6252 Halfword* phaseinfo_alias = R_CAST(Halfword*, phaseinfo);
6253 uintptr_t half_call_error_bit2 = 0;
6254 for (uint32_t widx = 0; ; ++widx) {
6255 if (widx >= word_ct_m1) {
6256 if (widx > word_ct_m1) {
6257 break;
6258 }
6259 loop_len = ModNz(sample_ct, kBitsPerWordD2);
6260 }
6261 uintptr_t geno_word = 0;
6262 uintptr_t phasepresent_hw_shifted = 0;
6263 Halfword phaseinfo_hw = 0;
6264 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
6265 const uintptr_t raw_val = gt_iter[sample_idx_lowbits];
6266 if ((raw_val & 0xfefe) == 0x202) {
6267 continue;
6268 }
6269 const uintptr_t bit_8 = raw_val & 0x100;
6270 phasepresent_hw_shifted |= bit_8 << sample_idx_lowbits;
6271 uint32_t second_allele_idx_p1 = raw_val >> 9;
6272 phaseinfo_hw |= (second_allele_idx_p1 & 1) << sample_idx_lowbits;
6273 uint32_t first_allele_idx_p1 = (raw_val & 0xff) >> 1;
6274 if (first_allele_idx_p1 > 3) {
6275 first_allele_idx_p1 = 3;
6276 }
6277 if (second_allele_idx_p1 > 3) {
6278 second_allele_idx_p1 = 3;
6279 }
6280 const uintptr_t result = biallelic_gt_lookup[first_allele_idx_p1 + second_allele_idx_p1 * 4];
6281 half_call_error_bit2 |= result;
6282 geno_word |= result << (2 * sample_idx_lowbits);
6283 }
6284 genovec[widx] = geno_word;
6285 phasepresent_alias[widx] = phasepresent_hw_shifted >> 8;
6286 phaseinfo_alias[widx] = phaseinfo_hw;
6287 gt_iter = &(gt_iter[kBitsPerWordD2]);
6288 }
6289 if (unlikely(half_call_error_bit2 & 4)) {
6290 return kBcfParseHalfCallError;
6291 }
6292 #endif
6293 } else {
6294 // triploid, etc.
6295 if (unlikely(bibcp->error_on_polyploid)) {
6296 return kBcfParsePolyploidError;
6297 }
6298 Halfword* phasepresent_alias = R_CAST(Halfword*, phasepresent);
6299 Halfword* phaseinfo_alias = R_CAST(Halfword*, phaseinfo);
6300 #ifdef USE_SHUFFLE8
6301 const uint32_t word_ct_m1 = (sample_ct - 1) / kBitsPerWordD2;
6302 uint32_t loop_len = kBitsPerWordD2;
6303 #endif
6304 const unsigned char* gt_iter = gt_main;
6305 uintptr_t half_call_error_bit2 = 0;
6306 for (uint32_t widx = 0; ; ++widx) {
6307 if (widx >= word_ct_m1) {
6308 if (widx > word_ct_m1) {
6309 break;
6310 }
6311 loop_len = ModNz(sample_ct, kBitsPerWordD2);
6312 }
6313 uintptr_t geno_word = 0;
6314 uintptr_t phasepresent_hw_shifted = 0;
6315 Halfword phaseinfo_hw = 0;
6316 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
6317 // may overread 1 byte
6318 uint32_t raw_val;
6319 memcpy(&raw_val, gt_iter, 4);
6320 gt_iter = &(gt_iter[value_ct]);
6321 if ((raw_val & 0xfffefe) == 0x810202) {
6322 continue;
6323 }
6324 uintptr_t result;
6325 if ((raw_val & 0x810000) != 0x810000) {
6326 // triploid (or malformed)
6327 result = 3;
6328 } else {
6329 const uintptr_t bit_8 = raw_val & 0x100;
6330 phasepresent_hw_shifted |= bit_8 << sample_idx_lowbits;
6331 uint32_t second_allele_idx_p1 = (raw_val >> 9) & 0x7f;
6332 phaseinfo_hw |= (second_allele_idx_p1 & 1) << sample_idx_lowbits;
6333 uint32_t first_allele_idx_p1 = (raw_val & 0xff) >> 1;
6334 if (first_allele_idx_p1 > 3) {
6335 first_allele_idx_p1 = 3;
6336 }
6337 if (second_allele_idx_p1 > 3) {
6338 second_allele_idx_p1 = 3;
6339 }
6340 result = biallelic_gt_lookup[first_allele_idx_p1 + second_allele_idx_p1 * 4];
6341 half_call_error_bit2 |= result;
6342 }
6343 geno_word |= result << (2 * sample_idx_lowbits);
6344 }
6345 genovec[widx] = geno_word;
6346 phasepresent_alias[widx] = phasepresent_hw_shifted >> 8;
6347 phaseinfo_alias[widx] = phaseinfo_hw;
6348 }
6349 if (unlikely(half_call_error_bit2 & 4)) {
6350 return kBcfParseHalfCallError;
6351 }
6352 }
6353 }
6354 BcfParseErr bcf_parse_err = BcfApplyGqDpFilters(bibcp, metap, record_start, genovec);
6355 if (unlikely(bcf_parse_err != kBcfParseOk)) {
6356 return bcf_parse_err;
6357 }
6358 if (value_ct != 1) {
6359 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
6360 // mask out all phasepresent bits which don't correspond to hets.
6361 MaskWordsToHalfwordsInvmatch(genovec, kMaskAAAA, sample_ctl2, phasepresent, phasepresent);
6362 }
6363 return kBcfParseOk;
6364 }
6365
6366 BcfParseErr BcfConvertPhasedMultiallelic(const BcfImportBaseContext* bibcp, const GparseReadBcfMetadata* metap, unsigned char* record_start, uint32_t allele_ct, uint32_t* __restrict patch_01_ctp, uint32_t* __restrict patch_10_ctp, uintptr_t* __restrict genovec, uintptr_t* __restrict patch_01_set, AlleleCode* __restrict patch_01_vals, uintptr_t* __restrict patch_10_set, AlleleCode* __restrict patch_10_vals, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo) {
6367 // yes, there's lots of duplication with BcfConvertUnphasedMultiallelic...
6368 const uint32_t sample_ct = bibcp->sample_ct;
6369 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
6370 ZeroWArr(sample_ctl2, genovec);
6371 BcfParseErr bcf_parse_err = BcfApplyGqDpFilters(bibcp, metap, record_start, genovec);
6372 if (unlikely(bcf_parse_err != kBcfParseOk)) {
6373 return bcf_parse_err;
6374 }
6375 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
6376 const uint32_t word_ct_m1 = (sample_ct - 1) / kBitsPerWordD2;
6377 patch_01_set[sample_ctl - 1] = 0;
6378 patch_10_set[sample_ctl - 1] = 0;
6379 Halfword* patch_01_set_alias = R_CAST(Halfword*, patch_01_set);
6380 Halfword* patch_10_set_alias = R_CAST(Halfword*, patch_10_set);
6381 phasepresent[sample_ctl - 1] = 0;
6382 Halfword* phasepresent_alias = R_CAST(Halfword*, phasepresent);
6383 Halfword* phaseinfo_alias = R_CAST(Halfword*, phaseinfo);
6384 const VcfHalfCall halfcall_mode = bibcp->halfcall_mode;
6385 AlleleCode* patch_01_iter = patch_01_vals;
6386 AlleleCode* patch_10_iter = patch_10_vals;
6387 uint32_t loop_len = kBitsPerWordD2;
6388 const unsigned char* gt_main = &(record_start[metap->gt_vec_offset * S_CAST(uintptr_t, kBytesPerVec)]);
6389 uint32_t value_type;
6390 uint32_t value_ct;
6391 ScanBcfTypeAligned(&gt_main, &value_type, &value_ct);
6392 if (unlikely((value_ct > 2) && bibcp->error_on_polyploid)) {
6393 return kBcfParsePolyploidError;
6394 }
6395 if (value_type == 1) {
6396 // int8
6397 if (allele_ct >= 64) {
6398 // don't misinterpret END_OF_VECTOR
6399 allele_ct = 63;
6400 }
6401 if (value_ct == 1) {
6402 ZeroWArr(sample_ctl, patch_01_set);
6403 ZeroWArr(sample_ctl, phasepresent);
6404 // phaseinfo doesn't matter
6405 BcfConvertMultiallelicHaploidInt8Gt(gt_main, sample_ct, allele_ct, genovec, patch_10_set_alias, &patch_10_iter);
6406 } else if (value_ct == 2) {
6407 const uint16_t* gt_iter = R_CAST(const uint16_t*, gt_main);
6408 for (uint32_t widx = 0; ; ++widx) {
6409 if (widx >= word_ct_m1) {
6410 if (widx > word_ct_m1) {
6411 break;
6412 }
6413 loop_len = ModNz(sample_ct, kBitsPerWordD2);
6414 }
6415 const uintptr_t gq_dp_fail_word = genovec[widx];
6416 uintptr_t geno_word = 0;
6417 uint32_t patch_01_set_hw = 0;
6418 uint32_t patch_10_set_hw = 0;
6419 uint32_t phasepresent_hw = 0;
6420 uint32_t phaseinfo_hw = 0;
6421 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
6422 const uint32_t raw_val = gt_iter[sample_idx_lowbits];
6423 const uint32_t phaseless_val = raw_val & 0xfefe;
6424 if ((phaseless_val == 0x202) || ((gq_dp_fail_word >> (2 * sample_idx_lowbits)) & 1)) {
6425 continue;
6426 }
6427 const uint32_t shifted_phaseless_val = phaseless_val >> 1;
6428 uint32_t first_allele_idx_p1 = shifted_phaseless_val & 0xff;
6429 uintptr_t result;
6430 if (first_allele_idx_p1 > allele_ct) {
6431 // assume end-of-vector
6432 result = 3;
6433 } else {
6434 uint32_t second_allele_idx_p1 = shifted_phaseless_val >> 8;
6435 const uint32_t cur_bit = 1U << sample_idx_lowbits;
6436 if (second_allele_idx_p1 > allele_ct) {
6437 // haploid
6438 if (!first_allele_idx_p1) {
6439 result = 3;
6440 } else {
6441 const uint32_t first_allele_idx = first_allele_idx_p1 - 1;
6442 if (first_allele_idx < 2) {
6443 result = first_allele_idx * 2;
6444 } else {
6445 result = 2;
6446 patch_10_set_hw |= cur_bit;
6447 *patch_10_iter++ = first_allele_idx;
6448 *patch_10_iter++ = first_allele_idx;
6449 }
6450 }
6451 } else {
6452 // diploid
6453 if (second_allele_idx_p1 < first_allele_idx_p1) {
6454 const uint32_t uii = first_allele_idx_p1;
6455 first_allele_idx_p1 = second_allele_idx_p1;
6456 second_allele_idx_p1 = uii;
6457 phaseinfo_hw |= cur_bit;
6458 }
6459 if (!first_allele_idx_p1) {
6460 // missing or half-call
6461 if ((!second_allele_idx_p1) || (halfcall_mode == kVcfHalfCallMissing)) {
6462 result = 3;
6463 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
6464 return kBcfParseHalfCallError;
6465 } else {
6466 const uint32_t second_allele_idx = second_allele_idx_p1 - 1;
6467 if (second_allele_idx < 2) {
6468 // kVcfHalfCallHaploid, kVcfHalfCallReference
6469 result = second_allele_idx << halfcall_mode;
6470 } else if (halfcall_mode == kVcfHalfCallReference) {
6471 result = 1;
6472 patch_01_set_hw |= cur_bit;
6473 *patch_01_iter++ = second_allele_idx;
6474 } else {
6475 result = 2;
6476 patch_10_set_hw |= cur_bit;
6477 *patch_10_iter++ = second_allele_idx;
6478 *patch_10_iter++ = second_allele_idx;
6479 }
6480 if ((raw_val & 0x100) && (result == 1)) {
6481 phasepresent_hw |= cur_bit;
6482 }
6483 }
6484 } else {
6485 if ((raw_val & 0x100) && (first_allele_idx_p1 != second_allele_idx_p1)) {
6486 phasepresent_hw |= cur_bit;
6487 }
6488 if (first_allele_idx_p1 == 1) {
6489 // note that we've handled the second_allele_idx_p1 == 0 and
6490 // == 1 cases earlier
6491 result = 1;
6492 if (second_allele_idx_p1 > 2) {
6493 patch_01_set_hw |= cur_bit;
6494 *patch_01_iter++ = second_allele_idx_p1 - 1;
6495 }
6496 } else {
6497 result = 2;
6498 if (second_allele_idx_p1 > 2) {
6499 patch_10_set_hw |= cur_bit;
6500 *patch_10_iter++ = first_allele_idx_p1 - 1;
6501 *patch_10_iter++ = second_allele_idx_p1 - 1;
6502 }
6503 }
6504 }
6505 }
6506 }
6507 geno_word |= result << (2 * sample_idx_lowbits);
6508 }
6509 genovec[widx] = geno_word | gq_dp_fail_word;
6510 patch_01_set_alias[widx] = patch_01_set_hw;
6511 patch_10_set_alias[widx] = patch_10_set_hw;
6512 phasepresent_alias[widx] = phasepresent_hw;
6513 phaseinfo_alias[widx] = phaseinfo_hw;
6514 gt_iter = &(gt_iter[kBitsPerWordD2]);
6515 }
6516 } else {
6517 const unsigned char* gt_iter = gt_main;
6518 for (uint32_t widx = 0; ; ++widx) {
6519 if (widx >= word_ct_m1) {
6520 if (widx > word_ct_m1) {
6521 break;
6522 }
6523 loop_len = ModNz(sample_ct, kBitsPerWordD2);
6524 }
6525 const uintptr_t gq_dp_fail_word = genovec[widx];
6526 uintptr_t geno_word = 0;
6527 uint32_t patch_01_set_hw = 0;
6528 uint32_t patch_10_set_hw = 0;
6529 uint32_t phasepresent_hw = 0;
6530 uint32_t phaseinfo_hw = 0;
6531 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
6532 // may overread 1 byte
6533 uint32_t raw_val;
6534 memcpy(&raw_val, gt_iter, 4);
6535 gt_iter = &(gt_iter[value_ct]);
6536 const uint32_t phaseless_val = raw_val & 0xfffefe;
6537 if ((phaseless_val == 0x810202) || ((gq_dp_fail_word >> (2 * sample_idx_lowbits)) & 1)) {
6538 continue;
6539 }
6540 uintptr_t result;
6541 if ((phaseless_val & 0x810000) != 0x810000) {
6542 // triploid+ (or malformed)
6543 result = 3;
6544 } else {
6545 const uint32_t shifted_phaseless_val = (phaseless_val & 0xffff) >> 1;
6546 // rest of this is identical to diploid case
6547 uint32_t first_allele_idx_p1 = shifted_phaseless_val & 0xff;
6548 if (first_allele_idx_p1 > allele_ct) {
6549 // assume end-of-vector
6550 result = 3;
6551 } else {
6552 uint32_t second_allele_idx_p1 = shifted_phaseless_val >> 8;
6553 const uint32_t cur_bit = 1U << sample_idx_lowbits;
6554 if (second_allele_idx_p1 > allele_ct) {
6555 // haploid
6556 if (!first_allele_idx_p1) {
6557 result = 3;
6558 } else {
6559 const uint32_t first_allele_idx = first_allele_idx_p1 - 1;
6560 if (first_allele_idx < 2) {
6561 result = first_allele_idx * 2;
6562 } else {
6563 result = 2;
6564 patch_10_set_hw |= cur_bit;
6565 *patch_10_iter++ = first_allele_idx;
6566 *patch_10_iter++ = first_allele_idx;
6567 }
6568 }
6569 } else {
6570 // diploid
6571 if (second_allele_idx_p1 < first_allele_idx_p1) {
6572 const uint32_t uii = first_allele_idx_p1;
6573 first_allele_idx_p1 = second_allele_idx_p1;
6574 second_allele_idx_p1 = uii;
6575 phaseinfo_hw |= cur_bit;
6576 }
6577 if (!first_allele_idx_p1) {
6578 // missing or half-call
6579 if ((!second_allele_idx_p1) || (halfcall_mode == kVcfHalfCallMissing)) {
6580 result = 3;
6581 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
6582 return kBcfParseHalfCallError;
6583 } else {
6584 const uint32_t second_allele_idx = second_allele_idx_p1 - 1;
6585 if (second_allele_idx < 2) {
6586 // kVcfHalfCallHaploid, kVcfHalfCallReference
6587 result = second_allele_idx << halfcall_mode;
6588 } else if (halfcall_mode == kVcfHalfCallReference) {
6589 result = 1;
6590 patch_01_set_hw |= cur_bit;
6591 *patch_01_iter++ = second_allele_idx;
6592 } else {
6593 result = 2;
6594 patch_10_set_hw |= cur_bit;
6595 *patch_10_iter++ = second_allele_idx;
6596 *patch_10_iter++ = second_allele_idx;
6597 }
6598 if ((raw_val & 0x100) && (result == 1)) {
6599 phasepresent_hw |= cur_bit;
6600 }
6601 }
6602 } else {
6603 if ((raw_val & 0x100) && (first_allele_idx_p1 != second_allele_idx_p1)) {
6604 phasepresent_hw |= cur_bit;
6605 }
6606 if (first_allele_idx_p1 == 1) {
6607 result = 1;
6608 if (second_allele_idx_p1 > 2) {
6609 patch_01_set_hw |= cur_bit;
6610 *patch_01_iter++ = second_allele_idx_p1 - 1;
6611 }
6612 } else {
6613 result = 2;
6614 if (second_allele_idx_p1 > 2) {
6615 patch_10_set_hw |= cur_bit;
6616 *patch_10_iter++ = first_allele_idx_p1 - 1;
6617 *patch_10_iter++ = second_allele_idx_p1 - 1;
6618 }
6619 }
6620 }
6621 }
6622 }
6623 }
6624 geno_word |= result << (2 * sample_idx_lowbits);
6625 }
6626 genovec[widx] = geno_word | gq_dp_fail_word;
6627 patch_01_set_alias[widx] = patch_01_set_hw;
6628 patch_10_set_alias[widx] = patch_10_set_hw;
6629 phasepresent_alias[widx] = phasepresent_hw;
6630 phaseinfo_alias[widx] = phaseinfo_hw;
6631 }
6632 }
6633 } else if (likely(value_type == 2)) {
6634 // int16
6635 if (value_ct == 1) {
6636 ZeroWArr(sample_ctl, patch_01_set);
6637 ZeroWArr(sample_ctl, phasepresent);
6638 // phaseinfo doesn't matter
6639 BcfConvertMultiallelicHaploidInt16Gt(gt_main, sample_ct, allele_ct, genovec, patch_10_set_alias, &patch_10_iter);
6640 } else if (value_ct == 2) {
6641 const uint32_t* gt_iter = R_CAST(const uint32_t*, gt_main);
6642 for (uint32_t widx = 0; ; ++widx) {
6643 if (widx >= word_ct_m1) {
6644 if (widx > word_ct_m1) {
6645 break;
6646 }
6647 loop_len = ModNz(sample_ct, kBitsPerWordD2);
6648 }
6649 const uintptr_t gq_dp_fail_word = genovec[widx];
6650 uintptr_t geno_word = 0;
6651 uint32_t patch_01_set_hw = 0;
6652 uint32_t patch_10_set_hw = 0;
6653 uint32_t phasepresent_hw = 0;
6654 uint32_t phaseinfo_hw = 0;
6655 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
6656 const uint32_t raw_val = gt_iter[sample_idx_lowbits];
6657 const uint32_t phaseless_val = raw_val & 0xfffefffeU;
6658 if ((phaseless_val == 0x20002) || ((gq_dp_fail_word >> (2 * sample_idx_lowbits)) & 1)) {
6659 continue;
6660 }
6661 const uint32_t shifted_phaseless_val = phaseless_val >> 1;
6662 uint32_t first_allele_idx_p1 = shifted_phaseless_val & 0xffff;
6663 uintptr_t result;
6664 if (first_allele_idx_p1 > allele_ct) {
6665 // assume end-of-vector
6666 result = 3;
6667 } else {
6668 uint32_t second_allele_idx_p1 = shifted_phaseless_val >> 16;
6669 const uint32_t cur_bit = 1U << sample_idx_lowbits;
6670 if (second_allele_idx_p1 > allele_ct) {
6671 // haploid
6672 if (!first_allele_idx_p1) {
6673 result = 3;
6674 } else {
6675 const uint32_t first_allele_idx = first_allele_idx_p1 - 1;
6676 if (first_allele_idx < 2) {
6677 result = first_allele_idx * 2;
6678 } else {
6679 result = 2;
6680 patch_10_set_hw |= cur_bit;
6681 *patch_10_iter++ = first_allele_idx;
6682 *patch_10_iter++ = first_allele_idx;
6683 }
6684 }
6685 } else {
6686 // diploid
6687 if (second_allele_idx_p1 < first_allele_idx_p1) {
6688 const uint32_t uii = first_allele_idx_p1;
6689 first_allele_idx_p1 = second_allele_idx_p1;
6690 second_allele_idx_p1 = uii;
6691 phaseinfo_hw |= cur_bit;
6692 }
6693 if (!first_allele_idx_p1) {
6694 // missing or half-call
6695 if ((!second_allele_idx_p1) || (halfcall_mode == kVcfHalfCallMissing)) {
6696 result = 3;
6697 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
6698 return kBcfParseHalfCallError;
6699 } else {
6700 const uint16_t second_allele_idx = second_allele_idx_p1 - 1;
6701 if (second_allele_idx < 2) {
6702 // kVcfHalfCallHaploid, kVcfHalfCallReference
6703 result = second_allele_idx << halfcall_mode;
6704 } else if (halfcall_mode == kVcfHalfCallReference) {
6705 result = 1;
6706 patch_01_set_hw |= cur_bit;
6707 *patch_01_iter++ = second_allele_idx;
6708 } else {
6709 result = 2;
6710 patch_10_set_hw |= cur_bit;
6711 *patch_10_iter++ = second_allele_idx;
6712 *patch_10_iter++ = second_allele_idx;
6713 }
6714 if ((raw_val & 0x10000) && (result == 1)) {
6715 phasepresent_hw |= cur_bit;
6716 }
6717 }
6718 } else {
6719 if ((raw_val & 0x10000) && (first_allele_idx_p1 != second_allele_idx_p1)) {
6720 phasepresent_hw |= cur_bit;
6721 }
6722 if (first_allele_idx_p1 == 1) {
6723 // note that we've handled the second_allele_idx_p1 == 0 and
6724 // == 1 cases earlier
6725 result = 1;
6726 if (second_allele_idx_p1 > 2) {
6727 patch_01_set_hw |= cur_bit;
6728 *patch_01_iter++ = second_allele_idx_p1 - 1;
6729 }
6730 } else {
6731 result = 2;
6732 if (second_allele_idx_p1 > 2) {
6733 patch_10_set_hw |= cur_bit;
6734 *patch_10_iter++ = first_allele_idx_p1 - 1;
6735 *patch_10_iter++ = second_allele_idx_p1 - 1;
6736 }
6737 }
6738 }
6739 }
6740 }
6741 geno_word |= result << (2 * sample_idx_lowbits);
6742 }
6743 genovec[widx] = geno_word | gq_dp_fail_word;
6744 patch_01_set_alias[widx] = patch_01_set_hw;
6745 patch_10_set_alias[widx] = patch_10_set_hw;
6746 phasepresent_alias[widx] = phasepresent_hw;
6747 phaseinfo_alias[widx] = phaseinfo_hw;
6748 gt_iter = &(gt_iter[kBitsPerWordD2]);
6749 }
6750 } else {
6751 const uint16_t* gt_iter = R_CAST(const uint16_t*, gt_main);
6752 for (uint32_t widx = 0; ; ++widx) {
6753 if (widx >= word_ct_m1) {
6754 if (widx > word_ct_m1) {
6755 break;
6756 }
6757 loop_len = ModNz(sample_ct, kBitsPerWordD2);
6758 }
6759 const uintptr_t gq_dp_fail_word = genovec[widx];
6760 uintptr_t geno_word = 0;
6761 uint32_t patch_01_set_hw = 0;
6762 uint32_t patch_10_set_hw = 0;
6763 uint32_t phasepresent_hw = 0;
6764 uint32_t phaseinfo_hw = 0;
6765 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) {
6766 // may overread 2 bytes
6767 uint64_t raw_val;
6768 memcpy(&raw_val, gt_iter, 8);
6769 gt_iter = &(gt_iter[value_ct]);
6770 const uint64_t phaseless_val = raw_val & 0xfffffffefffeLLU;
6771 if ((phaseless_val == 0x800100020002LLU) || ((gq_dp_fail_word >> (2 * sample_idx_lowbits)) & 1)) {
6772 continue;
6773 }
6774 uintptr_t result;
6775 if ((phaseless_val & 0x800100000000LLU) != 0x800100000000LLU) {
6776 // triploid+ (or malformed)
6777 result = 3;
6778 } else {
6779 const uint32_t shifted_phaseless_val = S_CAST(uint32_t, phaseless_val) >> 1;
6780 // rest of this is identical to diploid case
6781 uint32_t first_allele_idx_p1 = shifted_phaseless_val & 0xffff;
6782 if (first_allele_idx_p1 > allele_ct) {
6783 // assume end-of-vector
6784 result = 3;
6785 } else {
6786 uint32_t second_allele_idx_p1 = shifted_phaseless_val >> 16;
6787 const uint32_t cur_bit = 1U << sample_idx_lowbits;
6788 if (second_allele_idx_p1 > allele_ct) {
6789 // haploid
6790 if (!first_allele_idx_p1) {
6791 result = 3;
6792 } else {
6793 const uint32_t first_allele_idx = first_allele_idx_p1 - 1;
6794 if (first_allele_idx < 2) {
6795 result = first_allele_idx * 2;
6796 } else {
6797 result = 2;
6798 patch_10_set_hw |= cur_bit;
6799 *patch_10_iter++ = first_allele_idx;
6800 *patch_10_iter++ = first_allele_idx;
6801 }
6802 }
6803 } else {
6804 // diploid
6805 if (second_allele_idx_p1 < first_allele_idx_p1) {
6806 const uint32_t uii = first_allele_idx_p1;
6807 first_allele_idx_p1 = second_allele_idx_p1;
6808 second_allele_idx_p1 = uii;
6809 phaseinfo_hw |= cur_bit;
6810 }
6811 if (!first_allele_idx_p1) {
6812 // missing or half-call
6813 if ((!second_allele_idx_p1) || (halfcall_mode == kVcfHalfCallMissing)) {
6814 result = 3;
6815 } else if (unlikely(halfcall_mode == kVcfHalfCallError)) {
6816 return kBcfParseHalfCallError;
6817 } else {
6818 const uint32_t second_allele_idx = second_allele_idx_p1 - 1;
6819 if (second_allele_idx < 2) {
6820 // kVcfHalfCallHaploid, kVcfHalfCallReference
6821 result = second_allele_idx << halfcall_mode;
6822 } else if (halfcall_mode == kVcfHalfCallReference) {
6823 result = 1;
6824 patch_01_set_hw |= cur_bit;
6825 *patch_01_iter++ = second_allele_idx;
6826 } else {
6827 result = 2;
6828 patch_10_set_hw |= cur_bit;
6829 *patch_10_iter++ = second_allele_idx;
6830 *patch_10_iter++ = second_allele_idx;
6831 }
6832 if ((raw_val & 0x10000) && (result == 1)) {
6833 phasepresent_hw |= cur_bit;
6834 }
6835 }
6836 } else {
6837 if ((raw_val & 0x10000) && (first_allele_idx_p1 != second_allele_idx_p1)) {
6838 phasepresent_hw |= cur_bit;
6839 }
6840 if (first_allele_idx_p1 == 1) {
6841 result = 1;
6842 if (second_allele_idx_p1 > 2) {
6843 patch_01_set_hw |= cur_bit;
6844 *patch_01_iter++ = second_allele_idx_p1 - 1;
6845 }
6846 } else {
6847 result = 2;
6848 if (second_allele_idx_p1 > 2) {
6849 patch_10_set_hw |= cur_bit;
6850 *patch_10_iter++ = first_allele_idx_p1 - 1;
6851 *patch_10_iter++ = second_allele_idx_p1 - 1;
6852 }
6853 }
6854 }
6855 }
6856 }
6857 }
6858 }
6859 genovec[widx] = geno_word | gq_dp_fail_word;
6860 patch_01_set_alias[widx] = patch_01_set_hw;
6861 patch_10_set_alias[widx] = patch_10_set_hw;
6862 phasepresent_alias[widx] = phasepresent_hw;
6863 phaseinfo_alias[widx] = phaseinfo_hw;
6864 }
6865 }
6866 } else {
6867 return (value_type == 3)? kBcfParseWideGt : kBcfParseMalformedGeneric;
6868 }
6869 *patch_01_ctp = patch_01_iter - patch_01_vals;
6870 *patch_10_ctp = S_CAST(uintptr_t, patch_10_iter - patch_10_vals) / 2;
6871 return kBcfParseOk;
6872 }
6873
6874 BcfParseErr BcfConvertPhasedBiallelicDosage(const BcfImportContext* bicp, const GparseReadBcfMetadata* metap, unsigned char* record_start, uintptr_t* __restrict genovec, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo, uintptr_t* __restrict dosage_present, uintptr_t* __restrict dphase_present, Dosage** dosage_main_iter_ptr, SDosage** dphase_delta_iter_ptr) {
6875 // See VcfConvertPhasedBiallelicDosageLine().
6876 const BcfImportBaseContext* bibcp = &(bicp->bibc);
6877 const uint32_t sample_ct = bibcp->sample_ct;
6878 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
6879 ZeroWArr(sample_ctl2, genovec);
6880 BcfParseErr bcf_parse_err = BcfApplyGqDpFilters(bibcp, metap, record_start, genovec);
6881 if (unlikely(bcf_parse_err != kBcfParseOk)) {
6882 return bcf_parse_err;
6883 }
6884 const unsigned char* hds_main = nullptr;
6885 uint32_t hds_value_ct = 0;
6886 if (metap->hds_vec_offset != UINT32_MAX) {
6887 hds_main = &(record_start[metap->hds_vec_offset * S_CAST(uintptr_t, kBytesPerVec)]);
6888 uint32_t hds_value_type;
6889 ScanBcfTypeAligned(&hds_main, &hds_value_type, &hds_value_ct);
6890 if (unlikely(hds_value_type != 5)) {
6891 return kBcfParseNonfloatDosage;
6892 }
6893 if (unlikely((hds_value_ct > 2) && bicp->bibc.error_on_polyploid)) {
6894 return kBcfParsePolyploidError;
6895 }
6896 }
6897 const float* dosage_main = nullptr;
6898 uint32_t dosage_value_ct = 0;
6899 if (metap->dosage_vec_offset != UINT32_MAX) {
6900 const unsigned char* dosage_main_raw = &(record_start[metap->dosage_vec_offset * S_CAST(uintptr_t, kBytesPerVec)]);
6901 uint32_t dosage_value_type;
6902 ScanBcfTypeAligned(&dosage_main_raw, &dosage_value_type, &dosage_value_ct);
6903 if (unlikely(dosage_value_type != 5)) {
6904 return kBcfParseNonfloatDosage;
6905 }
6906 dosage_main = R_CAST(const float*, dosage_main_raw);
6907 }
6908 const unsigned char* gt_main = nullptr;
6909 uint32_t gt_value_type = 0;
6910 uint32_t gt_value_ct = 0;
6911 if (metap->gt_vec_offset != UINT32_MAX) {
6912 gt_main = &(record_start[metap->gt_vec_offset * S_CAST(uintptr_t, kBytesPerVec)]);
6913 ScanBcfTypeAligned(&gt_main, &gt_value_type, &gt_value_ct);
6914 if (unlikely(gt_value_type > 1)) {
6915 return kBcfParseWideGt;
6916 }
6917 if (unlikely((gt_value_ct > 2) && bicp->bibc.error_on_polyploid)) {
6918 return kBcfParsePolyploidError;
6919 }
6920 }
6921
6922 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
6923 phasepresent[sample_ctl - 1] = 0;
6924 dosage_present[sample_ctl - 1] = 0;
6925 dphase_present[sample_ctl - 1] = 0;
6926 Halfword* phasepresent_alias = R_CAST(Halfword*, phasepresent);
6927 Halfword* phaseinfo_alias = R_CAST(Halfword*, phaseinfo);
6928 Halfword* dosage_present_alias = R_CAST(Halfword*, dosage_present);
6929 Halfword* dphase_present_alias = R_CAST(Halfword*, dphase_present);
6930 Dosage* dosage_main_iter = *dosage_main_iter_ptr;
6931 SDosage* dphase_delta_iter = *dphase_delta_iter_ptr;
6932 const unsigned char* biallelic_gt_lookup = bibcp->biallelic_gt_lookup;
6933 const uint32_t sample_ctl2_m1 = sample_ctl2 - 1;
6934 const uint32_t dosage_is_gp = bicp->dosage_is_gp;
6935 const uint32_t dosage_erase_halfdist = bicp->dosage_erase_halfdist;
6936 const uint32_t dphase_erase_halfdist = dosage_erase_halfdist + kDosage4th;
6937 const double import_dosage_certainty = bicp->import_dosage_certainty;
6938 uint32_t loop_len = kBitsPerWordD2;
6939 uint16_t gt_raw = 0;
6940 uint32_t is_haploid_or_0ploid = (gt_value_ct == 1);
6941 uintptr_t half_call_error_bit2 = 0;
6942 uint32_t sample_idx = 0;
6943 for (uint32_t widx = 0; ; ++widx) {
6944 if (widx >= sample_ctl2_m1) {
6945 if (widx > sample_ctl2_m1) {
6946 break;
6947 }
6948 loop_len = ModNz(sample_ct, kBitsPerWordD2);
6949 }
6950 const uint32_t sample_idx_stop = sample_idx + loop_len;
6951 uintptr_t gq_dp_fail_word = genovec[widx];
6952 uintptr_t genovec_word = 0;
6953 uint32_t phasepresent_hw = 0;
6954 uint32_t phaseinfo_hw = 0;
6955 uint32_t dosage_present_hw = 0;
6956 uint32_t dphase_present_hw = 0;
6957 for (; sample_idx != sample_idx_stop; ++sample_idx, gq_dp_fail_word >>= 2) {
6958 if (gq_dp_fail_word & 1) {
6959 continue;
6960 }
6961 if (gt_value_ct) {
6962 memcpy(&gt_raw, &(gt_main[sample_idx * gt_value_ct]), 2);
6963 if (gt_value_ct > 1) {
6964 is_haploid_or_0ploid = gt_raw >> 15;
6965 }
6966 }
6967 const uint32_t sample_idx_lowbits = sample_idx % kBitsPerWordD2;
6968 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
6969 DosageParseResult dpr = kDosageParseOk;
6970 uintptr_t cur_geno = 3;
6971 int32_t cur_dphase_delta = 0;
6972 uint32_t hds_valid = 0;
6973 uint32_t dosage_int;
6974 if (!ParseBcfBiallelicHds(dosage_main, hds_main, dosage_value_ct, hds_value_ct, sample_idx, is_haploid_or_0ploid, dosage_is_gp, import_dosage_certainty, &dpr, &dosage_int, &cur_dphase_delta, &hds_valid)) {
6975 if (hds_valid) {
6976 const uint32_t dphase_halfdist1 = DphaseHalfdist(dosage_int + cur_dphase_delta);
6977 const uint32_t dphase_halfdist2 = DphaseHalfdist(dosage_int - cur_dphase_delta);
6978 if ((dphase_halfdist1 < dphase_erase_halfdist) || (dphase_halfdist2 < dphase_erase_halfdist)) {
6979 // Usually no need to fill cur_geno here, since it'll get corrected
6980 // by --hard-call-threshold.
6981 if (cur_dphase_delta) {
6982 dphase_present_hw |= shifted_bit;
6983 *dphase_delta_iter++ = cur_dphase_delta;
6984 } else if (dosage_int == kDosageMid) {
6985 // quasi-bugfix (18 Jun 2023): if dosage_int == kDosageMid and
6986 // cur_dphase_delta == 0, we shouldn't save an explicit dosage at
6987 // all; this is just an ordinary unphased het.
6988 cur_geno = 1;
6989 goto BcfConvertPhasedBiallelicDosage_geno_done;
6990 }
6991 dosage_present_hw |= shifted_bit;
6992 *dosage_main_iter++ = dosage_int;
6993 } else {
6994 // Not saving dosage, since it's too close to an integer
6995 // (--dosage-erase-threshold). Just directly synthesize the
6996 // hardcall we need.
6997 cur_geno = (dosage_int + kDosage4th) / kDosageMid;
6998 if (cur_geno == 1) {
6999 // Since dphase_erase_halfdist >= 8193, dphase_halfdist1 and
7000 // dphase_halfdist2 are both in [0, 8191] or [24577, 32768], so
7001 // it's always appropraite to save hardcall-phase.
7002 phasepresent_hw |= shifted_bit;
7003 if (cur_dphase_delta > 0) {
7004 phaseinfo_hw |= shifted_bit;
7005 }
7006 }
7007 }
7008 goto BcfConvertPhasedBiallelicDosage_geno_done;
7009 }
7010 // defer handling of unphased dosage
7011 } else if (unlikely(!dpr)) {
7012 return kBcfParseInvalidDosage;
7013 } else if (dpr == kDosageParseForceMissing) {
7014 goto BcfConvertPhasedBiallelicDosage_geno_done;
7015 }
7016 if (gt_main) {
7017 if (is_haploid_or_0ploid) {
7018 // gt_first == 0 -> missing (cur_geno == 3)
7019 // gt_first == 2 -> hom-ref (cur_geno == 0)
7020 // gt_first == 4 -> hom-alt (cur_geno == 2)
7021 cur_geno = (gt_raw & 0xff) - 2;
7022 // deliberate underflow
7023 if (cur_geno > 3) {
7024 cur_geno = 3;
7025 }
7026 } else if ((gt_value_ct == 2) || (gt_main[sample_idx * gt_value_ct + 2] == 0x81)) {
7027 // diploid
7028 const uint32_t bit_8 = gt_raw & 0x100;
7029 uint32_t first_allele_idx_p1 = (gt_raw & 0xff) >> 1;
7030 if (first_allele_idx_p1 > 3) {
7031 first_allele_idx_p1 = 3;
7032 }
7033 uint32_t second_allele_idx_p1 = gt_raw >> 9;
7034 if (second_allele_idx_p1 > 3) {
7035 second_allele_idx_p1 = 3;
7036 }
7037 cur_geno = biallelic_gt_lookup[first_allele_idx_p1 + second_allele_idx_p1 * 4];
7038 half_call_error_bit2 |= cur_geno;
7039 if ((cur_geno == 1) && bit_8) {
7040 phasepresent_hw |= shifted_bit;
7041 phaseinfo_hw |= (second_allele_idx_p1 & 1) << sample_idx_lowbits;
7042 }
7043 }
7044 }
7045 if (!dpr) {
7046 // now actually handle the unphased dosage
7047 const uint32_t cur_halfdist = BiallelicDosageHalfdist(dosage_int);
7048 if (cur_halfdist < dosage_erase_halfdist) {
7049 // ok for cur_geno to be 'wrong' for now, since it'll get corrected
7050 // by --hard-call-threshold
7051 dosage_present_hw |= shifted_bit;
7052 *dosage_main_iter++ = dosage_int;
7053 } else {
7054 // Not saving dosage, since it's too close to an integer, except
7055 // possibly in the implicit-phased-dosage edge case.
7056 // If that integer actually conflicts with the hardcall, we must
7057 // override the hardcall.
7058 cur_geno = (dosage_int + kDosage4th) / kDosageMid;
7059 if (phasepresent_hw & shifted_bit) {
7060 if (cur_geno != 1) {
7061 // Hardcall-phase no longer applies.
7062 phasepresent_hw ^= shifted_bit;
7063 } else if (cur_halfdist * 2 < dphase_erase_halfdist) {
7064 // Implicit phased-dosage, e.g. 0|0.99. More stringent
7065 // dosage_erase_halfdist applies.
7066 dosage_present_hw |= shifted_bit;
7067 *dosage_main_iter++ = dosage_int;
7068 }
7069 }
7070 }
7071 }
7072 BcfConvertPhasedBiallelicDosage_geno_done:
7073 genovec_word |= cur_geno << (2 * sample_idx_lowbits);
7074 }
7075 genovec[widx] = genovec_word | gq_dp_fail_word;
7076 phasepresent_alias[widx] = phasepresent_hw;
7077 phaseinfo_alias[widx] = phaseinfo_hw;
7078 dosage_present_alias[widx] = dosage_present_hw;
7079 dphase_present_alias[widx] = dphase_present_hw;
7080 }
7081 if (unlikely(half_call_error_bit2 & 4)) {
7082 return kBcfParseHalfCallError;
7083 }
7084 *dosage_main_iter_ptr = dosage_main_iter;
7085 *dphase_delta_iter_ptr = dphase_delta_iter;
7086 return kBcfParseOk;
7087 }
7088
7089 // 1: int8
7090 // 2: int16
7091 // 3: int32
7092 // 5: float
7093 // 7: char
7094 static const unsigned char kBcfBytesPerElem[16] = {0, 1, 2, 4, 0, 4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0};
7095
7096 typedef struct BcfGenoToPgenCtxStruct {
7097 BcfImportContext bic;
7098 uint32_t hard_call_halfdist;
7099
7100 unsigned char** thread_wkspaces;
7101
7102 uint32_t* thread_bidxs[2];
7103 GparseRecord* gparse[2];
7104 const uintptr_t* block_allele_idx_offsets[2];
7105
7106 // PglErr set by main thread
7107 BcfParseErr* bcf_parse_errs;
7108 uintptr_t* err_vrec_idxs;
7109 uint32_t parse_failed;
7110 } BcfGenoToPgenCtx;
7111
7112 THREAD_FUNC_DECL BcfGenoToPgenThread(void* raw_arg) {
7113 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
7114 const uintptr_t tidx = arg->tidx;
7115 BcfGenoToPgenCtx* ctx = S_CAST(BcfGenoToPgenCtx*, arg->sharedp->context);
7116
7117 const BcfImportContext* bicp = &(ctx->bic);
7118 const BcfImportBaseContext* bibcp = &(bicp->bibc);
7119 const uint32_t sample_ct = bibcp->sample_ct;
7120 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
7121 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
7122 const uint32_t hard_call_halfdist = ctx->hard_call_halfdist;
7123 unsigned char* thread_wkspace = ctx->thread_wkspaces[tidx];
7124 uintptr_t* patch_01_set = nullptr;
7125 AlleleCode* patch_01_vals = nullptr;
7126 uintptr_t* patch_10_set = nullptr;
7127 AlleleCode* patch_10_vals = nullptr;
7128 uintptr_t* phasepresent = nullptr;
7129 uintptr_t* phaseinfo = nullptr;
7130 uintptr_t* dosage_present = nullptr;
7131 Dosage* dosage_main = nullptr;
7132 uintptr_t* dphase_present = nullptr;
7133 SDosage* dphase_delta = nullptr;
7134 SDosage* tmp_dphase_delta = R_CAST(SDosage*, thread_wkspace);
7135 thread_wkspace = &(thread_wkspace[RoundUpPow2(sample_ct * sizeof(SDosage), kBytesPerVec)]);
7136 uintptr_t* write_patch_01_set = nullptr;
7137 AlleleCode* write_patch_01_vals = nullptr;
7138 uintptr_t* write_patch_10_set = nullptr;
7139 AlleleCode* write_patch_10_vals = nullptr;
7140 uintptr_t* write_phasepresent = nullptr;
7141 uintptr_t* write_phaseinfo = nullptr;
7142 uintptr_t* write_dosage_present = nullptr;
7143 Dosage* write_dosage_main = nullptr;
7144 uintptr_t* write_dphase_present = nullptr;
7145 SDosage* write_dphase_delta = nullptr;
7146 uint32_t cur_allele_ct = 2;
7147 uint32_t parity = 0;
7148 BcfParseErr bcf_parse_err = kBcfParseOk;
7149 uintptr_t vrec_idx = 0;
7150 do {
7151 const uintptr_t* block_allele_idx_offsets = ctx->block_allele_idx_offsets[parity];
7152 const uint32_t bidx_end = ctx->thread_bidxs[parity][tidx + 1];
7153 GparseRecord* cur_gparse = ctx->gparse[parity];
7154
7155 for (uint32_t bidx = ctx->thread_bidxs[parity][tidx]; bidx != bidx_end; ++bidx) {
7156 GparseRecord* grp = &(cur_gparse[bidx]);
7157 uint32_t patch_01_ct = 0;
7158 uint32_t patch_10_ct = 0;
7159 uint32_t cur_phasepresent_exists = 0;
7160 uint32_t dosage_ct = 0;
7161 uint32_t dphase_ct = 0;
7162 unsigned char* record_start = grp->record_start;
7163 GparseFlags gparse_flags = grp->flags;
7164 if (gparse_flags == kfGparseNull) {
7165 SetAllBits(2 * sample_ct, R_CAST(uintptr_t*, record_start));
7166 } else {
7167 if (block_allele_idx_offsets) {
7168 cur_allele_ct = block_allele_idx_offsets[bidx + 1] - block_allele_idx_offsets[bidx];
7169 }
7170 uintptr_t* genovec = GparseGetPointers(thread_wkspace, sample_ct, cur_allele_ct, gparse_flags, &patch_01_set, &patch_01_vals, &patch_10_set, &patch_10_vals, &phasepresent, &phaseinfo, &dosage_present, &dosage_main, &dphase_present, &dphase_delta);
7171 uintptr_t* write_genovec = GparseGetPointers(record_start, sample_ct, cur_allele_ct, gparse_flags, &write_patch_01_set, &write_patch_01_vals, &write_patch_10_set, &write_patch_10_vals, &write_phasepresent, &write_phaseinfo, &write_dosage_present, &write_dosage_main, &write_dphase_present, &write_dphase_delta);
7172 const GparseReadBcfMetadata* metap = &(grp->metadata.read_bcf);
7173 if ((metap->hds_vec_offset == UINT32_MAX) && (metap->dosage_vec_offset == UINT32_MAX)) {
7174 if (!(gparse_flags & kfGparseHphase)) {
7175 if (cur_allele_ct == 2) {
7176 bcf_parse_err = BcfConvertUnphasedBiallelic(bibcp, metap, record_start, genovec);
7177 } else {
7178 bcf_parse_err = BcfConvertUnphasedMultiallelic(bibcp, metap, record_start, cur_allele_ct, &patch_01_ct, &patch_10_ct, genovec, patch_01_set, patch_01_vals, patch_10_set, patch_10_vals);
7179 }
7180 } else {
7181 if (cur_allele_ct == 2) {
7182 bcf_parse_err = BcfConvertPhasedBiallelic(bibcp, metap, record_start, genovec, phasepresent, phaseinfo);
7183 } else {
7184 bcf_parse_err = BcfConvertPhasedMultiallelic(bibcp, metap, record_start, cur_allele_ct, &patch_01_ct, &patch_10_ct, genovec, patch_01_set, patch_01_vals, patch_10_set, patch_10_vals, phasepresent, phaseinfo);
7185 }
7186 cur_phasepresent_exists = !AllWordsAreZero(phasepresent, sample_ctl);
7187 }
7188 if (unlikely(bcf_parse_err)) {
7189 vrec_idx = metap->rec_idx;
7190 goto BcfGenoToPgenThread_malformed;
7191 }
7192 } else {
7193 Dosage* dosage_main_iter = dosage_main;
7194 SDosage* dphase_delta_iter = dphase_delta;
7195 if (cur_allele_ct == 2) {
7196 bcf_parse_err = BcfConvertPhasedBiallelicDosage(bicp, metap, record_start, genovec, phasepresent, phaseinfo, dosage_present, dphase_present, &dosage_main_iter, &dphase_delta_iter);
7197 } else {
7198 // multiallelic dosage: shouldn't be possible to get here yet
7199 exit(S_CAST(int32_t, kPglRetInternalError));
7200 }
7201 if (unlikely(bcf_parse_err)) {
7202 vrec_idx = metap->rec_idx;
7203 goto BcfGenoToPgenThread_malformed;
7204 }
7205 dosage_ct = dosage_main_iter - dosage_main;
7206 if (dosage_ct) {
7207 dphase_ct = ApplyHardCallThreshPhased(dosage_present, dosage_main, dosage_ct, hard_call_halfdist, genovec, phasepresent, phaseinfo, dphase_present, dphase_delta, tmp_dphase_delta);
7208 memcpy(write_dosage_present, dosage_present, sample_ctl * sizeof(intptr_t));
7209 memcpy(write_dosage_main, dosage_main, dosage_ct * sizeof(Dosage));
7210 if (dphase_ct) {
7211 memcpy(write_dphase_present, dphase_present, sample_ctl * sizeof(intptr_t));
7212 memcpy(write_dphase_delta, dphase_delta, dphase_ct * sizeof(SDosage));
7213 }
7214 }
7215 cur_phasepresent_exists = !AllWordsAreZero(phasepresent, sample_ctl);
7216 }
7217 memcpy(write_genovec, genovec, sample_ctl2 * sizeof(intptr_t));
7218 if (patch_01_ct) {
7219 memcpy(write_patch_01_set, patch_01_set, sample_ctl * sizeof(intptr_t));
7220 memcpy(write_patch_01_vals, patch_01_vals, patch_01_ct * sizeof(AlleleCode));
7221 }
7222 if (patch_10_ct) {
7223 memcpy(write_patch_10_set, patch_10_set, sample_ctl * sizeof(intptr_t));
7224 memcpy(write_patch_10_vals, patch_10_vals, patch_10_ct * sizeof(AlleleCode) * 2);
7225 }
7226 if (cur_phasepresent_exists || dphase_ct) {
7227 memcpy(write_phasepresent, phasepresent, sample_ctl * sizeof(intptr_t));
7228 memcpy(write_phaseinfo, phaseinfo, sample_ctl * sizeof(intptr_t));
7229 }
7230 }
7231
7232 grp->metadata.write.patch_01_ct = patch_01_ct;
7233 grp->metadata.write.patch_10_ct = patch_10_ct;
7234 grp->metadata.write.phasepresent_exists = cur_phasepresent_exists;
7235 grp->metadata.write.dosage_ct = dosage_ct;
7236 grp->metadata.write.multiallelic_dosage_ct = 0;
7237 grp->metadata.write.dphase_ct = dphase_ct;
7238 grp->metadata.write.multiallelic_dphase_ct = 0;
7239 }
7240 while (0) {
7241 BcfGenoToPgenThread_malformed:
7242 ctx->bcf_parse_errs[tidx] = bcf_parse_err;
7243 ctx->err_vrec_idxs[tidx] = vrec_idx;
7244 ctx->parse_failed = 1;
7245 break;
7246 }
7247 parity = 1 - parity;
7248 } while (!THREAD_BLOCK_FINISH(arg));
7249 THREAD_RETURN;
7250 }
7251
7252 // pgen_generated and psam_generated assumed to be initialized to 1.
7253 PglErr BcfToPgen(const char* bcfname, const char* preexisting_psamname, const char* const_fid, const char* dosage_import_field, MiscFlags misc_flags, ImportFlags import_flags, uint32_t no_samples_ok, uint32_t is_update_or_impute_sex, uint32_t is_splitpar, uint32_t hard_call_thresh, uint32_t dosage_erase_thresh, double import_dosage_certainty, char id_delim, char idspace_to, int32_t vcf_min_gq, int32_t vcf_min_dp, int32_t vcf_max_dp, VcfHalfCall halfcall_mode, FamCol fam_cols, uint32_t import_max_allele_ct, uint32_t max_thread_ct, char* outname, char* outname_end, ChrInfo* cip, uint32_t* pgen_generated_ptr, uint32_t* psam_generated_ptr) {
7254 // Yes, lots of this is copied-and-pasted from VcfToPgen(), but there are
7255 // enough differences that I don't think trying to handle them with the same
7256 // function is wise.
7257
7258 // Possible todo: make this take proper advantage of an index file when a
7259 // chromosome filter has been specified. (This requires an upgrade to
7260 // include/plink2_bgzf.)
7261 unsigned char* bigstack_mark = g_bigstack_base;
7262 unsigned char* bigstack_end_mark = g_bigstack_end;
7263 FILE* bcffile = nullptr;
7264 const char* bgzf_errmsg = nullptr;
7265 char* pvar_cswritep = nullptr;
7266 uintptr_t vrec_idx = 0;
7267 const uint32_t half_call_explicit_error = (halfcall_mode == kVcfHalfCallError);
7268 PglErr reterr = kPglRetSuccess;
7269 BcfParseErr bcf_parse_err = kBcfParseOk;
7270 CompressStreamState pvar_css;
7271 PreinitCstream(&pvar_css);
7272 ThreadGroup tg;
7273 PreinitThreads(&tg);
7274 BcfGenoToPgenCtx ctx;
7275 BgzfRawMtDecompressStream bgzf;
7276 PreinitBgzfRawMtStream(&bgzf);
7277 STPgenWriter spgw;
7278 PreinitSpgw(&spgw);
7279 {
7280 // See TextFileOpenInternal().
7281 bcffile = fopen(bcfname, FOPEN_RB);
7282 if (unlikely(!bcffile)) {
7283 const uint32_t slen = strlen(bcfname);
7284 if (!StrEndsWith(bcfname, ".bcf", slen)) {
7285 logerrprintfww("Error: Failed to open %s : %s. (--bcf expects a complete filename; did you forget '.bcf' at the end?)\n", bcfname, strerror(errno));
7286 } else {
7287 logerrprintfww(kErrprintfFopen, bcfname, strerror(errno));
7288 }
7289 goto BcfToPgen_ret_OPEN_FAIL;
7290 }
7291 const uint32_t decompress_thread_ct = ClipU32(max_thread_ct - 1, 1, 4);
7292 uint32_t header_size;
7293 {
7294 char bgzf_header[16];
7295 uint32_t nbytes = fread_unlocked(bgzf_header, 1, 16, bcffile);
7296 if (unlikely(ferror_unlocked(bcffile))) {
7297 reterr = kPglRetReadFail;
7298 goto BcfToPgen_ret_BGZF_FAIL;
7299 }
7300 if (unlikely((nbytes != 16) || (!IsBgzfHeader(bgzf_header)))) {
7301 snprintf(g_logbuf, kLogbufSize, "Error: %s is not a BCF2 file.\n", bcfname);
7302 goto BcfToPgen_ret_MALFORMED_INPUT_WW;
7303 }
7304 reterr = BgzfRawMtStreamInit(bgzf_header, decompress_thread_ct, bcffile, nullptr, &bgzf, &bgzf_errmsg);
7305 if (unlikely(reterr)) {
7306 goto BcfToPgen_ret_BGZF_FAIL;
7307 }
7308 unsigned char prefix_buf[9];
7309 unsigned char* prefix_end = &(prefix_buf[9]);
7310 unsigned char* dummy = prefix_buf;
7311 reterr = BgzfRawMtStreamRead(prefix_end, &bgzf, &dummy, &bgzf_errmsg);
7312 if (unlikely(reterr)) {
7313 goto BcfToPgen_ret_BGZF_FAIL;
7314 }
7315 if (unlikely((dummy != prefix_end) || (!memequal_sk(prefix_buf, "BCF")))) {
7316 snprintf(g_logbuf, kLogbufSize, "Error: %s is not a BCF2 file.\n", bcfname);
7317 goto BcfToPgen_ret_MALFORMED_INPUT_WW;
7318 }
7319 if (unlikely(prefix_buf[3] != 2)) {
7320 if (prefix_buf[3] == 4) {
7321 snprintf(g_logbuf, kLogbufSize, "Error: %s appears to be a BCF1 file; --bcf only supports BCF2. Use 'bcftools view' to convert it to a PLINK-readable BCF.\n", bcfname);
7322 } else {
7323 snprintf(g_logbuf, kLogbufSize, "Error: %s is not a BCF2 file.\n", bcfname);
7324 }
7325 goto BcfToPgen_ret_MALFORMED_INPUT_WW;
7326 }
7327 if (unlikely(prefix_buf[4] > 2)) {
7328 snprintf(g_logbuf, kLogbufSize, "Error: %s appears to be formatted as BCFv2.%u; this " PROG_NAME_STR " build only supports v2.0-2.2. You may need to obtain an updated version of PLINK.\n", bcfname, prefix_buf[4]);
7329 goto BcfToPgen_ret_MALFORMED_INPUT_WW;
7330 }
7331 memcpy(&header_size, &(prefix_buf[5]), sizeof(int32_t));
7332 if (unlikely(header_size < 59)) {
7333 goto BcfToPgen_ret_MALFORMED_INPUT_GENERIC;
7334 }
7335 }
7336 // can't be const due to how --vcf-idspace-to is implemented
7337 // we could free this before the main conversion loop, but unlikely to be
7338 // more than a few MB so I won't bother
7339 // + 9 to simplify second pass
7340 char* vcf_header;
7341 {
7342 char* vcf_header_alloc;
7343 if (unlikely(bigstack_alloc_c(header_size + (9 * k1LU), &vcf_header_alloc))) {
7344 goto BcfToPgen_ret_NOMEM;
7345 }
7346 vcf_header = &(vcf_header_alloc[9]);
7347 unsigned char* header_load_iter = R_CAST(unsigned char*, vcf_header);
7348 unsigned char* header_load_end = &(header_load_iter[header_size]);
7349 reterr = BgzfRawMtStreamRead(header_load_end, &bgzf, &header_load_iter, &bgzf_errmsg);
7350 if (unlikely(reterr)) {
7351 goto BcfToPgen_ret_BGZF_FAIL;
7352 }
7353 if (unlikely(header_load_iter != header_load_end)) {
7354 goto BcfToPgen_ret_MALFORMED_INPUT_GENERIC;
7355 }
7356 }
7357 if (unlikely(!strequal_k_unsafe(&(vcf_header[header_size - 2]), "\n"))) {
7358 goto BcfToPgen_ret_MALFORMED_TEXT_HEADER;
7359 }
7360 char* vcf_header_end = &(vcf_header[header_size - 1]);
7361 const uint32_t prohibit_extra_chr = (misc_flags / kfMiscProhibitExtraChr) & 1;
7362 uint32_t dosage_import_field_slen = 0;
7363
7364 uint32_t format_hds_search = 0;
7365
7366 uint32_t unforced_gp = 0;
7367 if (dosage_import_field) {
7368 dosage_import_field_slen = strlen(dosage_import_field);
7369 ctx.bic.dosage_is_gp = 0;
7370 if (strequal_k(dosage_import_field, "HDS", dosage_import_field_slen)) {
7371 format_hds_search = 1;
7372 // special case: search for DS and HDS
7373 dosage_import_field = &(dosage_import_field[1]);
7374 dosage_import_field_slen = 2;
7375 } else if (strequal_k(dosage_import_field, "GP-force", dosage_import_field_slen)) {
7376 dosage_import_field = kGpText;
7377 dosage_import_field_slen = 2;
7378 ctx.bic.dosage_is_gp = 1;
7379 } else if (strequal_k(dosage_import_field, "GP", dosage_import_field_slen)) {
7380 unforced_gp = (import_dosage_certainty == 0.0);
7381 ctx.bic.dosage_is_gp = 1;
7382 }
7383 }
7384
7385 ctx.bic.bibc.qual_mins[0] = vcf_min_gq;
7386 ctx.bic.bibc.qual_mins[1] = (vcf_min_dp == -1)? 0 : vcf_min_dp;
7387 ctx.bic.bibc.qual_maxs[0] = 0x7fffffff;
7388 ctx.bic.bibc.qual_maxs[1] = vcf_max_dp;
7389 // sample_ct set later
7390 if (halfcall_mode == kVcfHalfCallDefault) {
7391 halfcall_mode = kVcfHalfCallError;
7392 }
7393 ctx.bic.bibc.halfcall_mode = halfcall_mode;
7394 ctx.bic.bibc.error_on_polyploid = !(import_flags & kfImportPolyploidMissing);
7395 // Construct main biallelic GT-parsing lookup table.
7396 // Low 2 bits of index = first_allele_idx_p1 (or 3 for END_OF_VECTOR),
7397 // high 2 bits = second_allele_idx_p1.
7398 // Table value is 2-bit genotype value, or 4 for half-call error.
7399 {
7400 unsigned char* biallelic_gt_lookup = ctx.bic.bibc.biallelic_gt_lookup;
7401 biallelic_gt_lookup[0] = 3;
7402 biallelic_gt_lookup[1] = 4; // half-call
7403 biallelic_gt_lookup[2] = 4;
7404 biallelic_gt_lookup[3] = 3;
7405
7406 biallelic_gt_lookup[5] = 0;
7407 biallelic_gt_lookup[6] = 1;
7408 // ignore second value if first value is end-of-vector
7409 biallelic_gt_lookup[7] = 3;
7410
7411 biallelic_gt_lookup[10] = 2;
7412 biallelic_gt_lookup[11] = 3;
7413
7414 biallelic_gt_lookup[12] = 3;
7415 biallelic_gt_lookup[13] = 0;
7416 biallelic_gt_lookup[14] = 2;
7417 biallelic_gt_lookup[15] = 3;
7418
7419 if (halfcall_mode == kVcfHalfCallReference) {
7420 biallelic_gt_lookup[1] = 0;
7421 biallelic_gt_lookup[2] = 1;
7422 } else if (halfcall_mode == kVcfHalfCallHaploid) {
7423 biallelic_gt_lookup[1] = 0;
7424 biallelic_gt_lookup[2] = 2;
7425 } else if (halfcall_mode == kVcfHalfCallMissing) {
7426 biallelic_gt_lookup[1] = 3;
7427 biallelic_gt_lookup[2] = 3;
7428 }
7429
7430 biallelic_gt_lookup[4] = biallelic_gt_lookup[1];
7431 biallelic_gt_lookup[8] = biallelic_gt_lookup[2];
7432 biallelic_gt_lookup[9] = biallelic_gt_lookup[6];
7433 #ifdef USE_AVX2
7434 memcpy(&(biallelic_gt_lookup[16]), biallelic_gt_lookup, 16);
7435 #endif
7436 }
7437
7438 // always positive
7439 ctx.bic.dosage_erase_halfdist = kDosage4th - dosage_erase_thresh;
7440
7441 ctx.bic.import_dosage_certainty = import_dosage_certainty;
7442
7443 // Scan the text header block.
7444 // We perform the same validation as --vcf. In addition, we need to
7445 // construct the contig and generic-string dictionaries; the latter may
7446 // require awareness of IDX keys.
7447 // (There is also a comment in the specification about explicitly
7448 // specifying a dictionary with a ##dictionary line, but AFAICT that is
7449 // left over from early brainstorming, is not consistent with the rest of
7450 // the design, and is not supported by bcftools so I assume it's a spec
7451 // error.)
7452 // hrec_add_idx() in htslib's vcf.c always puts IDX at the end of the
7453 // header line, so I'll be lazy and print a not-yet-supported error message
7454 // if it's positioned elsewhere for now.
7455 uint32_t chrset_exists = 0;
7456 uint32_t contig_string_idx_end = 0;
7457 uint32_t fif_string_idx_end = 1; // fif = filter, info, format; initialized with FILTER/PASS
7458 uint32_t explicit_idx_keys = 2; // 2 = unknown status
7459 uint32_t header_line_idx = 1; // uint32 ok since uncompressed size < 2^32
7460 char* line_iter = vcf_header;
7461 for (; ; ++header_line_idx) {
7462 if (unlikely(line_iter == vcf_header_end)) {
7463 logerrputs("Error: No #CHROM header line in BCF text header block.\n");
7464 goto BcfToPgen_ret_MALFORMED_INPUT;
7465 }
7466 if (unlikely(*line_iter != '#')) {
7467 snprintf(g_logbuf, kLogbufSize, "Error: Line %u in BCF text header block does not start with '#'.\n", header_line_idx);
7468 goto BcfToPgen_ret_MALFORMED_INPUT_WW;
7469 }
7470 if (line_iter[1] != '#') {
7471 break;
7472 }
7473 char* line_main = &(line_iter[2]);
7474 char* line_end = AdvPastDelim(line_main, '\n');
7475 line_iter = line_end;
7476 // Recognized header lines:
7477 // ##fileformat: discard (regenerate; todo: conditionally error out)
7478 // ##fileDate: discard (regenerate)
7479 // ##source: discard (regenerate)
7480 // ##contig: ID added to contig dictionary, conditionally keep
7481 // ##FILTER: ID added to dictionary, otherwise passed through unchanged
7482 // ##INFO: note presence of INFO/PR, note presence of at least one non-PR
7483 // field, keep data (though, if INFO/PR is the *only* field,
7484 // omit it from the .pvar for consistency with --make-pgen
7485 // default); ID added to dictionary
7486 // update (8 Sep 2017): nonflag INFO/PR is noted, and not treated
7487 // specially unless provisional-reference INFO/PR output would
7488 // conflict with it
7489 // ##FORMAT: note presence of FORMAT/GT and FORMAT/GP, discard
7490 // (regenerate); ID added to dictionary
7491 // ##chrSet: if recognized, perform consistency check and/or update
7492 // chr_info
7493 //
7494 // Everything else (##reference, etc.) is passed through
7495 // unchanged.
7496 //
7497 // Because of how ##contig is handled (we only keep the lines which
7498 // correspond to chromosomes/contigs actually present in the BCF, and not
7499 // filtered out), we wait until the second pass to write the .pvar.
7500 if (StrStartsWithUnsafe(line_main, "chrSet=<")) {
7501 if (unlikely(chrset_exists)) {
7502 logerrputs("Error: Multiple ##chrSet header lines in BCF text header block.\n");
7503 goto BcfToPgen_ret_MALFORMED_INPUT;
7504 }
7505 chrset_exists = 1;
7506 // .pvar loader will print a warning if necessary
7507 reterr = ReadChrsetHeaderLine(&(line_main[8]), "--bcf file", misc_flags, header_line_idx, cip);
7508 if (unlikely(reterr)) {
7509 goto BcfToPgen_ret_1;
7510 }
7511 continue;
7512 }
7513 const uint32_t is_contig_line = StrStartsWithUnsafe(line_main, "contig=<");
7514 const uint32_t is_filter_line = StrStartsWithUnsafe(line_main, "FILTER=<");
7515 const uint32_t is_info_line = StrStartsWithUnsafe(line_main, "INFO=<");
7516 const uint32_t is_format_line = StrStartsWithUnsafe(line_main, "FORMAT=<");
7517 if (!(is_contig_line || is_filter_line || is_info_line || is_format_line)) {
7518 continue;
7519 }
7520 char* line_last_iter = &(line_end[-2]);
7521 // tolerate trailing spaces, not just \r
7522 while (ctou32(*line_last_iter) <= 32) {
7523 --line_last_iter;
7524 }
7525 if (unlikely(*line_last_iter != '>')) {
7526 snprintf(g_logbuf, kLogbufSize, "Error: Line %u in BCF text header block is malformed.\n", header_line_idx);
7527 goto BcfToPgen_ret_MALFORMED_INPUT_2;
7528 }
7529 --line_last_iter;
7530 // Assuming for now that the IDX key is at the end when present, it's
7531 // present iff:
7532 // - Last character inside <> is a digit.
7533 // - Last nondigit characters inside <> are ",IDX=".
7534 uint32_t cur_explicit_idx_key = 0;
7535 if (IsDigit(*line_last_iter)) {
7536 do {
7537 --line_last_iter;
7538 } while (IsDigit(*line_last_iter));
7539 cur_explicit_idx_key = StrStartsWithUnsafe(&(line_last_iter[-4]), ",IDX=");
7540 }
7541 // Points to leading '<' character.
7542 char* hkvline_iter = &(line_main[7 - 2 * is_info_line]);
7543
7544 if (explicit_idx_keys == 2) {
7545 explicit_idx_keys = cur_explicit_idx_key;
7546 if (!cur_explicit_idx_key) {
7547 // The BCF specification does not require IDX= to be at the end of
7548 // the line, but it does require it to be present on all
7549 // contig/FILTER/INFO/FORMAT lines if it's present on any.
7550 // Thus, if a conforming writer puts IDX= in the middle of any lines,
7551 // we'll detect that either here, or in the next cur_explicit_idx_key
7552 // != explicit_idx_keys check.
7553 reterr = BcfHeaderLineIdxCheck(hkvline_iter, header_line_idx);
7554 if (unlikely(reterr)) {
7555 goto BcfToPgen_ret_1;
7556 }
7557 }
7558 } else {
7559 if (unlikely(cur_explicit_idx_key != explicit_idx_keys)) {
7560 reterr = BcfHeaderLineIdxCheck(hkvline_iter, header_line_idx);
7561 if (reterr != kPglRetSuccess) {
7562 goto BcfToPgen_ret_1;
7563 }
7564 logerrputs("Error: Some contig/FILTER/INFO/FORMAT line(s) in the BCF text header block have\nIDX keys, and others don't; this is not permitted by the specification.\n");
7565 goto BcfToPgen_ret_MALFORMED_INPUT;
7566 }
7567 }
7568 // Now points past leading '<' character.
7569 ++hkvline_iter;
7570
7571 char* id_ptr;
7572 uint32_t id_slen;
7573 if (unlikely(HkvlineId(&hkvline_iter, &id_ptr, &id_slen))) {
7574 snprintf(g_logbuf, kLogbufSize, "Error: Line %u in BCF text header block is malformed.\n", header_line_idx);
7575 goto BcfToPgen_ret_MALFORMED_INPUT_2;
7576 }
7577 // Special case: FILTER/PASS IDX=0 line is implicit, we must be
7578 // indifferent to whether it's actually present. (Though when it is
7579 // present, it's subject to the same IDX= always/never-present rule as
7580 // the other header lines, which is why we don't perform this check
7581 // earlier.)
7582 if (is_filter_line && strequal_k(id_ptr, "PASS", id_slen)) {
7583 continue;
7584 }
7585 if (!cur_explicit_idx_key) {
7586 if (is_contig_line) {
7587 ++contig_string_idx_end;
7588 } else {
7589 ++fif_string_idx_end;
7590 }
7591 } else {
7592 uint32_t val;
7593 if (unlikely(ScanUintDefcap(&(line_last_iter[1]), &val))) {
7594 snprintf(g_logbuf, kLogbufSize, "Error: Invalid IDX= value on line %u of BCF text header block.\n", header_line_idx);
7595 goto BcfToPgen_ret_MALFORMED_INPUT_2;
7596 }
7597 if (is_contig_line) {
7598 if (val >= contig_string_idx_end) {
7599 contig_string_idx_end = val + 1;
7600 }
7601 } else {
7602 // Easier to check for duplicates on the second pass.
7603 if (val >= fif_string_idx_end) {
7604 fif_string_idx_end = val + 1;
7605 }
7606 }
7607 }
7608 }
7609
7610 FinalizeChrset(misc_flags, cip);
7611 // don't call FinalizeChrInfo here, since this may be followed by --pmerge,
7612 // etc.
7613
7614 if (unlikely(!StrStartsWithUnsafe(line_iter, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO"))) {
7615 snprintf(g_logbuf, kLogbufSize, "Error: Header line %u of BCF text header block does not have expected field sequence after #CHROM.\n", header_line_idx);
7616 goto BcfToPgen_ret_MALFORMED_INPUT_WW;
7617 }
7618 uint32_t sample_ct = 0;
7619 {
7620 char* linebuf_iter = &(line_iter[strlen("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO")]);
7621 if (StrStartsWithUnsafe(linebuf_iter, "\tFORMAT\t")) {
7622 reterr = VcfSampleLine(preexisting_psamname, const_fid, misc_flags, import_flags, fam_cols, id_delim, idspace_to, 'b', &(linebuf_iter[strlen("\tFORMAT\t")]), outname, outname_end, &sample_ct);
7623 if (unlikely(reterr)) {
7624 goto BcfToPgen_ret_1;
7625 }
7626 }
7627 }
7628 if (unlikely((!sample_ct) && (!no_samples_ok))) {
7629 logerrputs("Error: No samples in BCF text header block. (This is only permitted when you\nhaven't specified another operation which requires genotype or sample\ninformation.)\n");
7630 goto BcfToPgen_ret_DEGENERATE_DATA;
7631 }
7632 if (unlikely(sample_ct >= (1 << 24))) {
7633 snprintf(g_logbuf, kLogbufSize, "Error: BCF text header block has %u sample IDs, which is larger than the BCF limit of 2^24 - 1.\n", sample_ct);
7634 goto BcfToPgen_ret_MALFORMED_INPUT_WW;
7635 }
7636 ctx.bic.bibc.sample_ct = sample_ct;
7637 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
7638
7639 // Rescan header to save FILTER/INFO/FORMAT and contig ID dictionaries.
7640 // (We could also print a warning when an INFO key type declaration is
7641 // inconsistent with any variant entry, but that's not essential for
7642 // decoding; let's get this working first.)
7643 uintptr_t* bcf_contig_keep;
7644 const char** contig_names;
7645 uint32_t* contig_slens;
7646 const char** contig_out_names = nullptr; // spurious g++ 4.8 warning
7647 uint32_t* contig_out_slens = nullptr;
7648 char* contig_out_buf;
7649 const char** fif_strings;
7650 uint32_t* fif_slens;
7651 uintptr_t* bcf_contig_seen;
7652 uintptr_t* sample_nypbuf = nullptr;
7653 if (unlikely(bigstack_calloc_w(BitCtToWordCt(contig_string_idx_end), &bcf_contig_keep) ||
7654 bigstack_calloc_kcp(contig_string_idx_end, &contig_names) ||
7655 bigstack_calloc_u32(contig_string_idx_end, &contig_slens) ||
7656 bigstack_alloc_kcp(contig_string_idx_end, &contig_out_names) ||
7657 bigstack_alloc_u32(contig_string_idx_end, &contig_out_slens) ||
7658 // no chrtoa() result is longer than (3 + kMaxChrTextnumSlen)
7659 // characters long
7660 bigstack_alloc_c((kMaxChrTextnum + 1 + kChrOffsetCt) * (3 + kMaxChrTextnumSlen), &contig_out_buf) ||
7661 bigstack_calloc_kcp(fif_string_idx_end, &fif_strings) ||
7662 bigstack_calloc_u32(fif_string_idx_end, &fif_slens) ||
7663 bigstack_calloc_w(BitCtToWordCt(contig_string_idx_end), &bcf_contig_seen) ||
7664 bigstack_alloc_w(sample_ctl2, &sample_nypbuf))) {
7665 goto BcfToPgen_ret_NOMEM;
7666 }
7667 const uint32_t header_line_ct = header_line_idx;
7668 // sidx = string index
7669 uint32_t gt_sidx = 0; // replaces format_gt_exists
7670 uint32_t gq_sidx = 0; // replaces format_gq_relevant
7671 uint32_t dp_sidx = 0; // replaces format_dp_relevant
7672 uint32_t dosage_sidx = 0; // replaces format_dosage_relevant
7673 uint32_t hds_sidx = 0; // replaces later uses of format_hds_search
7674
7675 // replaces info_pr_exists... except that UINT32_MAX is the not-present
7676 // value, just in case there's an INFO/PASS field for some reason.
7677 uint32_t pr_sidx = UINT32_MAX;
7678
7679 uint32_t info_pr_nonflag_exists = 0;
7680 uint32_t info_nonpr_exists = 0;
7681
7682 // we don't want to clutter the second pass with too many instances of
7683 // fwrite_ck(), so we compute FILTER-column, INFO-column and allele length
7684 // bounds, and then size the write buffer accordingly.
7685 uint32_t other_slen_ubound = kMaxFloatGSlen; // QUAL, alleles, etc.
7686 uint64_t filter_info_slen_ubound = 1;
7687 {
7688 unsigned char* tmp_alloc_end = bigstack_end_mark;
7689 if (StoreStringAtEndK(g_bigstack_base, "PASS", strlen("PASS"), &tmp_alloc_end, &(fif_strings[0]))) {
7690 goto BcfToPgen_ret_NOMEM;
7691 }
7692 fif_slens[0] = 4;
7693 line_iter = vcf_header;
7694 uint32_t contig_idx = 0;
7695 uint32_t fif_idx = 1;
7696 uint32_t cur_header_idx = 0;
7697 for (header_line_idx = 1; header_line_idx != header_line_ct; ++header_line_idx) {
7698 char* line_main = &(line_iter[2]);
7699 char* line_end = AdvPastDelim(line_main, '\n');
7700 line_iter = line_end;
7701 const uint32_t is_contig_line = StrStartsWithUnsafe(line_main, "contig=<");
7702 const uint32_t is_filter_line = StrStartsWithUnsafe(line_main, "FILTER=<");
7703 const uint32_t is_info_line = StrStartsWithUnsafe(line_main, "INFO=<");
7704 const uint32_t is_format_line = StrStartsWithUnsafe(line_main, "FORMAT=<");
7705 if (!(is_contig_line || is_filter_line || is_info_line || is_format_line)) {
7706 continue;
7707 }
7708 const char* hkvline_iter = &(line_main[8 - 2 * is_info_line]);
7709 const char* id_ptr;
7710 uint32_t id_slen;
7711 // previously validated
7712 HkvlineIdK(&hkvline_iter, &id_ptr, &id_slen);
7713
7714 if (is_filter_line && strequal_k(id_ptr, "PASS", id_slen)) {
7715 continue;
7716 }
7717 if (explicit_idx_keys) {
7718 char* line_last_iter = &(line_end[-2]);
7719 while (ctou32(*line_last_iter) <= 32) {
7720 --line_last_iter;
7721 }
7722 --line_last_iter;
7723 while (IsDigit(*line_last_iter)) {
7724 --line_last_iter;
7725 }
7726 // previously validated
7727 ScanUintDefcap(&(line_last_iter[1]), &cur_header_idx);
7728 }
7729 const char** target;
7730 uint32_t* slen_dst;
7731 if (is_contig_line) {
7732 if (!explicit_idx_keys) {
7733 cur_header_idx = contig_idx++;
7734 }
7735 target = &(contig_names[cur_header_idx]);
7736 slen_dst = &(contig_slens[cur_header_idx]);
7737 } else {
7738 if (!explicit_idx_keys) {
7739 cur_header_idx = fif_idx++;
7740 }
7741 target = &(fif_strings[cur_header_idx]);
7742 slen_dst = &(fif_slens[cur_header_idx]);
7743 }
7744 // May enforce id_slen <= kMaxIdSlen here later. (Technically only
7745 // necessary if we use the key in e.g. error messages, which happens on
7746 // BCF export but not import.)
7747 if (*target) {
7748 // Duplicate IDX values are actually permitted, but only when the ID
7749 // string is identical.
7750 // (In the no-IDX case, if e.g. a FILTER and INFO key are identical,
7751 // their implicit IDX values are still different.)
7752 if (unlikely((id_slen != *slen_dst) || (!memequal(id_ptr, *target, id_slen)))) {
7753 snprintf(g_logbuf, kLogbufSize, "Error: Multiple %s IDs in BCF text header block have IDX=%u.\n", is_contig_line? "contig" : "FILTER/INFO/FORMAT", cur_header_idx);
7754 goto BcfToPgen_ret_MALFORMED_INPUT_WW;
7755 }
7756 } else {
7757 // technically only need to null-terminate contig names
7758 if (StoreStringAtEndK(g_bigstack_base, id_ptr, id_slen, &tmp_alloc_end, target)) {
7759 goto BcfToPgen_ret_NOMEM;
7760 }
7761 *slen_dst = id_slen;
7762 if (id_slen > other_slen_ubound) {
7763 other_slen_ubound = id_slen;
7764 }
7765 }
7766 if (is_contig_line || is_filter_line) {
7767 continue;
7768 }
7769 const char* numstr;
7770 const char* typestr;
7771 uint32_t num_slen;
7772 uint32_t type_slen;
7773 if (unlikely(HkvlineNumTypeK(hkvline_iter, &numstr, &num_slen, &typestr, &type_slen))) {
7774 snprintf(g_logbuf, kLogbufSize, "Error: Line %u in BCF text header block is malformed.\n", header_line_idx);
7775 goto BcfToPgen_ret_MALFORMED_INPUT_2;
7776 }
7777 if (is_info_line) {
7778 const uintptr_t is_flag = strequal_k(typestr, "Flag", type_slen);
7779 if (strequal_k(id_ptr, "PR", id_slen)) {
7780 if (unlikely((pr_sidx != UINT32_MAX) || info_pr_nonflag_exists)) {
7781 logerrputs("Error: Duplicate INFO/PR line in BCF text header block.\n");
7782 goto BcfToPgen_ret_MALFORMED_INPUT;
7783 }
7784 if (is_flag) {
7785 pr_sidx = cur_header_idx;
7786 } else {
7787 info_pr_nonflag_exists = 1;
7788 logerrprintfww("Warning: Line %u of BCF text header block has an unexpected definition of INFO/PR. This interferes with a few merge and liftover operations.\n", header_line_idx);
7789 }
7790 } else {
7791 info_nonpr_exists = 1;
7792 }
7793 continue;
7794 }
7795 // FORMAT
7796 if (strequal_k(id_ptr, "GT", id_slen)) {
7797 if (unlikely(gt_sidx)) {
7798 logerrputs("Error: Duplicate FORMAT/GT line in BCF text header block.\n");
7799 goto BcfToPgen_ret_MALFORMED_INPUT;
7800 }
7801 if (unlikely((!strequal_k(numstr, "1", num_slen)) || (!strequal_k(typestr, "String", type_slen)))) {
7802 snprintf(g_logbuf, kLogbufSize, "Error: Line %u of BCF text header block does not have expected FORMAT/GT format.\n", header_line_idx);
7803 goto BcfToPgen_ret_MALFORMED_INPUT_WW;
7804 }
7805 gt_sidx = cur_header_idx;
7806 } else if ((vcf_min_gq != -1) && strequal_k(id_ptr, "GQ", id_slen)) {
7807 if (unlikely(gq_sidx)) {
7808 logerrputs("Error: Duplicate FORMAT/GQ header line in BCF text header block.\n");
7809 goto BcfToPgen_ret_MALFORMED_INPUT;
7810 }
7811 if (unlikely(!strequal_k(numstr, "1", num_slen))) {
7812 snprintf(g_logbuf, kLogbufSize, "Error: Line %u of BCF text header block does not have expected FORMAT/GQ format.\n", header_line_idx);
7813 goto BcfToPgen_ret_MALFORMED_INPUT_WW;
7814 }
7815 gq_sidx = cur_header_idx;
7816 } else if (((vcf_min_dp != -1) || (vcf_max_dp != 0x7fffffff)) && strequal_k(id_ptr, "DP", id_slen)) {
7817 if (unlikely(dp_sidx)) {
7818 logerrputs("Error: Duplicate FORMAT/DP header line in BCF text header block.\n");
7819 goto BcfToPgen_ret_MALFORMED_INPUT;
7820 }
7821 if (unlikely(!strequal_k(numstr, "1", num_slen))) {
7822 snprintf(g_logbuf, kLogbufSize, "Error: Line %u of BCF text header block does not have expected FORMAT/DP format.\n", header_line_idx);
7823 goto BcfToPgen_ret_MALFORMED_INPUT_WW;
7824 }
7825 dp_sidx = cur_header_idx;
7826 } else if (dosage_import_field) {
7827 if ((id_slen == dosage_import_field_slen) && memequal(id_ptr, dosage_import_field, dosage_import_field_slen)) {
7828 if (unlikely(dosage_sidx)) {
7829 snprintf(g_logbuf, kLogbufSize, "Error: Duplicate FORMAT/%s header line in BCF text header block.\n", dosage_import_field);
7830 goto BcfToPgen_ret_MALFORMED_INPUT_WW;
7831 }
7832 dosage_sidx = cur_header_idx;
7833 } else if (format_hds_search && strequal_k(id_ptr, "HDS", id_slen)) {
7834 if (unlikely(hds_sidx)) {
7835 logerrputs("Error: Duplicate FORMAT/HDS header line in BCF text header block.\n");
7836 goto BcfToPgen_ret_MALFORMED_INPUT;
7837 }
7838 hds_sidx = cur_header_idx;
7839 } else if (unforced_gp && strequal_k(id_ptr, "DS", id_slen)) {
7840 logerrputs("Error: --bcf dosage=GP specified, but --import-dosage-certainty was not and\nFORMAT/DS header line is present.\nSince " PROG_NAME_STR " collapses genotype probabilities down to dosages (even when\nperforming simple operations like \"" PROG_NAME_STR " --bcf ... --export bgen-1.2 ...\"),\n'dosage=GP' almost never makes sense in this situation. Either change it to\n'dosage=DS' (if dosages are good enough for your analysis), or use another\nprogram to work with the genotype probabilities.\nThere is one notable exception to the preceding recommendation: you are writing\na script to process BCF files that are guaranteed to have FORMAT/GP, but may or\nmay not have FORMAT/DS. You can use 'dosage=GP-force' to suppress this error\nin that situation.\n");
7841 goto BcfToPgen_ret_INCONSISTENT_INPUT;
7842 }
7843 }
7844 }
7845 BigstackEndSet(tmp_alloc_end);
7846 }
7847 const uint32_t require_gt = (import_flags / kfImportVcfRequireGt) & 1;
7848 if (unlikely((!gt_sidx) && require_gt)) {
7849 logerrputs("Error: No FORMAT/GT key found in BCF text header block, when --vcf-require-gt\nwas specified.\n(If this header line is actually present, but with extra spaces or unusual\nfield ordering, standardize the header with e.g. bcftools.)\n");
7850 goto BcfToPgen_ret_INCONSISTENT_INPUT;
7851 }
7852 if ((!gq_sidx) && (vcf_min_gq != -1)) {
7853 logerrputs("Warning: No FORMAT/GQ key found in BCF text header block. --vcf-min-gq\nignored.\n(If this header line is actually present, but with extra spaces or unusual\nfield ordering, standardize the header with e.g. bcftools.)\n");
7854 }
7855 if ((!dp_sidx) && ((vcf_max_dp != 0x7fffffff) || (vcf_min_dp != -1))) {
7856 logerrputs("Warning: No FORMAT/DP key found in BCF text header block. --vcf-{max,min}-dp\nignored.\n(If this header line is actually present, but with extra spaces or unusual\nfield ordering, standardize the header with e.g. bcftools.)\n");
7857 }
7858 if (format_hds_search) {
7859 if (!hds_sidx) {
7860 if (!dosage_sidx) {
7861 logerrputs("Warning: No FORMAT/DS or :HDS key found in BCF text header block. Dosages will\nnot be imported.\n(If these header line(s) are actually present, but with extra spaces or unusual\nfield ordering, standardize the header with e.g. bcftools.)\n");
7862 } else {
7863 logerrputs("Warning: No FORMAT/HDS key found in BCF text header block. Dosages will be\nimported (from FORMAT/DS), but phase information will be limited or absent.\n");
7864 }
7865 }
7866 } else if ((!dosage_sidx) && dosage_import_field) {
7867 logerrprintfww("Warning: No FORMAT/%s key found in BCF text header block. Dosages will not be imported. (If this header line is actually present, but with extra spaces or unusual field ordering, standardize the header with e.g. bcftools.)\n", dosage_import_field);
7868 }
7869 const uint32_t ref_n_missing = (import_flags / kfImportVcfRefNMissing) & 1;
7870 if (unlikely(ref_n_missing && (pr_sidx == UINT32_MAX))) {
7871 logerrputs("Error: --vcf-ref-n-missing was specified, but the BCF does not have the\nINFO/PR header line that should be present in any .ped-derived BCF.\n");
7872 goto BcfToPgen_ret_INCONSISTENT_INPUT;
7873 }
7874
7875 memcpy(contig_out_names, contig_names, contig_string_idx_end * sizeof(intptr_t));
7876 memcpy(contig_out_slens, contig_slens, contig_string_idx_end * sizeof(int32_t));
7877
7878 unsigned char* bigstack_end_mark2 = g_bigstack_end;
7879 uintptr_t loadbuf_size = RoundDownPow2(bigstack_left() / 2, kEndAllocAlign);
7880 #ifdef __LP64__
7881 // l_shared and l_indiv are of type uint32_t, so we never need to look at
7882 // more than 8 GiB at a time.
7883 if (loadbuf_size > (k1LU << 33)) {
7884 loadbuf_size = k1LU << 33;
7885 }
7886 #endif
7887 // guaranteeing at least this many bytes allocated at bigstack_end
7888 // simplifies a bit of parsing logic
7889 if (loadbuf_size < (1 << 18)) {
7890 goto BcfToPgen_ret_NOMEM;
7891 }
7892 // Placed at end of arena so we can shrink it before the second pass
7893 // without fragmenting memory.
7894 unsigned char* loadbuf = S_CAST(unsigned char*, bigstack_end_alloc_raw(loadbuf_size));
7895
7896 uint32_t variant_ct = 0;
7897 uintptr_t max_variant_ct = bigstack_left() / sizeof(intptr_t);
7898 if (pr_sidx != UINT32_MAX) {
7899 // nonref_flags
7900 max_variant_ct -= BitCtToAlignedWordCt(max_variant_ct) * kWordsPerVec;
7901 }
7902 #ifdef __LP64__
7903 if (max_variant_ct > kPglMaxVariantCt) {
7904 max_variant_ct = kPglMaxVariantCt;
7905 }
7906 #endif
7907 // max(32, l_shared + l_indiv - 24)
7908 // (there are cheaper ways to handle gt_exists, but the memory savings are
7909 // unlikely to be significant.)
7910 uintptr_t loadbuf_size_needed = 32;
7911
7912 // Sum of GT, DS/GP, HDS, GQ, and DP vector lengths.
7913 uint32_t max_observed_rec_vecs = 0;
7914
7915 const uint32_t max_variant_ctaw = BitCtToAlignedWordCt(max_variant_ct);
7916 // don't need dosage_flags or dphase_flags; dosage overrides GT so slow
7917 // parse needed
7918 uintptr_t* nonref_flags = nullptr;
7919 if (pr_sidx != UINT32_MAX) {
7920 nonref_flags = S_CAST(uintptr_t*, bigstack_alloc_raw_rd(max_variant_ctaw * sizeof(intptr_t)));
7921 }
7922 char* contig_out_buf_iter = contig_out_buf;
7923 uintptr_t* nonref_flags_iter = nonref_flags;
7924 uintptr_t* allele_idx_offsets = R_CAST(uintptr_t*, g_bigstack_base);
7925 uintptr_t nonref_word = 0;
7926 uintptr_t allele_idx_end = 0;
7927 uint32_t max_allele_ct = 0;
7928 uint32_t phase_or_dosage_found = 0;
7929 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
7930 uint32_t par_warn_bcf_chrom = UINT32_MAX;
7931 while (1) {
7932 ++vrec_idx; // 1-based since it's only used in error messages
7933 unsigned char* loadbuf_read_iter = loadbuf;
7934 reterr = BgzfRawMtStreamRead(&(loadbuf[32]), &bgzf, &loadbuf_read_iter, &bgzf_errmsg);
7935 if (unlikely(reterr)) {
7936 goto BcfToPgen_ret_BGZF_FAIL_N;
7937 }
7938 if (&(loadbuf[32]) != loadbuf_read_iter) {
7939 if (likely(loadbuf_read_iter == loadbuf)) {
7940 // EOF
7941 // possible todo: verify empty block is present at end
7942 break;
7943 }
7944 goto BcfToPgen_ret_VREC_GENERIC;
7945 }
7946 const uint32_t* vrec_header = R_CAST(uint32_t*, loadbuf);
7947 // IMPORTANT: Official specification is wrong about the ordering of these
7948 // fields as of Feb 2020!! The correct ordering can be inferred from
7949 // bcf_read1_core() in htslib vcf.c:
7950 // [0]: l_shared
7951 // [1]: l_indiv
7952 // [2]: chrom
7953 // [3]: pos
7954 // [4]: rlen
7955 // [5]: qual, NOT n_allele_info
7956 // [6]: low 16 bits n_info, high 16 bits n_allele
7957 // [7]: low 24 bits n_sample, high 8 bits n_fmt
7958 const uint32_t l_shared = vrec_header[0];
7959 const uint32_t l_indiv = vrec_header[1];
7960 const uint32_t chrom = vrec_header[2];
7961 // Can ignore pos and qual on this pass. (QUAL/FILTER enforcement is now
7962 // handled by the .pvar loader.) Always ignore rlen for now, though we
7963 // may want to add a consistency check later.
7964 uint32_t n_allele = vrec_header[6] >> 16;
7965 const uint32_t n_info = vrec_header[6] & 0xffff;
7966 const uint32_t n_sample = vrec_header[7] & 0xffffff;
7967 const uint32_t n_fmt = vrec_header[7] >> 24;
7968
7969 if (unlikely((l_shared < 24) || (chrom >= contig_string_idx_end) || (n_sample != sample_ct))) {
7970 goto BcfToPgen_ret_VREC_GENERIC;
7971 }
7972 const uint64_t second_load_size = l_shared + S_CAST(uint64_t, l_indiv) - 24;
7973 if (unlikely(second_load_size > loadbuf_size)) {
7974 goto BcfToPgen_ret_NOMEM;
7975 }
7976 if (second_load_size > loadbuf_size_needed) {
7977 loadbuf_size_needed = second_load_size;
7978 }
7979 loadbuf_read_iter = loadbuf;
7980 unsigned char* indiv_end = &(loadbuf[second_load_size]);
7981 reterr = BgzfRawMtStreamRead(indiv_end, &bgzf, &loadbuf_read_iter, &bgzf_errmsg);
7982 if (unlikely(reterr)) {
7983 goto BcfToPgen_ret_BGZF_FAIL_N;
7984 }
7985 if (unlikely(indiv_end != loadbuf_read_iter)) {
7986 goto BcfToPgen_ret_VREC_GENERIC;
7987 }
7988
7989 // We've now decompressed to the end of the variant record, and can
7990 // safely skip the variant with "continue;". There are currently three
7991 // cases where we might want to do this: chromosome filters,
7992 // --import-max-alleles, and --vcf-require-gt.
7993 if (n_allele > import_max_allele_ct) {
7994 continue;
7995 }
7996 if (IsSet(bcf_contig_seen, chrom)) {
7997 if (!IsSet(bcf_contig_keep, chrom)) {
7998 continue;
7999 }
8000 } else if (!require_gt) {
8001 const uint32_t contig_slen = contig_slens[chrom];
8002 if (unlikely(!contig_slen)) {
8003 putc_unlocked('\n', stdout);
8004 logerrputs("Error: Empty contig ID in --bcf file.");
8005 goto BcfToPgen_ret_MALFORMED_INPUT;
8006 }
8007 // Don't want to mutate cip in require_gt case until we know the contig
8008 // is being kept.
8009 uint32_t cur_chr_code;
8010 reterr = GetOrAddChrCode(contig_names[chrom], "--bcf file", 0, contig_slen, prohibit_extra_chr, cip, &cur_chr_code);
8011 if (unlikely(reterr)) {
8012 goto BcfToPgen_ret_1;
8013 }
8014 SetBit(chrom, bcf_contig_seen);
8015 if (!IsSet(cip->chr_mask, cur_chr_code)) {
8016 continue;
8017 }
8018 SetBit(chrom, bcf_contig_keep);
8019 if (cur_chr_code <= cip->max_code) {
8020 char* rendered_chr_name = contig_out_buf_iter;
8021 contig_out_buf_iter = chrtoa(cip, cur_chr_code, rendered_chr_name);
8022 contig_out_names[chrom] = rendered_chr_name;
8023 contig_out_slens[chrom] = contig_out_buf_iter - rendered_chr_name;
8024 if (cur_chr_code == x_code) {
8025 par_warn_bcf_chrom = chrom;
8026 }
8027 }
8028 }
8029 const unsigned char* shared_end = indiv_end - l_indiv;
8030 const unsigned char* parse_iter = shared_end;
8031
8032 const unsigned char* gt_start = nullptr;
8033 const unsigned char* qual_starts[2];
8034 qual_starts[0] = nullptr;
8035 qual_starts[1] = nullptr;
8036 const unsigned char* dosage_start = nullptr;
8037 const unsigned char* hds_start = nullptr;
8038 uint32_t cur_observed_rec_vecs = 0;
8039 for (uint32_t fmt_idx = 0; fmt_idx != n_fmt; ++fmt_idx) {
8040 // 1. typed int indicating which FORMAT field
8041 // 2. shared type descriptor for each entry (usually a single byte)
8042 // 3. sample_ct entries
8043 uint32_t sidx;
8044 if (unlikely(ScanBcfTypedInt(&parse_iter, &sidx) || (parse_iter > indiv_end) || (sidx >= fif_string_idx_end))) {
8045 goto BcfToPgen_ret_VREC_GENERIC;
8046 }
8047 const uint32_t key_slen = fif_slens[sidx];
8048 const unsigned char* type_start = parse_iter;
8049 uint32_t value_type;
8050 uint32_t value_ct;
8051 if (unlikely((!key_slen) || ScanBcfType(&parse_iter, &value_type, &value_ct) || (parse_iter > indiv_end))) {
8052 goto BcfToPgen_ret_VREC_GENERIC;
8053 }
8054 const unsigned char* vec_start = parse_iter;
8055 if (value_ct) {
8056 const uint32_t bytes_per_elem = kBcfBytesPerElem[value_type];
8057 const uint64_t vec_byte_ct = bytes_per_elem * S_CAST(uint64_t, value_ct) * sample_ct;
8058 if (unlikely((!bytes_per_elem) || (S_CAST(uint64_t, indiv_end - parse_iter) < vec_byte_ct))) {
8059 goto BcfToPgen_ret_VREC_GENERIC;
8060 }
8061 parse_iter = &(parse_iter[vec_byte_ct]);
8062 }
8063 // defend against FORMAT/PASS edge case
8064 if (!sidx) {
8065 continue;
8066 }
8067 if (sidx == gt_sidx) {
8068 gt_start = type_start;
8069 } else if (sidx == gq_sidx) {
8070 qual_starts[0] = type_start;
8071 } else if (sidx == dp_sidx) {
8072 qual_starts[1] = type_start;
8073 } else if (sidx == dosage_sidx) {
8074 dosage_start = type_start;
8075 } else if (sidx == hds_sidx) {
8076 hds_start = type_start;
8077 } else {
8078 continue;
8079 }
8080 #ifdef __LP64__
8081 // bcf-type guaranteed to fit in <= 16 bytes
8082 ++cur_observed_rec_vecs;
8083 #else
8084 cur_observed_rec_vecs += DivUp(S_CAST(uintptr_t, vec_start - type_start), kBytesPerVec);
8085 #endif
8086 cur_observed_rec_vecs += DivUp(S_CAST(uintptr_t, parse_iter - vec_start), kBytesPerVec);
8087 }
8088 if (require_gt) {
8089 if (!gt_start) {
8090 continue;
8091 }
8092 if (!IsSet(bcf_contig_seen, chrom)) {
8093 uint32_t cur_chr_code;
8094 reterr = GetOrAddChrCode(contig_names[chrom], "--bcf file", 0, strlen(contig_names[chrom]), prohibit_extra_chr, cip, &cur_chr_code);
8095 if (unlikely(reterr)) {
8096 goto BcfToPgen_ret_1;
8097 }
8098 SetBit(chrom, bcf_contig_seen);
8099 if (!IsSet(cip->chr_mask, cur_chr_code)) {
8100 continue;
8101 }
8102 SetBit(chrom, bcf_contig_keep);
8103 if (cur_chr_code <= cip->max_code) {
8104 char* rendered_chr_name = contig_out_buf_iter;
8105 contig_out_buf_iter = chrtoa(cip, cur_chr_code, rendered_chr_name);
8106 contig_out_names[chrom] = rendered_chr_name;
8107 contig_out_slens[chrom] = contig_out_buf_iter - rendered_chr_name;
8108 if (cur_chr_code == x_code) {
8109 par_warn_bcf_chrom = chrom;
8110 }
8111 }
8112 }
8113 }
8114 // We finally know for sure that we need to convert this variant.
8115
8116 // Remainder of l_shared:
8117 // ID (typed string)
8118 // REF+ALT (n_allele typed strings)
8119 // FILTER (typed vector of integers)
8120 // INFO (n_info (typed integer, typed vector) pairs)
8121 // We scan these fields to compute an upper bound on the necessary .pvar
8122 // write-buffer size. In the unlikely pr_sidx != UINT32_MAX case, we
8123 // also need to scan for presence of INFO/PR.
8124 parse_iter = loadbuf;
8125 // ID, REF, ALT
8126 const uint32_t str_ignore_ct = n_allele + 1;
8127 for (uint32_t uii = 0; uii != str_ignore_ct; ++uii) {
8128 const char* str_start;
8129 uint32_t slen;
8130 if (unlikely(ScanBcfTypedString(shared_end, &parse_iter, &str_start, &slen))) {
8131 goto BcfToPgen_ret_VREC_GENERIC;
8132 }
8133 if (slen > other_slen_ubound) {
8134 other_slen_ubound = slen;
8135 }
8136 }
8137 // bugfix (22 Feb 2020): need to treat n_allele as 2 after this point
8138 // when it's 1
8139 if (n_allele == 1) {
8140 n_allele = 2;
8141 }
8142 // FILTER
8143 uint32_t value_type;
8144 uint32_t value_ct;
8145 if (unlikely(ScanBcfType(&parse_iter, &value_type, &value_ct) || (parse_iter > shared_end))) {
8146 goto BcfToPgen_ret_VREC_GENERIC;
8147 }
8148 if (value_ct) {
8149 const uint32_t value_type_m1 = value_type - 1;
8150 const uintptr_t vec_byte_ct = S_CAST(uintptr_t, value_ct) << value_type_m1;
8151 if (unlikely((value_type_m1 > 2) || (S_CAST(uintptr_t, shared_end - parse_iter) < vec_byte_ct))) {
8152 goto BcfToPgen_ret_VREC_GENERIC;
8153 }
8154 uint64_t cur_filter_slen = value_ct - 1; // delimiters
8155 if (!value_type_m1) {
8156 for (uint32_t filter_idx = 0; filter_idx != value_ct; ++filter_idx) {
8157 const uint32_t cur_val = parse_iter[filter_idx];
8158 if (cur_val == 0x80) {
8159 // missing
8160 ++cur_filter_slen;
8161 } else {
8162 const uint32_t key_slen = fif_slens[cur_val];
8163 if (unlikely((cur_val >= fif_string_idx_end) || (cur_val > 0x80) || (!key_slen))) {
8164 goto BcfToPgen_ret_VREC_GENERIC;
8165 }
8166 cur_filter_slen += key_slen;
8167 }
8168 }
8169 } else if (value_type_m1 == 1) {
8170 const uint16_t* filter_vec_alias = R_CAST(const uint16_t*, parse_iter);
8171 for (uint32_t filter_idx = 0; filter_idx != value_ct; ++filter_idx) {
8172 const uint32_t cur_val = filter_vec_alias[filter_idx];
8173 if (cur_val == 0x8000) {
8174 // missing
8175 ++cur_filter_slen;
8176 } else {
8177 // loadbuf_size >= 2^18, so fif_slens[65535] won't segfault
8178 const uint32_t key_slen = fif_slens[cur_val];
8179 if (unlikely((cur_val >= fif_string_idx_end) || (cur_val > 0x8000) || (!key_slen))) {
8180 goto BcfToPgen_ret_VREC_GENERIC;
8181 }
8182 cur_filter_slen += key_slen;
8183 }
8184 }
8185 } else {
8186 const uint32_t* filter_vec_alias = R_CAST(const uint32_t*, parse_iter);
8187 for (uint32_t filter_idx = 0; filter_idx != value_ct; ++filter_idx) {
8188 const uint32_t cur_val = filter_vec_alias[filter_idx];
8189 if (cur_val == 0x80000000U) {
8190 // missing
8191 ++cur_filter_slen;
8192 } else {
8193 if (unlikely(cur_val >= fif_string_idx_end)) {
8194 goto BcfToPgen_ret_VREC_GENERIC;
8195 }
8196 const uint32_t key_slen = fif_slens[cur_val];
8197 if (unlikely(!key_slen)) {
8198 goto BcfToPgen_ret_VREC_GENERIC;
8199 }
8200 cur_filter_slen += key_slen;
8201 }
8202 }
8203 }
8204 if (cur_filter_slen > filter_info_slen_ubound) {
8205 filter_info_slen_ubound = cur_filter_slen;
8206 }
8207 parse_iter = &(parse_iter[vec_byte_ct]);
8208 }
8209 // INFO
8210 uintptr_t info_pr_here = 0;
8211 if (n_info) {
8212 // bugfix (1 Jul 2021): avoid underflow when n_info == 0
8213 uint64_t cur_info_slen_ubound = n_info - 1;
8214 for (uint32_t uii = 0; uii != n_info; ++uii) {
8215 uint32_t sidx;
8216 if (unlikely(ScanBcfTypedInt(&parse_iter, &sidx) || (parse_iter > shared_end) || (sidx >= fif_string_idx_end))) {
8217 goto BcfToPgen_ret_VREC_GENERIC;
8218 }
8219 const uint32_t key_slen = fif_slens[sidx];
8220 if (unlikely((!key_slen) || ScanBcfType(&parse_iter, &value_type, &value_ct) || (parse_iter > shared_end))) {
8221 goto BcfToPgen_ret_VREC_GENERIC;
8222 }
8223 cur_info_slen_ubound += key_slen;
8224 if (value_ct) {
8225 const uint32_t bytes_per_elem = kBcfBytesPerElem[value_type];
8226 const uint64_t vec_byte_ct = bytes_per_elem * S_CAST(uint64_t, value_ct);
8227 if (unlikely((!bytes_per_elem) || (S_CAST(uint64_t, shared_end - parse_iter) < vec_byte_ct))) {
8228 goto BcfToPgen_ret_VREC_GENERIC;
8229 }
8230 if (value_type == 1) {
8231 // int8, max len 4 ("-127"), add 1 for comma
8232 cur_info_slen_ubound += 5 * S_CAST(uint64_t, value_ct);
8233 } else if (value_type == 2) {
8234 // int16, max len 6
8235 cur_info_slen_ubound += 7 * S_CAST(uint64_t, value_ct);
8236 } else if (value_type == 3) {
8237 // int32, max len 11
8238 cur_info_slen_ubound += 12 * S_CAST(uint64_t, value_ct);
8239 } else if (value_type == 5) {
8240 cur_info_slen_ubound += (kMaxFloatGSlen + 1) * S_CAST(uint64_t, value_ct);
8241 } else {
8242 // string
8243 cur_info_slen_ubound += value_ct + 1;
8244 }
8245 parse_iter = &(parse_iter[vec_byte_ct]);
8246 } else {
8247 // bugfix (8 Jan 2023): value_type == value_ct == 0
8248 // "untyped-missing" special case is always permitted, it's not
8249 // restricted to flags.
8250 //
8251 // value_ct == 0, value_type == 7 is also valid (string, missing).
8252 //
8253 // Otherwise, value_ct == 0 should not happen.
8254 if (value_type) {
8255 if (unlikely(value_type != 7)) {
8256 goto BcfToPgen_ret_VREC_GENERIC;
8257 }
8258 // Emit '=' with empty-string value.
8259 ++cur_info_slen_ubound;
8260 }
8261 }
8262 if (sidx == pr_sidx) {
8263 if (unlikely(info_pr_here)) {
8264 putc_unlocked('\n', stdout);
8265 snprintf(g_logbuf, kLogbufSize, "Error: Variant record #%" PRIuPTR " in --bcf file has multiple INFO/PR entries.\n", vrec_idx);
8266 goto BcfToPgen_ret_MALFORMED_INPUT_WW;
8267 }
8268 info_pr_here = 1;
8269 }
8270 }
8271 if (cur_info_slen_ubound > filter_info_slen_ubound) {
8272 filter_info_slen_ubound = cur_info_slen_ubound;
8273 }
8274 }
8275 if (unlikely(parse_iter != shared_end)) {
8276 goto BcfToPgen_ret_VREC_GENERIC;
8277 }
8278
8279 if (max_allele_ct < n_allele) {
8280 if (n_allele > kPglMaxAlleleCt) {
8281 putc_unlocked('\n', stdout);
8282 logerrprintfww("Error: Variant record #%" PRIuPTR " in --bcf file has %u alleles; this build of " PROG_NAME_STR " is limited to " PGL_MAX_ALLELE_CT_STR ". (You can use \"--import-max-alleles " PGL_MAX_ALLELE_CT_STR "\" to filter out such variants.)\n", vrec_idx, n_allele);
8283 reterr = kPglRetNotYetSupported;
8284 goto BcfToPgen_ret_1;
8285 }
8286 max_allele_ct = n_allele;
8287 }
8288 if (max_observed_rec_vecs < cur_observed_rec_vecs) {
8289 max_observed_rec_vecs = cur_observed_rec_vecs;
8290 }
8291 allele_idx_offsets[variant_ct] = allele_idx_end;
8292 allele_idx_end += n_allele;
8293 const uint32_t variant_idx_lowbits = variant_ct % kBitsPerWord;
8294 if (pr_sidx != UINT32_MAX) {
8295 nonref_word |= info_pr_here << variant_idx_lowbits;
8296 if (variant_idx_lowbits == (kBitsPerWord - 1)) {
8297 *nonref_flags_iter++ = nonref_word;
8298 nonref_word = 0;
8299 }
8300 }
8301 if (sample_ct && (!phase_or_dosage_found)) {
8302 // Check if there's at least one phased het call, and/or at least one
8303 // relevant dosage.
8304 // Don't bother multithreading this since it's trivial.
8305 if (dosage_start || hds_start) {
8306 if (n_allele == 2) {
8307 bcf_parse_err = BcfScanBiallelicHds(&(ctx.bic), gt_start, qual_starts, dosage_start, hds_start, &phase_or_dosage_found, sample_nypbuf);
8308 } else {
8309 putc_unlocked('\n', stdout);
8310 logerrputs("Error: --bcf multiallelic dosage import is under development.\n");
8311 reterr = kPglRetNotYetSupported;
8312 goto BcfToPgen_ret_1;
8313 }
8314 } else if (gt_start) {
8315 // scan for phase
8316 bcf_parse_err = BcfScanGt(&(ctx.bic), gt_start, qual_starts, &phase_or_dosage_found, sample_nypbuf);
8317 }
8318 if (unlikely(bcf_parse_err)) {
8319 goto BcfToPgen_ret_PARSE;
8320 }
8321 }
8322 if (unlikely(variant_ct++ == max_variant_ct)) {
8323 #ifdef __LP64__
8324 if (variant_ct == kPglMaxVariantCt) {
8325 putc_unlocked('\n', stdout);
8326 logerrputs("Error: " PROG_NAME_STR " does not support more than 2^31 - 3 variants. We recommend using\nother software for very deep studies of small numbers of genomes.\n");
8327 goto BcfToPgen_ret_MALFORMED_INPUT;
8328 }
8329 #endif
8330 goto BcfToPgen_ret_NOMEM;
8331 }
8332 if (!(variant_ct % 10000)) {
8333 printf("\r--bcf: %uk variants scanned.", variant_ct / 1000);
8334 fflush(stdout);
8335 }
8336 }
8337 if (variant_ct % kBitsPerWord) {
8338 if (nonref_flags_iter) {
8339 *nonref_flags_iter = nonref_word;
8340 }
8341 } else if (unlikely(!variant_ct)) {
8342 logerrputs("Error: No variants in --bcf file.\n");
8343 goto BcfToPgen_ret_DEGENERATE_DATA;
8344 }
8345
8346 const uintptr_t variant_skip_ct = vrec_idx - 1 - variant_ct;
8347 putc_unlocked('\r', stdout);
8348 if (!variant_skip_ct) {
8349 logprintf("--bcf: %u variant%s scanned.\n", variant_ct, (variant_ct == 1)? "" : "s");
8350 } else {
8351 logprintf("--bcf: %u variant%s scanned (%" PRIuPTR " skipped).\n", variant_ct, (variant_ct == 1)? "" : "s", variant_skip_ct);
8352 }
8353
8354 if (allele_idx_end > 2 * variant_ct) {
8355 allele_idx_offsets[variant_ct] = allele_idx_end;
8356 BigstackFinalizeW(allele_idx_offsets, variant_ct + 1);
8357 } else {
8358 allele_idx_offsets = nullptr;
8359 }
8360
8361 BigstackEndReset(bigstack_end_mark2);
8362 loadbuf_size = RoundUpPow2(loadbuf_size_needed, kEndAllocAlign);
8363 loadbuf = S_CAST(unsigned char*, bigstack_end_alloc_raw(loadbuf_size));
8364
8365 reterr = BgzfRawMtStreamRewind(&bgzf, &bgzf_errmsg);
8366 if (unlikely(reterr)) {
8367 if (reterr == kPglRetDecompressFail) {
8368 DPrintf("DecompressFail during initial rewind");
8369 goto BcfToPgen_ret_REWIND_FAIL;
8370 }
8371 goto BcfToPgen_ret_BGZF_FAIL;
8372 }
8373 {
8374 unsigned char* bcf_header_buf = R_CAST(unsigned char*, &(vcf_header[-9]));
8375 unsigned char* bcf_iter = bcf_header_buf;
8376 unsigned char* bcf_header_end = &(bcf_header_buf[header_size + 9 * k1LU]);
8377 reterr = BgzfRawMtStreamRead(bcf_header_end, &bgzf, &bcf_iter, &bgzf_errmsg);
8378 if (unlikely(reterr)) {
8379 goto BcfToPgen_ret_BGZF_FAIL;
8380 }
8381 if (unlikely(bcf_iter != bcf_header_end)) {
8382 errno = 0;
8383 reterr = kPglRetReadFail;
8384 goto BcfToPgen_ret_BGZF_FAIL;
8385 }
8386 }
8387
8388 uint32_t calc_thread_ct;
8389 // todo: tune this for BCF, these values were derived from VCF testing
8390 if (phase_or_dosage_found && (dosage_sidx || hds_sidx)) {
8391 calc_thread_ct = 1 + (sample_ct > 5) + (sample_ct > 12) + (sample_ct > 32) + (sample_ct > 512);
8392 } else {
8393 calc_thread_ct = 1 + (sample_ct > 40) + (sample_ct > 320);
8394 }
8395 if (calc_thread_ct + decompress_thread_ct > max_thread_ct) {
8396 calc_thread_ct = MAXV(1, max_thread_ct - decompress_thread_ct);
8397 }
8398
8399 const uint32_t variant_ctl = BitCtToWordCt(variant_ct);
8400 PgenGlobalFlags phase_dosage_gflags = kfPgenGlobal0;
8401 GparseFlags gparse_flags = kfGparse0; // yeah, this is a bit redundant
8402 if (phase_or_dosage_found || hds_sidx || dosage_sidx) {
8403 if ((!hds_sidx) && (!dosage_sidx)) {
8404 phase_dosage_gflags = kfPgenGlobalHardcallPhasePresent;
8405 gparse_flags = kfGparseHphase;
8406 } else {
8407 // thanks to automatic --hard-call-threshold, we may need to save
8408 // dosage-phase even when there's no HDS field
8409 phase_dosage_gflags = kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent;
8410 gparse_flags = kfGparseHphase | kfGparseDosage | kfGparseDphase;
8411 }
8412 }
8413 uint32_t nonref_flags_storage = 1;
8414 if (nonref_flags) {
8415 const uint32_t variant_ctl_m1 = variant_ctl - 1;
8416 const uintptr_t last_nonref_flags_word = nonref_flags[variant_ctl_m1];
8417 if (!last_nonref_flags_word) {
8418 for (uint32_t widx = 0; widx != variant_ctl_m1; ++widx) {
8419 if (nonref_flags[widx]) {
8420 nonref_flags_storage = 3;
8421 break;
8422 }
8423 }
8424 } else if (!((~last_nonref_flags_word) << ((-variant_ct) & (kBitsPerWord - 1)))) {
8425 nonref_flags_storage = 2;
8426 for (uint32_t widx = 0; widx != variant_ctl_m1; ++widx) {
8427 if (~nonref_flags[widx]) {
8428 nonref_flags_storage = 3;
8429 break;
8430 }
8431 }
8432 } else {
8433 nonref_flags_storage = 3;
8434 }
8435 if (nonref_flags_storage != 3) {
8436 // yeah, we may now have a temporary "memory leak" here (if
8437 // multiallelic variants are present, and thus allele_idx_offsets[]
8438 // must be kept around), but this array is typically only 1/64 the size
8439 // of allele_idx_offsets[].
8440 if (!allele_idx_offsets) {
8441 BigstackReset(nonref_flags);
8442 }
8443 nonref_flags = nullptr;
8444 }
8445 }
8446
8447 const uint64_t write_chunk_ubound = 32 + MAXV(other_slen_ubound, filter_info_slen_ubound);
8448 #ifndef __LP64__
8449 if (write_chunk_ubound > 0x7ff00000) {
8450 goto BcfToPgen_ret_NOMEM;
8451 }
8452 #endif
8453 const uint32_t output_zst = ((import_flags & (kfImportKeepAutoconv | kfImportKeepAutoconvVzs)) != kfImportKeepAutoconv);
8454 snprintf(outname_end, kMaxOutfnameExtBlen, ".pvar");
8455 if (output_zst) {
8456 snprintf(&(outname_end[5]), kMaxOutfnameExtBlen - 5, ".zst");
8457 }
8458 const uintptr_t overflow_buf_size = kCompressStreamBlock + MAXV(write_chunk_ubound, kCompressStreamBlock);
8459 reterr = InitCstreamAlloc(outname, 0, output_zst, sample_ct? 1 : MAXV(1, max_thread_ct - decompress_thread_ct), overflow_buf_size, &pvar_css, &pvar_cswritep);
8460 if (unlikely(reterr)) {
8461 goto BcfToPgen_ret_1;
8462 }
8463 line_iter = vcf_header;
8464 uint32_t contig_idx = UINT32_MAX; // deliberate overflow
8465 uint32_t idxeq_clipped = 0;
8466 for (header_line_idx = 1; header_line_idx != header_line_ct; ++header_line_idx) {
8467 char* line_start = line_iter;
8468 char* line_main = &(line_iter[2]);
8469 char* line_end = AdvPastDelim(line_main, '\n');
8470 line_iter = line_end;
8471 // chrSet skipped here since we call AppendChrsetLine after this loop
8472 if (StrStartsWithUnsafe(line_main, "fileformat=") || StrStartsWithUnsafe(line_main, "fileDate=") || StrStartsWithUnsafe(line_main, "source=") || StrStartsWithUnsafe(line_main, "FORMAT=") || StrStartsWithUnsafe(line_main, "chrSet=")) {
8473 continue;
8474 }
8475 // OS-agnostic newline clip.
8476 char* line_write_end = &(line_end[-1]);
8477 if (line_write_end[-1] == '\r') {
8478 --line_write_end;
8479 }
8480 const uint32_t is_contig_line = StrStartsWithUnsafe(line_main, "contig=<ID");
8481 if (explicit_idx_keys) {
8482 const uint32_t is_filter_line = StrStartsWithUnsafe(line_main, "FILTER=<ID");
8483 const uint32_t is_info_line = StrStartsWithUnsafe(line_main, "INFO=<ID");
8484 const uint32_t is_format_line = StrStartsWithUnsafe(line_main, "FORMAT=<ID");
8485 idxeq_clipped = is_contig_line || is_filter_line || is_info_line || is_format_line;
8486 if (idxeq_clipped) {
8487 // Clip ",IDX=123>".
8488 --line_write_end;
8489 do {
8490 --line_write_end;
8491 } while (IsDigit(*line_write_end));
8492 line_write_end = &(line_write_end[-4]);
8493 // line_write_end now points to the '=' in 'IDX='.
8494 }
8495 }
8496 if (is_contig_line) {
8497 if (explicit_idx_keys) {
8498 ScanUintDefcap(&(line_write_end[5]), &contig_idx);
8499 } else {
8500 ++contig_idx;
8501 }
8502 if (!IsSet(bcf_contig_keep, contig_idx)) {
8503 continue;
8504 }
8505 }
8506 if (unlikely(CsputsStd(line_start, line_write_end - line_start, &pvar_css, &pvar_cswritep))) {
8507 goto BcfToPgen_ret_WRITE_FAIL;
8508 }
8509 if (idxeq_clipped) {
8510 *pvar_cswritep++ = '>';
8511 }
8512 // NOT safe to use AppendBinaryEoln here.
8513 #ifdef _WIN32
8514 pvar_cswritep = strcpya_k(pvar_cswritep, "\r\n");
8515 #else
8516 *pvar_cswritep++ = '\n';
8517 #endif
8518 }
8519 if (cip->chrset_source) {
8520 AppendChrsetLine(cip, &pvar_cswritep);
8521 }
8522 pvar_cswritep = strcpya_k(pvar_cswritep, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER");
8523 if (info_nonpr_exists) {
8524 pvar_cswritep = strcpya_k(pvar_cswritep, "\tINFO");
8525 }
8526 AppendBinaryEoln(&pvar_cswritep);
8527 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
8528 goto BcfToPgen_ret_WRITE_FAIL;
8529 }
8530
8531 // may as well have a functional progress meter in no-samples case
8532 uint32_t main_block_size = MINV(65536, variant_ct);
8533 uint32_t per_thread_block_limit = main_block_size;
8534 uint32_t cur_thread_block_vidx_limit = 1;
8535 uintptr_t per_thread_byte_limit = 0;
8536 unsigned char* geno_bufs[2];
8537 // defensive
8538 geno_bufs[0] = nullptr;
8539 geno_bufs[1] = nullptr;
8540 if (hard_call_thresh == UINT32_MAX) {
8541 hard_call_thresh = kDosageMid / 10;
8542 }
8543 uintptr_t* bcf_haploid_mask = nullptr;
8544 const uint32_t hard_call_halfdist = kDosage4th - hard_call_thresh;
8545
8546 // See the analogous code in VcfToPgen().
8547 const uint32_t sex_info_avail = preexisting_psamname || is_update_or_impute_sex;
8548 if (par_warn_bcf_chrom != UINT32_MAX) {
8549 if ((import_flags & kfImportLaxChrX) || (!sample_ct)) {
8550 par_warn_bcf_chrom = UINT32_MAX;
8551 } else if (unlikely(!sex_info_avail)) {
8552 logerrputs("Error: chrX is present in the input file, but no sex information was provided;\nrerun this import with --psam or --update-sex. --split-par may also be\nappropriate.\n");
8553 goto BcfToPgen_ret_INCONSISTENT_INPUT;
8554 } else if ((!IsHumanChrset(cip)) || is_splitpar) {
8555 par_warn_bcf_chrom = UINT32_MAX;
8556 }
8557 }
8558 if (sample_ct) {
8559 if (dosage_import_field && strequal_k(dosage_import_field, "DS", dosage_import_field_slen) && (!require_gt)) {
8560 // Only need to initialize this when enforcing DS/haploid rule.
8561 const uint32_t word_ct = BitCtToWordCt(contig_string_idx_end);
8562 if (unlikely(bigstack_alloc_w(word_ct, &bcf_haploid_mask))) {
8563 goto BcfToPgen_ret_NOMEM;
8564 }
8565 if (cip->haploid_mask[0] & 1) {
8566 // all observed chromosomes are haploid
8567 memcpy(bcf_haploid_mask, bcf_contig_keep, word_ct * sizeof(intptr_t));
8568 } else {
8569 // chrX, chrY, and chrM are the affected chromosomes
8570 // bugfix (17 Jun 2022): we should be treating e.g. 23 and chrX
8571 // identically here, rather than only recognizing the latter
8572 ZeroWArr(word_ct, bcf_haploid_mask);
8573 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
8574 const uint32_t mt_code = cip->xymt_codes[kChrOffsetMT];
8575 uint32_t haploid_found = 0;
8576 for (uint32_t widx = 0; widx != word_ct; ++widx) {
8577 uintptr_t cur_word = bcf_contig_keep[widx];
8578 if (cur_word) {
8579 const uint32_t chrom_base = widx * kBitsPerWord;
8580 do {
8581 const uint32_t chrom = chrom_base + ctzw(cur_word);
8582 const uint32_t chr_code_raw = GetChrCodeRaw(contig_names[chrom]);
8583 if (((chr_code_raw < kChrRawX) && ((chr_code_raw == x_code) || (chr_code_raw == y_code) || (chr_code_raw == mt_code))) ||
8584 (chr_code_raw == kChrRawX) || (chr_code_raw == kChrRawY) || (chr_code_raw == kChrRawMT)) {
8585 haploid_found = 1;
8586 SetBit(chrom, bcf_haploid_mask);
8587 }
8588 cur_word &= cur_word - 1;
8589 } while (cur_word);
8590 }
8591 }
8592 if (!haploid_found) {
8593 BigstackReset(bcf_haploid_mask);
8594 bcf_haploid_mask = nullptr;
8595 }
8596 }
8597 }
8598 snprintf(outname_end, kMaxOutfnameExtBlen, ".pgen");
8599 uintptr_t spgw_alloc_cacheline_ct;
8600 uint32_t max_vrec_len;
8601 reterr = SpgwInitPhase1(outname, allele_idx_offsets, nonref_flags, variant_ct, sample_ct, max_allele_ct, kPgenWriteBackwardSeek, phase_dosage_gflags, nonref_flags_storage, &spgw, &spgw_alloc_cacheline_ct, &max_vrec_len);
8602 if (unlikely(reterr)) {
8603 if (reterr == kPglRetOpenFail) {
8604 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
8605 }
8606 goto BcfToPgen_ret_1;
8607 }
8608 unsigned char* spgw_alloc;
8609 if (unlikely(bigstack_alloc_uc(spgw_alloc_cacheline_ct * kCacheline, &spgw_alloc))) {
8610 goto BcfToPgen_ret_NOMEM;
8611 }
8612 SpgwInitPhase2(max_vrec_len, &spgw, spgw_alloc);
8613
8614 if (unlikely(bigstack_alloc_ucp(calc_thread_ct, &ctx.thread_wkspaces) ||
8615 bigstack_alloc_u32(calc_thread_ct + 1, &(ctx.thread_bidxs[0])) ||
8616 bigstack_alloc_u32(calc_thread_ct + 1, &(ctx.thread_bidxs[1])) ||
8617 bigstack_calloc_w(calc_thread_ct, &ctx.err_vrec_idxs))) {
8618 goto BcfToPgen_ret_NOMEM;
8619 }
8620 ctx.bcf_parse_errs = S_CAST(BcfParseErr*, bigstack_alloc_raw_rd(calc_thread_ct * sizeof(BcfParseErr)));
8621 if (unlikely(!ctx.bcf_parse_errs)) {
8622 goto BcfToPgen_ret_NOMEM;
8623 }
8624 ctx.hard_call_halfdist = hard_call_halfdist;
8625 ctx.parse_failed = 0;
8626 // defensive
8627 ctx.gparse[0] = nullptr;
8628 ctx.gparse[1] = nullptr;
8629 ctx.block_allele_idx_offsets[0] = nullptr;
8630 ctx.block_allele_idx_offsets[1] = nullptr;
8631 // Finished with all other memory allocations, so all remaining workspace
8632 // can be spent on multithreaded parsing. Spend up to 1/6 on
8633 // g_thread_wkspaces (tune this fraction later).
8634 // Probable todo: factor out common parts with bgen-1.3 initialization
8635 // into separate function(s).
8636 uint64_t max_write_byte_ct = GparseWriteByteCt(sample_ct, max_allele_ct, gparse_flags);
8637 // always allocate tmp_dphase_delta for now
8638 uint64_t thread_wkspace_cl_ct = DivUp(max_write_byte_ct + sample_ct * sizeof(SDosage), kCacheline);
8639 uintptr_t cachelines_avail = bigstack_left() / (6 * kCacheline);
8640 if (calc_thread_ct * thread_wkspace_cl_ct > cachelines_avail) {
8641 if (unlikely(thread_wkspace_cl_ct > cachelines_avail)) {
8642 goto BcfToPgen_ret_NOMEM;
8643 }
8644 calc_thread_ct = cachelines_avail / thread_wkspace_cl_ct;
8645 }
8646 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
8647 ctx.thread_wkspaces[tidx] = S_CAST(unsigned char*, bigstack_alloc_raw(thread_wkspace_cl_ct * kCacheline));
8648 ctx.bcf_parse_errs[tidx] = kBcfParseOk;
8649 }
8650
8651 // be pessimistic re: rounding
8652 cachelines_avail = (bigstack_left() / kCacheline) - 4;
8653 const uint64_t max_bytes_req_per_variant = sizeof(GparseRecord) + MAXV(max_observed_rec_vecs * S_CAST(uintptr_t, kBytesPerVec), max_write_byte_ct) + calc_thread_ct;
8654 if (unlikely(cachelines_avail * kCacheline < 2 * max_bytes_req_per_variant)) {
8655 goto BcfToPgen_ret_NOMEM;
8656 }
8657 // use worst-case gparse_flags since lines will usually be similar
8658 uintptr_t min_bytes_req_per_variant = sizeof(GparseRecord) + GparseWriteByteCt(sample_ct, 2, gparse_flags);
8659 main_block_size = (cachelines_avail * kCacheline) / (min_bytes_req_per_variant * 2);
8660 // this is arbitrary, there's no connection to kPglVblockSize
8661 if (main_block_size > 65536) {
8662 main_block_size = 65536;
8663 }
8664 // divide by 2 for better parallelism in small-variant-count case
8665 // round up per_thread_block_limit so we only have two blocks
8666 if (main_block_size > DivUp(variant_ct, 2)) {
8667 main_block_size = DivUp(variant_ct, 2) + calc_thread_ct - 1;
8668 }
8669 // may as well guarantee divisibility
8670 per_thread_block_limit = main_block_size / calc_thread_ct;
8671 main_block_size = per_thread_block_limit * calc_thread_ct;
8672 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
8673 goto BcfToPgen_ret_NOMEM;
8674 }
8675 ctx.gparse[0] = S_CAST(GparseRecord*, bigstack_alloc_raw_rd(main_block_size * sizeof(GparseRecord)));
8676 ctx.gparse[1] = S_CAST(GparseRecord*, bigstack_alloc_raw_rd(main_block_size * sizeof(GparseRecord)));
8677 SetThreadFuncAndData(BcfGenoToPgenThread, &ctx, &tg);
8678 cachelines_avail = bigstack_left() / (kCacheline * 2);
8679 geno_bufs[0] = S_CAST(unsigned char*, bigstack_alloc_raw(cachelines_avail * kCacheline));
8680 geno_bufs[1] = S_CAST(unsigned char*, bigstack_alloc_raw(cachelines_avail * kCacheline));
8681 // This is only used for comparison purposes, so it is unnecessary to
8682 // round it down to a multiple of kBytesPerVec even though every actual
8683 // record will be vector-aligned.
8684 per_thread_byte_limit = (cachelines_avail * kCacheline) / calc_thread_ct;
8685 }
8686
8687 vrec_idx = 0;
8688 // Main workflow:
8689 // 1. Set n=0, load genotype data for first main_block_size variants
8690 // while writing .pvar
8691 //
8692 // 2. Spawn threads processing batch n genotype data
8693 // 3. If n>0, write results for block (n-1)
8694 // 4. Increment n by 1
8695 // 5. Load/write-.pvar for batch (n+1) unless eof
8696 // 6. Join threads
8697 // 7. Goto step 2 unless eof
8698 //
8699 // 8. Write results for last block
8700 uint32_t prev_block_write_ct = 0;
8701 uintptr_t record_byte_ct = 0;
8702 uint32_t* thread_bidxs = nullptr;
8703 GparseRecord* cur_gparse = nullptr;
8704 unsigned char* geno_buf_iter = nullptr;
8705 unsigned char* cur_thread_byte_stop = nullptr;
8706
8707 // Placed here since these values need to persist to the next block
8708 // iteration when we run out of geno_bufs[parity] space.
8709 uint32_t chrom = 0;
8710 uint32_t pos = 0;
8711 uint32_t qual_bits = 0;
8712 uint32_t n_allele = 0;
8713 uint32_t n_info = 0;
8714 uint32_t n_fmt = 0;
8715 const unsigned char* shared_end = nullptr;
8716
8717 const unsigned char* gt_start = nullptr;
8718 const unsigned char* qual_starts[2];
8719 qual_starts[0] = nullptr;
8720 qual_starts[1] = nullptr;
8721 const unsigned char* dosage_start = nullptr;
8722 const unsigned char* hds_start = nullptr;
8723 uint32_t gt_type_blen = 0;
8724 uint32_t gt_main_blen = 0;
8725 uint32_t qual_type_blens[2];
8726 uint32_t qual_main_blens[2];
8727 qual_type_blens[0] = 0;
8728 qual_type_blens[1] = 0;
8729 qual_main_blens[0] = 0;
8730 qual_main_blens[1] = 0;
8731 uint32_t dosage_type_blen = 0;
8732 uint32_t dosage_main_blen = 0;
8733 uint32_t hds_type_blen = 0;
8734 uint32_t hds_main_blen = 0;
8735 uint32_t record_input_vec_ct = 0;
8736 uint32_t unflushed_line = 0;
8737
8738 uint32_t parity = 0;
8739 for (uint32_t vidx_start = 0; ; ) {
8740 uint32_t cur_block_write_ct = 0;
8741 if (!IsLastBlock(&tg)) {
8742 const uint32_t block_vidx_limit = variant_ct - vidx_start;
8743 cur_thread_block_vidx_limit = MINV(block_vidx_limit, per_thread_block_limit);
8744 uint32_t cur_thread_fill_idx = 0;
8745 if (sample_ct) {
8746 thread_bidxs = ctx.thread_bidxs[parity];
8747 cur_gparse = ctx.gparse[parity];
8748 if (allele_idx_offsets) {
8749 ctx.block_allele_idx_offsets[parity] = &(allele_idx_offsets[vidx_start]);
8750 }
8751 geno_buf_iter = geno_bufs[parity];
8752 cur_thread_byte_stop = &(geno_buf_iter[per_thread_byte_limit]);
8753 thread_bidxs[0] = 0;
8754 }
8755 uint32_t block_vidx = 0;
8756 uint32_t sidx = 0;
8757 GparseRecord* grp;
8758 if (unflushed_line) {
8759 // We haven't actually written the current .pvar line or copied
8760 // genotype/quality data over.
8761 unflushed_line = 0;
8762 goto BcfToPgen_load_keep;
8763 }
8764 while (1) {
8765 {
8766 ++vrec_idx;
8767 unsigned char* loadbuf_read_iter = loadbuf;
8768 reterr = BgzfRawMtStreamRead(&(loadbuf[32]), &bgzf, &loadbuf_read_iter, &bgzf_errmsg);
8769 if (unlikely(reterr)) {
8770 goto BcfToPgen_ret_BGZF_FAIL_N;
8771 }
8772 if (&(loadbuf[32]) != loadbuf_read_iter) {
8773 DPrintf("read only %" PRIdPTR " out of 32 initial bytes, vrec_idx=%" PRIuPTR "\n", loadbuf_read_iter - loadbuf, vrec_idx);
8774 goto BcfToPgen_ret_REWIND_FAIL_N;
8775 }
8776 // [0]: l_shared
8777 // [1]: l_indiv
8778 // [2]: chrom
8779 // [3]: pos
8780 // [4]: rlen
8781 // [5]: qual, NOT n_allele_info
8782 // [6]: low 16 bits n_info, high 16 bits n_allele
8783 // [7]: low 24 bits n_sample, high 8 bits n_fmt
8784 const uint32_t* vrec_header = R_CAST(uint32_t*, loadbuf);
8785 const uint32_t l_shared = vrec_header[0];
8786 const uint32_t l_indiv = vrec_header[1];
8787 chrom = vrec_header[2];
8788 pos = vrec_header[3];
8789 qual_bits = vrec_header[5];
8790 n_allele = vrec_header[6] >> 16;
8791 n_info = vrec_header[6] & 0xffff;
8792 n_fmt = vrec_header[7] >> 24;
8793 // skip validation performed in first pass
8794 const uint64_t second_load_size = l_shared + S_CAST(uint64_t, l_indiv) - 24;
8795 loadbuf_read_iter = loadbuf;
8796 unsigned char* indiv_end = &(loadbuf[second_load_size]);
8797 reterr = BgzfRawMtStreamRead(indiv_end, &bgzf, &loadbuf_read_iter, &bgzf_errmsg);
8798 if (unlikely(reterr)) {
8799 goto BcfToPgen_ret_BGZF_FAIL_N;
8800 }
8801 if (unlikely(indiv_end != loadbuf_read_iter)) {
8802 DPrintf("read only %" PRIdPTR " out of %" PRIu64 " later bytes, vrec_idx=%" PRIuPTR "\n", loadbuf_read_iter - &(loadbuf[32]), second_load_size - 32, vrec_idx);
8803 goto BcfToPgen_ret_REWIND_FAIL_N;
8804 }
8805
8806 // 1. check if we skip this variant. chromosome filter,
8807 // import_max_allele_ct, and require_gt can cause this.
8808 if ((n_allele > import_max_allele_ct) || (!IsSet(bcf_contig_keep, chrom))) {
8809 continue;
8810 }
8811 const uint32_t fail_on_ds_only = bcf_haploid_mask && IsSet(bcf_haploid_mask, chrom);
8812
8813 // obvious todo: move duplicated code between first and second pass
8814 // into separate functions
8815 shared_end = indiv_end - l_indiv;
8816 const unsigned char* parse_iter = shared_end;
8817
8818 gt_start = nullptr;
8819 qual_starts[0] = nullptr;
8820 qual_starts[1] = nullptr;
8821 dosage_start = nullptr;
8822 hds_start = nullptr;
8823 record_input_vec_ct = 0;
8824 uint32_t gt_exists = 0;
8825 for (uint32_t fmt_idx = 0; fmt_idx != n_fmt; ++fmt_idx) {
8826 // 1. typed int indicating which FORMAT field
8827 // 2. shared type descriptor for each entry (usually a single
8828 // byte)
8829 // 3. sample_ct entries
8830 // previously validated
8831 ScanBcfTypedInt(&parse_iter, &sidx);
8832 const unsigned char* type_start = parse_iter;
8833 uint32_t value_type;
8834 uint32_t value_ct;
8835 ScanBcfType(&parse_iter, &value_type, &value_ct);
8836 const uint32_t bytes_per_elem = kBcfBytesPerElem[value_type];
8837 const uint32_t vec_byte_ct = bytes_per_elem * value_ct * sample_ct;
8838 const uint32_t type_blen = parse_iter - type_start;
8839 parse_iter = &(parse_iter[vec_byte_ct]);
8840 if ((!sidx) || (!value_ct)) {
8841 if (sidx == gt_sidx) {
8842 gt_exists = 1;
8843 }
8844 continue;
8845 }
8846 if (sidx == gt_sidx) {
8847 gt_start = type_start;
8848 gt_type_blen = type_blen;
8849 gt_main_blen = vec_byte_ct;
8850 } else if (sidx == gq_sidx) {
8851 qual_starts[0] = type_start;
8852 qual_type_blens[0] = type_blen;
8853 qual_main_blens[0] = vec_byte_ct;
8854 } else if (sidx == dp_sidx) {
8855 qual_starts[1] = type_start;
8856 qual_type_blens[1] = type_blen;
8857 qual_main_blens[1] = vec_byte_ct;
8858 } else if (sidx == dosage_sidx) {
8859 dosage_start = type_start;
8860 dosage_type_blen = type_blen;
8861 dosage_main_blen = vec_byte_ct;
8862 } else if (sidx == hds_sidx) {
8863 hds_start = type_start;
8864 hds_type_blen = type_blen;
8865 hds_main_blen = vec_byte_ct;
8866 } else {
8867 continue;
8868 }
8869 #ifdef __LP64__
8870 ++record_input_vec_ct;
8871 #else
8872 record_input_vec_ct += DivUp(type_blen, kBytesPerVec);
8873 #endif
8874 record_input_vec_ct += DivUp(vec_byte_ct, kBytesPerVec);
8875 }
8876 if (require_gt && (!gt_exists)) {
8877 continue;
8878 }
8879 // We already have enough information to determine
8880 // write_byte_ct_limit.
8881 if ((!gt_start) && (!dosage_sidx) && (!hds_sidx)) {
8882 gparse_flags = kfGparseNull;
8883 } else {
8884 if ((!phase_or_dosage_found) && (!dosage_sidx) && (!hds_sidx)) {
8885 gparse_flags = kfGparse0;
8886 } else {
8887 if (unlikely(fail_on_ds_only && (!gt_start) && dosage_start && (!hds_start))) {
8888 snprintf(g_logbuf, kLogbufSize, "Error: Variant record #%" PRIuPTR " of --bcf file is for a chrX, chrM, or fully-haploid variant, and has a DS field without a companion GT field to clarify whether each DS value is on a 0..1 or 0..2 scale. This cannot be imported by " PROG_NAME_STR "; please e.g. regenerate the file with GT present.\n", vrec_idx);
8889 goto BcfToPgen_ret_MALFORMED_INPUT_WWN;
8890 }
8891 gparse_flags = (dosage_start || hds_start)? (kfGparseHphase | kfGparseDosage | kfGparseDphase) : kfGparseHphase;
8892 }
8893 }
8894 const uintptr_t write_byte_ct_limit = GparseWriteByteCt(sample_ct, n_allele, gparse_flags);
8895 record_byte_ct = MAXV(record_input_vec_ct * S_CAST(uintptr_t, kBytesPerVec), write_byte_ct_limit);
8896 if ((block_vidx == cur_thread_block_vidx_limit) || (S_CAST(uintptr_t, cur_thread_byte_stop - geno_buf_iter) < record_byte_ct)) {
8897 thread_bidxs[++cur_thread_fill_idx] = block_vidx;
8898 if (cur_thread_fill_idx == calc_thread_ct) {
8899 unflushed_line = 1;
8900 break;
8901 }
8902 cur_thread_byte_stop = &(cur_thread_byte_stop[per_thread_byte_limit]);
8903 cur_thread_block_vidx_limit = MINV(cur_thread_block_vidx_limit + per_thread_block_limit, block_vidx_limit);
8904 }
8905 }
8906 BcfToPgen_load_keep:
8907 // CHROM, POS
8908 pvar_cswritep = memcpyax(pvar_cswritep, contig_out_names[chrom], contig_out_slens[chrom], '\t');
8909 const uint32_t pos1 = pos + 1;
8910 pvar_cswritep = u32toa_x(pos1, '\t', pvar_cswritep);
8911 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
8912 goto BcfToPgen_ret_WRITE_FAIL;
8913 }
8914 if (par_warn_bcf_chrom == chrom) {
8915 if (unlikely((pos1 <= kPAR1IntersectionLast) || (pos1 >= kPAR2IntersectionFirst))) {
8916 putc_unlocked('\n', stdout);
8917 logerrputs("Error: Human chrX pseudoautosomal variant(s) appear to be present in the input\nBCF, but --split-par was not specified.\n");
8918 goto BcfToPgen_ret_INCONSISTENT_INPUT;
8919 }
8920 }
8921
8922 // ID
8923 const unsigned char* parse_iter = loadbuf;
8924 uint32_t slen;
8925 {
8926 const char* id_start;
8927 ScanBcfTypedString(shared_end, &parse_iter, &id_start, &slen);
8928 if (slen) {
8929 pvar_cswritep = memcpya(pvar_cswritep, id_start, slen);
8930 } else {
8931 *pvar_cswritep++ = '.';
8932 }
8933 *pvar_cswritep++ = '\t';
8934 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
8935 goto BcfToPgen_ret_WRITE_FAIL;
8936 }
8937
8938 // REF
8939 const char* ref_start;
8940 ScanBcfTypedString(shared_end, &parse_iter, &ref_start, &slen);
8941 pvar_cswritep = memcpyax(pvar_cswritep, ref_start, slen, '\t');
8942 if (ref_n_missing && (ref_start[0] == 'N') && (slen == 1)) {
8943 pvar_cswritep[-2] = '.';
8944 }
8945
8946 // ALT
8947 if (n_allele == 1) {
8948 *pvar_cswritep++ = '.';
8949 } else {
8950 for (uint32_t allele_idx = 1; allele_idx != n_allele; ++allele_idx) {
8951 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
8952 goto BcfToPgen_ret_WRITE_FAIL;
8953 }
8954 const char* cur_alt_start;
8955 ScanBcfTypedString(shared_end, &parse_iter, &cur_alt_start, &slen);
8956 pvar_cswritep = memcpyax(pvar_cswritep, cur_alt_start, slen, ',');
8957 }
8958 --pvar_cswritep;
8959 }
8960 *pvar_cswritep++ = '\t';
8961
8962 // QUAL
8963 if (S_CAST(int32_t, qual_bits) > 0x7f800000) {
8964 // NaN or missing
8965 // (could have fast path here for inf?)
8966 *pvar_cswritep++ = '.';
8967 } else {
8968 float qual_f;
8969 memcpy(&qual_f, &qual_bits, 4);
8970 pvar_cswritep = ftoa_g(qual_f, pvar_cswritep);
8971 }
8972 *pvar_cswritep++ = '\t';
8973 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
8974 goto BcfToPgen_ret_WRITE_FAIL;
8975 }
8976
8977 // FILTER
8978 uint32_t value_type;
8979 uint32_t value_ct;
8980 ScanBcfType(&parse_iter, &value_type, &value_ct);
8981 if (!value_ct) {
8982 *pvar_cswritep++ = '.';
8983 } else {
8984 const uint32_t value_type_m1 = value_type - 1;
8985 if (!value_type_m1) {
8986 for (uint32_t filter_idx = 0; filter_idx != value_ct; ++filter_idx) {
8987 const uint32_t cur_sidx = parse_iter[filter_idx];
8988 if (cur_sidx == 0x80) {
8989 *pvar_cswritep++ = '.';
8990 } else {
8991 pvar_cswritep = memcpya(pvar_cswritep, fif_strings[cur_sidx], fif_slens[cur_sidx]);
8992 }
8993 *pvar_cswritep++ = ';';
8994 }
8995 } else if (value_type_m1 == 1) {
8996 for (uint32_t filter_idx = 0; filter_idx != value_ct; ++filter_idx) {
8997 const uint32_t cur_sidx = CopyFromUnalignedOffsetU16ZX(parse_iter, filter_idx);
8998 if (cur_sidx == 0x8000) {
8999 *pvar_cswritep++ = '.';
9000 } else {
9001 pvar_cswritep = memcpya(pvar_cswritep, fif_strings[cur_sidx], fif_slens[cur_sidx]);
9002 }
9003 *pvar_cswritep++ = ';';
9004 }
9005 } else {
9006 for (uint32_t filter_idx = 0; filter_idx != value_ct; ++filter_idx) {
9007 uint32_t cur_sidx;
9008 CopyFromUnalignedOffsetU32(&cur_sidx, parse_iter, filter_idx);
9009 if (cur_sidx == 0x80000000U) {
9010 *pvar_cswritep++ = '.';
9011 } else {
9012 pvar_cswritep = memcpya(pvar_cswritep, fif_strings[cur_sidx], fif_slens[cur_sidx]);
9013 }
9014 *pvar_cswritep++ = ';';
9015 }
9016 }
9017 parse_iter = &(parse_iter[value_ct << value_type_m1]);
9018 --pvar_cswritep;
9019 }
9020 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
9021 goto BcfToPgen_ret_WRITE_FAIL;
9022 }
9023
9024 // INFO
9025 if (info_nonpr_exists) {
9026 *pvar_cswritep++ = '\t';
9027 if (!n_info) {
9028 *pvar_cswritep++ = '.';
9029 } else {
9030 for (uint32_t info_idx = 0; info_idx != n_info; ++info_idx) {
9031 ScanBcfTypedInt(&parse_iter, &sidx);
9032 pvar_cswritep = strcpya(pvar_cswritep, fif_strings[sidx]);
9033
9034 ScanBcfType(&parse_iter, &value_type, &value_ct);
9035 const uint32_t bytes_per_elem = kBcfBytesPerElem[value_type];
9036 const uint32_t vec_byte_ct = bytes_per_elem * value_ct;
9037 const unsigned char* cur_vec_start = parse_iter;
9038 parse_iter = &(parse_iter[vec_byte_ct]);
9039 if (value_type == 7) {
9040 // string
9041
9042 // Separated from other cases since we still write '=' when
9043 // value_ct == 0.
9044 *pvar_cswritep++ = '=';
9045
9046 // Unlike most other VCF/BCF fields, spaces are actually
9047 // allowed by the VCF spec here, so we need to detect
9048 // them.
9049 // We error out on them for now (possible todo:
9050 // autoconversion to "%20").
9051 if (unlikely(memchr(cur_vec_start, ' ', value_ct))) {
9052 snprintf(g_logbuf, kLogbufSize, "Error: INFO field in variant record #%" PRIuPTR " of --bcf file contains a space; this cannot be imported by " PROG_NAME_STR ". Remove or reformat the field before reattempting import.\n", vrec_idx);
9053 goto BcfToPgen_ret_MALFORMED_INPUT_WWN;
9054 }
9055 pvar_cswritep = memcpya(pvar_cswritep, cur_vec_start, value_ct);
9056 } else if (value_ct) {
9057 *pvar_cswritep++ = '=';
9058 // ugh. not a separate function for now since no other
9059 // code needs to do this
9060 if (value_type == 1) {
9061 // int8
9062 for (uint32_t value_idx = 0; value_idx != value_ct; ++value_idx) {
9063 const int8_t cur_val = S_CAST(int8_t, cur_vec_start[value_idx]);
9064 if (cur_val != -128) {
9065 pvar_cswritep = i32toa(cur_val, pvar_cswritep);
9066 } else {
9067 *pvar_cswritep++ = '.';
9068 }
9069 *pvar_cswritep++ = ',';
9070 }
9071 } else if (value_type == 2) {
9072 // int16
9073 for (uint32_t value_idx = 0; value_idx != value_ct; ++value_idx) {
9074 int16_t cur_val;
9075 CopyFromUnalignedOffsetI16(&cur_val, cur_vec_start, value_idx);
9076 if (cur_val != -32768) {
9077 pvar_cswritep = i32toa(cur_val, pvar_cswritep);
9078 } else {
9079 *pvar_cswritep++ = '.';
9080 }
9081 *pvar_cswritep++ = ',';
9082 }
9083 } else if (value_type == 3) {
9084 // int32
9085 for (uint32_t value_idx = 0; value_idx != value_ct; ++value_idx) {
9086 int32_t cur_val;
9087 CopyFromUnalignedOffsetI32(&cur_val, cur_vec_start, value_idx);
9088 if (cur_val != (-2147483647 - 1)) {
9089 pvar_cswritep = i32toa(cur_val, pvar_cswritep);
9090 } else {
9091 *pvar_cswritep++ = '.';
9092 }
9093 *pvar_cswritep++ = ',';
9094 }
9095 } else {
9096 // float
9097 for (uint32_t value_idx = 0; value_idx != value_ct; ++value_idx) {
9098 uint32_t cur_bits;
9099 CopyFromUnalignedOffsetU32(&cur_bits, cur_vec_start, value_idx);
9100 if (cur_bits != 0x7f800001) {
9101 float cur_float;
9102 memcpy(&cur_float, &cur_bits, 4);
9103 pvar_cswritep = ftoa_g(cur_float, pvar_cswritep);
9104 } else {
9105 *pvar_cswritep++ = '.';
9106 }
9107 *pvar_cswritep++ = ',';
9108 }
9109 }
9110 --pvar_cswritep;
9111 }
9112 *pvar_cswritep++ = ';';
9113 }
9114 --pvar_cswritep;
9115 }
9116 }
9117 AppendBinaryEoln(&pvar_cswritep);
9118 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
9119 goto BcfToPgen_ret_WRITE_FAIL;
9120 }
9121 if (!sample_ct) {
9122 if (++block_vidx == cur_thread_block_vidx_limit) {
9123 break;
9124 }
9125 continue;
9126 }
9127 }
9128
9129 grp = &(cur_gparse[block_vidx]);
9130 grp->record_start = geno_buf_iter;
9131 grp->flags = gparse_flags;
9132 grp->metadata.read_bcf.qual_vec_offsets[0] = UINT32_MAX;
9133 grp->metadata.read_bcf.qual_vec_offsets[1] = UINT32_MAX;
9134 grp->metadata.read_bcf.gt_vec_offset = UINT32_MAX;
9135 grp->metadata.read_bcf.dosage_vec_offset = UINT32_MAX;
9136 grp->metadata.read_bcf.hds_vec_offset = UINT32_MAX;
9137 grp->metadata.read_bcf.rec_idx = vrec_idx;
9138 uintptr_t copy_vec_offset = 0;
9139 for (uint32_t qual_idx = 0; qual_idx != 2; ++qual_idx) {
9140 if (qual_starts[qual_idx]) {
9141 grp->metadata.read_bcf.qual_vec_offsets[qual_idx] = copy_vec_offset;
9142 const uint32_t type_blen = qual_type_blens[qual_idx];
9143 const unsigned char* src_iter = qual_starts[qual_idx];
9144 memcpy(&(geno_buf_iter[copy_vec_offset * kBytesPerVec]), src_iter, type_blen);
9145 src_iter = &(src_iter[type_blen]);
9146 #ifdef __LP64__
9147 ++copy_vec_offset;
9148 #else
9149 copy_vec_offset += DivUp(type_blen, kBytesPerVec);
9150 #endif
9151 const uint32_t vec_blen = qual_main_blens[qual_idx];
9152 memcpy(&(geno_buf_iter[copy_vec_offset * kBytesPerVec]), src_iter, vec_blen);
9153 copy_vec_offset += DivUp(vec_blen, kBytesPerVec);
9154 }
9155 }
9156 if (gt_start) {
9157 grp->metadata.read_bcf.gt_vec_offset = copy_vec_offset;
9158 const unsigned char* src_iter = gt_start;
9159 memcpy(&(geno_buf_iter[copy_vec_offset * kBytesPerVec]), src_iter, gt_type_blen);
9160 src_iter = &(src_iter[gt_type_blen]);
9161 #ifdef __LP64__
9162 ++copy_vec_offset;
9163 #else
9164 copy_vec_offset += DivUp(gt_type_blen, kBytesPerVec);
9165 #endif
9166 memcpy(&(geno_buf_iter[copy_vec_offset * kBytesPerVec]), src_iter, gt_main_blen);
9167 copy_vec_offset += DivUp(gt_main_blen, kBytesPerVec);
9168 }
9169 if (dosage_start) {
9170 grp->metadata.read_bcf.dosage_vec_offset = copy_vec_offset;
9171 const unsigned char* src_iter = dosage_start;
9172 memcpy(&(geno_buf_iter[copy_vec_offset * kBytesPerVec]), src_iter, dosage_type_blen);
9173 src_iter = &(src_iter[dosage_type_blen]);
9174 #ifdef __LP64__
9175 ++copy_vec_offset;
9176 #else
9177 copy_vec_offset += DivUp(dosage_type_blen, kBytesPerVec);
9178 #endif
9179 memcpy(&(geno_buf_iter[copy_vec_offset * kBytesPerVec]), src_iter, dosage_main_blen);
9180 copy_vec_offset += DivUp(dosage_main_blen, kBytesPerVec);
9181 }
9182 if (hds_start) {
9183 grp->metadata.read_bcf.hds_vec_offset = copy_vec_offset;
9184 const unsigned char* src_iter = hds_start;
9185 memcpy(&(geno_buf_iter[copy_vec_offset * kBytesPerVec]), src_iter, hds_type_blen);
9186 src_iter = &(src_iter[hds_type_blen]);
9187 #ifdef __LP64__
9188 ++copy_vec_offset;
9189 #else
9190 copy_vec_offset += DivUp(hds_type_blen, kBytesPerVec);
9191 #endif
9192 memcpy(&(geno_buf_iter[copy_vec_offset * kBytesPerVec]), src_iter, hds_main_blen);
9193 // copy_vec_offset += DivUp(hds_main_blen, kBytesPerVec);
9194 }
9195 geno_buf_iter = &(geno_buf_iter[record_byte_ct]);
9196 ++block_vidx;
9197
9198 // true iff this is the last variant we're keeping in the entire
9199 // file
9200 if (block_vidx == block_vidx_limit) {
9201 for (; cur_thread_fill_idx != calc_thread_ct; ) {
9202 // save endpoint for current thread, and tell any leftover
9203 // threads to do nothing
9204 thread_bidxs[++cur_thread_fill_idx] = block_vidx;
9205 }
9206 break;
9207 }
9208 }
9209 cur_block_write_ct = block_vidx;
9210 }
9211 if (sample_ct) {
9212 if (vidx_start) {
9213 JoinThreads(&tg);
9214 if (unlikely(ctx.parse_failed)) {
9215 goto BcfToPgen_ret_THREAD_PARSE;
9216 }
9217 }
9218 if (!IsLastBlock(&tg)) {
9219 if (vidx_start + cur_block_write_ct == variant_ct) {
9220 DeclareLastThreadBlock(&tg);
9221 }
9222 if (unlikely(SpawnThreads(&tg))) {
9223 goto BcfToPgen_ret_THREAD_CREATE_FAIL;
9224 }
9225 }
9226 parity = 1 - parity;
9227 if (vidx_start) {
9228 // write *previous* block results
9229 reterr = GparseFlush(ctx.gparse[parity], allele_idx_offsets, prev_block_write_ct, &spgw);
9230 if (unlikely(reterr)) {
9231 goto BcfToPgen_ret_1;
9232 }
9233 }
9234 } else if (vidx_start + cur_block_write_ct == variant_ct) {
9235 break;
9236 }
9237 if (vidx_start == variant_ct) {
9238 break;
9239 }
9240 if (vidx_start) {
9241 printf("\r--bcf: %uk variants converted.", vidx_start / 1000);
9242 if (vidx_start <= main_block_size) {
9243 fputs(" \b\b\b\b", stdout);
9244 }
9245 fflush(stdout);
9246 }
9247 vidx_start += cur_block_write_ct;
9248 prev_block_write_ct = cur_block_write_ct;
9249 }
9250 if (unlikely(CswriteCloseNull(&pvar_css, pvar_cswritep))) {
9251 goto BcfToPgen_ret_WRITE_FAIL;
9252 }
9253 if (sample_ct) {
9254 reterr = SpgwFinish(&spgw);
9255 if (unlikely(reterr)) {
9256 goto BcfToPgen_ret_1;
9257 }
9258 }
9259 putc_unlocked('\r', stdout);
9260 char* write_iter = strcpya_k(g_logbuf, "--bcf: ");
9261 const uint32_t outname_base_slen = outname_end - outname;
9262 if (sample_ct) {
9263 write_iter = memcpya(write_iter, outname, outname_base_slen + 5);
9264 write_iter = strcpya_k(write_iter, " + ");
9265 } else {
9266 *pgen_generated_ptr = 0;
9267 }
9268 write_iter = memcpya(write_iter, outname, outname_base_slen);
9269 write_iter = strcpya_k(write_iter, ".pvar");
9270 if (output_zst) {
9271 write_iter = strcpya_k(write_iter, ".zst");
9272 }
9273 if (sample_ct && (!preexisting_psamname)) {
9274 write_iter = strcpya_k(write_iter, " + ");
9275 write_iter = memcpya(write_iter, outname, outname_base_slen);
9276 write_iter = strcpya_k(write_iter, ".psam");
9277 } else {
9278 *psam_generated_ptr = 0;
9279 }
9280 write_iter = strcpya_k(write_iter, " written");
9281 if (!sample_ct) {
9282 write_iter = strcpya_k(write_iter, " (no samples present)");
9283 }
9284 strcpy_k(write_iter, ".\n");
9285 WordWrapB(0);
9286 logputsb();
9287 }
9288 while (0) {
9289 BcfToPgen_ret_NOMEM:
9290 reterr = kPglRetNomem;
9291 break;
9292 BcfToPgen_ret_OPEN_FAIL:
9293 reterr = kPglRetOpenFail;
9294 break;
9295 BcfToPgen_ret_WRITE_FAIL:
9296 reterr = kPglRetWriteFail;
9297 break;
9298 BcfToPgen_ret_BGZF_FAIL_N:
9299 putc_unlocked('\n', stdout);
9300 BcfToPgen_ret_BGZF_FAIL:
9301 // ReadFail, DecompressFail, ThreadCreateFail, and RewindFail possible.
9302 if (reterr == kPglRetReadFail) {
9303 logerrprintfww(kErrprintfFread, bcfname, rstrerror(errno));
9304 } else if (reterr == kPglRetDecompressFail) {
9305 logerrprintfww(kErrprintfDecompress, bcfname, bgzf_errmsg);
9306 } else if (reterr == kPglRetRewindFail) {
9307 // forgot this case (13 Mar 2024)
9308 logerrprintfww(kErrprintfRewind, "--bcf file");
9309 }
9310 break;
9311 BcfToPgen_ret_REWIND_FAIL_N:
9312 putc_unlocked('\n', stdout);
9313 BcfToPgen_ret_REWIND_FAIL:
9314 logerrprintfww(kErrprintfRewind, "--bcf file");
9315 reterr = kPglRetRewindFail;
9316 break;
9317 BcfToPgen_ret_THREAD_PARSE:
9318 {
9319 // Doesn't really cost us anything to report the first error if multiple
9320 // converter threads error out in the same block, though we can't
9321 // generally guarantee that we'll report the first error in the file.
9322 for (uint32_t tidx = 0; ; ++tidx) {
9323 bcf_parse_err = ctx.bcf_parse_errs[tidx];
9324 if (bcf_parse_err) {
9325 vrec_idx = ctx.err_vrec_idxs[tidx];
9326 break;
9327 }
9328 }
9329 }
9330 BcfToPgen_ret_PARSE:
9331 if (bcf_parse_err == kBcfParseHalfCallError) {
9332 putc_unlocked('\n', stdout);
9333 logerrprintf("Error: Variant record #%" PRIuPTR " of --bcf file has a GT half-call.\n", vrec_idx);
9334 if (!half_call_explicit_error) {
9335 logerrputs("Use --vcf-half-call to specify how these should be processed.\n");
9336 }
9337 reterr = kPglRetMalformedInput;
9338 break;
9339 } else if (bcf_parse_err == kBcfParseInvalidDosage) {
9340 // probable todo: distinguish HDS errors (right now, it just prints
9341 // "invalid DS field" on all HDS errors).
9342 putc_unlocked('\n', stdout);
9343 logerrprintfww("Error: Variant record #%" PRIuPTR " of --bcf file has an invalid %s field.\n", vrec_idx, dosage_import_field);
9344 reterr = kPglRetInconsistentInput;
9345 break;
9346 } else if (bcf_parse_err == kBcfParsePolyploidError) {
9347 putc_unlocked('\n', stdout);
9348 logerrprintfww("Error: Variant record #%" PRIuPTR " of --bcf file has a polyploid genotype.%s\n", vrec_idx, (import_flags & kfImportPolyploidExplicitError)? "" : " (Use '--polyploid-mode missing' to treat these as missing values.)");
9349 reterr = kPglRetInconsistentInput;
9350 } else if (bcf_parse_err == kBcfParseWideGt) {
9351 putc_unlocked('\n', stdout);
9352 logerrprintfww("Error: Variant record #%" PRIuPTR " of --bcf file uses unexpectedly-wide integers for the GT field; only int8s are currently supported for n_allele < 64, and int16s for n_allele in [64, 16383].\n", vrec_idx);
9353 reterr = kPglRetNotYetSupported;
9354 break;
9355 } else if (bcf_parse_err == kBcfParseFloatDp) {
9356 putc_unlocked('\n', stdout);
9357 logerrprintfww("Error: Variant record #%" PRIuPTR " of --bcf file has a floating-point DP field; only integers are supported for now.\n", vrec_idx);
9358 reterr = kPglRetNotYetSupported;
9359 break;
9360 } else if (bcf_parse_err == kBcfParseNonfloatDosage) {
9361 putc_unlocked('\n', stdout);
9362 logerrprintfww("Error: Variant record #%" PRIuPTR " of --bcf file has a dosage field that isn't of Float type; this isn't currently supported.\n", vrec_idx);
9363 reterr = kPglRetNotYetSupported;
9364 break;
9365 }
9366 // kBcfParseMalformedGeneric
9367 BcfToPgen_ret_VREC_GENERIC:
9368 putc_unlocked('\n', stdout);
9369 logerrprintf("Error: Variant record #%" PRIuPTR " of --bcf file is malformed.\n", vrec_idx);
9370 reterr = kPglRetMalformedInput;
9371 break;
9372 BcfToPgen_ret_MALFORMED_INPUT_2:
9373 logerrputsb();
9374 BcfToPgen_ret_MALFORMED_INPUT:
9375 reterr = kPglRetMalformedInput;
9376 break;
9377 BcfToPgen_ret_MALFORMED_INPUT_WWN:
9378 putc_unlocked('\n', stdout);
9379 BcfToPgen_ret_MALFORMED_INPUT_WW:
9380 WordWrapB(0);
9381 logerrputsb();
9382 reterr = kPglRetMalformedInput;
9383 break;
9384 BcfToPgen_ret_MALFORMED_INPUT_GENERIC:
9385 logerrputs("Error: Malformed BCF file.\n");
9386 reterr = kPglRetMalformedInput;
9387 break;
9388 BcfToPgen_ret_MALFORMED_TEXT_HEADER:
9389 logerrputs("Error: Malformed BCF text header block.\n");
9390 reterr = kPglRetMalformedInput;
9391 break;
9392 BcfToPgen_ret_INCONSISTENT_INPUT:
9393 reterr = kPglRetInconsistentInput;
9394 break;
9395 BcfToPgen_ret_THREAD_CREATE_FAIL:
9396 reterr = kPglRetThreadCreateFail;
9397 break;
9398 BcfToPgen_ret_DEGENERATE_DATA:
9399 reterr = kPglRetDegenerateData;
9400 break;
9401 }
9402 BcfToPgen_ret_1:
9403 CleanupSpgw(&spgw, &reterr);
9404 CleanupThreads(&tg);
9405 CswriteCloseCond(&pvar_css, pvar_cswritep);
9406 CleanupBgzfRawMtStream(&bgzf);
9407 fclose_cond(bcffile);
9408 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
9409 return reterr;
9410 }
9411
9412
9413 ENUM_U31_DEF_START()
9414 kOxSampleColSkip, // processed during first pass
9415 kOxSampleColParent,
9416 kOxSampleColCatUnknown,
9417 kOxSampleColSex,
9418 kOxSampleColBinary,
9419 kOxSampleColQuantitative,
9420 kOxSampleColCatNumeric,
9421 kOxSampleColCatNames,
9422 ENUM_U31_DEF_END(OxSampleCol);
9423
9424 static_assert(5 * kMaxIdBlen <= kDecompressChunkSize, "OxSampleToPsam needs FID+IID+SID+PAT+MAT to fit in writebuf.");
9425 PglErr OxSampleToPsam(const char* samplename, const char* const_fid, const char* ox_missing_code, const char* missing_catname, MiscFlags misc_flags, ImportFlags import_flags, uint32_t psam_01, char id_delim, char* outname, char* outname_end, uint32_t* sample_ct_ptr) {
9426 unsigned char* bigstack_mark = g_bigstack_base;
9427 unsigned char* bigstack_end_mark = g_bigstack_end;
9428 FILE* psamfile = nullptr;
9429 PglErr reterr = kPglRetSuccess;
9430 uintptr_t line_idx = 0;
9431 TextStream sample_txs;
9432 PreinitTextStream(&sample_txs);
9433 {
9434 uint32_t missing_catname_slen = strlen(missing_catname);
9435
9436 uint32_t max_line_blen;
9437 if (unlikely(StandardizeMaxLineBlen(bigstack_left() / 4, &max_line_blen))) {
9438 goto OxSampleToPsam_ret_NOMEM;
9439 }
9440 reterr = InitTextStream(samplename, max_line_blen, 1, &sample_txs);
9441 if (unlikely(reterr)) {
9442 if (reterr == kPglRetOpenFail) {
9443 const uint32_t slen = strlen(samplename);
9444 if ((!StrEndsWith(samplename, ".sample", slen)) &&
9445 (!StrEndsWith(samplename, ".sample.gz", slen))) {
9446 logerrprintfww("Error: Failed to open %s : %s. (--sample expects a complete filename; did you forget '.sample' at the end?)\n", samplename, strerror(errno));
9447 goto OxSampleToPsam_ret_1;
9448 }
9449 }
9450 goto OxSampleToPsam_ret_TSTREAM_FAIL;
9451 }
9452 uint32_t mc_ct = 0;
9453 uintptr_t max_mc_blen = 1;
9454 char* sorted_mc = nullptr;
9455 if (!ox_missing_code) {
9456 if (unlikely(bigstack_alloc_c(3, &sorted_mc))) {
9457 goto OxSampleToPsam_ret_NOMEM;
9458 }
9459 strcpy_k(sorted_mc, "NA");
9460 mc_ct = 1;
9461 max_mc_blen = 3;
9462 } else {
9463 // er, this should use something like
9464 // CountAndMeasureMultistrReverseAlloc()...
9465 const char* missing_code_iter = ox_missing_code;
9466 while (*missing_code_iter) {
9467 while (*missing_code_iter == ',') {
9468 ++missing_code_iter;
9469 }
9470 if (!(*missing_code_iter)) {
9471 break;
9472 }
9473 ++mc_ct;
9474 const char* token_end = strchrnul(missing_code_iter, ',');
9475 uintptr_t token_slen = token_end - missing_code_iter;
9476 if (token_slen >= max_mc_blen) {
9477 max_mc_blen = token_slen + 1;
9478 }
9479 missing_code_iter = token_end;
9480 }
9481 if (mc_ct) {
9482 if (unlikely(bigstack_alloc_c(mc_ct * max_mc_blen, &sorted_mc))) {
9483 goto OxSampleToPsam_ret_NOMEM;
9484 }
9485 missing_code_iter = ox_missing_code;
9486 for (uintptr_t mc_idx = 0; mc_idx != mc_ct; ++mc_idx) {
9487 while (*missing_code_iter == ',') {
9488 ++missing_code_iter;
9489 }
9490 const char* token_end = strchrnul(missing_code_iter, ',');
9491 uintptr_t token_slen = token_end - missing_code_iter;
9492 memcpyx(&(sorted_mc[mc_idx * max_mc_blen]), missing_code_iter, token_slen, '\0');
9493 missing_code_iter = token_end;
9494 }
9495 // this was temporarily broken in June 2018 due to first
9496 // strcmp_overread() implementation returning 0 instead of -1 on
9497 // less-than
9498 qsort(sorted_mc, mc_ct, max_mc_blen, strcmp_overread_casted);
9499 }
9500 }
9501
9502 // First pass: Validate header rows, load ID and father/mother columns if
9503 // present, check for all-missing phenotype columns.
9504 line_idx = 1;
9505 char* line_start = TextGet(&sample_txs);
9506 if (unlikely(!line_start)) {
9507 if (TextStreamErrcode2(&sample_txs, &reterr)) {
9508 goto OxSampleToPsam_ret_TSTREAM_FAIL;
9509 }
9510 logerrputs("Error: Empty .sample file.\n");
9511 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9512 }
9513 char* token_end = CurTokenEnd(line_start);
9514 // Update (31 Aug 2020): First column is now treated as ID, with any column
9515 // name allowed, to support QCTOOLv2's .sample dialect.
9516 // Tolerate tab delimiter for now, though .sample spec technically
9517 // prohibits that.
9518 char* linebuf_iter = FirstNonTspace(token_end);
9519 uint32_t token_slen = strlen_se(linebuf_iter);
9520 const uint32_t id2_exists = strequal_k(linebuf_iter, "ID_2", token_slen);
9521 uint32_t col_ct = 1;
9522 if (id2_exists) {
9523 linebuf_iter = FirstNonTspace(&(linebuf_iter[token_slen]));
9524 id_delim = ' '; // this guarantees no conflict
9525 ++col_ct;
9526 }
9527 // 0 = not present, otherwise zero-based index; this is fine since first
9528 // column has to be (part of) sample ID
9529 uint32_t missing_col = 0;
9530 uint32_t father_col = 0;
9531 uint32_t mother_col = 0;
9532 uint32_t sex_col = 0;
9533 while (!IsEolnKns(*linebuf_iter)) {
9534 token_end = CurTokenEnd(linebuf_iter);
9535 token_slen = token_end - linebuf_iter;
9536 if (token_slen == 3) {
9537 if (MatchUpperK(linebuf_iter, "SEX")) {
9538 if (unlikely(sex_col)) {
9539 logerrputs("Error: Multiple sex columns in .sample file.\n");
9540 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9541 }
9542 sex_col = col_ct;
9543 }
9544 } else if (token_slen == 4) {
9545 if (unlikely(memequal(linebuf_iter, "ID_2", 4))) {
9546 if (id2_exists) {
9547 logerrputs("Error: Multiple 'ID_2' columns in .sample file.\n");
9548 } else {
9549 logerrputs("Error: Improperly positioned 'ID_2' column in .sample file (must be second).\n");
9550 }
9551 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9552 }
9553 } else if (token_slen == 6) {
9554 if (MatchUpperK(linebuf_iter, "FATHER")) {
9555 if (unlikely(father_col)) {
9556 logerrputs("Error: Multiple 'father' columns in .sample file.\n");
9557 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9558 }
9559 father_col = col_ct;
9560 } else if (MatchUpperK(linebuf_iter, "MOTHER")) {
9561 if (unlikely(mother_col)) {
9562 logerrputs("Error: Multiple 'mother' columns in .sample file.\n");
9563 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9564 }
9565 mother_col = col_ct;
9566 }
9567 } else if (MatchUpperKLen(linebuf_iter, "MISSING", token_slen)) {
9568 if (unlikely(missing_col)) {
9569 logerrputs("Error: Multiple 'missing' columns in .sample file.\n");
9570 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9571 }
9572 missing_col = col_ct;
9573 }
9574 ++col_ct;
9575 linebuf_iter = FirstNonTspace(token_end);
9576 }
9577 const uint32_t col_ctl = BitCtToWordCt(col_ct);
9578 uintptr_t* col_first_pass_remaining;
9579 uintptr_t* col_nm;
9580 unsigned char* col_types;
9581 // bugfix (21 Sep 2023): forgot to 0-initialize col_first_pass_remaining
9582 if (unlikely(bigstack_calloc_w(col_ctl, &col_first_pass_remaining) ||
9583 bigstack_calloc_w(col_ctl, &col_nm) ||
9584 bigstack_alloc_uc(col_ct, &col_types))) {
9585 goto OxSampleToPsam_ret_NOMEM;
9586 }
9587 if (col_ct > 1 + id2_exists) {
9588 FillBitsNz(1 + id2_exists, col_ct, col_first_pass_remaining);
9589 }
9590 ++line_idx;
9591 linebuf_iter = TextGet(&sample_txs);
9592 if (unlikely(!linebuf_iter)) {
9593 if (!TextStreamErrcode2(&sample_txs, &reterr)) {
9594 logerrputs("Error: Only one line in .sample file.\n");
9595 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9596 }
9597 goto OxSampleToPsam_ret_TSTREAM_FAIL;
9598 }
9599 uint32_t at_least_one_binary_pheno = 0;
9600 uint32_t initial_skip_col_ct = 0;
9601 for (uint32_t col_idx = 0; col_idx != col_ct; ++col_idx) {
9602 linebuf_iter = FirstNonTspace(linebuf_iter);
9603 const unsigned char col_type_char = *linebuf_iter;
9604 if (unlikely(IsEolnKns(col_type_char))) {
9605 logerrputs("Error: Second .sample header line has fewer tokens than the first.\n");
9606 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9607 }
9608 if (unlikely(!IsEolnKns(linebuf_iter[1]))) {
9609 *CurTokenEnd(linebuf_iter) = '\0';
9610 snprintf(g_logbuf, kLogbufSize, "Error: Unrecognized .sample variable type '%s'.\n", linebuf_iter);
9611 goto OxSampleToPsam_ret_MALFORMED_INPUT_WW;
9612 }
9613 // can make this table-driven
9614 OxSampleCol cur_col_type;
9615 if (col_type_char == 'D') {
9616 cur_col_type = kOxSampleColCatUnknown;
9617 } else if (col_type_char == 'B') {
9618 at_least_one_binary_pheno = 1;
9619 cur_col_type = kOxSampleColBinary;
9620 } else if ((col_type_char == 'C') || (col_type_char == 'P')) {
9621 cur_col_type = kOxSampleColQuantitative;
9622 } else if (likely(col_type_char == '0')) {
9623 ++initial_skip_col_ct;
9624 cur_col_type = kOxSampleColSkip;
9625 } else {
9626 snprintf(g_logbuf, kLogbufSize, "Error: Unrecognized .sample variable type '%c'.\n", col_type_char);
9627 goto OxSampleToPsam_ret_MALFORMED_INPUT_2;
9628 }
9629 col_types[col_idx] = cur_col_type;
9630 ++linebuf_iter;
9631 }
9632 linebuf_iter = FirstNonTspace(linebuf_iter);
9633 if (unlikely(!IsEolnKns(*linebuf_iter))) {
9634 logerrputs("Error: Second .sample header line has more tokens than the first.\n");
9635 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9636 }
9637 if (unlikely(col_types[0] != kOxSampleColSkip)) {
9638 logerrputs("Error: First column of second .sample header line must have type '0'.\n");
9639 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9640 }
9641 if (id2_exists) {
9642 if (unlikely(col_types[1] != kOxSampleColSkip)) {
9643 logerrputs("Error: ID_2 column in .sample file doesn't have type '0'.\n");
9644 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9645 }
9646 }
9647 if (missing_col) {
9648 if (unlikely(col_types[missing_col] != kOxSampleColSkip)) {
9649 logerrputs("Error: 'missing' column in .sample file doesn't have type '0'.\n");
9650 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9651 }
9652 ClearBit(missing_col, col_first_pass_remaining);
9653 }
9654 if (initial_skip_col_ct != 1 + id2_exists + (missing_col != 0)) {
9655 logerrputs("Error: Only ID and 'missing' columns are permitted to have type '0' in .sample\nfiles.\n");
9656 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9657 }
9658 if (father_col) {
9659 if (unlikely(col_types[father_col] != kOxSampleColCatUnknown)) {
9660 logerrputs("Error: .sample 'father' column is not of type 'D'.\n");
9661 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9662 }
9663 col_types[father_col] = kOxSampleColParent;
9664 }
9665 if (mother_col) {
9666 if (unlikely(col_types[mother_col] != kOxSampleColCatUnknown)) {
9667 logerrputs("Error: .sample 'mother' column is not of type 'D'.\n");
9668 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9669 }
9670 col_types[mother_col] = kOxSampleColParent;
9671 }
9672 if (sex_col) {
9673 if (unlikely(col_types[sex_col] != kOxSampleColCatUnknown)) {
9674 logerrputs("Error: .sample sex column is not of type 'D'.\n");
9675 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9676 }
9677 col_types[sex_col] = kOxSampleColSex;
9678 SetBit(sex_col, col_nm);
9679 ClearBit(sex_col, col_first_pass_remaining);
9680 }
9681 if (at_least_one_binary_pheno) {
9682 if (unlikely((bsearch_strbox("0", sorted_mc, 1, max_mc_blen, mc_ct) != -1) || (bsearch_strbox("1", sorted_mc, 1, max_mc_blen, mc_ct) != -1))) {
9683 logerrputs("Error: '0' and '1' are unacceptable missing case/control phenotype codes.\n");
9684 goto OxSampleToPsam_ret_INCONSISTENT_INPUT;
9685 }
9686 }
9687 ImportSampleIdContext isic;
9688 InitImportSampleIdContext(const_fid, misc_flags, import_flags, id_delim, &isic);
9689 unsigned char* tmp_alloc_base = g_bigstack_base;
9690 unsigned char* tmp_alloc_end = BigstackEndRoundedDown();
9691 char* all_ids_start = R_CAST(char*, tmp_alloc_base);
9692 const uint32_t parental_col_exists = father_col || mother_col;
9693 // doesn't include ID
9694 const uint32_t first_pass_main_col_ct = PopcountWords(col_first_pass_remaining, col_ctl);
9695 uint32_t first_pass_finished_col_ct = 0;
9696 char* father_start = nullptr;
9697 char* mother_start = nullptr;
9698 uint32_t father_slen = 0;
9699 uint32_t mother_slen = 0;
9700 while (1) {
9701 ++line_idx;
9702 line_start = TextGet(&sample_txs);
9703 if (!line_start) {
9704 if (likely(!TextStreamErrcode2(&sample_txs, &reterr))) {
9705 break;
9706 }
9707 goto OxSampleToPsam_ret_TSTREAM_FAIL;
9708 }
9709 token_end = CurTokenEnd(line_start);
9710 const uintptr_t col1_slen = token_end - line_start;
9711 if (id2_exists) {
9712 char* iid_start = FirstNonTspace(token_end);
9713 if (unlikely(IsEolnKns(*iid_start))) {
9714 goto OxSampleToPsam_ret_MISSING_TOKENS;
9715 }
9716 char* iid_end = CurTokenEnd(iid_start);
9717 const uintptr_t col2_slen = iid_end - iid_start;
9718 if (unlikely(col1_slen + 1 + col2_slen >= S_CAST(uintptr_t, tmp_alloc_end - tmp_alloc_base))) {
9719 goto OxSampleToPsam_ret_NOMEM;
9720 }
9721 tmp_alloc_base = memcpyua(tmp_alloc_base, line_start, col1_slen);
9722 *tmp_alloc_base++ = ' ';
9723 tmp_alloc_base = memcpyua(tmp_alloc_base, iid_start, col2_slen);
9724 token_end = iid_end;
9725 } else {
9726 if (unlikely(col1_slen >= S_CAST(uintptr_t, tmp_alloc_end - tmp_alloc_base))) {
9727 goto OxSampleToPsam_ret_NOMEM;
9728 }
9729 tmp_alloc_base = memcpyua(tmp_alloc_base, line_start, col1_slen);
9730 }
9731 *tmp_alloc_base++ = '\0';
9732 uintptr_t col_uidx_base = 0;
9733 uintptr_t cur_bits = col_first_pass_remaining[0];
9734 uint32_t prev_col_uidx = id2_exists;
9735 for (uint32_t uii = first_pass_finished_col_ct; uii != first_pass_main_col_ct; ++uii) {
9736 const uint32_t col_uidx = BitIter1(col_first_pass_remaining, &col_uidx_base, &cur_bits);
9737 linebuf_iter = NextTokenMult(token_end, col_uidx - prev_col_uidx);
9738 if (unlikely(!linebuf_iter)) {
9739 goto OxSampleToPsam_ret_MISSING_TOKENS;
9740 }
9741 prev_col_uidx = col_uidx;
9742 token_end = CurTokenEnd(linebuf_iter);
9743 token_slen = token_end - linebuf_iter;
9744 const OxSampleCol cur_col_type = S_CAST(OxSampleCol, col_types[col_uidx]);
9745 if (bsearch_strbox(linebuf_iter, sorted_mc, token_slen, max_mc_blen, mc_ct) != -1) {
9746 // Missing value.
9747 if (cur_col_type == kOxSampleColParent) {
9748 if (col_uidx == father_col) {
9749 father_start = nullptr;
9750 } else {
9751 mother_start = nullptr;
9752 }
9753 }
9754 continue;
9755 }
9756 if (cur_col_type == kOxSampleColCatUnknown) {
9757 if (IsCategoricalPhenostrNocsv(linebuf_iter)) {
9758 col_types[col_uidx] = kOxSampleColCatNames;
9759 } else {
9760 // Assume this is a column of positive integers. If this
9761 // assumption is false, we'll detect the problem during the second
9762 // pass.
9763 col_types[col_uidx] = kOxSampleColCatNumeric;
9764 }
9765 SetBit(col_uidx, col_nm);
9766 ClearBit(col_uidx, col_first_pass_remaining);
9767 ++first_pass_finished_col_ct;
9768 } else if ((cur_col_type == kOxSampleColBinary) || (cur_col_type == kOxSampleColQuantitative)) {
9769 SetBit(col_uidx, col_nm);
9770 ClearBit(col_uidx, col_first_pass_remaining);
9771 ++first_pass_finished_col_ct;
9772 } else if (cur_col_type == kOxSampleColParent) {
9773 if (col_uidx == father_col) {
9774 father_start = linebuf_iter;
9775 father_slen = token_end - linebuf_iter;
9776 } else {
9777 mother_start = linebuf_iter;
9778 mother_slen = token_end - linebuf_iter;
9779 }
9780 }
9781 }
9782 if (parental_col_exists) {
9783 if (father_start) {
9784 tmp_alloc_base = memcpyua(tmp_alloc_base, father_start, father_slen);
9785 *tmp_alloc_base++ = '\0';
9786 } else {
9787 tmp_alloc_base = memcpyua(tmp_alloc_base, "0", 2);
9788 }
9789 if (mother_start) {
9790 tmp_alloc_base = memcpyua(tmp_alloc_base, mother_start, mother_slen);
9791 *tmp_alloc_base++ = '\0';
9792 } else {
9793 tmp_alloc_base = memcpyua(tmp_alloc_base, "0", 2);
9794 }
9795 }
9796 }
9797 BigstackBaseSet(tmp_alloc_base);
9798 if (unlikely(line_idx > 0x80000001U)) {
9799 logerrputs("Error: " PROG_NAME_STR " does not support more than 2^31 - 2 samples.\n");
9800 goto OxSampleToPsam_ret_MALFORMED_INPUT;
9801 }
9802 const uint32_t sample_ct = line_idx - 3;
9803 if (unlikely(!sample_ct)) {
9804 logerrputs("Error: No samples in .sample file.\n");
9805 goto OxSampleToPsam_ret_DEGENERATE_DATA;
9806 }
9807 const char* all_ids_iter = all_ids_start;
9808 uint32_t nz_fid_exists = 0;
9809 uint32_t nz_sid_exists = 0;
9810 uint32_t nz_parent_exists = 0;
9811 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
9812 if (id_delim) {
9813 if (id2_exists) {
9814 // fast path for original case
9815 if (!nz_fid_exists) {
9816 nz_fid_exists = !memequal(all_ids_iter, "0 ", 2);
9817 }
9818 all_ids_iter = strnul(all_ids_iter);
9819 } else {
9820 const char* first_part_end = strchrnul(all_ids_iter, id_delim);
9821 if (unlikely(!(*first_part_end))) {
9822 logerrprintfww("Error: No instances of --id-delim argument '%c' in sample ID '%s'.\n", id_delim, all_ids_iter);
9823 goto OxSampleToPsam_ret_INCONSISTENT_INPUT;
9824 }
9825 const char* second_part_start = &(first_part_end[1]);
9826 const char* second_part_end = strchrnul(second_part_start, id_delim);
9827 if (*second_part_end) {
9828 const char* third_part_start = &(second_part_end[1]);
9829 const char* third_part_end = strchrnul(third_part_start, id_delim);
9830 if (unlikely(*third_part_end)) {
9831 logerrprintfww("Error: Too many instances of --id-delim argument '%c' in sample ID '%s'.\n", id_delim, all_ids_iter);
9832 goto OxSampleToPsam_ret_INCONSISTENT_INPUT;
9833 }
9834 if (!nz_fid_exists) {
9835 nz_fid_exists = (S_CAST(uintptr_t, first_part_end - all_ids_iter) != 1) || (*all_ids_iter != '0');
9836 }
9837 if (!nz_sid_exists) {
9838 nz_sid_exists = (S_CAST(uintptr_t, third_part_end - third_part_start) != 1) || (*third_part_start != '0');
9839 }
9840 all_ids_iter = third_part_end;
9841 } else {
9842 if (!isic.id_delim_sid) {
9843 if (!nz_fid_exists) {
9844 nz_fid_exists = (S_CAST(uintptr_t, first_part_end - all_ids_iter) != 1) || (*all_ids_iter != '0');
9845 }
9846 } else {
9847 if (!nz_sid_exists) {
9848 nz_sid_exists = (S_CAST(uintptr_t, second_part_end - second_part_start) != 1) || (*second_part_start != '0');
9849 }
9850 }
9851 all_ids_iter = second_part_end;
9852 }
9853 }
9854 } else {
9855 all_ids_iter = strnul(all_ids_iter);
9856 }
9857 ++all_ids_iter;
9858 if (parental_col_exists) {
9859 const char* paternal_id_end = strnul(all_ids_iter);
9860 const char* maternal_id_start = &(paternal_id_end[1]);
9861 const char* maternal_id_end = strnul(maternal_id_start);
9862 if (!nz_parent_exists) {
9863 // octal
9864 nz_parent_exists = !memequal(all_ids_iter, "\60\0\60", 4);
9865 }
9866 all_ids_iter = &(maternal_id_end[1]);
9867 }
9868 }
9869 // This overlaps with VcfSampleLine(); probably want to pull this into its
9870 // own function.
9871 if (id_delim) {
9872 if (!nz_fid_exists) {
9873 isic.omit_fid_0 = 1;
9874 }
9875 } else if ((!isic.const_fid) && (!isic.double_id)) {
9876 nz_fid_exists = 0;
9877 }
9878
9879 snprintf(outname_end, kMaxOutfnameExtBlen, ".psam");
9880 if (unlikely(fopen_checked(outname, FOPEN_WB, &psamfile))) {
9881 goto OxSampleToPsam_ret_OPEN_FAIL;
9882 }
9883 // We add col_ct, since positive-integer categorical phenotypes are
9884 // lengthened by 1 character ('C' added in front). (This bound can easily
9885 // be tightened, but it should practically never matter.)
9886 uintptr_t linebuf_size = max_line_blen + col_ct + kDecompressChunkSize;
9887 linebuf_size = MINV(linebuf_size, kMaxLongLine);
9888 char* writebuf;
9889 if (unlikely(bigstack_alloc_c(linebuf_size, &writebuf))) {
9890 goto OxSampleToPsam_ret_NOMEM;
9891 }
9892 char* write_iter = writebuf;
9893 *write_iter++ = '#';
9894 if (nz_fid_exists) {
9895 write_iter = strcpya_k(write_iter, "FID\t");
9896 }
9897 write_iter = strcpya_k(write_iter, "IID");
9898 if (nz_sid_exists) {
9899 write_iter = strcpya_k(write_iter, "\tSID");
9900 if (nz_fid_exists || isic.omit_fid_0) {
9901 isic.two_part_null_fid = isic.id_delim_sid;
9902 isic.two_part_null_sid = 1 - isic.id_delim_sid;
9903 }
9904 }
9905 if (nz_parent_exists) {
9906 write_iter = strcpya_k(write_iter, "\tPAT\tMAT");
9907 }
9908 write_iter = strcpya_k(write_iter, "\tSEX");
9909
9910 reterr = TextRewind(&sample_txs);
9911 if (unlikely(reterr)) {
9912 goto OxSampleToPsam_ret_TSTREAM_FAIL;
9913 }
9914 line_idx = 1;
9915 line_start = TextGet(&sample_txs);
9916 if (unlikely(!line_start)) {
9917 goto OxSampleToPsam_ret_TSTREAM_REWIND_FAIL;
9918 }
9919 token_end = line_start;
9920 for (uint32_t col_idx = 0; col_idx != col_ct; ++col_idx) {
9921 linebuf_iter = FirstNonTspace(token_end);
9922 if (unlikely(IsEolnKns(*linebuf_iter))) {
9923 goto OxSampleToPsam_ret_REWIND_FAIL;
9924 }
9925 token_end = CurTokenEnd(linebuf_iter);
9926 const OxSampleCol cur_col_type = S_CAST(OxSampleCol, col_types[col_idx]);
9927 if (cur_col_type > kOxSampleColSex) {
9928 if (IsSet(col_nm, col_idx)) {
9929 *write_iter++ = '\t';
9930 write_iter = memcpya(write_iter, linebuf_iter, token_end - linebuf_iter);
9931 }
9932 }
9933 }
9934 AppendBinaryEoln(&write_iter);
9935 if (unlikely(fwrite_checked(writebuf, write_iter - writebuf, psamfile))) {
9936 goto OxSampleToPsam_ret_WRITE_FAIL;
9937 }
9938 ++line_idx;
9939 line_start = TextGet(&sample_txs);
9940 if (unlikely(!line_start)) {
9941 goto OxSampleToPsam_ret_TSTREAM_REWIND_FAIL;
9942 }
9943 all_ids_iter = all_ids_start;
9944 const char ctrl_outchar = '1' - psam_01;
9945 const char case_outchar = ctrl_outchar + 1;
9946 line_start = TextGet(&sample_txs);
9947 for (; line_start; line_start = TextGet(&sample_txs)) {
9948 ++line_idx;
9949 write_iter = writebuf;
9950 const char* sample_id_end = strnul(all_ids_iter);
9951 reterr = ImportSampleId(all_ids_iter, sample_id_end, &isic, &write_iter);
9952 all_ids_iter = &(sample_id_end[1]);
9953 if (parental_col_exists) {
9954 const char* paternal_id_end = strnul(all_ids_iter);
9955 if (nz_parent_exists) {
9956 *write_iter++ = '\t';
9957 write_iter = memcpya(write_iter, all_ids_iter, paternal_id_end - all_ids_iter);
9958 }
9959 all_ids_iter = &(paternal_id_end[1]);
9960 const char* maternal_id_end = strnul(all_ids_iter);
9961 if (nz_parent_exists) {
9962 *write_iter++ = '\t';
9963 write_iter = memcpya(write_iter, all_ids_iter, maternal_id_end - all_ids_iter);
9964 }
9965 all_ids_iter = &(maternal_id_end[1]);
9966 }
9967 // flush now since backfilled sex is variable-length ("NA" vs. "1"/"2")
9968 if (unlikely(fwrite_checked(writebuf, write_iter - writebuf, psamfile))) {
9969 goto OxSampleToPsam_ret_WRITE_FAIL;
9970 }
9971
9972 char* cur_writebuf_start = writebuf;
9973 write_iter = strcpya_k(writebuf, "\tNA");
9974 token_end = line_start;
9975 for (uint32_t col_idx = 0; col_idx != col_ct; ++col_idx) {
9976 linebuf_iter = FirstNonTspace(token_end);
9977 if (unlikely(IsEolnKns(*linebuf_iter))) {
9978 goto OxSampleToPsam_ret_MISSING_TOKENS;
9979 }
9980 token_end = CurTokenEnd(linebuf_iter);
9981 const OxSampleCol cur_col_type = S_CAST(OxSampleCol, col_types[col_idx]);
9982 if ((cur_col_type < kOxSampleColSex) || (!IsSet(col_nm, col_idx))) {
9983 continue;
9984 }
9985 token_slen = token_end - linebuf_iter;
9986 const uint32_t is_missing = (bsearch_strbox(linebuf_iter, sorted_mc, token_slen, max_mc_blen, mc_ct) != -1);
9987 if (cur_col_type >= kOxSampleColCatNumeric) {
9988 *write_iter++ = '\t';
9989 if (!is_missing) {
9990 double dxx = 0.0;
9991 char* num_end = ScanadvDouble(linebuf_iter, &dxx);
9992 if (cur_col_type == kOxSampleColCatNumeric) {
9993 *write_iter++ = 'C';
9994 // .sample files are relatively small, so let's go ahead and
9995 // (i) validate we have a positive integer < 2^31
9996 // (ii) convert e.g. 9000000, 9000000., 9.0e6 all to 9000000
9997 int32_t ii = S_CAST(int32_t, dxx);
9998 if (unlikely((num_end != token_end) || (ii <= 0) || (S_CAST(double, ii) != dxx))) {
9999 *token_end = '\0';
10000 snprintf(g_logbuf, kLogbufSize, "Error: Invalid categorical phenotype value '%s' on line %" PRIuPTR ", column %u of .sample file (positive integer < 2^31 or --missing-code value expected).\n", linebuf_iter, line_idx, col_idx + 1);
10001 goto OxSampleToPsam_ret_INCONSISTENT_INPUT_WW;
10002 }
10003 write_iter = u32toa(ii, write_iter);
10004 } else {
10005 if (unlikely(num_end)) {
10006 logerrputs("Error: Mixed numeric/non-numeric categorical phenotype in .sample file.\n");
10007 goto OxSampleToPsam_ret_MALFORMED_INPUT;
10008 }
10009 write_iter = memcpya(write_iter, linebuf_iter, token_slen);
10010 }
10011 } else {
10012 write_iter = memcpya(write_iter, missing_catname, missing_catname_slen);
10013 }
10014 } else if (cur_col_type != kOxSampleColSex) {
10015 *write_iter++ = '\t';
10016 if (!is_missing) {
10017 if (cur_col_type == kOxSampleColBinary) {
10018 // tolerate "control"/"case" as well as 0/1
10019 if (strequal_k(linebuf_iter, "0", token_slen) || strequal_k(linebuf_iter, "control", token_slen)) {
10020 *write_iter++ = ctrl_outchar;
10021 } else if (likely(strequal_k(linebuf_iter, "1", token_slen) || strequal_k(linebuf_iter, "case", token_slen))) {
10022 *write_iter++ = case_outchar;
10023 } else {
10024 *token_end = '\0';
10025 snprintf(g_logbuf, kLogbufSize, "Error: Invalid binary phenotype value '%s' on line %" PRIuPTR ", column %u of .sample file ('0', '1', or --missing-code value expected).\n", linebuf_iter, line_idx, col_idx + 1);
10026 goto OxSampleToPsam_ret_INCONSISTENT_INPUT_WW;
10027 }
10028 } else {
10029 assert(cur_col_type == kOxSampleColQuantitative);
10030 double dxx = 0.0;
10031 if (unlikely(!ScantokDouble(linebuf_iter, &dxx))) {
10032 *token_end = '\0';
10033 snprintf(g_logbuf, kLogbufSize, "Error: Invalid quantitative phenotype value '%s' on line %" PRIuPTR ", column %u of .sample file (non-infinite number or --missing-code value expected).\n", linebuf_iter, line_idx, col_idx + 1);
10034 goto OxSampleToPsam_ret_INCONSISTENT_INPUT_WW;
10035 }
10036 // used over memcpy to make --data and --data --make-pgen the
10037 // same (could make that conditional on keep_autoconv?)
10038 write_iter = dtoa_g(dxx, write_iter);
10039 }
10040 } else {
10041 // bugfix (7 Jul 2023): forgot this branch
10042 write_iter = strcpya_k(write_iter, "NA");
10043 }
10044 } else {
10045 // sex
10046 if (!is_missing) {
10047 const unsigned char sex_ucc = *linebuf_iter;
10048 if ((token_slen == 1) && ((S_CAST(uint32_t, sex_ucc) - 49) < 2)) {
10049 ++cur_writebuf_start;
10050 cur_writebuf_start[0] = '\t';
10051 cur_writebuf_start[1] = sex_ucc;
10052 } else if (unlikely((token_slen != 1) || (sex_ucc != '0'))) {
10053 // tolerate '0' as a sex-only missing code even when not
10054 // explicitly specified
10055 *token_end = '\0';
10056 snprintf(g_logbuf, kLogbufSize, "Error: Invalid sex code '%s' on line %" PRIuPTR ", column %u of .sample file ('0', '1', '2', or --missing-code value expected).\n", linebuf_iter, line_idx, col_idx + 1);
10057 goto OxSampleToPsam_ret_INCONSISTENT_INPUT_WW;
10058 }
10059 }
10060 }
10061 }
10062 AppendBinaryEoln(&write_iter);
10063 if (unlikely(fwrite_checked(cur_writebuf_start, write_iter - cur_writebuf_start, psamfile))) {
10064 goto OxSampleToPsam_ret_WRITE_FAIL;
10065 }
10066 }
10067 if (unlikely(TextStreamErrcode2(&sample_txs, &reterr) ||
10068 (line_idx != sample_ct + 2))) {
10069 goto OxSampleToPsam_ret_TSTREAM_REWIND_FAIL;
10070 }
10071
10072 // no final writebuf flush since we didn't use usual manual-streaming
10073 // strategy
10074 // (probably change this?)
10075 if (unlikely(fclose_null(&psamfile))) {
10076 goto OxSampleToPsam_ret_WRITE_FAIL;
10077 }
10078 logprintfww("%u sample%s imported from .sample file to %s .\n", sample_ct, (sample_ct == 1)? "" : "s", outname);
10079 *sample_ct_ptr = sample_ct;
10080 }
10081 while (0) {
10082 OxSampleToPsam_ret_TSTREAM_FAIL:
10083 TextStreamErrPrint(".sample file", &sample_txs);
10084 break;
10085 OxSampleToPsam_ret_TSTREAM_REWIND_FAIL:
10086 TextStreamErrPrintRewind(".sample file", &sample_txs, &reterr);
10087 break;
10088 OxSampleToPsam_ret_REWIND_FAIL:
10089 logerrprintfww(kErrprintfRewind, ".sample file");
10090 reterr = kPglRetRewindFail;
10091 break;
10092 OxSampleToPsam_ret_NOMEM:
10093 reterr = kPglRetNomem;
10094 break;
10095 OxSampleToPsam_ret_OPEN_FAIL:
10096 reterr = kPglRetOpenFail;
10097 break;
10098 OxSampleToPsam_ret_WRITE_FAIL:
10099 reterr = kPglRetWriteFail;
10100 break;
10101 OxSampleToPsam_ret_MISSING_TOKENS:
10102 logerrprintf("Error: Line %" PRIuPTR " of .sample file has fewer tokens than expected.\n", line_idx);
10103 reterr = kPglRetMalformedInput;
10104 break;
10105 OxSampleToPsam_ret_MALFORMED_INPUT_WW:
10106 WordWrapB(0);
10107 OxSampleToPsam_ret_MALFORMED_INPUT_2:
10108 logerrputsb();
10109 OxSampleToPsam_ret_MALFORMED_INPUT:
10110 reterr = kPglRetMalformedInput;
10111 break;
10112 OxSampleToPsam_ret_INCONSISTENT_INPUT_WW:
10113 WordWrapB(0);
10114 logerrputsb();
10115 OxSampleToPsam_ret_INCONSISTENT_INPUT:
10116 reterr = kPglRetInconsistentInput;
10117 break;
10118 OxSampleToPsam_ret_DEGENERATE_DATA:
10119 reterr = kPglRetDegenerateData;
10120 break;
10121 }
10122 OxSampleToPsam_ret_1:
10123 CleanupTextStream2(".sample file", &sample_txs, &reterr);
10124 fclose_cond(psamfile);
10125 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
10126 return reterr;
10127 }
10128
10129 uint32_t Bgen11DosageImportCheck(uint32_t dosage_int_sum_thresh, uint32_t import_dosage_certainty_int, uint32_t dosage_erase_halfdist, uint32_t dosage_int0, uint32_t dosage_int1, uint32_t dosage_int2) {
10130 const uint32_t dosage_int_sum = dosage_int0 + dosage_int1 + dosage_int2;
10131 if ((dosage_int_sum <= dosage_int_sum_thresh) && (dosage_int0 < import_dosage_certainty_int) && (dosage_int1 < import_dosage_certainty_int) && (dosage_int2 < import_dosage_certainty_int)) {
10132 return 0;
10133 }
10134 // ties realistically happen, use banker's rounding
10135 // 1/65536 -> 0/32768
10136 // 3/65536 -> 2/32768
10137 // 5/65536 -> 2/32768
10138 const DosageProd write_dosage_int_numer = S_CAST(DosageProd, kDosageMid) * dosage_int1 + S_CAST(DosageProd, kDosageMax) * dosage_int2;
10139 uint32_t write_dosage_int;
10140 if (dosage_int_sum == kDosageMax) {
10141 // optimize common case
10142 write_dosage_int = ((write_dosage_int_numer + kDosageMid) / kDosageMax) - ((write_dosage_int_numer % (2 * S_CAST(DosageProd, kDosageMax))) == kDosageMid);
10143 } else {
10144 write_dosage_int = (write_dosage_int_numer + (dosage_int_sum / 2)) / dosage_int_sum;
10145 write_dosage_int -= (2 * (write_dosage_int_numer - write_dosage_int * dosage_int_sum) == dosage_int_sum) * (write_dosage_int % 2);
10146 }
10147 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
10148 return (halfdist < dosage_erase_halfdist);
10149 }
10150
10151 void Bgen11DosageImportUpdate(uint32_t dosage_int_sum_thresh, uint32_t import_dosage_certainty_int, uint32_t hard_call_halfdist, uint32_t dosage_erase_halfdist, uint32_t sample_idx_lowbits, uint32_t dosage_int0, uint32_t dosage_int1, uint32_t dosage_int2, uintptr_t* genovec_word_ptr, uint32_t* dosage_present_hw_ptr, Dosage** dosage_main_iterp) {
10152 const uint32_t dosage_int_sum = dosage_int0 + dosage_int1 + dosage_int2;
10153 if (dosage_int_sum <= dosage_int_sum_thresh) {
10154 if ((dosage_int0 < import_dosage_certainty_int) && (dosage_int1 < import_dosage_certainty_int) && (dosage_int2 < import_dosage_certainty_int)) {
10155 *genovec_word_ptr |= (3 * k1LU) << (2 * sample_idx_lowbits);
10156 return;
10157 }
10158 }
10159 const DosageProd write_dosage_int_numer = S_CAST(DosageProd, kDosageMid) * dosage_int1 + S_CAST(DosageProd, kDosageMax) * dosage_int2;
10160 uint32_t write_dosage_int;
10161 if (dosage_int_sum == kDosageMax) {
10162 write_dosage_int = ((write_dosage_int_numer + kDosageMid) / kDosageMax) - ((write_dosage_int_numer % (2 * S_CAST(DosageProd, kDosageMax))) == kDosageMid);
10163 } else {
10164 write_dosage_int = (write_dosage_int_numer + (dosage_int_sum / 2)) / dosage_int_sum;
10165 write_dosage_int -= (2 * (write_dosage_int_numer - write_dosage_int * dosage_int_sum) == dosage_int_sum) * (write_dosage_int % 2);
10166 }
10167 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
10168 if (halfdist < hard_call_halfdist) {
10169 *genovec_word_ptr |= (3 * k1LU) << (2 * sample_idx_lowbits);
10170 } else {
10171 *genovec_word_ptr |= ((write_dosage_int + (kDosage4th * k1LU)) / kDosageMid) << (2 * sample_idx_lowbits);
10172 if (halfdist >= dosage_erase_halfdist) {
10173 return;
10174 }
10175 }
10176 *dosage_present_hw_ptr |= 1U << sample_idx_lowbits;
10177 **dosage_main_iterp = write_dosage_int;
10178 *dosage_main_iterp += 1;
10179 }
10180
10181 // This may make a (tiny) allocation from the bottom of bigstack.
10182 // single_chr_str_ptr and single_chr_slen_ptr must be nullptr or non-null
10183 // together.
10184 // Ok for file_descrip to be nullptr if cur_chr_code_ptr is nullptr.
10185 PglErr InitOxfordSingleChr(const char* ox_single_chr_str, const char* file_descrip, const char** single_chr_str_ptr, uint32_t* single_chr_slen_ptr, uint32_t* cur_chr_code_ptr, ChrInfo* cip) {
10186 const uint32_t chr_code_raw = GetChrCodeRaw(ox_single_chr_str);
10187 if (chr_code_raw == UINT32_MAX) {
10188 // command-line parser guarantees that prohibit_extra_chr is false here
10189 const uint32_t chr_slen = strlen(ox_single_chr_str);
10190 if (single_chr_str_ptr) {
10191 *single_chr_str_ptr = ox_single_chr_str;
10192 *single_chr_slen_ptr = chr_slen;
10193 }
10194 PglErr reterr = kPglRetSuccess;
10195 if (cur_chr_code_ptr) {
10196 if (TryToAddChrName(ox_single_chr_str, file_descrip, 0, chr_slen, 0, cur_chr_code_ptr, cip) != kPglRetSuccess) {
10197 reterr = kPglRetInvalidCmdline;
10198 }
10199 }
10200 return reterr;
10201 }
10202 uint32_t chr_code = chr_code_raw;
10203 if (chr_code > cip->max_code) {
10204 if (chr_code < kMaxContigs) {
10205 logerrputs("Error: --oxford-single-chr chromosome code is not in the chromosome set.\n");
10206 return kPglRetInvalidCmdline;
10207 }
10208 chr_code = cip->xymt_codes[chr_code - kMaxContigs];
10209 if (IsI32Neg(chr_code)) {
10210 logerrputs("Error: --oxford-single-chr chromosome code is not in the chromosome set.\n");
10211 return kPglRetInvalidCmdline;
10212 }
10213 }
10214 if (!IsSet(cip->chr_mask, chr_code)) {
10215 logerrputs("Error: --oxford-single-chr chromosome code is excluded by chromosome filter.\n");
10216 return kPglRetInvalidCmdline;
10217 }
10218 if (cur_chr_code_ptr) {
10219 *cur_chr_code_ptr = chr_code;
10220 }
10221 if (single_chr_str_ptr) {
10222 char* chr_buf;
10223 if (unlikely(bigstack_alloc_c(kCacheline, &chr_buf))) {
10224 return kPglRetNomem;
10225 }
10226 char* chr_name_end = chrtoa(cip, chr_code, chr_buf);
10227 *single_chr_str_ptr = chr_buf;
10228 *single_chr_slen_ptr = chr_name_end - chr_buf;
10229 }
10230 return kPglRetSuccess;
10231 }
10232
10233 static_assert(sizeof(Dosage) == 2, "OxGenToPgen() needs to be updated.");
10234 PglErr OxGenToPgen(const char* genname, const char* samplename, const char* const_fid, const char* ox_single_chr_str, const char* ox_missing_code, const char* missing_catname, MiscFlags misc_flags, ImportFlags import_flags, OxfordImportFlags oxford_import_flags, uint32_t psam_01, uint32_t is_splitpar, uint32_t hard_call_thresh, uint32_t dosage_erase_thresh, double import_dosage_certainty, char id_delim, uint32_t max_thread_ct, char* outname, char* outname_end, ChrInfo* cip) {
10235 // Experimented with making this single-pass; that actually benchmarked a bit
10236 // slower than the current 2-pass algorithm. Yes, that might be because the
10237 // Mac I tested on has a crappy filesystem, but it's still enough reason to
10238 // leave this alone.
10239 unsigned char* bigstack_mark = g_bigstack_base;
10240 char* pvar_cswritep = nullptr;
10241 PglErr reterr = kPglRetSuccess;
10242 uintptr_t line_idx = 0;
10243 CompressStreamState pvar_css;
10244 PreinitCstream(&pvar_css);
10245 TextStream gen_txs;
10246 STPgenWriter spgw;
10247 PreinitTextStream(&gen_txs);
10248 PreinitSpgw(&spgw);
10249 {
10250 uint32_t sample_ct;
10251 reterr = OxSampleToPsam(samplename, const_fid, ox_missing_code, missing_catname, misc_flags, import_flags, psam_01, id_delim, outname, outname_end, &sample_ct);
10252 if (unlikely(reterr)) {
10253 goto OxGenToPgen_ret_1;
10254 }
10255 if (unlikely(sample_ct > (kMaxLongLine / 6))) {
10256 // impossible for a valid .gen line to fit in maximum-length load buffer
10257 logerrputs("Error: Too many samples for .gen file converter.\n");
10258 reterr = kPglRetNotYetSupported;
10259 goto OxGenToPgen_ret_1;
10260 }
10261 // Two passes:
10262 // 1. Count # of (non-chromosome-filtered) variants, write .pvar file, and
10263 // check if at least one non-hardcall needs to be saved.
10264 // 2. Write the .pgen.
10265 uint32_t max_line_blen;
10266 if (unlikely(StandardizeMaxLineBlen(bigstack_left() / 4, &max_line_blen))) {
10267 goto OxGenToPgen_ret_NOMEM;
10268 }
10269 const uint32_t decompress_thread_ct = 1 + (max_thread_ct > 2);
10270 reterr = ForceNonFifo(genname);
10271 if (unlikely(reterr)) {
10272 if (reterr == kPglRetOpenFail) {
10273 const uint32_t slen = strlen(genname);
10274 if ((!StrEndsWith(genname, ".gen", slen)) &&
10275 (!StrEndsWith(genname, ".gen.gz", slen))) {
10276 logerrprintfww("Error: Failed to open %s : %s. (--gen expects a complete filename; did you forget '.gen' at the end?)\n", genname, strerror(errno));
10277 } else {
10278 logerrprintfww(kErrprintfFopen, genname, strerror(errno));
10279 }
10280 } else {
10281 logerrprintfww(kErrprintfRewind, genname);
10282 }
10283 goto OxGenToPgen_ret_1;
10284 }
10285 reterr = InitTextStream(genname, max_line_blen, decompress_thread_ct, &gen_txs);
10286 if (unlikely(reterr)) {
10287 goto OxGenToPgen_ret_TSTREAM_FAIL;
10288 }
10289 const uint32_t prohibit_extra_chr = (misc_flags / kfMiscProhibitExtraChr) & 1;
10290 FinalizeChrset(misc_flags, cip);
10291
10292 snprintf(outname_end, kMaxOutfnameExtBlen, ".pvar");
10293 const uint32_t output_zst = (import_flags / kfImportKeepAutoconvVzs) & 1;
10294 if (output_zst) {
10295 snprintf(&(outname_end[5]), kMaxOutfnameExtBlen - 5, ".zst");
10296 }
10297 const uintptr_t overflow_buf_size = kCompressStreamBlock + max_line_blen;
10298 unsigned char* bigstack_mark2 = g_bigstack_base;
10299 reterr = InitCstreamAlloc(outname, 0, output_zst, 1, overflow_buf_size, &pvar_css, &pvar_cswritep);
10300 if (unlikely(reterr)) {
10301 goto OxGenToPgen_ret_1;
10302 }
10303
10304 const char* single_chr_str = nullptr;
10305 uint32_t single_chr_slen = 0;
10306 uint32_t cur_chr_code = 0;
10307 if (ox_single_chr_str) {
10308 reterr = InitOxfordSingleChr(ox_single_chr_str, ".gen file", &single_chr_str, &single_chr_slen, &cur_chr_code, cip);
10309 if (unlikely(reterr)) {
10310 goto OxGenToPgen_ret_1;
10311 }
10312 }
10313
10314 if (cip->chrset_source) {
10315 AppendChrsetLine(cip, &pvar_cswritep);
10316 }
10317 pvar_cswritep = strcpya_k(pvar_cswritep, "#CHROM\tPOS\tID\tREF\tALT" EOLN_STR);
10318
10319 // Explicit 32768 instead of kDosageMax since this is driven by the BGEN
10320 // 1.1 format, not plink2's dosage representation.
10321 // Note that command-line parser multiplies import_dosage_certainty by
10322 // (1 - kSmallEpsilon), and we want import_dosage_certainty_int to be 1
10323 // when import_dosage_certainty is zero.
10324 uint32_t import_dosage_certainty_int = 1 + S_CAST(int32_t, import_dosage_certainty * 32768);
10325 const uint32_t dosage_int_sum_thresh = 3 * (import_dosage_certainty_int - 1);
10326
10327 const uint32_t dosage_erase_halfdist = kDosage4th - dosage_erase_thresh;
10328 const uint32_t prov_ref_allele_second = !(oxford_import_flags & kfOxfordImportRefFirst);
10329 uint32_t dosage_exists = 0;
10330 uint32_t variant_ct = 0;
10331 uintptr_t variant_skip_ct = 0;
10332 char* line_iter = TextLineEnd(&gen_txs);
10333 ++line_idx;
10334 if (unlikely(!TextGetUnsafe2(&gen_txs, &line_iter))) {
10335 if (TextStreamErrcode2(&gen_txs, &reterr)) {
10336 goto OxGenToPgen_ret_TSTREAM_FAIL;
10337 }
10338 logerrputs("Error: Empty .gen file.\n");
10339 goto OxGenToPgen_ret_DEGENERATE_DATA;
10340 }
10341 uint32_t is_v2 = 0;
10342 {
10343 const uint32_t token_ct = CountTokens(line_iter);
10344 const uint32_t expected_v2_token_ct = 3 * sample_ct + 6;
10345 if (token_ct == expected_v2_token_ct) {
10346 is_v2 = 1;
10347 } else if (unlikely(token_ct != expected_v2_token_ct - 1)) {
10348 logerrprintfww("Error: Unexpected number of columns in .gen file (%u or %u expected).\n", expected_v2_token_ct - 1, expected_v2_token_ct);
10349 goto OxGenToPgen_ret_INCONSISTENT_INPUT;
10350 }
10351 }
10352 // sex_info_avail guaranteed to be true since .sample is required
10353 uint32_t par_warn_code = UINT32_MAX;
10354 if (!(import_flags & kfImportLaxChrX)) {
10355 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
10356 if ((!IsI32Neg(x_code)) && IsHumanChrset(cip) && (!is_splitpar)) {
10357 par_warn_code = x_code;
10358 }
10359 }
10360 goto OxGenToPgen_loop_start;
10361 for (; TextGetUnsafe2(&gen_txs, &line_iter); ++line_idx) {
10362 OxGenToPgen_loop_start:
10363 ; // make this work with plain C, as opposed to just C++, compilers
10364 char* chr_code_str = line_iter;
10365 char* chr_code_end = CurTokenEnd(chr_code_str);
10366 const char* variant_id_str = FirstNonTspace(chr_code_end);
10367 if (unlikely(IsEolnKns(*variant_id_str))) {
10368 goto OxGenToPgen_ret_MISSING_TOKENS;
10369 }
10370 if (is_v2) {
10371 variant_id_str = FirstNonTspace(CurTokenEnd(variant_id_str));
10372 if (unlikely(IsEolnKns(*variant_id_str))) {
10373 goto OxGenToPgen_ret_MISSING_TOKENS;
10374 }
10375 }
10376
10377 if (!single_chr_str) {
10378 reterr = GetOrAddChrCodeDestructive(".gen file", line_idx, prohibit_extra_chr, chr_code_str, chr_code_end, cip, &cur_chr_code);
10379 if (unlikely(reterr)) {
10380 if (strequal_k(chr_code_str, "---", chr_code_end - chr_code_str)) {
10381 logerrputs("(Did you forget --oxford-single-chr?)\n");
10382 }
10383 goto OxGenToPgen_ret_1;
10384 }
10385 if (!IsSet(cip->chr_mask, cur_chr_code)) {
10386 ++variant_skip_ct;
10387 continue;
10388 }
10389 pvar_cswritep = chrtoa(cip, cur_chr_code, pvar_cswritep);
10390 } else {
10391 pvar_cswritep = memcpya(pvar_cswritep, single_chr_str, single_chr_slen);
10392 }
10393 *pvar_cswritep++ = '\t';
10394 ++variant_ct;
10395
10396 const char* variant_id_end = CurTokenEnd(variant_id_str);
10397 const char* pos_str = FirstNonTspace(variant_id_end);
10398 if (unlikely(IsEolnKns(*pos_str))) {
10399 goto OxGenToPgen_ret_MISSING_TOKENS;
10400 }
10401 const char* pos_end = CurTokenEnd(pos_str);
10402 uint32_t cur_bp;
10403 if (unlikely(ScanUintDefcap(pos_str, &cur_bp))) {
10404 putc_unlocked('\n', stdout);
10405 snprintf(g_logbuf, kLogbufSize, "Error: Invalid bp coordinate on line %" PRIuPTR " of %s.\n", line_idx, genname);
10406 goto OxGenToPgen_ret_MALFORMED_INPUT_WW;
10407 }
10408
10409 pvar_cswritep = u32toa_x(cur_bp, '\t', pvar_cswritep);
10410 if (par_warn_code == cur_chr_code) {
10411 if (unlikely((cur_bp <= kPAR1IntersectionLast) || (cur_bp >= kPAR2IntersectionFirst))) {
10412 putc_unlocked('\n', stdout);
10413 logerrputs("Error: Human chrX pseudoautosomal variant(s) appear to be present in the input\n.gen, but --split-par was not specified.\n");
10414 goto OxGenToPgen_ret_INCONSISTENT_INPUT;
10415 }
10416 }
10417 const uint32_t variant_id_slen = variant_id_end - variant_id_str;
10418 if (unlikely(variant_id_slen > kMaxIdSlen)) {
10419 putc_unlocked('\n', stdout);
10420 logerrputs("Error: Variant names are limited to " MAX_ID_SLEN_STR " characters.\n");
10421 goto OxGenToPgen_ret_MALFORMED_INPUT;
10422 }
10423 pvar_cswritep = memcpyax(pvar_cswritep, variant_id_str, variant_id_slen, '\t');
10424
10425 // .gen specification does not define which column should be expected to
10426 // be the reference allele, and which the alternate. plink 1.9 assumed
10427 // alt was usually first, but the reverse seems to be more common now.
10428 // So:
10429 // If 'ref-first' or 'ref-last' was specified, we know what to do.
10430 // If not, we treat the second allele as the provisional reference, for
10431 // backward compatibility.
10432 const char* first_allele_str = FirstNonTspace(pos_end);
10433 if (unlikely(IsEolnKns(*first_allele_str))) {
10434 goto OxGenToPgen_ret_MISSING_TOKENS;
10435 }
10436 const char* first_allele_end = CurTokenEnd(first_allele_str);
10437 const char* second_allele_str = FirstNonTspace(first_allele_end);
10438 if (unlikely(IsEolnKns(*second_allele_str))) {
10439 goto OxGenToPgen_ret_MISSING_TOKENS;
10440 }
10441 const char* linebuf_iter = CurTokenEnd(second_allele_str);
10442 if (!prov_ref_allele_second) {
10443 pvar_cswritep = memcpyax(pvar_cswritep, first_allele_str, first_allele_end - first_allele_str, '\t');
10444 pvar_cswritep = memcpya(pvar_cswritep, second_allele_str, linebuf_iter - second_allele_str);
10445 } else {
10446 pvar_cswritep = memcpyax(pvar_cswritep, second_allele_str, linebuf_iter - second_allele_str, '\t');
10447 pvar_cswritep = memcpya(pvar_cswritep, first_allele_str, first_allele_end - first_allele_str);
10448 }
10449 AppendBinaryEoln(&pvar_cswritep);
10450 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
10451 goto OxGenToPgen_ret_WRITE_FAIL;
10452 }
10453
10454 if (!dosage_exists) {
10455 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
10456 linebuf_iter = FirstNonTspace(linebuf_iter);
10457 const char cc = *linebuf_iter;
10458 if (unlikely(IsEolnKns(cc))) {
10459 goto OxGenToPgen_ret_MISSING_TOKENS;
10460 }
10461 char cc2 = linebuf_iter[1];
10462 if ((cc2 == ' ') || (cc2 == '\t')) {
10463 // fast handling of "1 0 0 ", "0 1 0 ", "0 0 1 ", "0 0 0 " cases
10464 cc2 = linebuf_iter[3];
10465 if (((cc2 == ' ') || (cc2 == '\t')) && (ctou32(linebuf_iter[5]) <= 32)) {
10466 const uint32_t uii = ctou32(cc) - 48;
10467 const uint32_t ujj = ctou32(linebuf_iter[2]) - 48;
10468 const uint32_t ukk = ctou32(linebuf_iter[4]) - 48;
10469 if (((uii | ujj | ukk) < 2) && (uii + ujj + ukk < 2)) {
10470 linebuf_iter = &(linebuf_iter[5]);
10471 continue;
10472 }
10473 }
10474 }
10475 double prob_0alt;
10476 const char* first_dosage_str_end = ScanadvDouble(linebuf_iter, &prob_0alt);
10477 if (!first_dosage_str_end) {
10478 // triple-NA, etc. ok; treat as missing value
10479 linebuf_iter = NextTokenMult(linebuf_iter, 2);
10480 if (unlikely(!linebuf_iter)) {
10481 goto OxGenToPgen_ret_MISSING_TOKENS;
10482 }
10483 linebuf_iter = CurTokenEnd(linebuf_iter);
10484 continue;
10485 }
10486 if (unlikely(ctou32(*first_dosage_str_end) > ' ')) {
10487 goto OxGenToPgen_ret_INVALID_DOSAGE;
10488 }
10489 linebuf_iter = FirstNonTspace(first_dosage_str_end);
10490 if (unlikely(IsEolnKns(*linebuf_iter))) {
10491 goto OxGenToPgen_ret_MISSING_TOKENS;
10492 }
10493 double prob_1alt;
10494 linebuf_iter = ScantokDouble(linebuf_iter, &prob_1alt);
10495 if (unlikely(!linebuf_iter)) {
10496 goto OxGenToPgen_ret_INVALID_DOSAGE;
10497 }
10498 linebuf_iter = FirstNonTspace(linebuf_iter);
10499 if (unlikely(IsEolnKns(*linebuf_iter))) {
10500 goto OxGenToPgen_ret_MISSING_TOKENS;
10501 }
10502 double prob_2alt;
10503 linebuf_iter = ScantokDouble(linebuf_iter, &prob_2alt);
10504 if (unlikely(!linebuf_iter)) {
10505 goto OxGenToPgen_ret_INVALID_DOSAGE;
10506 }
10507 // bugfix: forgot the "multiply by 32768" part of "multiply by 32768
10508 // and round" .gen -> .bgen conversion.
10509 prob_0alt *= 32768;
10510 prob_1alt *= 32768;
10511 prob_2alt *= 32768;
10512
10513 // now treat this identically to bgen-1.1
10514 // Compare with 65535.4999999999 instead of 65535.5 since 0.5 +
10515 // <first floating point number below 65535.5> may evaluate to 65536.
10516 if (unlikely((prob_0alt < 0.0) || (prob_0alt >= 65535.4999999999) || (prob_1alt < 0.0) || (prob_1alt >= 65535.4999999999) || (prob_2alt < 0.0) || (prob_2alt >= 65535.4999999999))) {
10517 goto OxGenToPgen_ret_INVALID_DOSAGE;
10518 }
10519 const uint32_t dosage_int0 = S_CAST(int32_t, prob_0alt + 0.5);
10520 const uint32_t dosage_int1 = S_CAST(int32_t, prob_1alt + 0.5);
10521 const uint32_t dosage_int2 = S_CAST(int32_t, prob_2alt + 0.5);
10522 dosage_exists = Bgen11DosageImportCheck(dosage_int_sum_thresh, import_dosage_certainty_int, dosage_erase_halfdist, dosage_int0, dosage_int1, dosage_int2);
10523 if (dosage_exists) {
10524 break;
10525 }
10526 }
10527 }
10528 if (!(variant_ct % 1000)) {
10529 printf("\r--data/--gen: %uk variants scanned.", variant_ct / 1000);
10530 fflush(stdout);
10531 }
10532 line_iter = AdvPastDelim(K_CAST(char*, linebuf_iter), '\n');
10533 }
10534 if (unlikely(TextStreamErrcode2(&gen_txs, &reterr))) {
10535 goto OxGenToPgen_ret_TSTREAM_FAIL;
10536 }
10537 putc_unlocked('\r', stdout);
10538 if (unlikely(CswriteCloseNull(&pvar_css, pvar_cswritep))) {
10539 goto OxGenToPgen_ret_WRITE_FAIL;
10540 }
10541 if (unlikely(!variant_ct)) {
10542 logerrprintfww("Error: All %" PRIuPTR " variant%s in .gen file skipped due to chromosome filter.\n", variant_skip_ct, (variant_skip_ct == 1)? "" : "s");
10543 goto OxGenToPgen_ret_INCONSISTENT_INPUT;
10544 }
10545 logprintf("--data/--gen: %u variant%s scanned%s.\n", variant_ct, (variant_ct == 1)? "" : "s", dosage_exists? "" : " (all hardcalls)");
10546
10547 // second pass
10548 BigstackReset(bigstack_mark2);
10549 if (TextIsMt(&gen_txs) && (decompress_thread_ct > 1)) {
10550 // Close and reopen, so that we can reduce decompress_thread_ct to 1.
10551 char* dst = R_CAST(char*, TextStreamMemStart(&gen_txs));
10552 if (unlikely(CleanupTextStream(&gen_txs, &reterr))) {
10553 logerrprintfww(kErrprintfFread, ".gen file", rstrerror(errno));
10554 goto OxGenToPgen_ret_1;
10555 }
10556 reterr = TextStreamOpenEx(genname, kMaxLongLine, max_line_blen, 1, nullptr, dst, &gen_txs);
10557 if (unlikely(reterr)) {
10558 goto OxGenToPgen_ret_TSTREAM_FAIL;
10559 }
10560 } else {
10561 reterr = TextRewind(&gen_txs);
10562 if (unlikely(reterr)) {
10563 goto OxGenToPgen_ret_TSTREAM_FAIL;
10564 }
10565 }
10566
10567 snprintf(outname_end, kMaxOutfnameExtBlen, ".pgen");
10568 uintptr_t spgw_alloc_cacheline_ct;
10569 uint32_t max_vrec_len;
10570 reterr = SpgwInitPhase1(outname, nullptr, nullptr, variant_ct, sample_ct, 0, kPgenWriteBackwardSeek, dosage_exists? kfPgenGlobalDosagePresent : kfPgenGlobal0, (oxford_import_flags & kfOxfordImportRefUnknown)? 2 : 1, &spgw, &spgw_alloc_cacheline_ct, &max_vrec_len);
10571 if (unlikely(reterr)) {
10572 if (reterr == kPglRetOpenFail) {
10573 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
10574 }
10575 goto OxGenToPgen_ret_1;
10576 }
10577 unsigned char* spgw_alloc;
10578 if (unlikely(bigstack_alloc_uc(spgw_alloc_cacheline_ct * kCacheline, &spgw_alloc))) {
10579 goto OxGenToPgen_ret_NOMEM;
10580 }
10581 SpgwInitPhase2(max_vrec_len, &spgw, spgw_alloc);
10582
10583 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
10584 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
10585 uintptr_t* genovec;
10586 Halfword* dosage_present_hwarr;
10587 // if we weren't using bigstack_alloc, this would need to be sample_ctaw2
10588 if (unlikely(bigstack_alloc_w(sample_ctl2, &genovec) ||
10589 bigstack_alloc_hw(2 * sample_ctl, &dosage_present_hwarr))) {
10590 goto OxGenToPgen_ret_NOMEM;
10591 }
10592 Dosage* dosage_main = nullptr;
10593 if (dosage_exists) {
10594 if (unlikely(bigstack_alloc_dosage(sample_ct, &dosage_main))) {
10595 goto OxGenToPgen_ret_NOMEM;
10596 }
10597 }
10598 if (hard_call_thresh == UINT32_MAX) {
10599 hard_call_thresh = kDosageMid / 10;
10600 }
10601 const uint32_t hard_call_halfdist = kDosage4th - hard_call_thresh;
10602 const uint32_t sample_ctl2_m1 = sample_ctl2 - 1;
10603 const uintptr_t line_ct = line_idx - 1;
10604 uint32_t vidx = 0;
10605 line_iter = TextLineEnd(&gen_txs);
10606 for (line_idx = 1; line_idx <= line_ct; ++line_idx) {
10607 reterr = TextGetUnsafe(&gen_txs, &line_iter);
10608 if (unlikely(reterr)) {
10609 goto OxGenToPgen_ret_TSTREAM_FAIL;
10610 }
10611 char* chr_code_str = line_iter;
10612 char* chr_code_end = CurTokenEnd(chr_code_str);
10613 if (variant_skip_ct) {
10614 *chr_code_end = '\0';
10615 const uint32_t chr_code = GetChrCode(chr_code_str, cip, chr_code_end - chr_code_str);
10616 if (!IsSet(cip->chr_mask, chr_code)) {
10617 line_iter = AdvPastDelim(chr_code_end, '\n');
10618 continue;
10619 }
10620 }
10621 const char* linebuf_iter = NextTokenMult(FirstNonTspace(&(chr_code_end[1])), 4 + is_v2);
10622 uint32_t inner_loop_last = kBitsPerWordD2 - 1;
10623 Dosage* dosage_main_iter = dosage_main;
10624 for (uint32_t widx = 0; ; ++widx) {
10625 if (widx >= sample_ctl2_m1) {
10626 if (widx > sample_ctl2_m1) {
10627 break;
10628 }
10629 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
10630 }
10631 uintptr_t genovec_word = 0;
10632 uint32_t dosage_present_hw = 0;
10633 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
10634 linebuf_iter = FirstNonTspace(linebuf_iter);
10635 const char cc = *linebuf_iter;
10636 if (unlikely(IsEolnKns(cc))) {
10637 goto OxGenToPgen_ret_MISSING_TOKENS;
10638 }
10639 char cc2 = linebuf_iter[1];
10640 if ((cc2 == ' ') || (cc2 == '\t')) {
10641 cc2 = linebuf_iter[3];
10642 if (((cc2 == ' ') || (cc2 == '\t')) && (ctou32(linebuf_iter[5]) <= 32)) {
10643 const uint32_t uii = ctou32(cc) - 48;
10644 const uint32_t ujj = ctou32(linebuf_iter[2]) - 48;
10645 const uint32_t ukk = ctou32(linebuf_iter[4]) - 48;
10646 const uint32_t all_or = uii | ujj | ukk;
10647 if (all_or < 2) {
10648 if (!all_or) {
10649 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
10650 linebuf_iter = &(linebuf_iter[5]);
10651 continue;
10652 }
10653 if (uii + ujj + ukk == 1) {
10654 uintptr_t cur_geno = ukk * 2 + ujj;
10655 genovec_word |= cur_geno << (2 * sample_idx_lowbits);
10656 linebuf_iter = &(linebuf_iter[5]);
10657 continue;
10658 }
10659 }
10660 }
10661 }
10662 double prob_0alt;
10663 const char* first_dosage_str_end = ScanadvDouble(linebuf_iter, &prob_0alt);
10664 if (!first_dosage_str_end) {
10665 // ignore next two tokens if first token in triplet is not numeric,
10666 // since we treat this as missing regardless
10667 linebuf_iter = NextTokenMult(linebuf_iter, 2);
10668 if (unlikely(!linebuf_iter)) {
10669 goto OxGenToPgen_ret_MISSING_TOKENS;
10670 }
10671 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
10672 linebuf_iter = CurTokenEnd(linebuf_iter);
10673 continue;
10674 }
10675 if (unlikely(ctou32(*first_dosage_str_end) > ' ')) {
10676 goto OxGenToPgen_ret_INVALID_DOSAGE;
10677 }
10678 linebuf_iter = FirstNonTspace(first_dosage_str_end);
10679 if (unlikely(IsEolnKns(*linebuf_iter))) {
10680 goto OxGenToPgen_ret_MISSING_TOKENS;
10681 }
10682 double prob_1alt;
10683 linebuf_iter = ScantokDouble(linebuf_iter, &prob_1alt);
10684 if (unlikely(!linebuf_iter)) {
10685 goto OxGenToPgen_ret_INVALID_DOSAGE;
10686 }
10687 linebuf_iter = FirstNonTspace(linebuf_iter);
10688 if (unlikely(IsEolnKns(*linebuf_iter))) {
10689 goto OxGenToPgen_ret_MISSING_TOKENS;
10690 }
10691 double prob_2alt;
10692 linebuf_iter = ScantokDouble(linebuf_iter, &prob_2alt);
10693 if (unlikely(!linebuf_iter)) {
10694 goto OxGenToPgen_ret_INVALID_DOSAGE;
10695 }
10696 // bugfix
10697 prob_0alt *= 32768;
10698 prob_1alt *= 32768;
10699 prob_2alt *= 32768;
10700
10701 if (unlikely((prob_0alt < 0.0) || (prob_0alt >= 65535.4999999999) || (prob_1alt < 0.0) || (prob_1alt >= 65535.4999999999) || (prob_2alt < 0.0) || (prob_2alt >= 65535.4999999999))) {
10702 goto OxGenToPgen_ret_INVALID_DOSAGE;
10703 }
10704 const uint32_t dosage_int0 = S_CAST(int32_t, prob_0alt + 0.5);
10705 const uint32_t dosage_int1 = S_CAST(int32_t, prob_1alt + 0.5);
10706 const uint32_t dosage_int2 = S_CAST(int32_t, prob_2alt + 0.5);
10707 Bgen11DosageImportUpdate(dosage_int_sum_thresh, import_dosage_certainty_int, hard_call_halfdist, dosage_erase_halfdist, sample_idx_lowbits, dosage_int0, dosage_int1, dosage_int2, &genovec_word, &dosage_present_hw, &dosage_main_iter);
10708 }
10709 genovec[widx] = genovec_word;
10710 dosage_present_hwarr[widx] = dosage_present_hw;
10711 }
10712 if (prov_ref_allele_second) {
10713 GenovecInvertUnsafe(sample_ct, genovec);
10714 ZeroTrailingNyps(sample_ct, genovec);
10715 }
10716 if (dosage_main_iter != dosage_main) {
10717 const uint32_t dosage_ct = dosage_main_iter - dosage_main;
10718 if (prov_ref_allele_second) {
10719 BiallelicDosage16Invert(dosage_ct, dosage_main);
10720 }
10721 uintptr_t* __attribute__((may_alias)) dosage_present_warr = R_CAST(uintptr_t*, dosage_present_hwarr);
10722 reterr = SpgwAppendBiallelicGenovecDosage16(genovec, dosage_present_warr, dosage_main, dosage_ct, &spgw);
10723 if (unlikely(reterr)) {
10724 goto OxGenToPgen_ret_1;
10725 }
10726 } else {
10727 if (unlikely(SpgwAppendBiallelicGenovec(genovec, &spgw))) {
10728 goto OxGenToPgen_ret_WRITE_FAIL;
10729 }
10730 }
10731 ++vidx;
10732 if (!(vidx % 1000)) {
10733 printf("\r--data/--gen: %uk variants converted.", vidx / 1000);
10734 fflush(stdout);
10735 }
10736 line_iter = AdvPastDelim(K_CAST(char*, linebuf_iter), '\n');
10737 }
10738 reterr = SpgwFinish(&spgw);
10739 if (unlikely(reterr)) {
10740 goto OxGenToPgen_ret_1;
10741 }
10742 putc_unlocked('\r', stdout);
10743 char* write_iter = strcpya_k(g_logbuf, "--data/--gen: ");
10744 const uint32_t outname_base_slen = outname_end - outname;
10745 write_iter = memcpya(write_iter, outname, outname_base_slen + 5);
10746 write_iter = strcpya_k(write_iter, " + ");
10747 write_iter = memcpya(write_iter, outname, outname_base_slen);
10748 write_iter = strcpya_k(write_iter, ".pvar");
10749 if (output_zst) {
10750 write_iter = strcpya_k(write_iter, ".zst");
10751 }
10752 snprintf(write_iter, kLogbufSize - 2 * kPglFnamesize - 64, " written.\n");
10753 WordWrapB(0);
10754 logputsb();
10755 }
10756 while (0) {
10757 OxGenToPgen_ret_TSTREAM_FAIL:
10758 TextStreamErrPrint(".gen file", &gen_txs);
10759 break;
10760 OxGenToPgen_ret_NOMEM:
10761 reterr = kPglRetNomem;
10762 break;
10763 OxGenToPgen_ret_WRITE_FAIL:
10764 reterr = kPglRetWriteFail;
10765 break;
10766 OxGenToPgen_ret_INVALID_DOSAGE:
10767 putc_unlocked('\n', stdout);
10768 logerrprintf("Error: Line %" PRIuPTR " of .gen file has an invalid dosage value.\n", line_idx);
10769 reterr = kPglRetMalformedInput;
10770 break;
10771 OxGenToPgen_ret_MISSING_TOKENS:
10772 putc_unlocked('\n', stdout);
10773 logerrprintf("Error: Line %" PRIuPTR " of .gen file has fewer tokens than expected.\n", line_idx);
10774 reterr = kPglRetMalformedInput;
10775 break;
10776 OxGenToPgen_ret_MALFORMED_INPUT_WW:
10777 WordWrapB(0);
10778 logerrputsb();
10779 OxGenToPgen_ret_MALFORMED_INPUT:
10780 reterr = kPglRetMalformedInput;
10781 break;
10782 OxGenToPgen_ret_INCONSISTENT_INPUT:
10783 reterr = kPglRetInconsistentInput;
10784 break;
10785 OxGenToPgen_ret_DEGENERATE_DATA:
10786 reterr = kPglRetDegenerateData;
10787 break;
10788 }
10789 OxGenToPgen_ret_1:
10790 CleanupSpgw(&spgw, &reterr);
10791 CleanupTextStream2(".gen file", &gen_txs, &reterr);
10792 CswriteCloseCond(&pvar_css, pvar_cswritep);
10793 BigstackReset(bigstack_mark);
10794 return reterr;
10795 }
10796
10797 typedef struct BgenImportCommonStruct {
10798 uint32_t sample_ct;
10799 uint32_t dosage_erase_halfdist;
10800 uint32_t compression_mode;
10801
10802 struct libdeflate_decompressor** libdeflate_decompressors;
10803
10804 unsigned char** compressed_geno_starts[2];
10805
10806 uint32_t cur_block_size;
10807 } BgenImportCommon;
10808
10809 typedef struct Bgen11DosageScanCtxStruct {
10810 BgenImportCommon* common;
10811
10812 uint16_t** bgen_geno_bufs;
10813 uint32_t import_dosage_certainty_int;
10814
10815 uint32_t dosage_exists;
10816 PglErr reterr; // only kPglRetMalformedInput possible for now
10817 } Bgen11DosageScanCtx;
10818
10819 THREAD_FUNC_DECL Bgen11DosageScanThread(void* raw_arg) {
10820 // this bails as soon as a single non-hardcall is detected. still
10821 // multithreaded due to relatively low speed of zlib_decompress() call,
10822 // practical value of handling the all-hardcall case efficiently, and reduced
10823 // code complexity (locally more complex, but globally cleaner due to overlap
10824 // with Bgen11GenoToPgenThread()).
10825 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
10826 const uintptr_t tidx = arg->tidx;
10827 Bgen11DosageScanCtx* ctx = S_CAST(Bgen11DosageScanCtx*, arg->sharedp->context);
10828 BgenImportCommon* bicp = ctx->common;
10829
10830 const uint32_t sample_ct = bicp->sample_ct;
10831 uint16_t* bgen_geno_buf = ctx->bgen_geno_bufs[tidx];
10832 struct libdeflate_decompressor* decompressor = bicp->libdeflate_decompressors[tidx];
10833 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
10834 // hard_call_halfdist irrelevant here
10835 const uint32_t dosage_erase_halfdist = bicp->dosage_erase_halfdist;
10836 const uint32_t import_dosage_certainty_int = ctx->import_dosage_certainty_int;
10837 const uint32_t dosage_int_sum_thresh = 3 * (import_dosage_certainty_int - 1);
10838 const uint32_t compression_mode = bicp->compression_mode;
10839 // uint32_t vidx_base = 0;
10840 uint32_t parity = 0;
10841 do {
10842 const uintptr_t cur_block_size = bicp->cur_block_size;
10843 const uint32_t vidx_end = ((tidx + 1) * cur_block_size) / calc_thread_ct;
10844 uint32_t vidx = (tidx * cur_block_size) / calc_thread_ct;
10845 unsigned char* compressed_geno_iter = bicp->compressed_geno_starts[parity][vidx];
10846 uint16_t* bgen_probs = bgen_geno_buf;
10847 for (; vidx != vidx_end; ++vidx) {
10848 if (compression_mode) {
10849 uint32_t compressed_block_byte_ct;
10850 memcpy(&compressed_block_byte_ct, compressed_geno_iter, 4);
10851 compressed_geno_iter = &(compressed_geno_iter[4]);
10852 if (unlikely(libdeflate_zlib_decompress(decompressor, compressed_geno_iter, compressed_block_byte_ct, bgen_probs, 6 * sample_ct, nullptr) != LIBDEFLATE_SUCCESS)) {
10853 break;
10854 }
10855 compressed_geno_iter = &(compressed_geno_iter[compressed_block_byte_ct]);
10856 } else {
10857 bgen_probs = R_CAST(uint16_t*, compressed_geno_iter);
10858 compressed_geno_iter = &(compressed_geno_iter[6 * sample_ct]);
10859 }
10860 const uint16_t* bgen_probs_iter = bgen_probs;
10861 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
10862 const uint32_t dosage_int0 = *bgen_probs_iter++;
10863 const uint32_t dosage_int1 = *bgen_probs_iter++;
10864 const uint32_t dosage_int2 = *bgen_probs_iter++;
10865 const uint32_t dosage_int_sum = dosage_int0 + dosage_int1 + dosage_int2;
10866 if ((dosage_int_sum > dosage_int_sum_thresh) || (dosage_int0 >= import_dosage_certainty_int) || (dosage_int1 >= import_dosage_certainty_int) || (dosage_int2 >= import_dosage_certainty_int)) {
10867 // ties realistically happen, use banker's rounding
10868 // 1/65536 -> 0/32768
10869 // 3/65536 -> 2/32768
10870 // 5/65536 -> 2/32768
10871 const DosageProd write_dosage_int_numer = S_CAST(DosageProd, kDosageMid) * dosage_int1 + S_CAST(DosageProd, kDosageMax) * dosage_int2;
10872 uint32_t write_dosage_int;
10873 if (dosage_int_sum == kDosageMax) {
10874 // optimize common case
10875 write_dosage_int = ((write_dosage_int_numer + kDosageMid) / kDosageMax) - ((write_dosage_int_numer % (2 * S_CAST(DosageProd, kDosageMax))) == kDosageMid);
10876 } else {
10877 write_dosage_int = (write_dosage_int_numer + (dosage_int_sum / 2)) / dosage_int_sum;
10878 write_dosage_int -= (2 * (write_dosage_int_numer - write_dosage_int * dosage_int_sum) == dosage_int_sum) * (write_dosage_int % 2);
10879 }
10880 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
10881 if (halfdist < dosage_erase_halfdist) {
10882 goto Bgen11DosageScanThread_dosage_found;
10883 }
10884 }
10885 }
10886 }
10887 if (unlikely(vidx != vidx_end)) {
10888 // g_error_vidxs[tidx] = vidx + vidx_base;
10889 ctx->reterr = kPglRetMalformedInput;
10890 }
10891 while (0) {
10892 Bgen11DosageScanThread_dosage_found:
10893 ctx->dosage_exists = 1;
10894 }
10895 // vidx_base += cur_block_size;
10896 parity = 1 - parity;
10897 } while (!THREAD_BLOCK_FINISH(arg));
10898 THREAD_RETURN;
10899 }
10900
10901 typedef struct Bgen11GenoToPgenCtxStruct {
10902 BgenImportCommon* common;
10903
10904 uint16_t** bgen_geno_bufs;
10905 uint32_t hard_call_halfdist;
10906 uint32_t import_dosage_certainty_int;
10907 uint32_t prov_ref_allele_second;
10908
10909 uintptr_t* write_genovecs[2];
10910 uint32_t* write_dosage_cts[2];
10911 uintptr_t* write_dosage_presents[2];
10912 Dosage* write_dosage_mains[2];
10913
10914 PglErr reterr; // only kPglRetMalformedInput possible for now
10915 } Bgen11GenoToPgenCtx;
10916
10917 static_assert(sizeof(Dosage) == 2, "Bgen11GenoToPgenThread() needs to be updated.");
10918 THREAD_FUNC_DECL Bgen11GenoToPgenThread(void* raw_arg) {
10919 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
10920 const uintptr_t tidx = arg->tidx;
10921 Bgen11GenoToPgenCtx* ctx = S_CAST(Bgen11GenoToPgenCtx*, arg->sharedp->context);
10922 BgenImportCommon* bicp = ctx->common;
10923
10924 const uintptr_t sample_ct = bicp->sample_ct;
10925 uint16_t* bgen_geno_buf = ctx->bgen_geno_bufs[tidx];
10926 struct libdeflate_decompressor* decompressor = bicp->libdeflate_decompressors[tidx];
10927 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
10928 const uint32_t hard_call_halfdist = ctx->hard_call_halfdist;
10929 const uint32_t dosage_erase_halfdist = bicp->dosage_erase_halfdist;
10930 const uint32_t import_dosage_certainty_int = ctx->import_dosage_certainty_int;
10931 const uint32_t dosage_int_sum_thresh = 3 * (import_dosage_certainty_int - 1);
10932 const uint32_t compression_mode = bicp->compression_mode;
10933 const uint32_t prov_ref_allele_second = ctx->prov_ref_allele_second;
10934 const uintptr_t sample_ctaw2 = NypCtToAlignedWordCt(sample_ct);
10935 const uint32_t sample_ctl2_m1 = (sample_ct - 1) / kBitsPerWordD2;
10936 const uintptr_t sample_ctaw = BitCtToAlignedWordCt(sample_ct);
10937 // uint32_t vidx_base = 0;
10938 uint32_t parity = 0;
10939 do {
10940 const uintptr_t cur_block_write_ct = bicp->cur_block_size;
10941 uint32_t vidx = (tidx * cur_block_write_ct) / calc_thread_ct;
10942 const uint32_t vidx_end = ((tidx + 1) * cur_block_write_ct) / calc_thread_ct;
10943 unsigned char* compressed_geno_iter = bicp->compressed_geno_starts[parity][vidx];
10944 uintptr_t* write_genovec_iter = &(ctx->write_genovecs[parity][vidx * sample_ctaw2]);
10945 uint32_t* write_dosage_ct_iter = &(ctx->write_dosage_cts[parity][vidx]);
10946 Halfword* write_dosage_present_iter = DowncastWToHW(&(ctx->write_dosage_presents[parity][vidx * sample_ctaw]));
10947 Dosage* write_dosage_main_iter = &(ctx->write_dosage_mains[parity][vidx * sample_ct]);
10948 uint16_t* bgen_probs = bgen_geno_buf;
10949 for (; vidx != vidx_end; ++vidx) {
10950 if (compression_mode) {
10951 uint32_t compressed_block_byte_ct;
10952 memcpy(&compressed_block_byte_ct, compressed_geno_iter, 4);
10953 compressed_geno_iter = &(compressed_geno_iter[4]);
10954 if (unlikely(libdeflate_zlib_decompress(decompressor, compressed_geno_iter, compressed_block_byte_ct, bgen_probs, 6 * sample_ct, nullptr) != LIBDEFLATE_SUCCESS)) {
10955 break;
10956 }
10957 compressed_geno_iter = &(compressed_geno_iter[compressed_block_byte_ct]);
10958 } else {
10959 bgen_probs = R_CAST(uint16_t*, compressed_geno_iter);
10960 compressed_geno_iter = &(compressed_geno_iter[6 * sample_ct]);
10961 }
10962 const uint16_t* bgen_probs_iter = bgen_probs;
10963 Dosage* cur_dosage_main_iter = write_dosage_main_iter;
10964 uint32_t inner_loop_last = kBitsPerWordD2 - 1;
10965 for (uint32_t widx = 0; ; ++widx) {
10966 if (widx >= sample_ctl2_m1) {
10967 if (widx > sample_ctl2_m1) {
10968 break;
10969 }
10970 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
10971 }
10972 uintptr_t genovec_word = 0;
10973 uint32_t dosage_present_hw = 0;
10974 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
10975 const uint32_t dosage_int0 = *bgen_probs_iter++;
10976 const uint32_t dosage_int1 = *bgen_probs_iter++;
10977 const uint32_t dosage_int2 = *bgen_probs_iter++;
10978 const uint32_t dosage_int_sum = dosage_int0 + dosage_int1 + dosage_int2;
10979 if (dosage_int_sum <= dosage_int_sum_thresh) {
10980 if ((dosage_int0 < import_dosage_certainty_int) && (dosage_int1 < import_dosage_certainty_int) && (dosage_int2 < import_dosage_certainty_int)) {
10981 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
10982 continue;
10983 }
10984 }
10985 const DosageProd write_dosage_int_numer = S_CAST(DosageProd, kDosageMid) * dosage_int1 + S_CAST(DosageProd, kDosageMax) * dosage_int2;
10986 uint32_t write_dosage_int;
10987 if (dosage_int_sum == kDosageMax) {
10988 write_dosage_int = ((write_dosage_int_numer + kDosageMid) / kDosageMax) - ((write_dosage_int_numer % (2 * S_CAST(DosageProd, kDosageMax))) == kDosageMid);
10989 } else {
10990 write_dosage_int = (write_dosage_int_numer + (dosage_int_sum / 2)) / dosage_int_sum;
10991 write_dosage_int -= (2 * (write_dosage_int_numer - write_dosage_int * dosage_int_sum) == dosage_int_sum) * (write_dosage_int % 2);
10992 }
10993 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
10994 if (halfdist < hard_call_halfdist) {
10995 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
10996 } else {
10997 genovec_word |= ((write_dosage_int + (kDosage4th * k1LU)) / kDosageMid) << (2 * sample_idx_lowbits);
10998 if (halfdist >= dosage_erase_halfdist) {
10999 continue;
11000 }
11001 }
11002 dosage_present_hw |= 1U << sample_idx_lowbits;
11003 *cur_dosage_main_iter++ = write_dosage_int;
11004 }
11005 write_genovec_iter[widx] = genovec_word;
11006 write_dosage_present_iter[widx] = dosage_present_hw;
11007 }
11008 const uint32_t dosage_ct = cur_dosage_main_iter - write_dosage_main_iter;
11009 if (prov_ref_allele_second) {
11010 GenovecInvertUnsafe(sample_ct, write_genovec_iter);
11011 ZeroTrailingNyps(sample_ct, write_genovec_iter);
11012 if (dosage_ct) {
11013 BiallelicDosage16Invert(dosage_ct, write_dosage_main_iter);
11014 }
11015 }
11016 *write_dosage_ct_iter++ = dosage_ct;
11017 write_genovec_iter = &(write_genovec_iter[sample_ctaw2]);
11018 write_dosage_present_iter = &(write_dosage_present_iter[2 * sample_ctaw]);
11019 write_dosage_main_iter = &(write_dosage_main_iter[sample_ct]);
11020 }
11021 if (unlikely(vidx != vidx_end)) {
11022 // g_error_vidxs[tidx] = vidx + vidx_base;
11023 ctx->reterr = kPglRetMalformedInput;
11024 }
11025 // vidx_base += cur_block_write_ct;
11026 parity = 1 - parity;
11027 } while (!THREAD_BLOCK_FINISH(arg));
11028 THREAD_RETURN;
11029 }
11030
11031 HEADER_INLINE uintptr_t Bgen13GetOneVal(const unsigned char* prob_start, uint64_t prob_offset, uint32_t bit_precision, uintptr_t numer_mask) {
11032 const uint64_t bit_offset = prob_offset * bit_precision;
11033 uint64_t relevant_bits;
11034 // This can read slightly past the end of the buffer.
11035 memcpy(&relevant_bits, &(prob_start[bit_offset / CHAR_BIT]), sizeof(int64_t));
11036 return (relevant_bits >> (bit_offset % CHAR_BIT)) & numer_mask;
11037 }
11038
11039 HEADER_INLINE void Bgen13GetTwoVals(const unsigned char* prob_start, uint64_t prob_offset, uint32_t bit_precision, uintptr_t numer_mask, uintptr_t* first_val_ptr, uintptr_t* second_val_ptr) {
11040 const uint64_t bit_offset = prob_offset * bit_precision;
11041 uint64_t relevant_bits;
11042 // This can read slightly past the end of the buffer.
11043 // Note that with bit_precision=29 and variable ploidy,
11044 // (bit_offset % CHAR_BIT) == 7 is possible, so we may only get 57 bits when
11045 // we need 58; thus we don't support 29-31 bits for now.
11046 memcpy(&relevant_bits, &(prob_start[bit_offset / CHAR_BIT]), sizeof(int64_t));
11047 relevant_bits = relevant_bits >> (bit_offset % CHAR_BIT);
11048 *first_val_ptr = relevant_bits & numer_mask;
11049 *second_val_ptr = (relevant_bits >> bit_precision) & numer_mask;
11050 }
11051
11052 // returns nonzero if phase or dosage found.
11053 uint32_t Bgen13ScanBiallelicPhased(uintptr_t numer_a1, uintptr_t numer_a2, uintptr_t numer_mask, uint32_t numer_certainty_min, uint64_t magic_preadd, uint64_t magic_mult, uint32_t magic_postshift, uint32_t dosage_erase_halfdist) {
11054 // we're almost certainly exiting quickly, so hardcall bypass is unimportant
11055 // here.
11056
11057 // --import-dosage-certainty: Original plan was to treat the haplotype
11058 // dosages as independent, but unfortunately that produces a gross
11059 // export-reimport discontinuity. To avoid that discontinuity, we should
11060 // assume maximal het probability.
11061 const uintptr_t numer_sum = numer_a1 + numer_a2;
11062 if (numer_certainty_min) {
11063 const uint32_t dist_from_1 = abs_i32(numer_sum - numer_mask);
11064 if ((dist_from_1 < numer_certainty_min) && (numer_mask - dist_from_1 < numer_certainty_min)) {
11065 return 0;
11066 }
11067 }
11068 const uint32_t write_dosage_int = (magic_preadd + magic_mult * numer_sum) >> magic_postshift;
11069 if (numer_a1 != numer_a2) {
11070 // 'Found' if we save phase OR dosage info.
11071 // * Dosage is erased if phasedist1 and phasedist2 are both >=
11072 // dphase_erase_halfdist. But we still save phase if the two sides don't
11073 // round to the same integer.
11074 // * Otherwise, we usually save dosage. However, there's one exception:
11075 // write_dphase_delta_val == 0 and the dosage_erase_halfdist inequality
11076 // holds. Then we just save an unphased hardcall.
11077
11078 // +numer_mask to force this to be nonnegative
11079 const uint32_t write_dphase_delta_p1 = (magic_preadd + magic_mult * (numer_a1 + numer_mask - numer_a2)) >> magic_postshift;
11080 const int32_t write_dphase_delta_val = write_dphase_delta_p1 - kDosageMid;
11081
11082 // now on 0..32768 scale
11083 const uint32_t dphase_side1 = write_dosage_int + write_dphase_delta_val;
11084 const uint32_t dphase_side2 = write_dosage_int - write_dphase_delta_val;
11085
11086 const uint32_t dphase_halfdist1 = DphaseHalfdist(dphase_side1);
11087 const uint32_t dphase_halfdist2 = DphaseHalfdist(dphase_side2);
11088 const uint32_t dphase_erase_halfdist = dosage_erase_halfdist + kDosage4th;
11089 if ((dphase_halfdist1 >= dphase_erase_halfdist) && (dphase_halfdist2 >= dphase_erase_halfdist)) {
11090 return (((dphase_side1 + kDosageMid) ^ (dphase_side2 + kDosageMid)) & kDosageMax);
11091 }
11092 if (write_dphase_delta_val != 0) {
11093 return 1;
11094 }
11095 }
11096 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
11097 return (halfdist < dosage_erase_halfdist);
11098 }
11099
11100 /*
11101 // Reliably fast division by constants of the form 2^n - 1; see
11102 // http://ridiculousfish.com/blog/posts/labor-of-division-episode-iii.html
11103 // The general case also requires a preshift parameter, but it's always zero
11104 // for the odd .bgen denominators.
11105 typedef struct BgenMagicNumStruct {
11106 uint64_t totq_magic;
11107 uint32_t totq_postshift;
11108 uint32_t totq_incr;
11109 } BgenMagicNum;
11110
11111 static const BgenMagicNum kBgenMagicNums[25] = {
11112 {0, 0, 0},
11113 {1, 0, 0},
11114 {2863311531U, 33, 0},
11115 {1227133513U, 33, 1},
11116 {2290649225U, 35, 0},
11117 {1108378657U, 35, 1},
11118 {1090785345U, 36, 1},
11119 {270549121, 35, 1},
11120 {2155905153U, 39, 0},
11121 {134480385, 36, 1},
11122 {1074791425U, 40, 1},
11123 {4196353, 33, 1},
11124 {16781313, 36, 1},
11125 {67117057, 39, 1},
11126 {268451841, 42, 1},
11127 {1073774593U, 45, 1},
11128 {2147516417U, 47, 0},
11129 {131073, 34, 1},
11130 {262145, 36, 1},
11131 {524289, 38, 1},
11132 {1048577, 40, 1},
11133 {2097153, 42, 1},
11134 {4194305, 44, 1},
11135 {8388609, 46, 1},
11136 {16777217, 48, 1}
11137 // need to switch to a different algorithm past this point thanks to overflow
11138 // issues
11139 };
11140 */
11141
11142 // bgen-1.3 diploid import requires the following operation (haploid is
11143 // identical except b is always zero):
11144 // round((32768a + 16384b)/(2^{bit precision} - 1))
11145 // floor((32768a + 16384b)/(2^{bit_precision} - 1) + 0.5)
11146 // = floor((32768a + 16384b + 2^{bit_precision - 1})
11147 // / (2^{bit_precision} - 1))
11148 // = (totq_magic * (32768a + 16384b + 2^{bits-1} + totq_incr))
11149 // >> totq_postshift
11150 //
11151 // This works fine for bit_precision <= 16, anyway. There are two issues which
11152 // come up with higher precision:
11153 // 1. The ridiculous_fish magic numbers assume a 32-bit dividend. Our dividend
11154 // is guaranteed to be divisible by 2^14, but it can be as large as
11155 // (2^{bits} - 1) * 2^15 + 2^{bits-1}.
11156 // 2. Relatedly, the current sequence of operations multiplies totq_magic by
11157 // (dividend + totq_incr) (where totq_incr is zero or one); this
11158 // intermediate result must not overflow a uint64_t.
11159 // It turns out that neither of these problems are relevant for bit_precision
11160 // in [17, 24], but there's a failure at bits=25.
11161 //
11162 // However, the following rearrangement works for bits in [2, 31]:
11163 // (preadd + (totq_magic * (2a + b))) >> (totq_postshift - 14)
11164 // where preadd := (totq_magic * (2^{bits-1} + totq_incr)) >> 14
11165 // and setting {preadd = 0, mult = 2^14, postshift = 0} works well enough for
11166 // bits=1.
11167 // It fails for bits=32, 2a+b=2147614719.
11168 //
11169 // The following code was used to generate and validate the body of the table
11170 // below:
11171 // for (uint32_t uii = 2; uii <= 31; ++uii) {
11172 // const uint32_t divisor = (1LLU << uii) - 1U;
11173 // uint64_t mult;
11174 // uint32_t preshift;
11175 // uint32_t postshift;
11176 // uint32_t incr;
11177 // DivisionMagicNums(divisor, &mult, &preshift, &postshift, &incr);
11178 // const uint64_t half = 1U << (uii - 1);
11179 // const uint64_t preadd = (mult * (half + incr)) >> 14;
11180 // const uint32_t postshift_m14 = postshift - 14;
11181 // printf("{%llu%s, %llu%s, %u},\n", preadd, (preadd > 0x7fffffff)? "LLU" : "", mult, (mult > 0x7fffffff)? "U" : "", postshift_m14);
11182 // for (uint64_t ullii = 0; ullii <= 2 * divisor; ++ullii) {
11183 // uint64_t numer = ullii * 16384;
11184 // uint64_t true_result = (numer + half) / divisor;
11185 // uint64_t my_result = (preadd + mult * ullii) >> postshift_m14;
11186 // if (true_result != my_result) {
11187 // printf("failure: bits=%u, 2a+b=%llu\n", uii, ullii);
11188 // exit(1);
11189 // }
11190 // }
11191 // }
11192
11193 static_assert(kDosageMid == 16384, "bgen-1.3 import magic numbers must be changed.");
11194 typedef struct BgenMagicNumStruct {
11195 uint64_t preadd;
11196 uint32_t mult; // must copy this into a uint64_t
11197 uint32_t postshift;
11198 } BgenMagicNum;
11199
11200 // We throw a not-yet-supported error on bits>28 for now.
11201 CONSTI32(kMaxBgenImportBits, 28);
11202
11203 static const BgenMagicNum kBgenMagicNums[kMaxBgenImportBits + 1] = {
11204 {0, 0, 0},
11205 {0, 16384, 0},
11206 {349525, 2863311531U, 19},
11207 {374491, 1227133513, 19},
11208 {1118481, 2290649225U, 21},
11209 {1150051, 1108378657, 21},
11210 {2197016, 1090785345, 22},
11211 {1073345, 270549121, 21},
11212 {16843009, 2155905153U, 25},
11213 {2109464, 134480385, 22},
11214 {33652832, 1074791425, 26},
11215 {262528, 4196353, 19},
11216 {2098688, 16781313, 22},
11217 {16783360, 67117057, 25},
11218 {134242305, 268451841, 28},
11219 {1073840131, 1073774593, 31},
11220 {4295032834LLU, 2147516417U, 33},
11221 {524300, 131073, 20},
11222 {2097176, 262145, 22},
11223 {8388656, 524289, 24},
11224 {33554528, 1048577, 26},
11225 {134217920, 2097153, 28},
11226 {536871296, 4194305, 30},
11227 {2147484416LLU, 8388609, 32},
11228 {8589936128LLU, 16777217, 34},
11229 {34359741440LLU, 33554433, 36},
11230 {137438959616LLU, 67108865, 38},
11231 {549755826176LLU, 134217729, 40},
11232 {2199023280128LLU, 268435457, 42}
11233 // ,{8796093071360LLU, 536870913, 44}
11234 // ,{35184372187136LLU, 1073741825, 46}
11235 // ,{140737488551936LLU, 2147483649U, 48}
11236 };
11237
11238 typedef struct Bgen13DosageOrPhaseScanCtxStruct {
11239 BgenImportCommon* common;
11240 // For each bit precision level, how large must
11241 // max(numerators, 2^{bit_precision} - 1 - [sum of numerators])
11242 // be to avoid throwing out the genotype?
11243 // Idempotence (consistently get same data back after export and reimport) is
11244 // not possible for --import-dosage-certainty, so we may as well operate on
11245 // the pre-conversion numerators.
11246 uint32_t* bgen_import_dosage_certainty_thresholds;
11247
11248 unsigned char** thread_wkspaces;
11249
11250 uint32_t* thread_bidxs[2];
11251 uint16_t* bgen_allele_cts[2];
11252 uint32_t* uncompressed_genodata_byte_cts[2];
11253
11254 const char** err_extra;
11255
11256 // high 32 bits = bidx, earlier one takes precedence
11257 // next 16 bits = tidx if relevant (to look up err_extra)
11258 // next 8 bits = uint8_t(BgenImportErrSubtype)
11259 // low 8 bits = uint8_t(PglErr)
11260 uint64_t err_info;
11261
11262 uint32_t error_on_polyploid;
11263 uint32_t vidx_start;
11264
11265 uint32_t dosage_exists;
11266 } Bgen13DosageOrPhaseScanCtx;
11267
11268 ENUM_U31_DEF_START()
11269 kBgenImportErrSubtype0,
11270 kBgenImportErrSubtypeLibdeflateZdecompress,
11271 kBgenImportErrSubtypeZstdDecompress,
11272 kBgenImportErrSubtypeSampleCtMismatch,
11273 kBgenImportErrSubtypePloidyOutOfRange,
11274 kBgenImportErrSubtypePolyploid,
11275 kBgenImportErrSubtypeIsPhasedOutOfRange,
11276 kBgenImportErrSubtypeBitPrecisionOutOfRange,
11277 kBgenImportErrSubtypeBitPrecisionUnsupported,
11278 kBgenImportErrSubtypeAlleleCtUnsupported,
11279 kBgenImportErrSubtypeUncompressedByteCtMismatch,
11280 kBgenImportErrSubtypeNumeratorOverflow,
11281 kBgenImportErrSubtypeProbOffsetMismatch,
11282 kBgenImportErrSubtypeInvalidMissingPloidy,
11283 ENUM_U31_DEF_END(BgenImportErrSubtype);
11284
11285 void PrintBgenImportErr(const char** err_extra, uint64_t err_info, uint32_t vidx_base) {
11286 const BgenImportErrSubtype err_subtype = S_CAST(BgenImportErrSubtype, (err_info >> 8) & 255);
11287 const uint32_t vidx = (err_info >> 32) + vidx_base;
11288 logputs("\n");
11289 switch (err_subtype) {
11290 case kBgenImportErrSubtypeLibdeflateZdecompress:
11291 snprintf(g_logbuf, kLogbufSize, "Error: .bgen libdeflate_zlib_decompress() failure, vidx=%u.\n", vidx);
11292 break;
11293 case kBgenImportErrSubtypeZstdDecompress:
11294 {
11295 const uint32_t tidx = (err_info >> 16) & 65535;
11296 snprintf(g_logbuf, kLogbufSize, "Error: .bgen ZSTD_decompress() failure, vidx=%u: %s\n", vidx, err_extra[tidx]);
11297 }
11298 break;
11299 case kBgenImportErrSubtypeSampleCtMismatch:
11300 snprintf(g_logbuf, kLogbufSize, "Error: .bgen sample_ct mismatch, vidx=%u.\n", vidx);
11301 break;
11302 case kBgenImportErrSubtypePloidyOutOfRange:
11303 snprintf(g_logbuf, kLogbufSize, "Error: .bgen ploidy out of range, vidx=%u.\n", vidx);
11304 break;
11305 case kBgenImportErrSubtypePolyploid:
11306 snprintf(g_logbuf, kLogbufSize, "Error: Polyploid genotype in .bgen file, vidx=%u.\n", vidx);
11307 break;
11308 case kBgenImportErrSubtypeIsPhasedOutOfRange:
11309 snprintf(g_logbuf, kLogbufSize, "Error: .bgen is_phased out of range, vidx=%u.\n", vidx);
11310 break;
11311 case kBgenImportErrSubtypeBitPrecisionOutOfRange:
11312 snprintf(g_logbuf, kLogbufSize, "Error: .bgen bit_precision out of range, vidx=%u.\n", vidx);
11313 break;
11314 case kBgenImportErrSubtypeBitPrecisionUnsupported:
11315 snprintf(g_logbuf, kLogbufSize, "Error: .bgen bit_precision unsupported, vidx=%u.\n", vidx);
11316 break;
11317 case kBgenImportErrSubtypeAlleleCtUnsupported:
11318 snprintf(g_logbuf, kLogbufSize, "Error: .bgen allele_ct unsupported, vidx=%u.\n", vidx);
11319 break;
11320 case kBgenImportErrSubtypeUncompressedByteCtMismatch:
11321 snprintf(g_logbuf, kLogbufSize, "Error: .bgen uncompressed_byte_ct mismatch, vidx=%u.\n", vidx);
11322 break;
11323 case kBgenImportErrSubtypeNumeratorOverflow:
11324 snprintf(g_logbuf, kLogbufSize, "Error: .bgen numerator overflow, vidx=%u.\n", vidx);
11325 break;
11326 case kBgenImportErrSubtypeProbOffsetMismatch:
11327 snprintf(g_logbuf, kLogbufSize, "Error: .bgen prob_offset mismatch, vidx=%u.\n", vidx);
11328 break;
11329 case kBgenImportErrSubtypeInvalidMissingPloidy:
11330 snprintf(g_logbuf, kLogbufSize, "Error: Invalid .bgen missing_and_ploidy byte, vidx=%u.\n", vidx);
11331 break;
11332 default:
11333 ;
11334 const PglErr reterr = S_CAST(PglErr, err_info & 255);
11335 if (reterr == kPglRetNomem) {
11336 return;
11337 }
11338 assert(0);
11339 snprintf(g_logbuf, kLogbufSize, "Error: .bgen import internal error, vidx=%u.\n", vidx);
11340 }
11341 WordWrapB(0);
11342 logerrputsb();
11343 }
11344
11345 static_assert(sizeof(Dosage) == 2, "Bgen13DosageOrPhaseScanThread() needs to be updated.");
11346 THREAD_FUNC_DECL Bgen13DosageOrPhaseScanThread(void* raw_arg) {
11347 // This bails as soon as a single phased or dosage call is detected; that's
11348 // enough to determine the header format.
11349 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
11350 const uintptr_t tidx = arg->tidx;
11351 Bgen13DosageOrPhaseScanCtx* ctx = S_CAST(Bgen13DosageOrPhaseScanCtx*, arg->sharedp->context);
11352 BgenImportCommon* bicp = ctx->common;
11353
11354 const uint32_t sample_ct = bicp->sample_ct;
11355 const uint32_t dosage_erase_halfdist = bicp->dosage_erase_halfdist;
11356 const uint32_t* bgen_import_dosage_certainty_thresholds = ctx->bgen_import_dosage_certainty_thresholds;
11357 const uint32_t compression_mode = bicp->compression_mode;
11358 const unsigned char* cur_uncompressed_geno = nullptr;
11359 struct libdeflate_decompressor* decompressor = bicp->libdeflate_decompressors[tidx];
11360 if (compression_mode) {
11361 cur_uncompressed_geno = ctx->thread_wkspaces[tidx];
11362 }
11363 uint32_t parity = 0;
11364 uint64_t new_err_info = 0;
11365 do {
11366 {
11367 const uint32_t bidx_end = ctx->thread_bidxs[parity][tidx + 1];
11368 uint32_t bidx = ctx->thread_bidxs[parity][tidx];
11369 unsigned char** compressed_geno_starts = bicp->compressed_geno_starts[parity];
11370 const uint16_t* bgen_allele_cts = ctx->bgen_allele_cts[parity];
11371 const uint32_t* uncompressed_genodata_byte_cts = ctx->uncompressed_genodata_byte_cts[parity];
11372 for (; bidx != bidx_end; ++bidx) {
11373 const unsigned char* compressed_geno_start = compressed_geno_starts[bidx];
11374 const unsigned char* compressed_geno_end = compressed_geno_starts[bidx + 1];
11375 uint32_t compressed_byte_ct = compressed_geno_end - compressed_geno_start;
11376 uint32_t uncompressed_byte_ct;
11377 if (compression_mode) {
11378 uncompressed_byte_ct = uncompressed_genodata_byte_cts[bidx];
11379 if (compression_mode == 1) {
11380 if (unlikely(libdeflate_zlib_decompress(decompressor, compressed_geno_start, compressed_byte_ct, K_CAST(unsigned char*, cur_uncompressed_geno), uncompressed_byte_ct, nullptr) != LIBDEFLATE_SUCCESS)) {
11381 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeLibdeflateZdecompress) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11382 goto Bgen13DosageOrPhaseScanThread_err;
11383 }
11384 } else {
11385 const uintptr_t extracted_byte_ct = ZSTD_decompress(K_CAST(unsigned char*, cur_uncompressed_geno), uncompressed_byte_ct, compressed_geno_start, compressed_byte_ct);
11386 if (unlikely(extracted_byte_ct != uncompressed_byte_ct)) {
11387 assert(ZSTD_isError(extracted_byte_ct));
11388 ctx->err_extra[tidx] = ZSTD_getErrorName(extracted_byte_ct);
11389 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (tidx << 16) | (S_CAST(uint32_t, kBgenImportErrSubtypeZstdDecompress) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11390 goto Bgen13DosageOrPhaseScanThread_err;
11391 }
11392 }
11393 } else {
11394 cur_uncompressed_geno = compressed_geno_start;
11395 uncompressed_byte_ct = compressed_byte_ct;
11396 }
11397 // 4 bytes: sample_ct
11398 // 2 bytes: # of alleles, must match bgen_allele_cts[bidx]
11399 // 1 byte: min ploidy
11400 // 1 byte: max ploidy
11401 // sample_ct bytes: low 6 bits = ploidy, top bit = missingness
11402 // 1 byte: 1 if phased, 0 if not
11403 // 1 byte: # of bits of probability precision
11404 uint32_t stored_sample_ct;
11405 memcpy(&stored_sample_ct, cur_uncompressed_geno, sizeof(int32_t));
11406 if (unlikely((uncompressed_byte_ct < 10 + sample_ct) || (sample_ct != stored_sample_ct))) {
11407 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeSampleCtMismatch) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11408 goto Bgen13DosageOrPhaseScanThread_err;
11409 }
11410 const uint32_t cur_allele_ct = bgen_allele_cts[bidx];
11411 /*
11412 uint16_t stored_allele_ct;
11413 memcpy(&stored_allele_ct, &(cur_uncompressed_geno[4]), sizeof(int16_t));
11414 if (unlikely(stored_allele_ct != cur_allele_ct)) {
11415 goto Bgen13DosageOrPhaseScanThread_malformed;
11416 }
11417 */
11418 const uint32_t min_ploidy = cur_uncompressed_geno[6];
11419 const uint32_t max_ploidy = cur_uncompressed_geno[7];
11420 if (unlikely((min_ploidy > max_ploidy) || (max_ploidy > 63))) {
11421 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypePloidyOutOfRange) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11422 goto Bgen13DosageOrPhaseScanThread_err;
11423 }
11424 if (unlikely(max_ploidy > 2)) {
11425 if (ctx->error_on_polyploid) {
11426 // you can't fire me, I quit!
11427 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypePolyploid) << 8) | S_CAST(uint32_t, kPglRetInconsistentInput);
11428 goto Bgen13DosageOrPhaseScanThread_err;
11429 }
11430 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypePolyploid) << 8) | S_CAST(uint32_t, kPglRetNotYetSupported);
11431 goto Bgen13DosageOrPhaseScanThread_err;
11432 }
11433 const unsigned char* missing_and_ploidy_info = &(cur_uncompressed_geno[8]);
11434 const unsigned char* probs_start = &(cur_uncompressed_geno[10 + sample_ct]);
11435 const uint32_t is_phased = probs_start[-2];
11436 if (unlikely(is_phased > 1)) {
11437 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeIsPhasedOutOfRange) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11438 goto Bgen13DosageOrPhaseScanThread_err;
11439 }
11440 const uint32_t bit_precision = probs_start[-1];
11441 if (unlikely((!bit_precision) || (bit_precision > 32))) {
11442 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeBitPrecisionOutOfRange) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11443 goto Bgen13DosageOrPhaseScanThread_err;
11444 }
11445 if (unlikely(bit_precision > kMaxBgenImportBits)) {
11446 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeBitPrecisionUnsupported) << 8) | S_CAST(uint32_t, kPglRetNotYetSupported);
11447 goto Bgen13DosageOrPhaseScanThread_err;
11448 }
11449
11450 if (cur_allele_ct != 2) {
11451 // shouldn't be possible to get here for now
11452 assert(0);
11453 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeAlleleCtUnsupported) << 8) | S_CAST(uint32_t, kPglRetNotYetSupported);
11454 goto Bgen13DosageOrPhaseScanThread_err;
11455 }
11456 const uint64_t magic_preadd = kBgenMagicNums[bit_precision].preadd;
11457 const uint64_t magic_mult = kBgenMagicNums[bit_precision].mult;
11458 const uint32_t magic_postshift = kBgenMagicNums[bit_precision].postshift;
11459
11460 // also equal to denominator
11461 const uintptr_t numer_mask = (1U << bit_precision) - 1;
11462
11463 uint32_t numer_certainty_min = 0;
11464 if (bgen_import_dosage_certainty_thresholds) {
11465 numer_certainty_min = bgen_import_dosage_certainty_thresholds[bit_precision];
11466 }
11467
11468 if (min_ploidy == max_ploidy) {
11469 // faster handling of common cases (no need to keep checking if
11470 // we've read past the end)
11471 if (unlikely(uncompressed_byte_ct != 10 + sample_ct + DivUp(S_CAST(uint64_t, bit_precision) * max_ploidy * sample_ct, CHAR_BIT))) {
11472 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeUncompressedByteCtMismatch) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11473 goto Bgen13DosageOrPhaseScanThread_err;
11474 }
11475 if (max_ploidy < 2) {
11476 if (!max_ploidy) {
11477 // don't need to do anything in all-ploidy-0 case
11478 continue;
11479 }
11480 // biallelic, haploid
11481 // make sample_idx uint64_t so that when we multiply it by
11482 // bit_precision to get bit_offset, we don't have to worry about
11483 // overflow
11484 for (uintptr_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
11485 const uint32_t missing_and_ploidy = missing_and_ploidy_info[sample_idx];
11486 // treat anything else as missing
11487 if (missing_and_ploidy != 1) {
11488 continue;
11489 }
11490 const uintptr_t numer_a = Bgen13GetOneVal(probs_start, sample_idx, bit_precision, numer_mask);
11491 if ((numer_a < numer_certainty_min) && (numer_mask - numer_certainty_min < numer_a)) {
11492 continue;
11493 }
11494 const uint32_t write_dosage_int = (magic_preadd + magic_mult * 2 * numer_a) >> magic_postshift;
11495 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
11496 if (halfdist < dosage_erase_halfdist) {
11497 goto Bgen13DosageOrPhaseScanThread_found;
11498 }
11499 }
11500 continue;
11501 }
11502 // could combine the diploid phased and unphased cases into one loop,
11503 // but much of the similarity is superficial: ((2 + 1) choose 2) - 1
11504 // just happens to be equal to (2 - 1) * 2
11505 if (!is_phased) {
11506 // It's likely only one thread can execute this due to memory
11507 // limitations (since we don't know whether multiallelic variants
11508 // are present in advance, we try to use 4 GiB buffers), so this is
11509 // frequently more of a bottleneck than the full-decode loop when
11510 // no phase or dosage info is in the file.
11511 uintptr_t sample_idx = 0;
11512 #ifdef __LP64__
11513 // Fast paths for common cases.
11514 if (bit_precision == 8) {
11515 // 1x2 bytes per entry
11516 const uint32_t full_vec_ct = sample_ct / kInt16PerVec;
11517 // If all bytes are equal to 0 or numer_mask, all calls in this
11518 // block must be hardcall/missing.
11519 const VecUc vec0 = vecuc_setzero();
11520 const VecUc vecmax = vecuc_set1(numer_mask);
11521 uint32_t vec_idx = 0;
11522 for (; vec_idx != full_vec_ct; ++vec_idx) {
11523 const VecUc cur_vec = vecuc_loadu(&(probs_start[vec_idx * kBytesPerVec]));
11524 const VecUc safe_bytes = (cur_vec == vec0) | (cur_vec == vecmax);
11525 if (!vec0255_is_all_set(safe_bytes)) {
11526 break;
11527 }
11528 }
11529 sample_idx = vec_idx * kInt16PerVec;
11530 } else if (bit_precision == 16) {
11531 // 2x2 bytes per entry
11532 const uint32_t full_vec_ct = sample_ct / (kBytesPerVec / 4);
11533 // If all uint16s are equal to 0 or numer_mask, all calls in this
11534 // block must be hardcall/missing.
11535 const VecU16 vec0 = vecu16_setzero();
11536 const VecU16 vecmax = vecu16_set1(numer_mask);
11537 uint32_t vec_idx = 0;
11538 for (; vec_idx != full_vec_ct; ++vec_idx) {
11539 const VecU16 cur_vec = vecu16_loadu(&(probs_start[vec_idx * kBytesPerVec]));
11540 const VecU16 safe_u16s = (cur_vec == vec0) | (cur_vec == vecmax);
11541 if (!vec0255u16_is_all_set(safe_u16s)) {
11542 break;
11543 }
11544 }
11545 sample_idx = vec_idx * (kBytesPerVec / 4);
11546 }
11547 #endif
11548 for (; sample_idx != sample_ct; ++sample_idx) {
11549 const uint32_t missing_and_ploidy = missing_and_ploidy_info[sample_idx];
11550 // treat anything else as missing
11551 if (missing_and_ploidy != 2) {
11552 continue;
11553 }
11554 uintptr_t numer_aa;
11555 uintptr_t numer_ab;
11556 Bgen13GetTwoVals(probs_start, sample_idx * 2, bit_precision, numer_mask, &numer_aa, &numer_ab);
11557 // common trivial cases
11558 if (!numer_aa) {
11559 if ((!numer_ab) || (numer_ab == numer_mask)) {
11560 continue;
11561 }
11562 } else if ((numer_aa == numer_mask) && (!numer_ab)) {
11563 continue;
11564 }
11565 if ((numer_aa < numer_certainty_min) && (numer_ab < numer_certainty_min) && (numer_mask - numer_certainty_min < numer_aa + numer_ab)) {
11566 // treat as missing
11567 continue;
11568 }
11569 const uint32_t write_dosage_int = (magic_preadd + magic_mult * (2 * numer_aa + numer_ab)) >> magic_postshift;
11570 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
11571 if (halfdist < dosage_erase_halfdist) {
11572 goto Bgen13DosageOrPhaseScanThread_found;
11573 }
11574 }
11575 continue;
11576 }
11577 // biallelic, phased, diploid
11578 for (uintptr_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
11579 const uint32_t missing_and_ploidy = missing_and_ploidy_info[sample_idx];
11580 if (missing_and_ploidy != 2) {
11581 continue;
11582 }
11583 uintptr_t numer_a1;
11584 uintptr_t numer_a2;
11585 Bgen13GetTwoVals(probs_start, sample_idx * 2, bit_precision, numer_mask, &numer_a1, &numer_a2);
11586 if (Bgen13ScanBiallelicPhased(numer_a1, numer_a2, numer_mask, numer_certainty_min, magic_preadd, magic_mult, magic_postshift, dosage_erase_halfdist)) {
11587 goto Bgen13DosageOrPhaseScanThread_found;
11588 }
11589 }
11590 continue;
11591 }
11592 // biallelic, variable ploidy
11593 const uint64_t remaining_bit_ct = 8LLU * (uncompressed_byte_ct - S_CAST(uintptr_t, probs_start - cur_uncompressed_geno));
11594 const uint64_t prob_offset_end = remaining_bit_ct / bit_precision;
11595 uintptr_t prob_offset = 0;
11596 if (!is_phased) {
11597 for (uintptr_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
11598 uint32_t missing_and_ploidy = missing_and_ploidy_info[sample_idx];
11599 if (missing_and_ploidy == 2) {
11600 if (unlikely(prob_offset + 2 > prob_offset_end)) {
11601 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeProbOffsetMismatch) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11602 goto Bgen13DosageOrPhaseScanThread_err;
11603 }
11604 uintptr_t numer_aa;
11605 uintptr_t numer_ab;
11606 Bgen13GetTwoVals(probs_start, prob_offset, bit_precision, numer_mask, &numer_aa, &numer_ab);
11607 prob_offset += 2;
11608 if ((numer_aa < numer_certainty_min) && (numer_ab < numer_certainty_min) && (numer_mask - numer_certainty_min < numer_aa + numer_ab)) {
11609 // treat as missing
11610 continue;
11611 }
11612 const uint32_t write_dosage_int = (magic_preadd + magic_mult * (2 * numer_aa + numer_ab)) >> magic_postshift;
11613 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
11614 if (halfdist < dosage_erase_halfdist) {
11615 goto Bgen13DosageOrPhaseScanThread_found;
11616 }
11617 } else {
11618 if (missing_and_ploidy == 1) {
11619 // this is slightly liberal (we don't care to validate in
11620 // missing case); implementation would be different in a bgen
11621 // validator
11622 // note that this can't be moved before the if(), since
11623 // missing-ploidy could be zero
11624 if (unlikely(prob_offset >= prob_offset_end)) {
11625 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeProbOffsetMismatch) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11626 goto Bgen13DosageOrPhaseScanThread_err;
11627 }
11628 const uintptr_t numer_a = Bgen13GetOneVal(probs_start, prob_offset, bit_precision, numer_mask);
11629 ++prob_offset;
11630 if ((numer_a < numer_certainty_min) && (numer_mask - numer_certainty_min < numer_a)) {
11631 continue;
11632 }
11633 const uint32_t write_dosage_int = (magic_preadd + magic_mult * numer_a * 2) >> magic_postshift;
11634 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
11635 if (halfdist < dosage_erase_halfdist) {
11636 goto Bgen13DosageOrPhaseScanThread_found;
11637 }
11638 } else {
11639 // treat as missing
11640 missing_and_ploidy &= 127;
11641 if (unlikely(missing_and_ploidy > 2)) {
11642 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeInvalidMissingPloidy) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11643 goto Bgen13DosageOrPhaseScanThread_err;
11644 }
11645 prob_offset += missing_and_ploidy;
11646 }
11647 }
11648 }
11649 continue;
11650 }
11651 // biallelic, variable ploidy, phased
11652 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
11653 uint32_t missing_and_ploidy = missing_and_ploidy_info[sample_idx];
11654 if (missing_and_ploidy == 2) {
11655 if (unlikely(prob_offset + 2 > prob_offset_end)) {
11656 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeProbOffsetMismatch) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11657 goto Bgen13DosageOrPhaseScanThread_err;
11658 }
11659 uintptr_t numer_a1;
11660 uintptr_t numer_a2;
11661 Bgen13GetTwoVals(probs_start, prob_offset, bit_precision, numer_mask, &numer_a1, &numer_a2);
11662 prob_offset += 2;
11663 if (Bgen13ScanBiallelicPhased(numer_a1, numer_a2, numer_mask, numer_certainty_min, magic_preadd, magic_mult, magic_postshift, dosage_erase_halfdist)) {
11664 goto Bgen13DosageOrPhaseScanThread_found;
11665 }
11666 } else {
11667 if (missing_and_ploidy == 1) {
11668 if (unlikely(prob_offset >= prob_offset_end)) {
11669 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeProbOffsetMismatch) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11670 goto Bgen13DosageOrPhaseScanThread_err;
11671 }
11672 const uintptr_t numer_a = Bgen13GetOneVal(probs_start, prob_offset, bit_precision, numer_mask);
11673 ++prob_offset;
11674 if ((numer_a < numer_certainty_min) && (numer_mask - numer_certainty_min < numer_a)) {
11675 continue;
11676 }
11677 const uint32_t write_dosage_int = (magic_preadd + magic_mult * numer_a * 2) >> magic_postshift;
11678 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
11679 if (halfdist < dosage_erase_halfdist) {
11680 goto Bgen13DosageOrPhaseScanThread_found;
11681 }
11682 } else {
11683 // treat as missing
11684 missing_and_ploidy &= 127;
11685 if (unlikely(missing_and_ploidy > 2)) {
11686 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeInvalidMissingPloidy) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11687 goto Bgen13DosageOrPhaseScanThread_err;
11688 }
11689 prob_offset += missing_and_ploidy;
11690 }
11691 }
11692 }
11693 }
11694 }
11695 while (0) {
11696 Bgen13DosageOrPhaseScanThread_found:
11697 ctx->dosage_exists = 1;
11698 break;
11699 }
11700 parity = 1 - parity;
11701 } while (!THREAD_BLOCK_FINISH(arg));
11702 while (0) {
11703 Bgen13DosageOrPhaseScanThread_err:
11704 UpdateU64IfSmaller(new_err_info, &ctx->err_info);
11705 THREAD_BLOCK_FINISH(arg);
11706 break;
11707 }
11708 THREAD_RETURN;
11709 }
11710
11711
11712 // two trivial cases manually checked before this function is called, compiler
11713 // is currently too dumm to handle them appropriately quickly if they're the
11714 // first lines of this function, even when it's inline
11715 // returns 1 if no dosage
11716 // todo: more tests re: whether this should be inlined
11717 uint32_t Bgen13ConvertBiallelicPhased(uint32_t sample_idx_lowbits, uintptr_t numer_a1, uintptr_t numer_a2, uintptr_t numer_mask, uint32_t numer_certainty_min, uint64_t magic_preadd, uint64_t magic_mult, uint32_t magic_postshift, uint32_t hard_call_halfdist, uint32_t dosage_erase_halfdist, uintptr_t* genovec_word_ptr, uint32_t* __restrict phasepresent_hw_ptr, uint32_t* __restrict phaseinfo_hw_ptr, uint32_t* __restrict dphase_present_hw_ptr, SDosage** dphase_delta_iterp, uint32_t* write_dosage_int_ptr) {
11718 const uint32_t sample_idx_lowbits_x2 = sample_idx_lowbits * 2;
11719 if (numer_certainty_min) {
11720 // bugfix (29 Apr 2019): This check was not implemented correctly.
11721 //
11722 // Correct VCF HDS-import code:
11723 // dist_from_1 = fabs(1.0 - dosage_sum);
11724 // if ((1.0 - dist_from_1 <= import_dosage_certainty) && (dist_from_1 <= import_dosage_certainty)) {
11725 // (force missing)
11726 // }
11727 const uintptr_t numer_sum = numer_a1 + numer_a2;
11728 const uint32_t dist_from_1 = abs_i32(numer_sum - numer_mask);
11729 if ((dist_from_1 < numer_certainty_min) && (numer_mask - dist_from_1 < numer_certainty_min)) {
11730 *genovec_word_ptr |= (3 * k1LU) << sample_idx_lowbits_x2;
11731 return 1;
11732 }
11733 }
11734 const uint32_t write_dosage_int = (magic_preadd + magic_mult * (numer_a1 + numer_a2)) >> magic_postshift;
11735 if (numer_a1 == numer_a2) {
11736 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
11737 if (halfdist < hard_call_halfdist) {
11738 *genovec_word_ptr |= (3 * k1LU) << sample_idx_lowbits_x2;
11739 } else {
11740 *genovec_word_ptr |= ((write_dosage_int + (kDosage4th * k1LU)) / kDosageMid) << sample_idx_lowbits_x2;
11741 if (halfdist >= dosage_erase_halfdist) {
11742 return 1;
11743 }
11744 }
11745 *write_dosage_int_ptr = write_dosage_int;
11746 return 0;
11747 }
11748 const uint32_t write_dphase_delta_p1 = (magic_preadd + magic_mult * (numer_a1 + numer_mask - numer_a2)) >> magic_postshift;
11749 int32_t write_dphase_delta_val = write_dphase_delta_p1 - kDosageMid;
11750
11751 // now on 0..32768 scale
11752 const uint32_t dphase_side1 = write_dosage_int + write_dphase_delta_val;
11753 const uint32_t dphase_side2 = write_dosage_int - write_dphase_delta_val;
11754
11755 const uint32_t dphase_halfdist1 = DphaseHalfdist(dphase_side1);
11756 const uint32_t dphase_halfdist2 = DphaseHalfdist(dphase_side2);
11757 const uint32_t dphase_erase_halfdist = dosage_erase_halfdist + kDosage4th;
11758 if ((dphase_halfdist1 >= dphase_erase_halfdist) && (dphase_halfdist2 >= dphase_erase_halfdist)) {
11759 // --dosage-erase-threshold only applies to phased dosage when both sides
11760 // are within [threshold/2] of an integer; otherwise we have a
11761 // discontinuity between
11762 // dosage=0.103=0.0515|0.0515 (dphase omitted) and
11763 // dosage=0.103=0.051|0.052.
11764 // Note that, since we don't allow the --dosage-erase-threshold value
11765 // to exceed the --hard-call-threshold value, the dosage component of
11766 // 0|1:0.85 cannot be erased by any --dosage-erase-threshold setting when
11767 // importing with --hard-call-threshold 0.2; it is necessary to use e.g.
11768 // "--make-pgen erase-dosage" instead.
11769 const uintptr_t geno1 = (dphase_side1 + kDosageMid) / kDosageMax;
11770 const uintptr_t geno2 = (dphase_side2 + kDosageMid) / kDosageMax;
11771 uintptr_t cur_geno = geno1 + geno2;
11772 // This duplicate code isn't strictly necessary, but I expect it to pay off
11773 // since all phased-het hardcalls go here.
11774 *genovec_word_ptr |= cur_geno << sample_idx_lowbits_x2;
11775 if (cur_geno == 1) {
11776 *phasepresent_hw_ptr |= 1U << sample_idx_lowbits;
11777 *phaseinfo_hw_ptr |= geno1 << sample_idx_lowbits;
11778 }
11779 return 1;
11780 }
11781 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
11782 // reference allele assumed to be second here, so haplotype dosages are for
11783 // alt1.
11784 if (halfdist < hard_call_halfdist) {
11785 // --hard-call-threshold must not care about phased dosage; otherwise we
11786 // have a discontinuity between
11787 // dosage=0.998=0.499|0.499 (dphase omitted) and
11788 // 0.998=0.498|0.5.
11789 *genovec_word_ptr |= (3 * k1LU) << sample_idx_lowbits_x2;
11790 } else {
11791 const uintptr_t cur_geno = (write_dosage_int + (kDosage4th * k1LU)) / kDosageMid;
11792 *genovec_word_ptr |= cur_geno << sample_idx_lowbits_x2;
11793 if (cur_geno == 1) {
11794 // generate hardcall-phase from dosage-phase iff delta > 0.5.
11795 // bugfix (22 Apr 2018): (write_dphase_delta_val >> 31) is actually
11796 // undefined behavior for an int32_t; must cast to uint32_t first
11797 const uint32_t neg_sign_bit = -(S_CAST(uint32_t, write_dphase_delta_val) >> 31);
11798 const uint32_t abs_write_dphase_delta_val = (S_CAST(uint32_t, write_dphase_delta_val) ^ neg_sign_bit) - neg_sign_bit;
11799 if (abs_write_dphase_delta_val > kDosage4th) {
11800 *phasepresent_hw_ptr |= 1U << sample_idx_lowbits;
11801 // phaseinfo_hw bit set for 1|0
11802 // todo: check if branch is faster
11803 *phaseinfo_hw_ptr |= (neg_sign_bit + 1) << sample_idx_lowbits;
11804 if ((abs_write_dphase_delta_val == write_dosage_int) || (abs_write_dphase_delta_val + write_dosage_int == kDosageMax)) {
11805 // can omit explicit dphase_delta in this case
11806 write_dphase_delta_val = 0;
11807 }
11808 } else if ((halfdist >= dosage_erase_halfdist) && (!write_dphase_delta_val)) {
11809 // unphased het hardcall special case
11810 return 1;
11811 }
11812 }
11813 }
11814 // we should never get here in bit_precision == 1 case
11815 if (write_dphase_delta_val != 0) {
11816 *dphase_present_hw_ptr |= 1U << sample_idx_lowbits;
11817 **dphase_delta_iterp = write_dphase_delta_val;
11818 *dphase_delta_iterp += 1;
11819 }
11820 *write_dosage_int_ptr = write_dosage_int;
11821 return 0;
11822 }
11823
11824 typedef struct Bgen13GenoToPgenCtxStruct {
11825 BgenImportCommon* common;
11826 uint32_t error_on_polyploid;
11827 uint32_t hard_call_halfdist;
11828 uint32_t* bgen_import_dosage_certainty_thresholds;
11829 uint32_t prov_ref_allele_second;
11830
11831 unsigned char** thread_wkspaces;
11832 uint32_t* thread_bidxs[2];
11833 GparseRecord* gparse[2];
11834 const uintptr_t* block_allele_idx_offsets[2];
11835
11836 const char** err_extra;
11837
11838 uint64_t err_info;
11839 } Bgen13GenoToPgenCtx;
11840
11841 static_assert(sizeof(Dosage) == 2, "Bgen13GenoToPgenThread() needs to be updated.");
11842 THREAD_FUNC_DECL Bgen13GenoToPgenThread(void* raw_arg) {
11843 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
11844 const uintptr_t tidx = arg->tidx;
11845 Bgen13GenoToPgenCtx* ctx = S_CAST(Bgen13GenoToPgenCtx*, arg->sharedp->context);
11846 BgenImportCommon* bicp = ctx->common;
11847
11848 const uintptr_t sample_ct = bicp->sample_ct;
11849 const uint32_t hard_call_halfdist = ctx->hard_call_halfdist;
11850 const uint32_t dosage_erase_halfdist = bicp->dosage_erase_halfdist;
11851 const uint32_t* bgen_import_dosage_certainty_thresholds = ctx->bgen_import_dosage_certainty_thresholds;
11852 const uint32_t compression_mode = bicp->compression_mode;
11853 const uint32_t prov_ref_allele_second = ctx->prov_ref_allele_second;
11854 const uint32_t sample_ctl2_m1 = (sample_ct - 1) / kBitsPerWordD2;
11855 const uintptr_t sample_ctl = BitCtToWordCt(sample_ct);
11856 const unsigned char* cur_uncompressed_geno = ctx->thread_wkspaces[tidx];
11857 struct libdeflate_decompressor* decompressor = bicp->libdeflate_decompressors[tidx];
11858 uintptr_t* patch_01_set = nullptr;
11859 AlleleCode* patch_01_vals = nullptr;
11860 uintptr_t* patch_10_set = nullptr;
11861 AlleleCode* patch_10_vals = nullptr;
11862 uintptr_t* __attribute__((may_alias)) phasepresent = nullptr;
11863 uintptr_t* __attribute__((may_alias)) phaseinfo = nullptr;
11864 uintptr_t* __attribute__((may_alias)) dosage_present = nullptr;
11865 Dosage* dosage_main = nullptr;
11866 uintptr_t* __attribute__((may_alias)) dphase_present = nullptr;
11867 SDosage* dphase_delta = nullptr;
11868 uint32_t cur_allele_ct = 2;
11869 uint32_t parity = 0;
11870 uint64_t new_err_info = 0;
11871 do {
11872 {
11873 const uintptr_t* block_allele_idx_offsets = ctx->block_allele_idx_offsets[parity];
11874 const uint32_t bidx_end = ctx->thread_bidxs[parity][tidx + 1];
11875 uint32_t bidx = ctx->thread_bidxs[parity][tidx];
11876 GparseRecord* cur_gparse = ctx->gparse[parity];
11877
11878 for (; bidx != bidx_end; ++bidx) {
11879 GparseRecord* grp = &(cur_gparse[bidx]);
11880 const uint32_t compressed_byte_ct = grp->metadata.read_bgen.input_byte_ct;
11881 uint32_t uncompressed_byte_ct;
11882 if (compression_mode) {
11883 uncompressed_byte_ct = grp->metadata.read_bgen.uncompressed_byte_ct;
11884 if (compression_mode == 1) {
11885 if (unlikely(libdeflate_zlib_decompress(decompressor, grp->record_start, compressed_byte_ct, K_CAST(unsigned char*, cur_uncompressed_geno), uncompressed_byte_ct, nullptr) != LIBDEFLATE_SUCCESS)) {
11886 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeLibdeflateZdecompress) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11887 goto Bgen13GenoToPgenThread_err;
11888 }
11889 } else {
11890 const uintptr_t extracted_byte_ct = ZSTD_decompress(K_CAST(unsigned char*, cur_uncompressed_geno), uncompressed_byte_ct, grp->record_start, compressed_byte_ct);
11891 if (unlikely(extracted_byte_ct != uncompressed_byte_ct)) {
11892 assert(ZSTD_isError(extracted_byte_ct));
11893 ctx->err_extra[tidx] = ZSTD_getErrorName(extracted_byte_ct);
11894 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (tidx << 16) | (S_CAST(uint32_t, kBgenImportErrSubtypeZstdDecompress) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11895 goto Bgen13GenoToPgenThread_err;
11896 }
11897 }
11898 } else {
11899 uncompressed_byte_ct = compressed_byte_ct;
11900 memcpy(K_CAST(unsigned char*, cur_uncompressed_geno), grp->record_start, compressed_byte_ct);
11901 }
11902 // 4 bytes: sample_ct
11903 // 2 bytes: # of alleles, must match bgen_allele_cts[bidx]
11904 // 1 byte: min ploidy
11905 // 1 byte: max ploidy
11906 // sample_ct bytes: low 6 bits = ploidy, top bit = missingness
11907 // 1 byte: 1 if phased, 0 if not
11908 // 1 byte: # of bits of probability precision (we just support 8 and 16
11909 // for now, add others later)
11910 uint32_t stored_sample_ct;
11911 memcpy(&stored_sample_ct, cur_uncompressed_geno, sizeof(int32_t));
11912 if (unlikely((uncompressed_byte_ct < 10 + sample_ct) || (sample_ct != stored_sample_ct))) {
11913 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeSampleCtMismatch) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11914 goto Bgen13GenoToPgenThread_err;
11915 }
11916 if (block_allele_idx_offsets) {
11917 cur_allele_ct = block_allele_idx_offsets[bidx + 1] - block_allele_idx_offsets[bidx];
11918 }
11919 /*
11920 uint16_t stored_allele_ct;
11921 memcpy_k(&stored_allele_ct, &(cur_uncompressed_geno[4]), sizeof(int16_t));
11922 if (unlikely(stored_allele_ct != cur_allele_ct)) {
11923 goto Bgen13GenoToPgenThread_malformed;
11924 }
11925 */
11926 const uint32_t min_ploidy = cur_uncompressed_geno[6];
11927 const uint32_t max_ploidy = cur_uncompressed_geno[7];
11928 if (unlikely((min_ploidy > max_ploidy) || (max_ploidy > 63))) {
11929 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypePloidyOutOfRange) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11930 goto Bgen13GenoToPgenThread_err;
11931 }
11932 if (unlikely(max_ploidy > 2)) {
11933 if (ctx->error_on_polyploid) {
11934 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypePolyploid) << 8) | S_CAST(uint32_t, kPglRetInconsistentInput);
11935 goto Bgen13GenoToPgenThread_err;
11936 }
11937 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypePolyploid) << 8) | S_CAST(uint32_t, kPglRetNotYetSupported);
11938 goto Bgen13GenoToPgenThread_err;
11939 }
11940 const unsigned char* missing_and_ploidy_iter = &(cur_uncompressed_geno[8]);
11941 const unsigned char* probs_start = &(cur_uncompressed_geno[10 + sample_ct]);
11942 const uint32_t is_phased = probs_start[-2];
11943 if (unlikely(is_phased > 1)) {
11944 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeIsPhasedOutOfRange) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11945 goto Bgen13GenoToPgenThread_err;
11946 }
11947 const uint32_t bit_precision = probs_start[-1];
11948 if (unlikely((!bit_precision) || (bit_precision > 32))) {
11949 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeBitPrecisionOutOfRange) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11950 goto Bgen13GenoToPgenThread_err;
11951 }
11952 if (unlikely(bit_precision > kMaxBgenImportBits)) {
11953 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeBitPrecisionUnsupported) << 8) | S_CAST(uint32_t, kPglRetNotYetSupported);
11954 goto Bgen13GenoToPgenThread_err;
11955 }
11956 if (cur_allele_ct != 2) {
11957 // shouldn't be possible to get here for now
11958 assert(0);
11959 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeAlleleCtUnsupported) << 8) | S_CAST(uint32_t, kPglRetNotYetSupported);
11960 goto Bgen13GenoToPgenThread_err;
11961 }
11962 uintptr_t* genovec = GparseGetPointers(grp->record_start, sample_ct, cur_allele_ct, grp->flags, &patch_01_set, &patch_01_vals, &patch_10_set, &patch_10_vals, &phasepresent, &phaseinfo, &dosage_present, &dosage_main, &dphase_present, &dphase_delta);
11963 Dosage* dosage_main_iter = dosage_main;
11964 SDosage* dphase_delta_iter = dphase_delta;
11965 uint32_t cur_phasepresent_exists = 0;
11966 // turns out UKB haplotype files still use bit_precision == 16, so
11967 // don't bother implementing movemask-based bit_precision == 1
11968 // optimization for now
11969 const uint64_t magic_preadd = kBgenMagicNums[bit_precision].preadd;
11970 const uint64_t magic_mult = kBgenMagicNums[bit_precision].mult;
11971 const uint32_t magic_postshift = kBgenMagicNums[bit_precision].postshift;
11972
11973 // also equal to denominator
11974 const uintptr_t numer_mask = (1U << bit_precision) - 1;
11975
11976 uint32_t numer_certainty_min = 0;
11977 if (bgen_import_dosage_certainty_thresholds) {
11978 numer_certainty_min = bgen_import_dosage_certainty_thresholds[bit_precision];
11979 }
11980
11981 uint32_t inner_loop_last = kBitsPerWordD2 - 1;
11982 if (min_ploidy == max_ploidy) {
11983 // faster handling of common cases (no need to keep checking if
11984 // we've read past the end)
11985 if (unlikely(uncompressed_byte_ct != 10 + sample_ct + DivUp(S_CAST(uint64_t, bit_precision) * max_ploidy * sample_ct, CHAR_BIT))) {
11986 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeUncompressedByteCtMismatch) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
11987 goto Bgen13GenoToPgenThread_err;
11988 }
11989 if (max_ploidy == 2) {
11990 if (!is_phased) {
11991 // Could start with vectorized scan which proceeds until first
11992 // inexact dosage? Logic needs to be slightly different from
11993 // scan thread since we need to look at missing_and_ploidy.
11994 // On the other hand, decompression already seems to be ~3/4 of
11995 // compute time here, so I won't worry about that optimization
11996 // for now.
11997 for (uint32_t widx = 0; ; ++widx) {
11998 if (widx >= sample_ctl2_m1) {
11999 if (widx > sample_ctl2_m1) {
12000 break;
12001 }
12002 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
12003 }
12004 const uintptr_t prob_offset_base = widx * kBitsPerWord;
12005 uintptr_t genovec_word = 0;
12006 uint32_t dosage_present_hw = 0;
12007 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
12008 const uint32_t missing_and_ploidy = *missing_and_ploidy_iter++;
12009 if (missing_and_ploidy != 2) {
12010 // (could also validate that missing_and_ploidy == 130)
12011 Bgen13GenoToPgenThread_diploid_unphased_missing:
12012 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
12013 continue;
12014 }
12015 uintptr_t numer_aa;
12016 uintptr_t numer_ab;
12017 Bgen13GetTwoVals(probs_start, prob_offset_base + 2 * sample_idx_lowbits, bit_precision, numer_mask, &numer_aa, &numer_ab);
12018 // common trivial cases
12019 if (!numer_aa) {
12020 if (!numer_ab) {
12021 continue;
12022 }
12023 if (numer_ab == numer_mask) {
12024 genovec_word |= k1LU << (2 * sample_idx_lowbits);
12025 continue;
12026 }
12027 } else if ((numer_aa == numer_mask) && (!numer_ab)) {
12028 genovec_word |= (2 * k1LU) << (2 * sample_idx_lowbits);
12029 continue;
12030 }
12031 if (unlikely(numer_aa + numer_ab > numer_mask)) {
12032 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeNumeratorOverflow) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
12033 goto Bgen13GenoToPgenThread_err;
12034 }
12035 if ((numer_aa < numer_certainty_min) && (numer_ab < numer_certainty_min) && (numer_mask - numer_certainty_min < numer_aa + numer_ab)) {
12036 // missing due to --import-dosage-certainty
12037 goto Bgen13GenoToPgenThread_diploid_unphased_missing;
12038 }
12039 const uint32_t write_dosage_int = (magic_preadd + magic_mult * (2 * numer_aa + numer_ab)) >> magic_postshift;
12040 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
12041 if (halfdist < hard_call_halfdist) {
12042 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
12043 } else {
12044 genovec_word |= ((write_dosage_int + (kDosage4th * k1LU)) / kDosageMid) << (2 * sample_idx_lowbits);
12045 if (halfdist >= dosage_erase_halfdist) {
12046 continue;
12047 }
12048 }
12049 dosage_present_hw |= 1U << sample_idx_lowbits;
12050 *dosage_main_iter++ = write_dosage_int;
12051 }
12052 genovec[widx] = genovec_word;
12053 R_CAST(Halfword*, dosage_present)[widx] = dosage_present_hw;
12054 }
12055 } else {
12056 // biallelic, phased, diploid
12057 // may want a fast path for bit_precision == 1
12058 phasepresent[sample_ctl - 1] = 0;
12059 for (uint32_t widx = 0; ; ++widx) {
12060 if (widx >= sample_ctl2_m1) {
12061 if (widx > sample_ctl2_m1) {
12062 break;
12063 }
12064 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
12065 }
12066 const uintptr_t prob_offset_base = widx * kBitsPerWord;
12067 uintptr_t genovec_word = 0;
12068 uint32_t phasepresent_hw = 0;
12069 uint32_t phaseinfo_hw = 0;
12070 uint32_t dosage_present_hw = 0;
12071 uint32_t dphase_present_hw = 0;
12072 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
12073 const uint32_t missing_and_ploidy = *missing_and_ploidy_iter++;
12074 if (missing_and_ploidy != 2) {
12075 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
12076 continue;
12077 }
12078 uintptr_t numer_a1;
12079 uintptr_t numer_a2;
12080 Bgen13GetTwoVals(probs_start, prob_offset_base + 2 * sample_idx_lowbits, bit_precision, numer_mask, &numer_a1, &numer_a2);
12081 if ((!numer_a1) && (!numer_a2)) {
12082 continue;
12083 }
12084 if ((numer_a1 == numer_mask) && (numer_a2 == numer_mask)) {
12085 genovec_word |= (2 * k1LU) << (2 * sample_idx_lowbits);
12086 continue;
12087 }
12088 uint32_t write_dosage_int;
12089 if (Bgen13ConvertBiallelicPhased(sample_idx_lowbits, numer_a1, numer_a2, numer_mask, numer_certainty_min, magic_preadd, magic_mult, magic_postshift, hard_call_halfdist, dosage_erase_halfdist, &genovec_word, &phasepresent_hw, &phaseinfo_hw, &dphase_present_hw, &dphase_delta_iter, &write_dosage_int)) {
12090 continue;
12091 }
12092 dosage_present_hw |= 1U << sample_idx_lowbits;
12093 *dosage_main_iter++ = write_dosage_int;
12094 }
12095 genovec[widx] = genovec_word;
12096 R_CAST(Halfword*, phasepresent)[widx] = phasepresent_hw;
12097 R_CAST(Halfword*, phaseinfo)[widx] = phaseinfo_hw;
12098 R_CAST(Halfword*, dosage_present)[widx] = dosage_present_hw;
12099 R_CAST(Halfword*, dphase_present)[widx] = dphase_present_hw;
12100 }
12101 cur_phasepresent_exists = !AllWordsAreZero(phasepresent, sample_ctl);
12102 }
12103 } else if (max_ploidy) {
12104 // biallelic, haploid
12105 for (uint32_t widx = 0; ; ++widx) {
12106 if (widx >= sample_ctl2_m1) {
12107 if (widx > sample_ctl2_m1) {
12108 break;
12109 }
12110 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
12111 }
12112 const uintptr_t prob_offset_base = widx * kBitsPerWordD2;
12113 uintptr_t genovec_word = 0;
12114 uint32_t dosage_present_hw = 0;
12115 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
12116 const uint32_t missing_and_ploidy = *missing_and_ploidy_iter++;
12117 if (missing_and_ploidy != 1) {
12118 Bgen13GenoToPgenThread_haploid_missing:
12119 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
12120 continue;
12121 }
12122 const uintptr_t numer_a = Bgen13GetOneVal(probs_start, prob_offset_base + sample_idx_lowbits, bit_precision, numer_mask);
12123 if ((numer_a < numer_certainty_min) && (numer_mask - numer_certainty_min < numer_a)) {
12124 goto Bgen13GenoToPgenThread_haploid_missing;
12125 }
12126 const uint32_t write_dosage_int = (magic_preadd + magic_mult * numer_a * 2) >> magic_postshift;
12127 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
12128 if (halfdist < hard_call_halfdist) {
12129 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
12130 } else {
12131 genovec_word |= ((write_dosage_int + (kDosage4th * k1LU)) / kDosageMid) << (2 * sample_idx_lowbits);
12132 if (halfdist >= dosage_erase_halfdist) {
12133 continue;
12134 }
12135 }
12136 dosage_present_hw |= 1U << sample_idx_lowbits;
12137 *dosage_main_iter++ = write_dosage_int;
12138 }
12139 genovec[widx] = genovec_word;
12140 R_CAST(Halfword*, dosage_present)[widx] = dosage_present_hw;
12141 }
12142 } else {
12143 // all-ploidy-0, set everything to missing
12144 SetAllBits(sample_ct * 2, genovec);
12145 }
12146 } else {
12147 // biallelic, variable ploidy
12148 const uint64_t remaining_bit_ct = 8LLU * (uncompressed_byte_ct - S_CAST(uintptr_t, probs_start - cur_uncompressed_geno));
12149 const uint64_t prob_offset_end = remaining_bit_ct / bit_precision;
12150 uintptr_t prob_offset = 0;
12151 if (!is_phased) {
12152 for (uint32_t widx = 0; ; ++widx) {
12153 if (widx >= sample_ctl2_m1) {
12154 if (widx > sample_ctl2_m1) {
12155 break;
12156 }
12157 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
12158 }
12159 uintptr_t genovec_word = 0;
12160 uint32_t dosage_present_hw = 0;
12161 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
12162 uint32_t missing_and_ploidy = *missing_and_ploidy_iter++;
12163 uint32_t write_dosage_int;
12164 if (missing_and_ploidy == 2) {
12165 if (unlikely(prob_offset + 2 > prob_offset_end)) {
12166 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeProbOffsetMismatch) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
12167 goto Bgen13GenoToPgenThread_err;
12168 }
12169 uintptr_t numer_aa;
12170 uintptr_t numer_ab;
12171 Bgen13GetTwoVals(probs_start, prob_offset, bit_precision, numer_mask, &numer_aa, &numer_ab);
12172 prob_offset += 2;
12173 if (unlikely(numer_aa + numer_ab > numer_mask)) {
12174 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeNumeratorOverflow) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
12175 goto Bgen13GenoToPgenThread_err;
12176 }
12177 if ((numer_aa < numer_certainty_min) && (numer_ab < numer_certainty_min) && (numer_mask - numer_certainty_min < numer_aa + numer_ab)) {
12178 // missing due to --import-dosage-certainty
12179 goto Bgen13GenoToPgenThread_generic_unphased_missing;
12180 }
12181 write_dosage_int = (magic_preadd + magic_mult * (2 * numer_aa + numer_ab)) >> magic_postshift;
12182 } else {
12183 if (missing_and_ploidy != 1) {
12184 missing_and_ploidy &= 127;
12185 if (unlikely(missing_and_ploidy > 2)) {
12186 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeInvalidMissingPloidy) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
12187 goto Bgen13GenoToPgenThread_err;
12188 }
12189 prob_offset += missing_and_ploidy;
12190 Bgen13GenoToPgenThread_generic_unphased_missing:
12191 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
12192 continue;
12193 }
12194 if (unlikely(prob_offset >= prob_offset_end)) {
12195 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeProbOffsetMismatch) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
12196 goto Bgen13GenoToPgenThread_err;
12197 }
12198 const uintptr_t numer_a = Bgen13GetOneVal(probs_start, prob_offset, bit_precision, numer_mask);
12199 ++prob_offset;
12200 if ((numer_a < numer_certainty_min) && (numer_mask - numer_certainty_min < numer_a)) {
12201 goto Bgen13GenoToPgenThread_generic_unphased_missing;
12202 }
12203 write_dosage_int = (magic_preadd + magic_mult * numer_a * 2) >> magic_postshift;
12204 }
12205 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
12206 if (halfdist < hard_call_halfdist) {
12207 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
12208 } else {
12209 genovec_word |= ((write_dosage_int + (kDosage4th * k1LU)) / kDosageMid) << (2 * sample_idx_lowbits);
12210 if (halfdist >= dosage_erase_halfdist) {
12211 continue;
12212 }
12213 }
12214 dosage_present_hw |= 1U << sample_idx_lowbits;
12215 *dosage_main_iter++ = write_dosage_int;
12216 }
12217 genovec[widx] = genovec_word;
12218 R_CAST(Halfword*, dosage_present)[widx] = dosage_present_hw;
12219 }
12220 } else {
12221 // biallelic, phased, variable ploidy
12222 phasepresent[sample_ctl - 1] = 0;
12223 for (uint32_t widx = 0; ; ++widx) {
12224 if (widx >= sample_ctl2_m1) {
12225 if (widx > sample_ctl2_m1) {
12226 break;
12227 }
12228 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
12229 }
12230 uintptr_t genovec_word = 0;
12231 uint32_t phasepresent_hw = 0;
12232 uint32_t phaseinfo_hw = 0;
12233 uint32_t dosage_present_hw = 0;
12234 uint32_t dphase_present_hw = 0;
12235 uint32_t write_dosage_int;
12236 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
12237 uint32_t missing_and_ploidy = *missing_and_ploidy_iter++;
12238 if (missing_and_ploidy == 2) {
12239 if (unlikely(prob_offset + 2 > prob_offset_end)) {
12240 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeProbOffsetMismatch) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
12241 goto Bgen13GenoToPgenThread_err;
12242 }
12243 uintptr_t numer_a1;
12244 uintptr_t numer_a2;
12245 Bgen13GetTwoVals(probs_start, prob_offset, bit_precision, numer_mask, &numer_a1, &numer_a2);
12246 prob_offset += 2;
12247 if ((!numer_a1) && (!numer_a2)) {
12248 continue;
12249 }
12250 if ((numer_a1 == numer_mask) && (numer_a2 == numer_mask)) {
12251 genovec_word |= (2 * k1LU) << (2 * sample_idx_lowbits);
12252 continue;
12253 }
12254 if (Bgen13ConvertBiallelicPhased(sample_idx_lowbits, numer_a1, numer_a2, numer_mask, numer_certainty_min, magic_preadd, magic_mult, magic_postshift, hard_call_halfdist, dosage_erase_halfdist, &genovec_word, &phasepresent_hw, &phaseinfo_hw, &dphase_present_hw, &dphase_delta_iter, &write_dosage_int)) {
12255 continue;
12256 }
12257 } else {
12258 if (missing_and_ploidy != 1) {
12259 missing_and_ploidy &= 127;
12260 if (unlikely(missing_and_ploidy > 2)) {
12261 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeInvalidMissingPloidy) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
12262 goto Bgen13GenoToPgenThread_err;
12263 }
12264 prob_offset += missing_and_ploidy;
12265 Bgen13GenoToPgenThread_generic_phased_missing:
12266 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
12267 continue;
12268 }
12269 if (unlikely(prob_offset >= prob_offset_end)) {
12270 new_err_info = (S_CAST(uint64_t, bidx) << 32) | (S_CAST(uint32_t, kBgenImportErrSubtypeProbOffsetMismatch) << 8) | S_CAST(uint32_t, kPglRetMalformedInput);
12271 goto Bgen13GenoToPgenThread_err;
12272 }
12273 const uintptr_t numer_a = Bgen13GetOneVal(probs_start, prob_offset, bit_precision, numer_mask);
12274 ++prob_offset;
12275 if ((numer_a < numer_certainty_min) && (numer_mask - numer_certainty_min < numer_a)) {
12276 goto Bgen13GenoToPgenThread_generic_phased_missing;
12277 }
12278 write_dosage_int = (magic_preadd + magic_mult * numer_a * 2) >> magic_postshift;
12279 const uint32_t halfdist = BiallelicDosageHalfdist(write_dosage_int);
12280 if (halfdist < hard_call_halfdist) {
12281 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
12282 } else {
12283 genovec_word |= ((write_dosage_int + (kDosage4th * k1LU)) / kDosageMid) << (2 * sample_idx_lowbits);
12284 // bugfix (22 Apr 2018): forgot this check
12285 if (halfdist >= dosage_erase_halfdist) {
12286 continue;
12287 }
12288 }
12289 }
12290 dosage_present_hw |= 1U << sample_idx_lowbits;
12291 *dosage_main_iter++ = write_dosage_int;
12292 }
12293 genovec[widx] = genovec_word;
12294 // bugfix (22 Apr 2018): didn't save phasepresent, etc.
12295 R_CAST(Halfword*, phasepresent)[widx] = phasepresent_hw;
12296 R_CAST(Halfword*, phaseinfo)[widx] = phaseinfo_hw;
12297 R_CAST(Halfword*, dosage_present)[widx] = dosage_present_hw;
12298 R_CAST(Halfword*, dphase_present)[widx] = dphase_present_hw;
12299 }
12300 cur_phasepresent_exists = !AllWordsAreZero(phasepresent, sample_ctl);
12301 }
12302 }
12303 if (!(sample_ctl2_m1 % 2)) {
12304 // needed for dosage_present. don't think it's needed for
12305 // dphase_present, but play that safe for now
12306 R_CAST(Halfword*, dosage_present)[sample_ctl2_m1 + 1] = 0;
12307 R_CAST(Halfword*, dphase_present)[sample_ctl2_m1 + 1] = 0;
12308 }
12309 const uint32_t dosage_ct = dosage_main_iter - dosage_main;
12310 uint32_t dphase_ct = dphase_delta_iter - dphase_delta;
12311 // note that this is inverted from bgen-1.1
12312 if (!prov_ref_allele_second) {
12313 GenovecInvertUnsafe(sample_ct, genovec);
12314 ZeroTrailingNyps(sample_ct, genovec);
12315 if (dosage_ct) {
12316 BiallelicDosage16Invert(dosage_ct, dosage_main);
12317 if (dphase_ct) {
12318 BiallelicDphase16Invert(dphase_ct, dphase_delta);
12319 }
12320 }
12321 }
12322 grp->metadata.write.patch_01_ct = 0;
12323 grp->metadata.write.patch_10_ct = 0;
12324 grp->metadata.write.phasepresent_exists = cur_phasepresent_exists;
12325 grp->metadata.write.dosage_ct = dosage_ct;
12326 grp->metadata.write.multiallelic_dosage_ct = 0;
12327 grp->metadata.write.dphase_ct = dphase_ct;
12328 grp->metadata.write.multiallelic_dphase_ct = 0;
12329 }
12330 }
12331 parity = 1 - parity;
12332 } while (!THREAD_BLOCK_FINISH(arg));
12333 while (0) {
12334 Bgen13GenoToPgenThread_err:
12335 UpdateU64IfSmaller(new_err_info, &ctx->err_info);
12336 THREAD_BLOCK_FINISH(arg);
12337 break;
12338 }
12339 THREAD_RETURN;
12340 }
12341
12342 static_assert(sizeof(Dosage) == 2, "OxBgenToPgen() needs to be updated.");
12343 PglErr OxBgenToPgen(const char* bgenname, const char* samplename, const char* const_fid, const char* ox_single_chr_str, const char* ox_missing_code, const char* missing_catname, MiscFlags misc_flags, ImportFlags import_flags, OxfordImportFlags oxford_import_flags, uint32_t psam_01, uint32_t is_update_or_impute_sex, uint32_t is_splitpar, uint32_t hard_call_thresh, uint32_t dosage_erase_thresh, double import_dosage_certainty, char id_delim, char idspace_to, uint32_t import_max_allele_ct, uint32_t max_thread_ct, char* outname, char* outname_end, ChrInfo* cip) {
12344 unsigned char* bigstack_mark = g_bigstack_base;
12345 unsigned char* bigstack_end_mark = g_bigstack_end;
12346 FILE* bgenfile = nullptr;
12347
12348 // only if no sample file specified, and .bgen has sample IDs. (possible
12349 // todo: consistency check when both sources of sample IDs are present?)
12350 FILE* psamfile = nullptr;
12351
12352 char* pvar_cswritep = nullptr;
12353 const uint32_t sex_info_avail = samplename[0] || is_update_or_impute_sex;
12354 CompressStreamState pvar_css;
12355 PreinitCstream(&pvar_css);
12356 ThreadGroup tg;
12357 PreinitThreads(&tg);
12358 STPgenWriter spgw;
12359 PglErr reterr = kPglRetSuccess;
12360 PreinitSpgw(&spgw);
12361 BgenImportCommon common;
12362 common.libdeflate_decompressors = nullptr;
12363 {
12364 // Pass 1: Determine whether there's at least one non-hardcall needs to be
12365 // saved, and if a chromosome filter was specified, count the
12366 // number of variants which pass the filter.
12367 // For bgen-1.2/1.3, the .pvar is also written in this pass.
12368 // For bgen-1.1, we can usually early-bail when no chromosome
12369 // filter is involved, so .pvar writing is postponed till the
12370 // second pass.
12371 // Pass 2: Write .pgen file.
12372 //
12373 // Possible todo: reduce this to 1-pass in some circumstances. Punt for
12374 // now, though, since the current workflow makes good use of the scanning
12375 // pass to bound conversion-pass per-thread buffer sizes.
12376 if (unlikely(fopen_checked(bgenname, FOPEN_RB, &bgenfile))) {
12377 goto OxBgenToPgen_ret_OPEN_FAIL;
12378 }
12379 uint32_t initial_uints[5];
12380 if (unlikely(!fread_unlocked(&initial_uints[0], 20, 1, bgenfile))) {
12381 // this could be malformed input as well; could distinguish later?
12382 goto OxBgenToPgen_ret_READ_FAIL;
12383 }
12384 if (unlikely(initial_uints[1] > initial_uints[0])) {
12385 logerrputs("Error: Invalid .bgen header.\n");
12386 goto OxBgenToPgen_ret_MALFORMED_INPUT;
12387 }
12388 const uint32_t sample_ct = initial_uints[3];
12389 if (unlikely(initial_uints[4] && (initial_uints[4] != 0x6e656762))) {
12390 logerrputs("Error: Invalid .bgen magic number.\n");
12391 goto OxBgenToPgen_ret_MALFORMED_INPUT;
12392 }
12393 const uint32_t header_variant_ct = initial_uints[2];
12394 if (unlikely(!header_variant_ct)) {
12395 logerrputs("Error: Empty .bgen file.\n");
12396 goto OxBgenToPgen_ret_DEGENERATE_DATA;
12397 }
12398
12399 if (unlikely(fseeko(bgenfile, initial_uints[1], SEEK_SET))) {
12400 goto OxBgenToPgen_ret_READ_FAIL;
12401 }
12402 uint32_t header_flags;
12403 if (unlikely(!fread_unlocked(&header_flags, 4, 1, bgenfile))) {
12404 goto OxBgenToPgen_ret_READ_FAIL;
12405 }
12406 const uint32_t compression_mode = header_flags & 3;
12407 const uint32_t layout = (header_flags >> 2) & 15;
12408 if (unlikely(!layout)) {
12409 logerrputs("Error: BGEN v1.0 files are not supported by " PROG_NAME_STR ".\n");
12410 goto OxBgenToPgen_ret_MALFORMED_INPUT;
12411 }
12412 if (unlikely((compression_mode == 3) || (layout > 2))) {
12413 logerrputs("Error: Unrecognized BGEN version. Use gen-convert or a similar tool to\ndowncode to BGEN v1.3 if you want to process this data with " PROG_NAME_STR ".\n");
12414 goto OxBgenToPgen_ret_MALFORMED_INPUT;
12415 }
12416 if (unlikely((compression_mode == 2) && (layout == 1))) {
12417 logerrputs("Error: Invalid .bgen header.\n");
12418 goto OxBgenToPgen_ret_MALFORMED_INPUT;
12419 }
12420 logprintf("--bgen: %u variant%s declared in header, format v1.%c.\n", header_variant_ct, (header_variant_ct == 1)? "" : "s", (layout == 1)? '1' : ((compression_mode == 2)? '3' : '2'));
12421 uint32_t raw_variant_ct = header_variant_ct;
12422 if (samplename[0]) {
12423 uint32_t sfile_sample_ct;
12424 reterr = OxSampleToPsam(samplename, const_fid, ox_missing_code, missing_catname, misc_flags, import_flags, psam_01, id_delim, outname, outname_end, &sfile_sample_ct);
12425 if (unlikely(reterr)) {
12426 goto OxBgenToPgen_ret_1;
12427 }
12428 if (unlikely(sfile_sample_ct != sample_ct)) {
12429 logerrprintf("Error: .sample file has %u sample%s, while .bgen file has %u.\n", sfile_sample_ct, (sfile_sample_ct == 1)? "" : "s", sample_ct);
12430 goto OxBgenToPgen_ret_INCONSISTENT_INPUT;
12431 }
12432 if (header_flags >> 31) {
12433 uint32_t sample_id_block_byte_ct;
12434 uint32_t sample_id_block_entry_ct;
12435 if (unlikely((!fread_unlocked(&sample_id_block_byte_ct, 4, 1, bgenfile)) ||
12436 (!fread_unlocked(&sample_id_block_entry_ct, 4, 1, bgenfile)))) {
12437 goto OxBgenToPgen_ret_READ_FAIL;
12438 }
12439 if (unlikely((S_CAST(uint64_t, sample_id_block_byte_ct) + initial_uints[1] > initial_uints[0]) ||
12440 (sample_id_block_entry_ct != sample_ct))) {
12441 logerrputs("Error: Invalid .bgen header.\n");
12442 goto OxBgenToPgen_ret_MALFORMED_INPUT;
12443 }
12444 }
12445 } else {
12446 if (unlikely(!(header_flags >> 31))) {
12447 logerrputs("Error: .bgen file does not contain sample IDs, and no .sample file was\nspecified.\n");
12448 goto OxBgenToPgen_ret_INCONSISTENT_INPUT;
12449 }
12450 // possible todo: optionally error out if sample IDs aren't consistent
12451 // between .bgen and .sample, using ImportIidFromSampleId()
12452
12453 // see VcfSampleLine()
12454 uint32_t sample_id_block_byte_ct;
12455 uint32_t sample_id_block_entry_ct;
12456 if (unlikely((!fread_unlocked(&sample_id_block_byte_ct, 4, 1, bgenfile)) ||
12457 (!fread_unlocked(&sample_id_block_entry_ct, 4, 1, bgenfile)))) {
12458 goto OxBgenToPgen_ret_READ_FAIL;
12459 }
12460 if (unlikely((sample_id_block_byte_ct < 8) ||
12461 (S_CAST(uint64_t, sample_id_block_byte_ct) + initial_uints[1] > initial_uints[0]) ||
12462 (sample_id_block_entry_ct != sample_ct))) {
12463 logerrputs("Error: Invalid .bgen header.\n");
12464 goto OxBgenToPgen_ret_MALFORMED_INPUT;
12465 }
12466 sample_id_block_byte_ct -= 8;
12467 char* sample_id_block_main;
12468 if (unlikely(bigstack_alloc_c(sample_id_block_byte_ct, &sample_id_block_main))) {
12469 goto OxBgenToPgen_ret_NOMEM;
12470 }
12471 char* sample_id_block_end = &(sample_id_block_main[sample_id_block_byte_ct]);
12472 if (unlikely(fread_checked(sample_id_block_main, sample_id_block_byte_ct, bgenfile))) {
12473 goto OxBgenToPgen_ret_READ_FAIL;
12474 }
12475
12476 // Always check if any tab/eoln characters are present, and error out if
12477 // so.
12478 // if id_delim != ' ', also check if spaces are present; if so, replace
12479 // with --idspace-to character or error out
12480 char* sample_id_block_iter = sample_id_block_main;
12481 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
12482 uint16_t input_id_slen;
12483 memcpy_k(&input_id_slen, sample_id_block_iter, sizeof(int16_t));
12484
12485 // need to check this to avoid read-past-the-end indeterminate
12486 // behavior
12487 if (unlikely(S_CAST(uintptr_t, sample_id_block_end - sample_id_block_iter) < input_id_slen + (2 * k1LU))) {
12488 logerrputs("Error: Invalid .bgen header.\n");
12489 goto OxBgenToPgen_ret_MALFORMED_INPUT;
12490 }
12491 char* sample_id_iter = &(sample_id_block_iter[2]);
12492 char* sample_id_end = &(sample_id_iter[input_id_slen]);
12493 uint32_t char_code_min = 32 + (id_delim != ' ');
12494 for (; sample_id_iter != sample_id_end; ++sample_id_iter) {
12495 const uint32_t char_code = ctou32(*sample_id_iter);
12496 if (char_code < char_code_min) {
12497 if (unlikely(char_code < 32)) {
12498 logerrputs("Error: .bgen sample ID contains tabs, newlines, and/or nonprinting characters.\n");
12499 goto OxBgenToPgen_ret_MALFORMED_INPUT;
12500 }
12501 if (unlikely(!idspace_to)) {
12502 logerrputs("Error: .bgen sample ID contains space(s). Use --idspace-to to convert them to\nanother character, or \"--id-delim ' '\" to interpret the spaces as FID/IID or\nIID/SID delimiters.\n");
12503 goto OxBgenToPgen_ret_INCONSISTENT_INPUT;
12504 }
12505 *sample_id_iter = idspace_to;
12506 }
12507 }
12508 sample_id_block_iter = sample_id_end;
12509 }
12510 snprintf(outname_end, kMaxOutfnameExtBlen, ".psam");
12511 if (unlikely(fopen_checked(outname, FOPEN_WB, &psamfile))) {
12512 goto OxBgenToPgen_ret_OPEN_FAIL;
12513 }
12514 ImportSampleIdContext isic;
12515 InitImportSampleIdContext(const_fid, misc_flags, import_flags, id_delim, &isic);
12516 uint32_t write_fid = 1;
12517 uint32_t write_sid = 0;
12518 if (id_delim) {
12519 sample_id_block_iter = sample_id_block_main;
12520 uint32_t nonzero_first_field_observed = 0;
12521 for (uint32_t sample_idx = 0; ; ) {
12522 uint16_t input_id_slen;
12523 memcpy_k(&input_id_slen, sample_id_block_iter, sizeof(int16_t));
12524 char* sample_id_iter = &(sample_id_block_iter[2]);
12525 // previously verified that this is in-bounds
12526 char* sample_id_end = &(sample_id_iter[input_id_slen]);
12527 char* first_delim = S_CAST(char*, memchr(sample_id_iter, ctou32(id_delim), sample_id_end - sample_id_iter));
12528 if (unlikely(!first_delim)) {
12529 snprintf(g_logbuf, kLogbufSize, "Error: No '%c' in sample ID.\n", id_delim);
12530 goto OxBgenToPgen_ret_INCONSISTENT_INPUT_2;
12531 }
12532 if (!nonzero_first_field_observed) {
12533 nonzero_first_field_observed = (first_delim != &(sample_id_iter[1])) || (sample_id_iter[0] != '0');
12534 }
12535 sample_id_iter = &(first_delim[1]);
12536 if (memchr(sample_id_iter, ctou32(id_delim), sample_id_end - sample_id_iter)) {
12537 isic.two_part_null_fid = isic.id_delim_sid;
12538 isic.two_part_null_sid = 1 - isic.id_delim_sid;
12539 write_fid = 1;
12540 write_sid = 1;
12541 if (!nonzero_first_field_observed) {
12542 sample_id_block_iter = sample_id_end;
12543 while (++sample_idx != sample_ct) {
12544 uint16_t new_input_id_slen;
12545 memcpy_k(&new_input_id_slen, sample_id_block_iter, sizeof(int16_t));
12546 sample_id_iter = &(sample_id_block_iter[2]);
12547 // We actually need to error out on new_input_id_slen < 2, but
12548 // that'll happen in the next loop.
12549 if ((new_input_id_slen < 2) || (sample_id_iter[0] != '0') || (sample_id_iter[1] != id_delim)) {
12550 nonzero_first_field_observed = 1;
12551 break;
12552 }
12553 sample_id_block_iter = &(sample_id_iter[new_input_id_slen]);
12554 }
12555 }
12556 break;
12557 }
12558 sample_id_block_iter = sample_id_end;
12559 if (++sample_idx == sample_ct) {
12560 if (isic.id_delim_sid) {
12561 write_fid = 0;
12562 write_sid = 1;
12563 }
12564 break;
12565 }
12566 }
12567 if (!nonzero_first_field_observed) {
12568 write_fid = 0;
12569 isic.omit_fid_0 = 1;
12570 }
12571 } else if ((!isic.const_fid) && (!isic.double_id)) {
12572 write_fid = 0;
12573 }
12574 char* textbuf = g_textbuf;
12575 char* write_iter = textbuf;
12576 *write_iter++ = '#';
12577 if (write_fid) {
12578 write_iter = strcpya_k(write_iter, "FID\t");
12579 }
12580 write_iter = strcpya_k(write_iter, "IID");
12581 if (write_sid) {
12582 write_iter = strcpya_k(write_iter, "\tSID");
12583 }
12584 write_iter = strcpya_k(write_iter, "\tSEX");
12585 AppendBinaryEoln(&write_iter);
12586 char* textbuf_flush = &(textbuf[kMaxMediumLine]);
12587 sample_id_block_iter = sample_id_block_main;
12588 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
12589 uint16_t input_id_slen;
12590 memcpy_k(&input_id_slen, sample_id_block_iter, sizeof(int16_t));
12591 char* sample_id_start = &(sample_id_block_iter[2]);
12592 char* sample_id_end = &(sample_id_start[input_id_slen]);
12593 reterr = ImportSampleId(sample_id_start, sample_id_end, &isic, &write_iter);
12594 // SEX
12595 write_iter = strcpya_k(write_iter, "\tNA");
12596 AppendBinaryEoln(&write_iter);
12597 if (write_iter >= textbuf_flush) {
12598 if (unlikely(fwrite_checked(textbuf, write_iter - textbuf, psamfile))) {
12599 goto OxBgenToPgen_ret_WRITE_FAIL;
12600 }
12601 write_iter = textbuf;
12602 }
12603 sample_id_block_iter = sample_id_end;
12604 }
12605 if (unlikely(sample_id_block_iter != &(sample_id_block_main[sample_id_block_byte_ct]))) {
12606 logerrputs("Error: Invalid .bgen header.\n");
12607 goto OxBgenToPgen_ret_MALFORMED_INPUT;
12608 }
12609 if (write_iter != textbuf) {
12610 if (unlikely(fwrite_checked(textbuf, write_iter - textbuf, psamfile))) {
12611 goto OxBgenToPgen_ret_WRITE_FAIL;
12612 }
12613 }
12614 BigstackReset(sample_id_block_main);
12615 if (unlikely(fclose_null(&psamfile))) {
12616 goto OxBgenToPgen_ret_WRITE_FAIL;
12617 }
12618 logprintfww("--bgen: %u sample ID%s written to %s .\n", sample_ct, (sample_ct == 1)? "" : "s", outname);
12619 }
12620 if (unlikely(fseeko(bgenfile, initial_uints[0] + 4, SEEK_SET))) {
12621 goto OxBgenToPgen_ret_READ_FAIL;
12622 }
12623 const uint32_t prohibit_extra_chr = (misc_flags / kfMiscProhibitExtraChr) & 1;
12624 FinalizeChrset(misc_flags, cip);
12625 const uint32_t autosome_ct_p1 = cip->autosome_ct + 1;
12626 uint32_t chr_filter_exists = (PopcountBitRange(cip->chr_mask, 0, autosome_ct_p1) != autosome_ct_p1) || ((!prohibit_extra_chr) && (cip->is_include_stack || cip->incl_excl_name_stack));
12627 if (!chr_filter_exists) {
12628 for (uint32_t xymt_idx = 0; xymt_idx != kChrOffsetCt; ++xymt_idx) {
12629 if (!IsI32Neg(cip->xymt_codes[xymt_idx])) {
12630 if (!IsSet(cip->chr_mask, autosome_ct_p1 + xymt_idx)) {
12631 chr_filter_exists = 1;
12632 break;
12633 }
12634 }
12635 }
12636 }
12637
12638 if (unlikely(BIGSTACK_ALLOC_X(struct libdeflate_decompressor*, max_thread_ct, &common.libdeflate_decompressors))) {
12639 goto OxBgenToPgen_ret_NOMEM;
12640 }
12641 ZeroPtrArr(max_thread_ct, common.libdeflate_decompressors);
12642 // make libdeflate_alloc_decompressor() calls later, when we know how many
12643 // decompressor threads we're using
12644
12645 uint32_t cur_chr_code = 0;
12646 if (ox_single_chr_str) {
12647 reterr = InitOxfordSingleChr(ox_single_chr_str, "--bgen file", nullptr, nullptr, &cur_chr_code, cip);
12648 if (unlikely(reterr)) {
12649 goto OxBgenToPgen_ret_1;
12650 }
12651 }
12652 snprintf(outname_end, kMaxOutfnameExtBlen, ".pvar");
12653 const uint32_t output_zst = (import_flags / kfImportKeepAutoconvVzs) & 1;
12654 if (output_zst) {
12655 snprintf(&(outname_end[5]), kMaxOutfnameExtBlen - 5, ".zst");
12656 }
12657 const uintptr_t overflow_buf_size = 2 * kCompressStreamBlock + kCacheline;
12658 reterr = InitCstreamAlloc(outname, 0, output_zst, 1, overflow_buf_size, &pvar_css, &pvar_cswritep);
12659 if (unlikely(reterr)) {
12660 goto OxBgenToPgen_ret_1;
12661 }
12662 if (cip->chrset_source) {
12663 AppendChrsetLine(cip, &pvar_cswritep);
12664 }
12665 pvar_cswritep = strcpya_k(pvar_cswritep, "#CHROM\tPOS\tID\tREF\tALT" EOLN_STR);
12666
12667 const uint32_t snpid_chr = (oxford_import_flags & kfOxfordImportBgenSnpIdChr);
12668
12669 // true for both provisional-reference and real-reference second
12670 const uint32_t prov_ref_allele_second = !(oxford_import_flags & kfOxfordImportRefFirst);
12671
12672 const uint32_t allow_overstated_variant_ct = (import_flags / kfImportLaxBgen) & 1;
12673
12674 if (hard_call_thresh == UINT32_MAX) {
12675 hard_call_thresh = kDosageMid / 10;
12676 }
12677 const uint32_t sample_ctaw2 = NypCtToAlignedWordCt(sample_ct);
12678 const uint32_t sample_ctaw = BitCtToAlignedWordCt(sample_ct);
12679 uint32_t dosage_exists = 0;
12680 common.sample_ct = sample_ct;
12681 common.dosage_erase_halfdist = kDosage4th - dosage_erase_thresh;
12682 common.compression_mode = compression_mode;
12683 uint32_t par_warn_code = UINT32_MAX;
12684 if (!(import_flags & kfImportLaxChrX)) {
12685 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
12686 if ((!IsI32Neg(x_code)) && ((!sex_info_avail) || (IsHumanChrset(cip) && (!is_splitpar)))) {
12687 par_warn_code = x_code;
12688 }
12689 }
12690 if (layout == 1) {
12691 // v1.1
12692 // this block belongs in its own function...
12693 Bgen11DosageScanCtx scan_ctx;
12694 scan_ctx.common = &common;
12695 scan_ctx.dosage_exists = 0;
12696 scan_ctx.reterr = kPglRetSuccess;
12697 uintptr_t loadbuf_size = RoundDownPow2(bigstack_left() / 4, kCacheline);
12698 #ifdef __LP64__
12699 if (loadbuf_size > kMaxLongLine) {
12700 loadbuf_size = kMaxLongLine;
12701 }
12702 #endif
12703 // must have enough space for chromosome and variant IDs
12704 if (unlikely(loadbuf_size < 2 * 65536)) {
12705 goto OxBgenToPgen_ret_NOMEM;
12706 }
12707 unsigned char* loadbuf = S_CAST(unsigned char*, bigstack_alloc_raw(loadbuf_size));
12708 scan_ctx.import_dosage_certainty_int = 1 + S_CAST(int32_t, import_dosage_certainty * 32768);
12709 uintptr_t bgen_geno_max_byte_ct = 6LU * sample_ct;
12710 if (compression_mode) {
12711 bgen_geno_max_byte_ct = libdeflate_deflate_compress_bound(nullptr, bgen_geno_max_byte_ct);
12712 }
12713 if (unlikely(bgen_geno_max_byte_ct > UINT32_MAX)) {
12714 logerrputs("Error: Too many samples for .bgen format.\n");
12715 goto OxBgenToPgen_ret_MALFORMED_INPUT;
12716 }
12717 bgen_geno_max_byte_ct += compression_mode * 4;
12718 // thread-count-independent:
12719 // (everything after "2 *" rounded up to cacheline)
12720 // compressed_geno_bufs: 2 * bgen_geno_max_byte_ct * main_block_size
12721 // common.compressed_geno_starts: 2 * sizeof(intptr_t) *
12722 // main_block_size
12723 // ctx.write_genovecs: 2 * sample_ctaw2 * sizeof(intptr_t) *
12724 // main_block_size
12725 // ctx.write_dosage_cts: 2 * sizeof(int32_t) * main_block_size
12726 // ctx.write_dosage_presents: 2 * sample_ctaw * sizeof(intptr_t) *
12727 // main_block_size
12728 // ctx.write_dosage_mains (main bottleneck): 2 * sample_ct *
12729 // sizeof(Dosage)
12730 // additional requirement per thread:
12731 // ctx.bgen_geno_bufs: sample_ct * 3 * sizeof(int16_t)
12732
12733 uint32_t calc_thread_ct = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
12734 if ((!compression_mode) && (calc_thread_ct > 2)) {
12735 // computation doesn't seem to saturate when decompression is involved
12736 // (well, it didn't before libdeflate, anyway. recheck this.)
12737 calc_thread_ct = 2;
12738 }
12739 if (calc_thread_ct > header_variant_ct) {
12740 calc_thread_ct = header_variant_ct;
12741 }
12742 if (unlikely(bigstack_alloc_u16p(calc_thread_ct, &scan_ctx.bgen_geno_bufs))) {
12743 goto OxBgenToPgen_ret_NOMEM;
12744 }
12745 const uint32_t sample_ct_x3 = sample_ct * 3;
12746 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
12747 if (unlikely(bigstack_alloc_u16(sample_ct_x3, &(scan_ctx.bgen_geno_bufs[tidx])))) {
12748 goto OxBgenToPgen_ret_NOMEM;
12749 }
12750 }
12751 uintptr_t cachelines_avail_m12 = bigstack_left() / kCacheline;
12752 // reserve 1/8 of remaining memory for writer
12753 cachelines_avail_m12 -= cachelines_avail_m12 / 8;
12754 if (unlikely(cachelines_avail_m12 < 12)) {
12755 goto OxBgenToPgen_ret_NOMEM;
12756 }
12757 // we're making 12 allocations; be pessimistic re: rounding
12758 cachelines_avail_m12 -= 12;
12759 const uintptr_t bytes_req_per_in_block_variant = 2 * (bgen_geno_max_byte_ct + sizeof(intptr_t) + sample_ctaw2 * sizeof(intptr_t) + sizeof(int32_t) + sample_ctaw * sizeof(intptr_t) + sample_ct * sizeof(Dosage));
12760 uintptr_t main_block_size = (cachelines_avail_m12 * kCacheline) / bytes_req_per_in_block_variant;
12761 if (main_block_size > 65536) {
12762 main_block_size = 65536;
12763 } else if (unlikely(main_block_size < 8)) {
12764 // this threshold is arbitrary
12765 goto OxBgenToPgen_ret_NOMEM;
12766 }
12767 if (calc_thread_ct > main_block_size / 8) {
12768 calc_thread_ct = main_block_size / 8;
12769 }
12770 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
12771 goto OxBgenToPgen_ret_NOMEM;
12772 }
12773 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
12774 common.libdeflate_decompressors[tidx] = libdeflate_alloc_decompressor();
12775 if (unlikely(!common.libdeflate_decompressors[tidx])) {
12776 goto OxBgenToPgen_ret_NOMEM;
12777 }
12778 }
12779 Bgen11GenoToPgenCtx ctx;
12780 ctx.common = &common;
12781 ctx.bgen_geno_bufs = scan_ctx.bgen_geno_bufs;
12782 ctx.hard_call_halfdist = kDosage4th - hard_call_thresh;
12783 ctx.import_dosage_certainty_int = scan_ctx.import_dosage_certainty_int;
12784 ctx.prov_ref_allele_second = prov_ref_allele_second;
12785 ctx.reterr = kPglRetSuccess;
12786 unsigned char* compressed_geno_bufs[2];
12787 if (unlikely(bigstack_alloc_uc(bgen_geno_max_byte_ct * main_block_size, &(compressed_geno_bufs[0])) ||
12788 bigstack_alloc_uc(bgen_geno_max_byte_ct * main_block_size, &(compressed_geno_bufs[1])) ||
12789 bigstack_alloc_ucp(main_block_size, &(common.compressed_geno_starts[0])) ||
12790 bigstack_alloc_ucp(main_block_size, &(common.compressed_geno_starts[1])) ||
12791 bigstack_alloc_w(sample_ctaw2 * main_block_size, &(ctx.write_genovecs[0])) ||
12792 bigstack_alloc_w(sample_ctaw2 * main_block_size, &(ctx.write_genovecs[1])) ||
12793 bigstack_alloc_u32(main_block_size, &(ctx.write_dosage_cts[0])) ||
12794 bigstack_alloc_u32(main_block_size, &(ctx.write_dosage_cts[1])) ||
12795 bigstack_alloc_w(sample_ctaw * main_block_size, &(ctx.write_dosage_presents[0])) ||
12796 bigstack_alloc_w(sample_ctaw * main_block_size, &(ctx.write_dosage_presents[1])) ||
12797 bigstack_alloc_dosage(sample_ct * main_block_size, &(ctx.write_dosage_mains[0])) ||
12798 bigstack_alloc_dosage(sample_ct * main_block_size, &(ctx.write_dosage_mains[1])))) {
12799 // this should be impossible
12800 assert(0);
12801 goto OxBgenToPgen_ret_NOMEM;
12802 }
12803 SetThreadFuncAndData(Bgen11DosageScanThread, &scan_ctx, &tg);
12804
12805 // likely cases are (i) non-hardcall near top of the file, and (ii) no
12806 // non-hardcalls at all. to handle the first case efficiently, we want
12807 // the first blocks to be small so we bail quickly; to handle the second
12808 // case efficiently, we want large blocks on average. so we start with
12809 // a minimal block size and then repeatedly double.
12810 uint32_t variant_ct = 0;
12811 uint32_t block_vidx = 0;
12812 uint32_t cur_block_size = calc_thread_ct;
12813 uint32_t parity = 0;
12814 uintptr_t compressed_block_byte_ct = 6LU * sample_ct;
12815 unsigned char** compressed_geno_starts = common.compressed_geno_starts[0];
12816 unsigned char* bgen_geno_iter = compressed_geno_bufs[0];
12817 uint32_t skip = 0;
12818 for (uint32_t variant_uidx = 0; variant_uidx != header_variant_ct; ) {
12819 uint32_t uii;
12820 {
12821 const uintptr_t bytes_read = fread_unlocked(&uii, 1, 4, bgenfile);
12822 if (bytes_read != 4) {
12823 // don't know of a bgen-1.1 use case, but may as well make
12824 // --lax-bgen-import have a consistent effect.
12825 if (likely(allow_overstated_variant_ct && (!bytes_read))) {
12826 raw_variant_ct = variant_uidx;
12827 putc_unlocked('\n', stdout);
12828 logprintf("--lax-bgen-import: .bgen file actually contains %u variant%s.\n", raw_variant_ct, (raw_variant_ct == 1)? "" : "s");
12829 break;
12830 }
12831 goto OxBgenToPgen_ret_READ_FAIL;
12832 }
12833 }
12834 if (unlikely(uii != sample_ct)) {
12835 putc_unlocked('\n', stdout);
12836 logerrputs("Error: Unexpected number of samples specified in SNP block header.\n");
12837 goto OxBgenToPgen_ret_MALFORMED_INPUT;
12838 }
12839 uint16_t snpid_slen;
12840 if (unlikely(!fread_unlocked(&snpid_slen, 2, 1, bgenfile))) {
12841 goto OxBgenToPgen_ret_READ_FAIL;
12842 }
12843 if (!snpid_chr) {
12844 if (unlikely(fseeko(bgenfile, snpid_slen, SEEK_CUR))) {
12845 goto OxBgenToPgen_ret_READ_FAIL;
12846 }
12847 } else {
12848 if (unlikely(!snpid_slen)) {
12849 putc_unlocked('\n', stdout);
12850 logerrputs("Error: Length-0 SNP ID in .bgen file.\n");
12851 goto OxBgenToPgen_ret_INCONSISTENT_INPUT;
12852 }
12853 if (unlikely(!fread_unlocked(loadbuf, snpid_slen, 1, bgenfile))) {
12854 goto OxBgenToPgen_ret_READ_FAIL;
12855 }
12856 // loadbuf[snpid_slen] = '\0';
12857 }
12858 uint16_t rsid_slen;
12859 if (unlikely(!fread_unlocked(&rsid_slen, 2, 1, bgenfile))) {
12860 goto OxBgenToPgen_ret_READ_FAIL;
12861 }
12862 if (unlikely(fseeko(bgenfile, rsid_slen, SEEK_CUR))) {
12863 goto OxBgenToPgen_ret_READ_FAIL;
12864 }
12865 uint16_t chr_name_slen;
12866 if (unlikely(!fread_unlocked(&chr_name_slen, 2, 1, bgenfile))) {
12867 goto OxBgenToPgen_ret_READ_FAIL;
12868 }
12869 if (ox_single_chr_str) {
12870 if (unlikely(fseeko(bgenfile, chr_name_slen, SEEK_CUR))) {
12871 goto OxBgenToPgen_ret_READ_FAIL;
12872 }
12873 } else {
12874 if (!snpid_chr) {
12875 if (unlikely(!chr_name_slen)) {
12876 putc_unlocked('\n', stdout);
12877 logerrputs("Error: Length-0 chromosome ID in .bgen file.\n");
12878 goto OxBgenToPgen_ret_INCONSISTENT_INPUT;
12879 }
12880 if (unlikely(!fread_unlocked(loadbuf, chr_name_slen, 1, bgenfile))) {
12881 goto OxBgenToPgen_ret_READ_FAIL;
12882 }
12883 if (strequal_k(R_CAST(char*, loadbuf), "NA", chr_name_slen)) {
12884 loadbuf[0] = '0';
12885 chr_name_slen = 1;
12886 }
12887 } else {
12888 chr_name_slen = snpid_slen;
12889 }
12890 loadbuf[chr_name_slen] = '\0';
12891 reterr = GetOrAddChrCode(R_CAST(char*, loadbuf), "--bgen file", 0, chr_name_slen, prohibit_extra_chr, cip, &cur_chr_code);
12892 if (unlikely(reterr)) {
12893 goto OxBgenToPgen_ret_1;
12894 }
12895 skip = !IsSet(cip->chr_mask, cur_chr_code);
12896 }
12897
12898 uint32_t cur_bp; // ignore in this pass
12899 if (unlikely(!fread_unlocked(&cur_bp, 4, 1, bgenfile))) {
12900 goto OxBgenToPgen_ret_READ_FAIL;
12901 }
12902
12903 // allele count always 2 and not stored when layout=1
12904 for (uint32_t allele_idx = 0; allele_idx != 2; ++allele_idx) {
12905 uint32_t allele_slen;
12906 if (unlikely(!fread_unlocked(&allele_slen, 4, 1, bgenfile))) {
12907 goto OxBgenToPgen_ret_READ_FAIL;
12908 }
12909 if (unlikely(fseeko(bgenfile, allele_slen, SEEK_CUR))) {
12910 goto OxBgenToPgen_ret_READ_FAIL;
12911 }
12912 }
12913
12914 if (compression_mode) {
12915 #ifdef __LP64__
12916 compressed_block_byte_ct = 0;
12917 #endif
12918 if (unlikely(!fread_unlocked(&compressed_block_byte_ct, 4, 1, bgenfile))) {
12919 goto OxBgenToPgen_ret_READ_FAIL;
12920 }
12921 }
12922 ++variant_uidx;
12923 if (!(variant_uidx % 1000)) {
12924 printf("\r--bgen: %uk variants scanned.", variant_uidx / 1000);
12925 fflush(stdout);
12926 }
12927 if (dosage_exists || skip) {
12928 if (unlikely(fseeko(bgenfile, compressed_block_byte_ct, SEEK_CUR))) {
12929 goto OxBgenToPgen_ret_READ_FAIL;
12930 }
12931 // bugfix (25 Jun 2017): block_vidx should be left unchanged here
12932 variant_ct += 1 - skip;
12933 continue;
12934 }
12935 compressed_geno_starts[block_vidx] = bgen_geno_iter;
12936 if (compression_mode) {
12937 memcpy(bgen_geno_iter, &compressed_block_byte_ct, 4);
12938 bgen_geno_iter = &(bgen_geno_iter[4]);
12939 }
12940 if (unlikely(fread_checked(bgen_geno_iter, compressed_block_byte_ct, bgenfile))) {
12941 goto OxBgenToPgen_ret_READ_FAIL;
12942 }
12943 bgen_geno_iter = &(bgen_geno_iter[compressed_block_byte_ct]);
12944 ++block_vidx;
12945 if (block_vidx == cur_block_size) {
12946 parity = 1 - parity;
12947 if (ThreadsAreActive(&tg)) {
12948 // process *previous* block results
12949 JoinThreads(&tg);
12950 reterr = scan_ctx.reterr;
12951 if (unlikely(reterr)) {
12952 goto OxBgenToPgen_ret_bgen11_thread_fail;
12953 }
12954 dosage_exists = scan_ctx.dosage_exists;
12955 if (dosage_exists) {
12956 // don't need to scan for any more dosages
12957 StopThreads(&tg);
12958 if ((!chr_filter_exists) && (!allow_overstated_variant_ct)) {
12959 break;
12960 }
12961 continue;
12962 }
12963 }
12964 common.cur_block_size = cur_block_size;
12965 if (unlikely(SpawnThreads(&tg))) {
12966 goto OxBgenToPgen_ret_THREAD_CREATE_FAIL;
12967 }
12968 compressed_geno_starts = common.compressed_geno_starts[parity];
12969 bgen_geno_iter = compressed_geno_bufs[parity];
12970 block_vidx = 0;
12971 variant_ct += cur_block_size;
12972 if (cur_block_size < main_block_size) {
12973 cur_block_size *= 2;
12974 if (cur_block_size > main_block_size) {
12975 cur_block_size = main_block_size;
12976 }
12977 }
12978 }
12979 }
12980
12981 if (!chr_filter_exists) {
12982 variant_ct = raw_variant_ct;
12983 } else {
12984 variant_ct += block_vidx;
12985 if (variant_ct < calc_thread_ct) {
12986 if (unlikely(!variant_ct)) {
12987 putc_unlocked('\n', stdout);
12988 logerrprintfww("Error: All %u variant%s in .bgen file skipped due to chromosome filter.\n", raw_variant_ct, (raw_variant_ct == 1)? "" : "s");
12989 goto OxBgenToPgen_ret_INCONSISTENT_INPUT;
12990 }
12991 // bugfix (7 Oct 2017): with fewer variants than threads, need to
12992 // force initial launch here
12993 common.cur_block_size = variant_ct;
12994 if (unlikely(SpawnThreads(&tg))) {
12995 goto OxBgenToPgen_ret_THREAD_CREATE_FAIL;
12996 }
12997 block_vidx = 0;
12998 }
12999 }
13000 if (ThreadsAreActive(&tg)) {
13001 JoinThreads(&tg);
13002 reterr = scan_ctx.reterr;
13003 if (unlikely(reterr)) {
13004 goto OxBgenToPgen_ret_bgen11_thread_fail;
13005 }
13006 if (block_vidx && (!scan_ctx.dosage_exists)) {
13007 common.cur_block_size = block_vidx;
13008 } else {
13009 common.cur_block_size = 0;
13010 }
13011 DeclareLastThreadBlock(&tg);
13012 if (unlikely(SpawnThreads(&tg))) {
13013 goto OxBgenToPgen_ret_THREAD_CREATE_FAIL;
13014 }
13015 JoinThreads(&tg);
13016 reterr = scan_ctx.reterr;
13017 if (unlikely(reterr)) {
13018 goto OxBgenToPgen_ret_bgen11_thread_fail;
13019 }
13020 dosage_exists = scan_ctx.dosage_exists;
13021 }
13022
13023 if (unlikely(fseeko(bgenfile, initial_uints[0] + 4, SEEK_SET))) {
13024 goto OxBgenToPgen_ret_READ_FAIL;
13025 }
13026 snprintf(outname_end, kMaxOutfnameExtBlen, ".pgen");
13027 uintptr_t spgw_alloc_cacheline_ct;
13028 uint32_t max_vrec_len;
13029 reterr = SpgwInitPhase1(outname, nullptr, nullptr, variant_ct, sample_ct, 0, kPgenWriteBackwardSeek, dosage_exists? kfPgenGlobalDosagePresent : kfPgenGlobal0, (oxford_import_flags & kfOxfordImportRefUnknown)? 2 : 1, &spgw, &spgw_alloc_cacheline_ct, &max_vrec_len);
13030 if (unlikely(reterr)) {
13031 if (reterr == kPglRetOpenFail) {
13032 putc_unlocked('\n', stdout);
13033 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
13034 }
13035 goto OxBgenToPgen_ret_1;
13036 }
13037 unsigned char* spgw_alloc;
13038 if (unlikely(bigstack_alloc_uc(spgw_alloc_cacheline_ct * kCacheline, &spgw_alloc))) {
13039 goto OxBgenToPgen_ret_NOMEM;
13040 }
13041 SpgwInitPhase2(max_vrec_len, &spgw, spgw_alloc);
13042
13043 // Main workflow:
13044 // 1. Set n=0, load genotype data for first main_block_size variants
13045 // while writing .pvar
13046 //
13047 // 2. Spawn threads processing batch n genotype data
13048 // 3. If n>0, write results for block (n-1)
13049 // 4. Increment n by 1
13050 // 5. Load/write-.pvar for batch (n+1) unless eof
13051 // 6. Join threads
13052 // 7. Goto step 2 unless eof
13053 //
13054 // 8. Write results for last block
13055 //
13056 // (May be better to change this to use one output buffer instead of 2.)
13057 uint32_t prev_block_write_ct = 0;
13058 parity = 0;
13059 SetThreadFuncAndData(Bgen11GenoToPgenThread, &ctx, &tg);
13060 for (uint32_t vidx_start = 0; ; ) {
13061 uint32_t cur_block_write_ct = 0;
13062 if (!IsLastBlock(&tg)) {
13063 cur_block_write_ct = MINV(variant_ct - vidx_start, main_block_size);
13064 compressed_geno_starts = common.compressed_geno_starts[parity];
13065 bgen_geno_iter = compressed_geno_bufs[parity];
13066 for (block_vidx = 0; block_vidx != cur_block_write_ct; ) {
13067 uint32_t uii;
13068 if (unlikely(!fread_unlocked(&uii, 4, 1, bgenfile))) {
13069 goto OxBgenToPgen_ret_READ_FAIL;
13070 }
13071 if (unlikely(uii != sample_ct)) {
13072 putc_unlocked('\n', stdout);
13073 logerrputs("Error: Unexpected number of samples specified in SNP block header.\n");
13074 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13075 }
13076 uint16_t snpid_slen;
13077 if (unlikely(!fread_unlocked(&snpid_slen, 2, 1, bgenfile))) {
13078 goto OxBgenToPgen_ret_READ_FAIL;
13079 }
13080 char* rsid_start = R_CAST(char*, loadbuf);
13081 if (!snpid_chr) {
13082 if (unlikely(fseeko(bgenfile, snpid_slen, SEEK_CUR))) {
13083 goto OxBgenToPgen_ret_READ_FAIL;
13084 }
13085 } else {
13086 if (unlikely(!snpid_slen)) {
13087 putc_unlocked('\n', stdout);
13088 logerrputs("Error: Length-0 SNP ID in .bgen file.\n");
13089 goto OxBgenToPgen_ret_INCONSISTENT_INPUT;
13090 }
13091 if (unlikely(!fread_unlocked(loadbuf, snpid_slen, 1, bgenfile))) {
13092 goto OxBgenToPgen_ret_READ_FAIL;
13093 }
13094 // loadbuf[snpid_slen] = '\0';
13095 rsid_start = R_CAST(char*, &(loadbuf[snpid_slen + 1]));
13096 }
13097 uint16_t rsid_slen;
13098 if (unlikely(!fread_unlocked(&rsid_slen, 2, 1, bgenfile))) {
13099 goto OxBgenToPgen_ret_READ_FAIL;
13100 }
13101 if (unlikely(!rsid_slen)) {
13102 putc_unlocked('\n', stdout);
13103 logerrputs("Error: Length-0 rsID in .bgen file.\n");
13104 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13105 }
13106 if (unlikely(!fread_unlocked(rsid_start, rsid_slen, 1, bgenfile))) {
13107 goto OxBgenToPgen_ret_READ_FAIL;
13108 }
13109 char* loadbuf_iter = &(rsid_start[rsid_slen]);
13110 char* chr_name_start = loadbuf_iter;
13111 uint16_t chr_name_slen;
13112 if (unlikely(!fread_unlocked(&chr_name_slen, 2, 1, bgenfile))) {
13113 goto OxBgenToPgen_ret_READ_FAIL;
13114 }
13115 if (ox_single_chr_str) {
13116 if (unlikely(fseeko(bgenfile, chr_name_slen, SEEK_CUR))) {
13117 goto OxBgenToPgen_ret_READ_FAIL;
13118 }
13119 } else {
13120 if (!snpid_chr) {
13121 if (unlikely(!chr_name_slen)) {
13122 putc_unlocked('\n', stdout);
13123 logerrputs("Error: Length-0 chromosome ID in .bgen file.\n");
13124 goto OxBgenToPgen_ret_INCONSISTENT_INPUT;
13125 }
13126 if (unlikely(!fread_unlocked(chr_name_start, chr_name_slen, 1, bgenfile))) {
13127 goto OxBgenToPgen_ret_READ_FAIL;
13128 }
13129 if (strequal_k(chr_name_start, "NA", chr_name_slen)) {
13130 chr_name_start[0] = '0';
13131 chr_name_slen = 1;
13132 }
13133 } else {
13134 if (unlikely(fseeko(bgenfile, chr_name_slen, SEEK_CUR))) {
13135 goto OxBgenToPgen_ret_READ_FAIL;
13136 }
13137 chr_name_start = R_CAST(char*, loadbuf);
13138 chr_name_slen = snpid_slen;
13139 }
13140 chr_name_start[chr_name_slen] = '\0';
13141 cur_chr_code = GetChrCode(chr_name_start, cip, chr_name_slen);
13142 skip = !IsSet(cip->chr_mask, cur_chr_code);
13143 }
13144
13145 uint32_t cur_bp;
13146 uint32_t a1_slen;
13147 if (unlikely((!fread_unlocked(&cur_bp, 4, 1, bgenfile)) ||
13148 (!fread_unlocked(&a1_slen, 4, 1, bgenfile)))) {
13149 goto OxBgenToPgen_ret_READ_FAIL;
13150 }
13151 if (skip) {
13152 uint32_t a2_slen;
13153 if (unlikely(fseeko(bgenfile, a1_slen, SEEK_CUR) ||
13154 (!fread_unlocked(&a2_slen, 4, 1, bgenfile)) ||
13155 fseeko(bgenfile, a2_slen, SEEK_CUR))) {
13156 goto OxBgenToPgen_ret_READ_FAIL;
13157 }
13158 if (compression_mode) {
13159 #ifdef __LP64__
13160 compressed_block_byte_ct = 0;
13161 #endif
13162 if (unlikely(!fread_unlocked(&compressed_block_byte_ct, 4, 1, bgenfile))) {
13163 goto OxBgenToPgen_ret_READ_FAIL;
13164 }
13165 }
13166 if (unlikely(fseeko(bgenfile, compressed_block_byte_ct, SEEK_CUR))) {
13167 goto OxBgenToPgen_ret_READ_FAIL;
13168 }
13169 continue;
13170 }
13171 char* a1_ptr = loadbuf_iter;
13172 if (unlikely(!a1_slen)) {
13173 putc_unlocked('\n', stdout);
13174 logerrputs("Error: Empty allele code in .bgen file.\n");
13175 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13176 }
13177 // TODO: enforce a consistent, configurable limit across the
13178 // program (2^26 default?)
13179 if (unlikely(a1_slen > 1000000000)) {
13180 putc_unlocked('\n', stdout);
13181 logerrputs("Error: Allele code in .bgen file has more than 1 billion characters.\n");
13182 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13183 }
13184 if (unlikely(a1_slen + S_CAST(uintptr_t, a1_ptr - R_CAST(char*, loadbuf)) > loadbuf_size)) {
13185 goto OxBgenToPgen_ret_NOMEM;
13186 }
13187 if (unlikely(!fread_unlocked(a1_ptr, a1_slen, 1, bgenfile))) {
13188 goto OxBgenToPgen_ret_READ_FAIL;
13189 }
13190 char* a2_ptr = &(a1_ptr[a1_slen]);
13191 uint32_t a2_slen;
13192 if (unlikely(!fread_unlocked(&a2_slen, 4, 1, bgenfile))) {
13193 goto OxBgenToPgen_ret_READ_FAIL;
13194 }
13195 if (unlikely(!a2_slen)) {
13196 putc_unlocked('\n', stdout);
13197 logerrputs("Error: Empty allele code in .bgen file.\n");
13198 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13199 }
13200 if (unlikely(a2_slen > 1000000000)) {
13201 putc_unlocked('\n', stdout);
13202 logerrputs("Error: Allele code in .bgen file has more than 1 billion characters.\n");
13203 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13204 }
13205 if (unlikely(a2_slen + S_CAST(uintptr_t, a2_ptr - R_CAST(char*, loadbuf)) > loadbuf_size)) {
13206 goto OxBgenToPgen_ret_NOMEM;
13207 }
13208 if (unlikely(!fread_unlocked(a2_ptr, a2_slen, 1, bgenfile))) {
13209 goto OxBgenToPgen_ret_READ_FAIL;
13210 }
13211 if (compression_mode) {
13212 #ifdef __LP64__
13213 compressed_block_byte_ct = 0;
13214 #endif
13215 if (unlikely(!fread_unlocked(&compressed_block_byte_ct, 4, 1, bgenfile))) {
13216 goto OxBgenToPgen_ret_READ_FAIL;
13217 }
13218 }
13219 pvar_cswritep = chrtoa(cip, cur_chr_code, pvar_cswritep);
13220 *pvar_cswritep++ = '\t';
13221 if (unlikely(cur_bp > kMaxBp)) {
13222 putc_unlocked('\n', stdout);
13223 logerrputs("Error: Invalid bp coordinate (> 2^31 - 2) in .bgen file\n");
13224 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13225 }
13226 if (par_warn_code == cur_chr_code) {
13227 if (unlikely((!sex_info_avail) || (cur_bp <= kPAR1IntersectionLast) || (cur_bp >= kPAR2IntersectionFirst))) {
13228 putc_unlocked('\n', stdout);
13229 goto OxBgenToPgen_ret_SLOPPY_CHRX;
13230 }
13231 }
13232 pvar_cswritep = u32toa_x(cur_bp, '\t', pvar_cswritep);
13233 pvar_cswritep = memcpyax(pvar_cswritep, rsid_start, rsid_slen, '\t');
13234 if (prov_ref_allele_second) {
13235 uint32_t swap_slen = a1_slen;
13236 a1_slen = a2_slen;
13237 a2_slen = swap_slen;
13238 char* swap_ptr = a1_ptr;
13239 a1_ptr = a2_ptr;
13240 a2_ptr = swap_ptr;
13241 }
13242 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
13243 goto OxBgenToPgen_ret_WRITE_FAIL;
13244 }
13245 if (a1_slen < kMaxMediumLine) {
13246 pvar_cswritep = memcpya(pvar_cswritep, a1_ptr, a1_slen);
13247 } else {
13248 if (unlikely(CsputsStd(a1_ptr, a1_slen, &pvar_css, &pvar_cswritep))) {
13249 goto OxBgenToPgen_ret_WRITE_FAIL;
13250 }
13251 }
13252 *pvar_cswritep++ = '\t';
13253 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
13254 goto OxBgenToPgen_ret_WRITE_FAIL;
13255 }
13256 if (a2_slen < kMaxMediumLine) {
13257 pvar_cswritep = memcpya(pvar_cswritep, a2_ptr, a2_slen);
13258 } else {
13259 if (unlikely(CsputsStd(a2_ptr, a2_slen, &pvar_css, &pvar_cswritep))) {
13260 goto OxBgenToPgen_ret_WRITE_FAIL;
13261 }
13262 }
13263 AppendBinaryEoln(&pvar_cswritep);
13264
13265 compressed_geno_starts[block_vidx] = bgen_geno_iter;
13266 if (compression_mode) {
13267 memcpy(bgen_geno_iter, &compressed_block_byte_ct, 4);
13268 bgen_geno_iter = &(bgen_geno_iter[4]);
13269 }
13270 if (unlikely(fread_checked(bgen_geno_iter, compressed_block_byte_ct, bgenfile))) {
13271 goto OxBgenToPgen_ret_READ_FAIL;
13272 }
13273 bgen_geno_iter = &(bgen_geno_iter[compressed_block_byte_ct]);
13274 ++block_vidx;
13275 }
13276 }
13277 if (vidx_start) {
13278 JoinThreads(&tg);
13279 reterr = ctx.reterr;
13280 if (unlikely(reterr)) {
13281 goto OxBgenToPgen_ret_bgen11_thread_fail;
13282 }
13283 }
13284 if (!IsLastBlock(&tg)) {
13285 common.cur_block_size = cur_block_write_ct;
13286 if (vidx_start + cur_block_write_ct == variant_ct) {
13287 DeclareLastThreadBlock(&tg);
13288 }
13289 if (unlikely(SpawnThreads(&tg))) {
13290 goto OxBgenToPgen_ret_THREAD_CREATE_FAIL;
13291 }
13292 }
13293 parity = 1 - parity;
13294 if (vidx_start) {
13295 // write *previous* block results
13296 uintptr_t* write_genovec_iter = ctx.write_genovecs[parity];
13297 uint32_t* write_dosage_ct_iter = ctx.write_dosage_cts[parity];
13298 uintptr_t* write_dosage_present_iter = ctx.write_dosage_presents[parity];
13299 Dosage* write_dosage_main_iter = ctx.write_dosage_mains[parity];
13300 for (uint32_t vidx = vidx_start - prev_block_write_ct; vidx != vidx_start; ++vidx) {
13301 const uint32_t cur_dosage_ct = *write_dosage_ct_iter++;
13302 if (!cur_dosage_ct) {
13303 if (unlikely(SpgwAppendBiallelicGenovec(write_genovec_iter, &spgw))) {
13304 goto OxBgenToPgen_ret_WRITE_FAIL;
13305 }
13306 } else {
13307 reterr = SpgwAppendBiallelicGenovecDosage16(write_genovec_iter, write_dosage_present_iter, write_dosage_main_iter, cur_dosage_ct, &spgw);
13308 if (unlikely(reterr)) {
13309 goto OxBgenToPgen_ret_1;
13310 }
13311 }
13312 write_genovec_iter = &(write_genovec_iter[sample_ctaw2]);
13313 write_dosage_present_iter = &(write_dosage_present_iter[sample_ctaw]);
13314 write_dosage_main_iter = &(write_dosage_main_iter[sample_ct]);
13315 }
13316 }
13317 if (vidx_start == variant_ct) {
13318 break;
13319 }
13320 if (vidx_start) {
13321 printf("\r--bgen: %uk variants converted.", vidx_start / 1000);
13322 if (vidx_start <= main_block_size) {
13323 fputs(" \b\b\b\b", stdout);
13324 }
13325 fflush(stdout);
13326 }
13327 vidx_start += cur_block_write_ct;
13328 prev_block_write_ct = cur_block_write_ct;
13329 }
13330 } else {
13331 // v1.2-1.3
13332 uintptr_t* allele_idx_offsets;
13333 if (unlikely(bigstack_end_alloc_w(raw_variant_ct + 1, &allele_idx_offsets))) {
13334 goto OxBgenToPgen_ret_NOMEM;
13335 }
13336
13337 Bgen13DosageOrPhaseScanCtx scan_ctx;
13338 scan_ctx.common = &common;
13339 scan_ctx.bgen_import_dosage_certainty_thresholds = nullptr;
13340 if (import_dosage_certainty > (1.0 - kSmallEpsilon) / 3.0) {
13341 scan_ctx.bgen_import_dosage_certainty_thresholds = S_CAST(uint32_t*, bigstack_alloc_raw_rd((kMaxBgenImportBits + 1) * sizeof(int32_t)));
13342 for (uint32_t bit_precision = 1; bit_precision != (kMaxBgenImportBits + 1); ++bit_precision) {
13343 const uint32_t denom = (1U << bit_precision) - 1;
13344 const double denom_d = u31tod(denom);
13345 scan_ctx.bgen_import_dosage_certainty_thresholds[bit_precision] = 1 + S_CAST(int32_t, import_dosage_certainty * denom_d);
13346 }
13347 }
13348 // bugfix (2 Jul 2017): if max_thread_ct == 1 but there's >12GiB memory,
13349 // limit to 1 thread rather than (max_thread_ct - 1)...
13350 uint32_t calc_thread_ct_limit = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
13351 if (calc_thread_ct_limit > raw_variant_ct) {
13352 calc_thread_ct_limit = raw_variant_ct;
13353 }
13354
13355 scan_ctx.thread_wkspaces = S_CAST(unsigned char**, bigstack_alloc_raw_rd(calc_thread_ct_limit * sizeof(intptr_t)));
13356 scan_ctx.thread_bidxs[0] = S_CAST(uint32_t*, bigstack_alloc_raw_rd((calc_thread_ct_limit + 1) * sizeof(int32_t)));
13357 scan_ctx.thread_bidxs[1] = S_CAST(uint32_t*, bigstack_alloc_raw_rd((calc_thread_ct_limit + 1) * sizeof(int32_t)));
13358 uintptr_t main_block_size = 65536;
13359 if (unlikely(bigstack_alloc_kcp(calc_thread_ct_limit, &(scan_ctx.err_extra)) ||
13360 // ***** all bigstack allocations from this point on are
13361 // reset before pass 2 *****
13362 // probably want to change this to use Gparse...
13363 bigstack_alloc_u16(main_block_size, &(scan_ctx.bgen_allele_cts[0])) ||
13364 bigstack_alloc_u16(main_block_size, &(scan_ctx.bgen_allele_cts[1])) ||
13365 bigstack_alloc_ucp(main_block_size + 1, &(common.compressed_geno_starts[0])) ||
13366 bigstack_alloc_ucp(main_block_size + 1, &(common.compressed_geno_starts[1])))) {
13367 goto OxBgenToPgen_ret_NOMEM;
13368 }
13369 if (compression_mode) {
13370 if (unlikely(bigstack_alloc_u32(main_block_size, &(scan_ctx.uncompressed_genodata_byte_cts[0])) ||
13371 bigstack_alloc_u32(main_block_size, &(scan_ctx.uncompressed_genodata_byte_cts[1])))) {
13372 goto OxBgenToPgen_ret_NOMEM;
13373 }
13374 } else {
13375 // defensive
13376 scan_ctx.uncompressed_genodata_byte_cts[0] = nullptr;
13377 scan_ctx.uncompressed_genodata_byte_cts[1] = nullptr;
13378 }
13379
13380 // ploidy >2 is not supported by PLINK 2. (A future build may have code
13381 // to treat those calls as missing instead of erroring out, as is done
13382 // with VCF ploidy >2. But I'll wait until this case actually comes up
13383 // in the wild...)
13384 // But even without that, the diploid worst case of 65535 alleles,
13385 // unphased 32-bit probabilities blows past the 4GiB uncompressed record
13386 // size limit with just 1 sample! Consequences:
13387 // * A simple way to avoid unnecessary NOMEM errors is to give each
13388 // thread 4GiB of decompression workspace on the first pass. This may
13389 // greatly reduce the number of decompression worker threads we can
13390 // deploy, but for the first pass that's acceptable: the worker threads
13391 // will usually all exit almost immediately (since we just need to
13392 // determine whether *any* phase/dosage info needs to be saved).
13393 // * Even 1 thread x 4GiB won't always be available, especially since we
13394 // have a double-buffering workflow which requires additional
13395 // allocations summing to more than twice the decompression workspace.
13396 // So we need to be able to fall back to a smaller decompression
13397 // workspace size, and throw NOMEM when it's insufficient.
13398 // * Of course, records will almost always be far smaller than 4GiB.
13399 // During the first pass, we'll see every uncompressed record size
13400 // (even if the decompression worker threads terminate early), so we
13401 // can usually increase the number of worker threads before the second
13402 // pass.
13403 // Overall memory allocation for first pass:
13404 // loadbuf_size (~1/7, up to 2GiB) : Chromosome code/variant ID/allele
13405 // code load buffer.
13406 // mainbuf_size (~2/7) : Compressed genotype data buffer 0, up to 4GiB
13407 // per decompression thread
13408 // mainbuf_size : Compressed genotype data buffer 1
13409 // mainbuf_size : Decompression thread workspace(s)
13410 // Second pass:
13411 // mainbuf_size (~1/6) : Decompression thread workspaces.
13412 // 16K : .bgen chromosome code load buffer.
13413 // remainder (~5/6) : Single-threaded .pgen writer, and Gparse
13414 // double-buffer.
13415 uintptr_t loadbuf_size = RoundDownPow2(bigstack_left() / 7, kCacheline);
13416 if (loadbuf_size > kMaxLongLine) {
13417 loadbuf_size = kMaxLongLine;
13418 } else if (unlikely(loadbuf_size < 2 * 65536)) {
13419 // don't want to worry about chromosome/variant ID buffer space checks
13420 // in inner loop
13421 goto OxBgenToPgen_ret_NOMEM;
13422 }
13423 unsigned char* loadbuf = S_CAST(unsigned char*, bigstack_alloc_raw(loadbuf_size));
13424
13425 uintptr_t mainbuf_size = RoundDownPow2(bigstack_left() / 3, kCacheline);
13426 uint32_t calc_thread_ct = 1;
13427 uintptr_t thread_wkspace_size;
13428 #ifdef __LP64__
13429 // hard compressed and uncompressed record length limits of 2^31 - 1
13430 // bytes, since these are represented as uint32s in the file.
13431 if (mainbuf_size > 0x100000000LLU) {
13432 thread_wkspace_size = 0x100000000LLU;
13433 mainbuf_size &= 0xffffffff00000000LLU;
13434 calc_thread_ct = mainbuf_size >> 32;
13435 if (calc_thread_ct > calc_thread_ct_limit) {
13436 calc_thread_ct = calc_thread_ct_limit;
13437 mainbuf_size = S_CAST(uintptr_t, calc_thread_ct_limit) << 32;
13438 }
13439 } else {
13440 thread_wkspace_size = mainbuf_size;
13441 }
13442 #else
13443 thread_wkspace_size = mainbuf_size;
13444 #endif
13445 // note that thread_wkspace_size is the size limit for a compressed
13446 // variant record *and* the uncompressed form
13447
13448 if (main_block_size > raw_variant_ct + calc_thread_ct - 1) {
13449 main_block_size = raw_variant_ct + calc_thread_ct - 1;
13450 }
13451 uint32_t per_thread_block_limit = main_block_size / calc_thread_ct;
13452 // may as well guarantee divisibility
13453 main_block_size = per_thread_block_limit * calc_thread_ct;
13454 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
13455 goto OxBgenToPgen_ret_NOMEM;
13456 }
13457 if (compression_mode == 1) {
13458 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
13459 common.libdeflate_decompressors[tidx] = libdeflate_alloc_decompressor();
13460 if (unlikely(!common.libdeflate_decompressors[tidx])) {
13461 goto OxBgenToPgen_ret_NOMEM;
13462 }
13463 }
13464 }
13465 unsigned char* compressed_geno_bufs[2];
13466 compressed_geno_bufs[0] = S_CAST(unsigned char*, bigstack_alloc_raw(mainbuf_size));
13467 compressed_geno_bufs[1] = S_CAST(unsigned char*, bigstack_alloc_raw(mainbuf_size));
13468 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
13469 scan_ctx.thread_wkspaces[tidx] = S_CAST(unsigned char*, bigstack_alloc_raw(thread_wkspace_size));
13470 }
13471 scan_ctx.err_info = (~0LLU) << 32;
13472 scan_ctx.error_on_polyploid = !(import_flags & kfImportPolyploidMissing);
13473 SetThreadFuncAndData(Bgen13DosageOrPhaseScanThread, &scan_ctx, &tg);
13474
13475 uint32_t variant_ct = 0;
13476
13477 uint32_t block_vidx = 0;
13478
13479 // bgen-1.2 and -1.3 records can vary wildly in size, so we're a bit more
13480 // careful with load balancing here. (possible todo: bgzf-style atomic
13481 // operations)
13482 uint32_t cur_per_thread_block_limit = 1;
13483 uint32_t cur_thread_block_vidx_limit = 1;
13484 uint32_t cur_thread_fill_idx = 0;
13485
13486 uint32_t parity = 0;
13487 uint32_t* thread_bidxs = scan_ctx.thread_bidxs[0];
13488 uint16_t* bgen_allele_cts = scan_ctx.bgen_allele_cts[0];
13489 unsigned char** compressed_geno_starts = common.compressed_geno_starts[0];
13490 uint32_t* uncompressed_genodata_byte_cts = scan_ctx.uncompressed_genodata_byte_cts[0];
13491 unsigned char* bgen_geno_iter = compressed_geno_bufs[0];
13492 unsigned char* cur_geno_buf_end = &(bgen_geno_iter[thread_wkspace_size]);
13493 thread_bidxs[0] = 0;
13494 compressed_geno_starts[0] = bgen_geno_iter;
13495 uintptr_t* allele_idx_offsets_iter = allele_idx_offsets;
13496 uintptr_t tot_allele_ct = 0;
13497 uint32_t max_allele_ct = 2;
13498 uint32_t max_compressed_geno_blen = 0;
13499 uint32_t max_uncompressed_geno_blen = 0;
13500 uint32_t uncompressed_genodata_byte_ct = 0;
13501 uint32_t skip_chr = 0;
13502 uint32_t import_max_alleles_skip_ct = 0;
13503
13504 // temporary kludge
13505 uint32_t multiallelic_tmp_skip_ct = 0;
13506
13507 for (uint32_t variant_uidx = 0; variant_uidx != header_variant_ct; ) {
13508 // format is mostly identical to bgen 1.1; but there's no sample count,
13509 // and there is an allele count
13510 // logic is more similar to the second bgen 1.1 pass since we write the
13511 // .pvar here.
13512 uint16_t snpid_slen;
13513 {
13514 const uintptr_t bytes_read = fread_unlocked(&snpid_slen, 1, 2, bgenfile);
13515 if (bytes_read != 2) {
13516 if (likely(!bytes_read)) {
13517 putc_unlocked('\n', stdout);
13518 if (likely(allow_overstated_variant_ct)) {
13519 raw_variant_ct = variant_uidx;
13520 logprintf("--lax-bgen-import: .bgen file actually contains %u variant%s.\n", raw_variant_ct, (raw_variant_ct == 1)? "" : "s");
13521 break;
13522 }
13523 logerrprintfww("Error: .bgen file actually contains %u variant%s; header is incorrect. Add --lax-bgen-import to force import.\n", variant_uidx, (variant_uidx == 1)? "" : "s");
13524 goto OxBgenToPgen_ret_INCONSISTENT_INPUT;
13525 }
13526 goto OxBgenToPgen_ret_READ_FAIL;
13527 }
13528 }
13529 char* rsid_start = R_CAST(char*, loadbuf);
13530 if (!snpid_chr) {
13531 if (unlikely(fseeko(bgenfile, snpid_slen, SEEK_CUR))) {
13532 goto OxBgenToPgen_ret_READ_FAIL;
13533 }
13534 } else {
13535 if (unlikely(!snpid_slen)) {
13536 putc_unlocked('\n', stdout);
13537 logerrputs("Error: Length-0 SNP ID in .bgen file.\n");
13538 goto OxBgenToPgen_ret_INCONSISTENT_INPUT;
13539 }
13540 if (unlikely(!fread_unlocked(loadbuf, snpid_slen, 1, bgenfile))) {
13541 goto OxBgenToPgen_ret_READ_FAIL;
13542 }
13543 // loadbuf[snpid_slen] = '\0';
13544 rsid_start = R_CAST(char*, &(loadbuf[snpid_slen + 1]));
13545 }
13546 uint16_t rsid_slen;
13547 if (unlikely(!fread_unlocked(&rsid_slen, 2, 1, bgenfile))) {
13548 goto OxBgenToPgen_ret_READ_FAIL;
13549 }
13550 if (unlikely(!rsid_slen)) {
13551 putc_unlocked('\n', stdout);
13552 logerrputs("Error: Length-0 rsID in .bgen file.\n");
13553 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13554 }
13555 if (unlikely(!fread_unlocked(rsid_start, rsid_slen, 1, bgenfile))) {
13556 goto OxBgenToPgen_ret_READ_FAIL;
13557 }
13558 char* loadbuf_iter = &(rsid_start[rsid_slen]);
13559 char* chr_name_start = loadbuf_iter;
13560 uint16_t chr_name_slen;
13561 if (unlikely(!fread_unlocked(&chr_name_slen, 2, 1, bgenfile))) {
13562 goto OxBgenToPgen_ret_READ_FAIL;
13563 }
13564 if (ox_single_chr_str) {
13565 if (unlikely(fseeko(bgenfile, chr_name_slen, SEEK_CUR))) {
13566 goto OxBgenToPgen_ret_READ_FAIL;
13567 }
13568 } else {
13569 if (!snpid_chr) {
13570 if (unlikely(!chr_name_slen)) {
13571 putc_unlocked('\n', stdout);
13572 logerrputs("Error: Length-0 chromosome ID in .bgen file.\n");
13573 goto OxBgenToPgen_ret_INCONSISTENT_INPUT;
13574 }
13575 if (unlikely(!fread_unlocked(chr_name_start, chr_name_slen, 1, bgenfile))) {
13576 goto OxBgenToPgen_ret_READ_FAIL;
13577 }
13578 if (strequal_k(chr_name_start, "NA", chr_name_slen)) {
13579 chr_name_start[0] = '0';
13580 chr_name_slen = 1;
13581 }
13582 } else {
13583 if (unlikely(fseeko(bgenfile, chr_name_slen, SEEK_CUR))) {
13584 goto OxBgenToPgen_ret_READ_FAIL;
13585 }
13586 chr_name_start = R_CAST(char*, loadbuf);
13587 chr_name_slen = snpid_slen;
13588 }
13589 // chromosome ID length restriction enforced here, so we don't check
13590 // earlier
13591 chr_name_start[chr_name_slen] = '\0';
13592 reterr = GetOrAddChrCode(chr_name_start, "--bgen file", 0, chr_name_slen, prohibit_extra_chr, cip, &cur_chr_code);
13593 if (unlikely(reterr)) {
13594 goto OxBgenToPgen_ret_1;
13595 }
13596 skip_chr = !IsSet(cip->chr_mask, cur_chr_code);
13597 }
13598
13599 uint32_t cur_bp;
13600 uint32_t cur_allele_ct = 0;
13601 if (unlikely((!fread_unlocked(&cur_bp, 4, 1, bgenfile)) ||
13602 (!fread_unlocked(&cur_allele_ct, 2, 1, bgenfile)))) {
13603 goto OxBgenToPgen_ret_READ_FAIL;
13604 }
13605 if (unlikely(cur_allele_ct < 2)) {
13606 // this is undefined in the 1.3 standard; prohibit for now
13607 putc_unlocked('\n', stdout);
13608 logerrputs("Error: .bgen variant has fewer than two alleles.\n");
13609 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13610 }
13611 ++variant_uidx;
13612 if (!(variant_uidx % 1000)) {
13613 printf("\r--bgen: %uk variants scanned.", variant_uidx / 1000);
13614 fflush(stdout);
13615 }
13616
13617 // the "cur_allele_ct > 2" part is a temporary kludge
13618 if (skip_chr || (cur_allele_ct > 2)) {
13619 if (!skip_chr) {
13620 if (cur_allele_ct > import_max_allele_ct) {
13621 ++import_max_alleles_skip_ct;
13622 } else {
13623 ++multiallelic_tmp_skip_ct;
13624 }
13625 }
13626 for (uint32_t allele_idx = 0; allele_idx != cur_allele_ct; ++allele_idx) {
13627 uint32_t cur_allele_slen;
13628 if (unlikely((!fread_unlocked(&cur_allele_slen, 4, 1, bgenfile)) ||
13629 fseeko(bgenfile, cur_allele_slen, SEEK_CUR))) {
13630 goto OxBgenToPgen_ret_READ_FAIL;
13631 }
13632 }
13633 uint32_t genodata_byte_ct;
13634 if (unlikely((!fread_unlocked(&genodata_byte_ct, 4, 1, bgenfile)) ||
13635 fseeko(bgenfile, genodata_byte_ct, SEEK_CUR))) {
13636 goto OxBgenToPgen_ret_READ_FAIL;
13637 }
13638 continue;
13639 }
13640 if (unlikely(rsid_slen > kMaxIdSlen)) {
13641 // enforce this iff we aren't skipping
13642 putc_unlocked('\n', stdout);
13643 logerrputs("Error: Variant names are limited to " MAX_ID_SLEN_STR " characters.\n");
13644 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13645 }
13646 // special handling of first two alleles since either may be
13647 // reference, so we may need to swap order
13648 char* a1_ptr = loadbuf_iter;
13649 uint32_t a1_slen;
13650 if (unlikely(!fread_unlocked(&a1_slen, 4, 1, bgenfile))) {
13651 goto OxBgenToPgen_ret_READ_FAIL;
13652 }
13653 if (unlikely(!a1_slen)) {
13654 putc_unlocked('\n', stdout);
13655 logerrputs("Error: Empty allele code in .bgen file.\n");
13656 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13657 }
13658 if (unlikely(a1_slen > 1000000000)) {
13659 putc_unlocked('\n', stdout);
13660 logerrputs("Error: Allele code in .bgen file has more than 1 billion characters.\n");
13661 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13662 }
13663 if (unlikely(a1_slen + S_CAST(uintptr_t, a1_ptr - R_CAST(char*, loadbuf)) > loadbuf_size)) {
13664 goto OxBgenToPgen_ret_NOMEM;
13665 }
13666 if (unlikely(!fread_unlocked(a1_ptr, a1_slen, 1, bgenfile))) {
13667 goto OxBgenToPgen_ret_READ_FAIL;
13668 }
13669 char* a2_ptr = &(a1_ptr[a1_slen]);
13670 uint32_t a2_slen;
13671 if (unlikely(!fread_unlocked(&a2_slen, 4, 1, bgenfile))) {
13672 goto OxBgenToPgen_ret_READ_FAIL;
13673 }
13674 if (unlikely(!a2_slen)) {
13675 putc_unlocked('\n', stdout);
13676 logerrputs("Error: Empty allele code in .bgen file.\n");
13677 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13678 }
13679 if (unlikely(a2_slen > 1000000000)) {
13680 putc_unlocked('\n', stdout);
13681 logerrputs("Error: Allele code in .bgen file has more than 1 billion characters.\n");
13682 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13683 }
13684 if (unlikely(a2_slen + S_CAST(uintptr_t, a2_ptr - R_CAST(char*, loadbuf)) > loadbuf_size)) {
13685 goto OxBgenToPgen_ret_NOMEM;
13686 }
13687 if (unlikely(!fread_unlocked(a2_ptr, a2_slen, 1, bgenfile))) {
13688 goto OxBgenToPgen_ret_READ_FAIL;
13689 }
13690 pvar_cswritep = chrtoa(cip, cur_chr_code, pvar_cswritep);
13691 *pvar_cswritep++ = '\t';
13692 if (unlikely(cur_bp > kMaxBp)) {
13693 putc_unlocked('\n', stdout);
13694 logerrputs("Error: Invalid bp coordinate (> 2^31 - 2) in .bgen file\n");
13695 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13696 }
13697 if (par_warn_code == cur_chr_code) {
13698 if (unlikely((!sex_info_avail) || (cur_bp <= kPAR1IntersectionLast) || (cur_bp >= kPAR2IntersectionFirst))) {
13699 putc_unlocked('\n', stdout);
13700 goto OxBgenToPgen_ret_SLOPPY_CHRX;
13701 }
13702 }
13703 pvar_cswritep = u32toa_x(cur_bp, '\t', pvar_cswritep);
13704 pvar_cswritep = memcpyax(pvar_cswritep, rsid_start, rsid_slen, '\t');
13705 if (prov_ref_allele_second) {
13706 const uint32_t swap_slen = a1_slen;
13707 a1_slen = a2_slen;
13708 a2_slen = swap_slen;
13709 char* swap_ptr = a1_ptr;
13710 a1_ptr = a2_ptr;
13711 a2_ptr = swap_ptr;
13712 }
13713 // allele codes may be too large for write buffer
13714 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
13715 goto OxBgenToPgen_ret_WRITE_FAIL;
13716 }
13717 if (a1_slen < kMaxMediumLine) {
13718 pvar_cswritep = memcpya(pvar_cswritep, a1_ptr, a1_slen);
13719 } else {
13720 if (unlikely(CsputsStd(a1_ptr, a1_slen, &pvar_css, &pvar_cswritep))) {
13721 goto OxBgenToPgen_ret_WRITE_FAIL;
13722 }
13723 }
13724 *pvar_cswritep++ = '\t';
13725 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
13726 goto OxBgenToPgen_ret_WRITE_FAIL;
13727 }
13728 if (a2_slen < kMaxMediumLine) {
13729 pvar_cswritep = memcpya(pvar_cswritep, a2_ptr, a2_slen);
13730 } else {
13731 if (unlikely(CsputsStd(a2_ptr, a2_slen, &pvar_css, &pvar_cswritep))) {
13732 goto OxBgenToPgen_ret_WRITE_FAIL;
13733 }
13734 }
13735 for (uint32_t allele_idx = 2; allele_idx != cur_allele_ct; ++allele_idx) {
13736 // (can't actually reach here yet since we're skipping multiallelics
13737 // for now)
13738 // safe to use entire loadbuf for this
13739 assert(0);
13740 uint32_t cur_allele_slen;
13741 if (unlikely(!fread_unlocked(&cur_allele_slen, 4, 1, bgenfile))) {
13742 goto OxBgenToPgen_ret_READ_FAIL;
13743 }
13744 if (unlikely(!cur_allele_slen)) {
13745 putc_unlocked('\n', stdout);
13746 logerrputs("Error: Empty allele code in .bgen file.\n");
13747 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13748 }
13749 if (unlikely(cur_allele_slen > 1000000000)) {
13750 putc_unlocked('\n', stdout);
13751 logerrputs("Error: Allele code in .bgen file has more than 1 billion characters.\n");
13752 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13753 }
13754 if (unlikely(cur_allele_slen > loadbuf_size)) {
13755 goto OxBgenToPgen_ret_NOMEM;
13756 }
13757 if (unlikely(!fread_unlocked(loadbuf, cur_allele_slen, 1, bgenfile))) {
13758 goto OxBgenToPgen_ret_READ_FAIL;
13759 }
13760 *pvar_cswritep++ = ',';
13761 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
13762 goto OxBgenToPgen_ret_WRITE_FAIL;
13763 }
13764 if (cur_allele_slen < kMaxMediumLine) {
13765 pvar_cswritep = memcpya(pvar_cswritep, loadbuf, cur_allele_slen);
13766 } else {
13767 if (unlikely(CsputsStd(R_CAST(char*, loadbuf), cur_allele_slen, &pvar_css, &pvar_cswritep))) {
13768 goto OxBgenToPgen_ret_WRITE_FAIL;
13769 }
13770 }
13771 }
13772
13773 AppendBinaryEoln(&pvar_cswritep);
13774 *allele_idx_offsets_iter++ = tot_allele_ct;
13775 tot_allele_ct += cur_allele_ct;
13776 if (cur_allele_ct > max_allele_ct) {
13777 max_allele_ct = cur_allele_ct;
13778 }
13779 uint32_t genodata_byte_ct;
13780 if (unlikely(!fread_unlocked(&genodata_byte_ct, 4, 1, bgenfile))) {
13781 goto OxBgenToPgen_ret_READ_FAIL;
13782 }
13783 if (genodata_byte_ct > max_compressed_geno_blen) {
13784 max_compressed_geno_blen = genodata_byte_ct;
13785 }
13786 if (uncompressed_genodata_byte_cts) {
13787 if (unlikely(genodata_byte_ct < 4)) {
13788 logerrputs("Error: Invalid compressed block length in .bgen file.\n");
13789 goto OxBgenToPgen_ret_MALFORMED_INPUT;
13790 }
13791 if (unlikely(!fread_unlocked(&uncompressed_genodata_byte_ct, 4, 1, bgenfile))) {
13792 goto OxBgenToPgen_ret_READ_FAIL;
13793 }
13794 if (uncompressed_genodata_byte_ct > max_uncompressed_geno_blen) {
13795 max_uncompressed_geno_blen = uncompressed_genodata_byte_ct;
13796 }
13797 genodata_byte_ct -= 4;
13798 }
13799 if (dosage_exists) {
13800 if (unlikely(fseeko(bgenfile, genodata_byte_ct, SEEK_CUR))) {
13801 goto OxBgenToPgen_ret_READ_FAIL;
13802 }
13803 ++variant_ct;
13804 continue;
13805 }
13806
13807 if ((block_vidx == cur_thread_block_vidx_limit) || (S_CAST(uintptr_t, cur_geno_buf_end - bgen_geno_iter) < genodata_byte_ct)) {
13808 if (unlikely(!block_vidx)) {
13809 goto OxBgenToPgen_ret_NOMEM;
13810 }
13811 thread_bidxs[++cur_thread_fill_idx] = block_vidx;
13812 if (cur_thread_fill_idx == calc_thread_ct) {
13813 parity = 1 - parity;
13814 if (ThreadsAreActive(&tg)) {
13815 // process *previous* block results
13816 JoinThreads(&tg);
13817 reterr = S_CAST(PglErr, scan_ctx.err_info & 255);
13818 if (unlikely(reterr)) {
13819 PrintBgenImportErr(scan_ctx.err_extra, scan_ctx.err_info, scan_ctx.vidx_start);
13820 goto OxBgenToPgen_ret_1;
13821 }
13822 dosage_exists = scan_ctx.dosage_exists;
13823 if (dosage_exists) {
13824 // don't need to scan for any more dosages
13825 StopThreads(&tg);
13826
13827 // however, unlike bgen-1.1 case, we can never do full
13828 // early-exit since we have to scan for multiallelic variants:
13829 // writer must be initialized with (i) an accurate variant
13830 // count, which is temporarily affected by skipped multiallelic
13831 // variants, and (ii) when we no longer skip them, the
13832 // PgenWriter constructor still needs a maximum allele count so
13833 // it can allocate properly-sized buffers.
13834 if (unlikely(fseeko(bgenfile, genodata_byte_ct, SEEK_CUR))) {
13835 goto OxBgenToPgen_ret_READ_FAIL;
13836 }
13837 ++variant_ct;
13838 continue;
13839 }
13840 }
13841 scan_ctx.vidx_start = variant_ct;
13842 if (unlikely(SpawnThreads(&tg))) {
13843 goto OxBgenToPgen_ret_THREAD_CREATE_FAIL;
13844 }
13845 compressed_geno_starts = common.compressed_geno_starts[parity];
13846 uncompressed_genodata_byte_cts = scan_ctx.uncompressed_genodata_byte_cts[parity];
13847 thread_bidxs = scan_ctx.thread_bidxs[parity];
13848 bgen_allele_cts = scan_ctx.bgen_allele_cts[parity];
13849 bgen_geno_iter = compressed_geno_bufs[parity];
13850 thread_bidxs[0] = 0;
13851 compressed_geno_starts[0] = bgen_geno_iter;
13852 variant_ct += block_vidx;
13853 block_vidx = 0;
13854 if (cur_per_thread_block_limit < per_thread_block_limit) {
13855 cur_per_thread_block_limit *= 2;
13856 if (cur_per_thread_block_limit > per_thread_block_limit) {
13857 cur_per_thread_block_limit = per_thread_block_limit;
13858 }
13859 }
13860 cur_thread_block_vidx_limit = 0;
13861 cur_thread_fill_idx = 0;
13862 }
13863 cur_geno_buf_end = &(bgen_geno_iter[thread_wkspace_size]);
13864 cur_thread_block_vidx_limit += cur_per_thread_block_limit;
13865 }
13866 bgen_allele_cts[block_vidx] = cur_allele_ct;
13867 if (uncompressed_genodata_byte_cts) {
13868 uncompressed_genodata_byte_cts[block_vidx] = uncompressed_genodata_byte_ct;
13869 }
13870 if (unlikely(fread_checked(bgen_geno_iter, genodata_byte_ct, bgenfile))) {
13871 goto OxBgenToPgen_ret_READ_FAIL;
13872 }
13873 bgen_geno_iter = &(bgen_geno_iter[genodata_byte_ct]);
13874 compressed_geno_starts[++block_vidx] = bgen_geno_iter;
13875 }
13876 variant_ct += block_vidx;
13877 if (import_max_alleles_skip_ct) {
13878 putc_unlocked('\n', stdout);
13879 logprintf("--import-max-alleles: %u variant%s skipped.\n", import_max_alleles_skip_ct, (import_max_alleles_skip_ct == 1)? "" : "s");
13880 }
13881 if (multiallelic_tmp_skip_ct) {
13882 putc_unlocked('\n', stdout);
13883 logerrprintfww("Warning: %u multiallelic variant%s skipped%s (not yet supported).\n", multiallelic_tmp_skip_ct, (multiallelic_tmp_skip_ct == 1)? "" : "s", (import_max_allele_ct < 0x7ffffffe)? ", on top of --import-max-alleles filter" : "");
13884 }
13885 if (unlikely(!variant_ct)) {
13886 putc_unlocked('\n', stdout);
13887 logerrprintf("Error: All %u variant%s in .bgen file skipped.\n", raw_variant_ct, (raw_variant_ct == 1)? "" : "s");
13888 goto OxBgenToPgen_ret_INCONSISTENT_INPUT;
13889 }
13890 if (variant_ct == block_vidx) {
13891 // with multiple threads, there's no guarantee that even the first
13892 // decompression job has launched (e.g. there's only 1 variant on the
13893 // relevant chromosome in the entire .bgen, and calc_thread_ct == 2).
13894 thread_bidxs[cur_thread_fill_idx + 1] = block_vidx;
13895 scan_ctx.vidx_start = 0;
13896 if (unlikely(SpawnThreads(&tg))) {
13897 goto OxBgenToPgen_ret_THREAD_CREATE_FAIL;
13898 }
13899 block_vidx = 0;
13900 }
13901 chr_filter_exists = (variant_ct + import_max_alleles_skip_ct + multiallelic_tmp_skip_ct != raw_variant_ct);
13902 if (ThreadsAreActive(&tg)) {
13903 JoinThreads(&tg);
13904 reterr = S_CAST(PglErr, scan_ctx.err_info & 255);
13905 if (unlikely(reterr)) {
13906 PrintBgenImportErr(scan_ctx.err_extra, scan_ctx.err_info, scan_ctx.vidx_start);
13907 goto OxBgenToPgen_ret_1;
13908 }
13909 if ((!block_vidx) || scan_ctx.dosage_exists) {
13910 // ignore thread_bidxs[] in this case
13911 StopThreads(&tg);
13912 } else {
13913 for (; cur_thread_fill_idx != calc_thread_ct; ) {
13914 // save endpoint for current thread, and tell any leftover threads
13915 // to do nothing
13916 thread_bidxs[++cur_thread_fill_idx] = block_vidx;
13917 }
13918 DeclareLastThreadBlock(&tg);
13919 scan_ctx.vidx_start = variant_ct - block_vidx;
13920 SpawnThreads(&tg);
13921 JoinThreads(&tg);
13922 reterr = S_CAST(PglErr, scan_ctx.err_info & 255);
13923 if (unlikely(reterr)) {
13924 PrintBgenImportErr(scan_ctx.err_extra, scan_ctx.err_info, scan_ctx.vidx_start);
13925 goto OxBgenToPgen_ret_bgen13_thread_fail;
13926 }
13927 }
13928 dosage_exists = scan_ctx.dosage_exists;
13929 }
13930
13931 if (max_allele_ct == 2) {
13932 allele_idx_offsets = nullptr;
13933 BigstackEndReset(bigstack_end_mark);
13934 } else {
13935 // not yet possible
13936 reterr = kPglRetNotYetSupported;
13937 goto OxBgenToPgen_ret_1;
13938 *allele_idx_offsets_iter = tot_allele_ct;
13939 }
13940 if (unlikely(fseeko(bgenfile, initial_uints[0] + 4, SEEK_SET))) {
13941 goto OxBgenToPgen_ret_READ_FAIL;
13942 }
13943 snprintf(outname_end, kMaxOutfnameExtBlen, ".pgen");
13944 uintptr_t spgw_alloc_cacheline_ct;
13945 uint32_t max_vrec_len;
13946 reterr = SpgwInitPhase1(outname, allele_idx_offsets, nullptr, variant_ct, sample_ct, max_allele_ct, kPgenWriteBackwardSeek, dosage_exists? (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent) : kfPgenGlobal0, (oxford_import_flags & kfOxfordImportRefUnknown)? 2 : 1, &spgw, &spgw_alloc_cacheline_ct, &max_vrec_len);
13947 if (unlikely(reterr)) {
13948 if (reterr == kPglRetOpenFail) {
13949 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
13950 }
13951 goto OxBgenToPgen_ret_1;
13952 }
13953
13954 BigstackReset(scan_ctx.bgen_allele_cts[0]);
13955
13956 // only needs to fit chromosome codes in second pass
13957 loadbuf = S_CAST(unsigned char*, bigstack_alloc_raw_rd(kMaxIdBlen));
13958 unsigned char* spgw_alloc;
13959 if (unlikely(bigstack_alloc_uc(spgw_alloc_cacheline_ct * kCacheline, &spgw_alloc))) {
13960 goto OxBgenToPgen_ret_NOMEM;
13961 }
13962 if (!uncompressed_genodata_byte_cts) {
13963 max_uncompressed_geno_blen = max_compressed_geno_blen;
13964 }
13965 // Now that we know max_uncompressed_geno_blen, try to increase
13966 // calc_thread_ct, and resize ctx.thread_wkspaces[tidx] (and also resize
13967 // compressed_geno_bufs[] in next step).
13968 // Additional *6 in denominator since we want to limit these allocations
13969 // to 1/6 of remaining workspace.
13970 thread_wkspace_size = RoundUpPow2(max_uncompressed_geno_blen, kCacheline);
13971 // bugfix (16 Jul 2017): was computing cachelines_avail, not bytes_avail
13972 uintptr_t bytes_avail = RoundDownPow2(bigstack_left() / 6, kCacheline);
13973 uint32_t old_calc_thread_ct = calc_thread_ct;
13974 if (calc_thread_ct_limit * thread_wkspace_size <= bytes_avail) {
13975 calc_thread_ct = calc_thread_ct_limit;
13976 } else {
13977 calc_thread_ct = bytes_avail / thread_wkspace_size;
13978 if (unlikely(!calc_thread_ct)) {
13979 goto OxBgenToPgen_ret_NOMEM;
13980 }
13981 }
13982 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
13983 goto OxBgenToPgen_ret_NOMEM;
13984 }
13985 Bgen13GenoToPgenCtx ctx;
13986 ctx.common = &common;
13987 ctx.err_extra = scan_ctx.err_extra;
13988 ctx.error_on_polyploid = !(import_flags & kfImportPolyploidMissing);
13989 ctx.hard_call_halfdist = kDosage4th - hard_call_thresh;
13990 ctx.bgen_import_dosage_certainty_thresholds = scan_ctx.bgen_import_dosage_certainty_thresholds;
13991 ctx.prov_ref_allele_second = prov_ref_allele_second;
13992 ctx.thread_wkspaces = scan_ctx.thread_wkspaces;
13993 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
13994 ctx.thread_wkspaces[tidx] = S_CAST(unsigned char*, bigstack_alloc_raw(thread_wkspace_size));
13995 }
13996 ctx.thread_bidxs[0] = scan_ctx.thread_bidxs[0];
13997 ctx.thread_bidxs[1] = scan_ctx.thread_bidxs[1];
13998 if (compression_mode == 1) {
13999 for (uint32_t tidx = old_calc_thread_ct; tidx < calc_thread_ct; ++tidx) {
14000 common.libdeflate_decompressors[tidx] = libdeflate_alloc_decompressor();
14001 if (unlikely(!common.libdeflate_decompressors[tidx])) {
14002 goto OxBgenToPgen_ret_NOMEM;
14003 }
14004 }
14005 }
14006 bytes_avail -= thread_wkspace_size * calc_thread_ct;
14007
14008 // const GparseFlags gparse_flags = dosage_exists? (kfGparseHphase | kfGparseDosage | kfGparseDphase) : kfGparse0;
14009 // unconditionally reserve space for everything but multiallelics for now
14010 const GparseFlags gparse_flags = kfGparseHphase | kfGparseDosage | kfGparseDphase;
14011 const uint64_t max_write_byte_ct = GparseWriteByteCt(sample_ct, max_allele_ct, gparse_flags);
14012 uintptr_t cachelines_avail = bigstack_left() / kCacheline;
14013 if (unlikely(cachelines_avail < 4)) {
14014 goto OxBgenToPgen_ret_NOMEM;
14015 }
14016 // we're making 4 allocations; be pessimistic re: rounding
14017 cachelines_avail -= 4;
14018 // may as well include calc_thread_ct thanks to potential
14019 // per_thread_byte_limit adverse rounding
14020 const uint64_t max_bytes_req_per_variant = sizeof(GparseRecord) + MAXV(max_compressed_geno_blen, max_write_byte_ct) + calc_thread_ct;
14021 if (unlikely(cachelines_avail * kCacheline < 2 * max_bytes_req_per_variant)) {
14022 goto OxBgenToPgen_ret_NOMEM;
14023 }
14024 uintptr_t min_bytes_req_per_variant = sizeof(GparseRecord) + GparseWriteByteCt(sample_ct, 2, gparse_flags);
14025 main_block_size = (cachelines_avail * kCacheline) / (min_bytes_req_per_variant * 2);
14026 // this is arbitrary, there's no connection to kPglVblockSize
14027 if (main_block_size > 65536) {
14028 main_block_size = 65536;
14029 }
14030 // divide by 2 for better parallelism in small-variant-count case
14031 // round up per_thread_block_limit so we only have two blocks
14032 if (main_block_size > DivUp(raw_variant_ct, 2)) {
14033 main_block_size = DivUp(raw_variant_ct, 2) + calc_thread_ct - 1;
14034 }
14035 // may as well guarantee divisibility
14036 per_thread_block_limit = main_block_size / calc_thread_ct;
14037 main_block_size = per_thread_block_limit * calc_thread_ct;
14038 ctx.gparse[0] = S_CAST(GparseRecord*, bigstack_alloc_raw_rd(main_block_size * sizeof(GparseRecord)));
14039 ctx.gparse[1] = S_CAST(GparseRecord*, bigstack_alloc_raw_rd(main_block_size * sizeof(GparseRecord)));
14040 ctx.block_allele_idx_offsets[0] = nullptr; // defensive
14041 ctx.block_allele_idx_offsets[1] = nullptr;
14042 ctx.err_info = (~0LLU) << 32;
14043 SetThreadFuncAndData(Bgen13GenoToPgenThread, &ctx, &tg);
14044 cachelines_avail = bigstack_left() / (kCacheline * 2);
14045 if (unlikely(bigstack_alloc_uc(cachelines_avail * kCacheline, &(compressed_geno_bufs[0])) ||
14046 bigstack_alloc_uc(cachelines_avail * kCacheline, &(compressed_geno_bufs[1])))) {
14047 assert(0);
14048 goto OxBgenToPgen_ret_NOMEM;
14049 }
14050 const uintptr_t per_thread_byte_limit = (cachelines_avail * kCacheline) / calc_thread_ct;
14051
14052 SpgwInitPhase2(max_vrec_len, &spgw, spgw_alloc);
14053
14054 // Main workflow:
14055 // 1. Set n=0, load genotype data for first main_block_size variants
14056 // while writing .pvar
14057 //
14058 // 2. Spawn threads processing batch n genotype data
14059 // 3. If n>0, write results for block (n-1)
14060 // 4. Increment n by 1
14061 // 5. Load/write-.pvar for batch (n+1) unless eof
14062 // 6. Join threads
14063 // 7. Goto step 2 unless eof
14064 //
14065 // 8. Write results for last block
14066 uint32_t prev_block_write_ct = 0;
14067 uint32_t prev_genodata_byte_ct = 0;
14068 uintptr_t prev_record_byte_ct = 0;
14069 uint32_t prev_allele_ct = 0;
14070 parity = 0;
14071 for (uint32_t vidx_start = 0; ; ) {
14072 uint32_t cur_block_write_ct = 0;
14073 if (!IsLastBlock(&tg)) {
14074 const uint32_t block_vidx_limit = variant_ct - vidx_start;
14075 cur_thread_block_vidx_limit = MINV(block_vidx_limit, per_thread_block_limit);
14076 cur_thread_fill_idx = 0;
14077 thread_bidxs = ctx.thread_bidxs[parity];
14078 GparseRecord* cur_gparse = ctx.gparse[parity];
14079 if (allele_idx_offsets) {
14080 ctx.block_allele_idx_offsets[parity] = &(allele_idx_offsets[vidx_start]);
14081 }
14082 bgen_geno_iter = compressed_geno_bufs[parity];
14083 unsigned char* cur_thread_byte_stop = &(bgen_geno_iter[per_thread_byte_limit]);
14084 thread_bidxs[0] = 0;
14085 block_vidx = 0;
14086 // strictly speaking, prev_genodata_byte_ct and genodata_byte_ct
14087 // can be collapsed into one variable, as well as
14088 // {block_vidx, cur_block_write_ct}, but not a big deal if the
14089 // compiler fails to see this
14090 uint32_t genodata_byte_ct = prev_genodata_byte_ct;
14091 uint32_t cur_allele_ct = prev_allele_ct;
14092 uintptr_t record_byte_ct = prev_record_byte_ct;
14093 GparseRecord* grp;
14094 if (!genodata_byte_ct) {
14095 goto OxBgenToPgen_load13_start;
14096 }
14097 // we may stop before main_block_size due to insufficient space in
14098 // compressed_geno_buf. if so, the file pointer is right before the
14099 // genotype data, rather than at the beginning of a variant record.
14100 while (1) {
14101 grp = &(cur_gparse[block_vidx]);
14102 grp->record_start = bgen_geno_iter;
14103 grp->flags = gparse_flags;
14104 grp->metadata.read_bgen.input_byte_ct = genodata_byte_ct;
14105 if (compression_mode) {
14106 grp->metadata.read_bgen.uncompressed_byte_ct = uncompressed_genodata_byte_ct;
14107 }
14108 if (unlikely(fread_checked(bgen_geno_iter, genodata_byte_ct, bgenfile))) {
14109 goto OxBgenToPgen_ret_READ_FAIL;
14110 }
14111 bgen_geno_iter = &(bgen_geno_iter[record_byte_ct]);
14112 ++block_vidx;
14113
14114 uint16_t snpid_slen;
14115 // true iff this is the last variant we're keeping in the entire
14116 // file
14117 if (block_vidx == block_vidx_limit) {
14118 for (; cur_thread_fill_idx != calc_thread_ct; ) {
14119 // save endpoint for current thread, and tell any leftover
14120 // threads to do nothing
14121 thread_bidxs[++cur_thread_fill_idx] = block_vidx;
14122 }
14123 break;
14124 }
14125 OxBgenToPgen_load13_start:
14126 if (unlikely(!fread_unlocked(&snpid_slen, 2, 1, bgenfile))) {
14127 goto OxBgenToPgen_ret_READ_FAIL;
14128 }
14129
14130 if (!snpid_chr) {
14131 if (unlikely(fseeko(bgenfile, snpid_slen, SEEK_CUR))) {
14132 goto OxBgenToPgen_ret_READ_FAIL;
14133 }
14134 } else {
14135 if (unlikely(!fread_unlocked(loadbuf, snpid_slen, 1, bgenfile))) {
14136 goto OxBgenToPgen_ret_READ_FAIL;
14137 }
14138 loadbuf[snpid_slen] = '\0';
14139 }
14140 uint16_t rsid_slen;
14141 if (unlikely(!fread_unlocked(&rsid_slen, 2, 1, bgenfile))) {
14142 goto OxBgenToPgen_ret_READ_FAIL;
14143 }
14144 if (unlikely(fseeko(bgenfile, rsid_slen, SEEK_CUR))) {
14145 goto OxBgenToPgen_ret_READ_FAIL;
14146 }
14147 uint16_t chr_name_slen;
14148 if (unlikely(!fread_unlocked(&chr_name_slen, 2, 1, bgenfile))) {
14149 goto OxBgenToPgen_ret_READ_FAIL;
14150 }
14151 if (ox_single_chr_str) {
14152 if (unlikely(fseeko(bgenfile, chr_name_slen, SEEK_CUR))) {
14153 goto OxBgenToPgen_ret_READ_FAIL;
14154 }
14155 } else {
14156 if (!snpid_chr) {
14157 if (unlikely(!fread_unlocked(loadbuf, chr_name_slen, 1, bgenfile))) {
14158 goto OxBgenToPgen_ret_READ_FAIL;
14159 }
14160 if (strequal_k(R_CAST(char*, loadbuf), "NA", chr_name_slen)) {
14161 memcpy_k(loadbuf, "0", 2);
14162 chr_name_slen = 1;
14163 } else {
14164 loadbuf[chr_name_slen] = '\0';
14165 }
14166 } else {
14167 if (unlikely(fseeko(bgenfile, chr_name_slen, SEEK_CUR))) {
14168 goto OxBgenToPgen_ret_READ_FAIL;
14169 }
14170 chr_name_slen = snpid_slen;
14171 }
14172 if (chr_filter_exists) {
14173 const uint32_t cur_chr_code2 = GetChrCode(R_CAST(char*, loadbuf), cip, chr_name_slen);
14174
14175 // we scanned all the variants
14176 assert(!IsI32Neg(cur_chr_code2));
14177
14178 skip_chr = !IsSet(cip->chr_mask, cur_chr_code2);
14179 }
14180 }
14181
14182 uint32_t cur_bp; // ignore in this pass
14183 if (unlikely(!fread_unlocked(&cur_bp, 4, 1, bgenfile))) {
14184 goto OxBgenToPgen_ret_READ_FAIL;
14185 }
14186
14187 cur_allele_ct = 0;
14188 if (unlikely(!fread_unlocked(&cur_allele_ct, 2, 1, bgenfile))) {
14189 goto OxBgenToPgen_ret_READ_FAIL;
14190 }
14191 for (uint32_t allele_idx = 0; allele_idx != cur_allele_ct; ++allele_idx) {
14192 uint32_t allele_slen;
14193 if (unlikely(!fread_unlocked(&allele_slen, 4, 1, bgenfile))) {
14194 goto OxBgenToPgen_ret_READ_FAIL;
14195 }
14196 if (unlikely(fseeko(bgenfile, allele_slen, SEEK_CUR))) {
14197 goto OxBgenToPgen_ret_READ_FAIL;
14198 }
14199 }
14200 if (unlikely(!fread_unlocked(&genodata_byte_ct, 4, 1, bgenfile))) {
14201 goto OxBgenToPgen_ret_READ_FAIL;
14202 }
14203
14204 // "cur_allele_ct > 2" is temporary kludge
14205 if (skip_chr || (cur_allele_ct > 2)) {
14206 if (unlikely(fseeko(bgenfile, genodata_byte_ct, SEEK_CUR))) {
14207 goto OxBgenToPgen_ret_READ_FAIL;
14208 }
14209 goto OxBgenToPgen_load13_start;
14210 }
14211 if (compression_mode) {
14212 if (unlikely(!fread_unlocked(&uncompressed_genodata_byte_ct, 4, 1, bgenfile))) {
14213 goto OxBgenToPgen_ret_READ_FAIL;
14214 }
14215 genodata_byte_ct -= 4;
14216 }
14217 const uintptr_t write_byte_ct_limit = GparseWriteByteCt(sample_ct, cur_allele_ct, gparse_flags);
14218 record_byte_ct = MAXV(RoundUpPow2(genodata_byte_ct, kBytesPerVec), write_byte_ct_limit);
14219
14220 if ((block_vidx == cur_thread_block_vidx_limit) || (S_CAST(uintptr_t, cur_thread_byte_stop - bgen_geno_iter) < record_byte_ct)) {
14221 thread_bidxs[++cur_thread_fill_idx] = block_vidx;
14222 if (cur_thread_fill_idx == calc_thread_ct) {
14223 prev_allele_ct = cur_allele_ct;
14224 prev_genodata_byte_ct = genodata_byte_ct;
14225 prev_record_byte_ct = record_byte_ct;
14226 break;
14227 }
14228 cur_thread_byte_stop = &(cur_thread_byte_stop[per_thread_byte_limit]);
14229 cur_thread_block_vidx_limit = MINV(cur_thread_block_vidx_limit + per_thread_block_limit, block_vidx_limit);
14230 }
14231 }
14232 cur_block_write_ct = block_vidx;
14233 }
14234 if (vidx_start) {
14235 JoinThreads(&tg);
14236 reterr = S_CAST(PglErr, ctx.err_info);
14237 if (unlikely(reterr)) {
14238 PrintBgenImportErr(ctx.err_extra, ctx.err_info, vidx_start - prev_block_write_ct);
14239 goto OxBgenToPgen_ret_1;
14240 }
14241 }
14242 if (!IsLastBlock(&tg)) {
14243 if (vidx_start + cur_block_write_ct == variant_ct) {
14244 DeclareLastThreadBlock(&tg);
14245 }
14246 if (unlikely(SpawnThreads(&tg))) {
14247 goto OxBgenToPgen_ret_THREAD_CREATE_FAIL;
14248 }
14249 }
14250 parity = 1 - parity;
14251 if (vidx_start) {
14252 // write *previous* block results
14253 reterr = GparseFlush(ctx.gparse[parity], allele_idx_offsets, prev_block_write_ct, &spgw);
14254 if (unlikely(reterr)) {
14255 goto OxBgenToPgen_ret_1;
14256 }
14257 }
14258 if (vidx_start == variant_ct) {
14259 break;
14260 }
14261 if (vidx_start) {
14262 printf("\r--bgen: %uk variants converted.", vidx_start / 1000);
14263 if (vidx_start <= main_block_size) {
14264 fputs(" \b\b\b\b", stdout);
14265 }
14266 fflush(stdout);
14267 }
14268 vidx_start += cur_block_write_ct;
14269 prev_block_write_ct = cur_block_write_ct;
14270 }
14271 }
14272 if (unlikely(CswriteCloseNull(&pvar_css, pvar_cswritep))) {
14273 goto OxBgenToPgen_ret_WRITE_FAIL;
14274 }
14275
14276 reterr = SpgwFinish(&spgw);
14277 if (unlikely(reterr)) {
14278 goto OxBgenToPgen_ret_1;
14279 }
14280 putc_unlocked('\r', stdout);
14281 char* write_iter = strcpya_k(g_logbuf, "--bgen: ");
14282 const uint32_t outname_base_slen = outname_end - outname;
14283 write_iter = memcpya(write_iter, outname, outname_base_slen + 5);
14284 write_iter = strcpya_k(write_iter, " + ");
14285 write_iter = memcpya(write_iter, outname, outname_base_slen);
14286 write_iter = strcpya_k(write_iter, ".pvar");
14287 if (output_zst) {
14288 write_iter = strcpya_k(write_iter, ".zst");
14289 }
14290 write_iter = strcpya_k(write_iter, " written");
14291 if (!dosage_exists) {
14292 write_iter = strcpya_k(write_iter, " (only unphased hardcalls)");
14293 }
14294 snprintf(write_iter, kLogbufSize - 2 * kPglFnamesize - 64, ".\n");
14295 WordWrapB(0);
14296 logputsb();
14297 }
14298 while (0) {
14299 OxBgenToPgen_ret_NOMEM:
14300 reterr = kPglRetNomem;
14301 break;
14302 OxBgenToPgen_ret_OPEN_FAIL:
14303 reterr = kPglRetOpenFail;
14304 break;
14305 OxBgenToPgen_ret_READ_FAIL:
14306 if (feof_unlocked(bgenfile)) {
14307 errno = 0;
14308 }
14309 putc_unlocked('\n', stdout);
14310 logerrprintfww(kErrprintfFread, bgenname, rstrerror(errno));
14311 reterr = kPglRetReadFail;
14312 break;
14313 OxBgenToPgen_ret_WRITE_FAIL:
14314 reterr = kPglRetWriteFail;
14315 break;
14316 OxBgenToPgen_ret_MALFORMED_INPUT:
14317 reterr = kPglRetMalformedInput;
14318 break;
14319 OxBgenToPgen_ret_INCONSISTENT_INPUT_2:
14320 logerrputsb();
14321 OxBgenToPgen_ret_INCONSISTENT_INPUT:
14322 reterr = kPglRetInconsistentInput;
14323 break;
14324 OxBgenToPgen_ret_THREAD_CREATE_FAIL:
14325 reterr = kPglRetThreadCreateFail;
14326 break;
14327 OxBgenToPgen_ret_DEGENERATE_DATA:
14328 reterr = kPglRetDegenerateData;
14329 break;
14330 OxBgenToPgen_ret_SLOPPY_CHRX:
14331 if (!sex_info_avail) {
14332 logerrputs("Error: chrX is present in the input file, but no sex information was provided;\nrerun this import with --sample or --update-sex. --split-par may also be\nappropriate.\n");
14333 } else {
14334 logerrputs("Error: Human chrX pseudoautosomal variant(s) appear to be present in the\ninput .bgen, but --split-par was not specified.\n");
14335 }
14336 reterr = kPglRetInconsistentInput;
14337 break;
14338 OxBgenToPgen_ret_bgen13_thread_fail:
14339 if (reterr == kPglRetInconsistentInput) {
14340 // --polyploid-mode note doesn't help here
14341 putc_unlocked('\n', stdout);
14342 logerrputs("Error: Polyploid genotype in .bgen file.\n");
14343 } else if (reterr == kPglRetMalformedInput) {
14344 OxBgenToPgen_ret_bgen11_thread_fail:
14345 putc_unlocked('\n', stdout);
14346 logerrputs("Error: Invalid compressed SNP block in .bgen file.\n");
14347 } else if (reterr == kPglRetNotYetSupported) {
14348 putc_unlocked('\n', stdout);
14349 logerrputs("Error: BGEN import doesn't currently support multiallelic variants, 29-32 bit\nprobability precision, or ploidy > 2.\n");
14350 }
14351 // note that nomem is also possible here
14352 }
14353 OxBgenToPgen_ret_1:
14354 if (common.libdeflate_decompressors) {
14355 for (uint32_t tidx = 0; tidx != max_thread_ct; ++tidx) {
14356 if (!common.libdeflate_decompressors[tidx]) {
14357 break;
14358 }
14359 libdeflate_free_decompressor(common.libdeflate_decompressors[tidx]);
14360 }
14361 // common.libdeflate_decompressors = nullptr;
14362 }
14363 CleanupSpgw(&spgw, &reterr);
14364 CleanupThreads(&tg);
14365 fclose_cond(bgenfile);
14366 fclose_cond(psamfile);
14367 CswriteCloseCond(&pvar_css, pvar_cswritep);
14368 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
14369 return reterr;
14370 }
14371
14372 PglErr ScanHapsForHet(const char* loadbuf_iter, const char* hapsname, uint32_t sample_ct, uint32_t is_haploid, uintptr_t line_idx_haps, uint32_t* at_least_one_het_ptr) {
14373 PglErr reterr = kPglRetSuccess;
14374 {
14375 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
14376 const uint32_t first_hap_char_code = ctou32(*loadbuf_iter);
14377 const uint32_t first_hap_int = first_hap_char_code - 48;
14378 // will .haps files ever support triallelic variants? don't worry about
14379 // that for now
14380 const char* post_first_hap = &(loadbuf_iter[1]);
14381 if (unlikely((first_hap_int >= 2) || (ctou32(*post_first_hap) > 32))) {
14382 if (first_hap_char_code <= 32) {
14383 goto ScanHapsForHet_ret_MISSING_TOKENS;
14384 }
14385 goto ScanHapsForHet_ret_INVALID_TOKEN;
14386 }
14387 const char* second_hap = FirstNonTspace(post_first_hap);
14388 const char* post_second_hap = &(second_hap[1]);
14389 const uint32_t second_hap_char_code = ctou32(*second_hap);
14390 const uint32_t second_hap_int = second_hap_char_code - 48;
14391 const uint32_t post_second_hap_char_code = ctou32(*post_second_hap);
14392 if ((second_hap_int >= 2) || (post_second_hap_char_code > 32)) {
14393 // if haploid, permit '-' in second column
14394 if (unlikely((!is_haploid) || (second_hap_char_code != 45))) {
14395 if (second_hap_char_code <= 32) {
14396 goto ScanHapsForHet_ret_MISSING_TOKENS;
14397 }
14398 if ((second_hap_char_code == 45) && (post_second_hap_char_code <= 32)) {
14399 goto ScanHapsForHet_ret_HAPLOID_TOKEN;
14400 }
14401 goto ScanHapsForHet_ret_INVALID_TOKEN;
14402 }
14403 } else if (first_hap_int != second_hap_int) {
14404 *at_least_one_het_ptr = 1;
14405 break;
14406 }
14407 loadbuf_iter = FirstNonTspace(post_second_hap);
14408 }
14409 }
14410 while (0) {
14411 ScanHapsForHet_ret_HAPLOID_TOKEN:
14412 snprintf(g_logbuf, kLogbufSize, "Error: Haploid-only token on line %" PRIuPTR " of %s.\n", line_idx_haps, hapsname);
14413 reterr = kPglRetInconsistentInput;
14414 break;
14415 ScanHapsForHet_ret_INVALID_TOKEN:
14416 snprintf(g_logbuf, kLogbufSize, "Error: Invalid token on line %" PRIuPTR " of %s.\n", line_idx_haps, hapsname);
14417 reterr = kPglRetMalformedInput;
14418 break;
14419 ScanHapsForHet_ret_MISSING_TOKENS:
14420 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx_haps, hapsname);
14421 reterr = kPglRetMalformedInput;
14422 break;
14423 }
14424 return reterr;
14425 }
14426
14427 PglErr OxHapslegendToPgen(const char* hapsname, const char* legendname, const char* samplename, const char* const_fid, const char* ox_single_chr_str, const char* ox_missing_code, const char* missing_catname, MiscFlags misc_flags, ImportFlags import_flags, OxfordImportFlags oxford_import_flags, uint32_t psam_01, uint32_t is_update_or_impute_sex, uint32_t is_splitpar, char id_delim, uint32_t max_thread_ct, char* outname, char* outname_end, ChrInfo* cip, uint32_t* pgi_generated_ptr) {
14428 unsigned char* bigstack_mark = g_bigstack_base;
14429 FILE* psamfile = nullptr;
14430 uintptr_t line_idx_haps = 0;
14431 uintptr_t line_idx_legend = 0;
14432 PglErr reterr = kPglRetSuccess;
14433 char* pvar_cswritep = nullptr;
14434 CompressStreamState pvar_css;
14435 PreinitCstream(&pvar_css);
14436 TextStream haps_txs;
14437 TextStream legend_txs;
14438 STPgenWriter spgw;
14439 PreinitTextStream(&haps_txs);
14440 PreinitTextStream(&legend_txs);
14441 PreinitSpgw(&spgw);
14442 {
14443 uint32_t sfile_sample_ct = 0;
14444 if (samplename[0]) {
14445 reterr = OxSampleToPsam(samplename, const_fid, ox_missing_code, missing_catname, misc_flags, import_flags, psam_01, id_delim, outname, outname_end, &sfile_sample_ct);
14446 if (unlikely(reterr)) {
14447 goto OxHapslegendToPgen_ret_1;
14448 }
14449 if (unlikely(sfile_sample_ct > (kMaxLongLine / 4))) {
14450 logerrputs("Error: Too many samples for .haps file converter.\n");
14451 reterr = kPglRetNotYetSupported;
14452 goto OxHapslegendToPgen_ret_1;
14453 }
14454 }
14455
14456 const uint32_t output_zst = (import_flags / kfImportKeepAutoconvVzs) & 1;
14457 uint32_t max_line_blen;
14458 if (StandardizeMaxLineBlen(bigstack_left() / (4 + output_zst), &max_line_blen)) {
14459 goto OxHapslegendToPgen_ret_NOMEM;
14460 }
14461 reterr = InitTextStream(hapsname, max_line_blen, ClipU32(max_thread_ct - 1, 1, 4), &haps_txs);
14462 if (unlikely(reterr)) {
14463 if (reterr == kPglRetOpenFail) {
14464 const uint32_t slen = strlen(hapsname);
14465 if ((!StrEndsWith(hapsname, ".haps", slen)) &&
14466 (!StrEndsWith(hapsname, ".haps.gz", slen))) {
14467 logerrprintfww("Error: Failed to open %s : %s. (--haps expects a complete filename; did you forget '.haps' at the end?)\n", hapsname, strerror(errno));
14468 goto OxHapslegendToPgen_ret_1;
14469 }
14470 }
14471 goto OxHapslegendToPgen_ret_TSTREAM_FAIL_HAPS;
14472 }
14473 snprintf(outname_end, kMaxOutfnameExtBlen, ".pvar");
14474 if (output_zst) {
14475 snprintf(&(outname_end[5]), kMaxOutfnameExtBlen - 5, ".zst");
14476 }
14477 const uintptr_t overflow_buf_size = kCompressStreamBlock + max_line_blen;
14478 reterr = InitCstreamAlloc(outname, 0, output_zst, 1, overflow_buf_size, &pvar_css, &pvar_cswritep);
14479 if (unlikely(reterr)) {
14480 goto OxHapslegendToPgen_ret_1;
14481 }
14482 pvar_cswritep = strcpya_k(pvar_cswritep, "#CHROM\tPOS\tID\tREF\tALT" EOLN_STR);
14483 ++line_idx_haps;
14484 char* haps_line_iter = TextGet(&haps_txs);
14485 if (unlikely(!haps_line_iter)) {
14486 if (!TextStreamErrcode2(&haps_txs, &reterr)) {
14487 snprintf(g_logbuf, kLogbufSize, "Error: %s is empty.\n", hapsname);
14488 goto OxHapslegendToPgen_ret_INCONSISTENT_INPUT_WW;
14489 }
14490 goto OxHapslegendToPgen_ret_TSTREAM_FAIL_HAPS;
14491 }
14492 const uint32_t token_ct = CountTokens(haps_line_iter);
14493 FinalizeChrset(misc_flags, cip);
14494 const char* single_chr_str = nullptr;
14495 char* legend_line_start = nullptr;
14496 uint32_t single_chr_slen = 0;
14497 uint32_t cur_chr_code = 0;
14498 uint32_t is_haploid = 0;
14499 // Count number of samples in the .haps file.
14500 // Note that the user is not required to provide a .sample file. So, if a
14501 // .sample file is provided, verify the count is as expected; if not,
14502 // generate a .psam with the correct sample count once we know what it is.
14503 uint32_t sample_ct;
14504 if (legendname[0]) {
14505 if (unlikely(token_ct % 2)) {
14506 snprintf(g_logbuf, kLogbufSize, "Error: %s has an odd number of tokens in the first line. (With --haps + --legend, the .haps file is expected to have no header columns.)\n", hapsname);
14507 goto OxHapslegendToPgen_ret_MALFORMED_INPUT_WW;
14508 }
14509 sample_ct = token_ct / 2;
14510 // Other .legend-specific initialization.
14511 reterr = InitOxfordSingleChr(ox_single_chr_str, "--legend argument", &single_chr_str, &single_chr_slen, &cur_chr_code, cip);
14512 if (unlikely(reterr)) {
14513 goto OxHapslegendToPgen_ret_1;
14514 }
14515 is_haploid = IsSet(cip->haploid_mask, cur_chr_code);
14516 reterr = InitTextStream(legendname, max_line_blen, 1, &legend_txs);
14517 if (unlikely(reterr)) {
14518 if (reterr == kPglRetOpenFail) {
14519 const uint32_t slen = strlen(legendname);
14520 if (!StrEndsWith(legendname, ".legend", slen)) {
14521 logerrprintfww("Error: Failed to open %s : %s. (--legend expects a complete filename; did you forget '.legend' at the end?)\n", legendname, strerror(errno));
14522 goto OxHapslegendToPgen_ret_1;
14523 }
14524 }
14525 goto OxHapslegendToPgen_ret_TSTREAM_FAIL_LEGEND;
14526 }
14527 ++line_idx_legend;
14528 legend_line_start = TextGet(&legend_txs);
14529 if (unlikely(!legend_line_start)) {
14530 if (!TextStreamErrcode2(&legend_txs, &reterr)) {
14531 snprintf(g_logbuf, kLogbufSize, "Error: %s is empty.\n", legendname);
14532 goto OxHapslegendToPgen_ret_MALFORMED_INPUT_WW;
14533 }
14534 goto OxHapslegendToPgen_ret_TSTREAM_FAIL_LEGEND;
14535 }
14536 // require at least 4 columns, in ID/pos/A1/A2 order; header text is
14537 // permitted to vary. tolerate and ignore extra columns.
14538 if (unlikely(!NextTokenMult(legend_line_start, 3))) {
14539 goto OxHapslegendToPgen_ret_MISSING_TOKENS_LEGEND;
14540 }
14541 } else {
14542 // !legendname[0]
14543 if (unlikely((token_ct < 7) || (!(token_ct % 2)))) {
14544 snprintf(g_logbuf, kLogbufSize, "Error: Unexpected token count in line %" PRIuPTR " of %s (should be odd, >5).\n", line_idx_haps, hapsname);
14545 goto OxHapslegendToPgen_ret_MALFORMED_INPUT_WW;
14546 }
14547 sample_ct = (token_ct - 5) / 2;
14548 }
14549 if (sfile_sample_ct) {
14550 if (unlikely(sfile_sample_ct != sample_ct)) {
14551 snprintf(g_logbuf, kLogbufSize, "Error: .sample file has %u sample%s, while %s has %u.\n", sfile_sample_ct, (sfile_sample_ct == 1)? "" : "s", hapsname, sample_ct);
14552 goto OxHapslegendToPgen_ret_INCONSISTENT_INPUT_WW;
14553 }
14554 } else {
14555 // create a dummy .psam file with "per0", "per1", etc. IDs, matching
14556 // --dummy
14557 unsigned char* bigstack_mark2 = g_bigstack_base;
14558 char* writebuf = S_CAST(char*, bigstack_alloc_raw(kMaxMediumLine + max_line_blen));
14559 char* writebuf_flush = &(writebuf[kMaxMediumLine]);
14560 snprintf(outname_end, kMaxOutfnameExtBlen, ".psam");
14561 if (unlikely(fopen_checked(outname, FOPEN_WB, &psamfile))) {
14562 goto OxHapslegendToPgen_ret_OPEN_FAIL;
14563 }
14564 char* write_iter = strcpya_k(writebuf, "#IID\tSEX" EOLN_STR);
14565 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
14566 write_iter = strcpya_k(write_iter, "per");
14567 write_iter = u32toa(sample_idx, write_iter);
14568 write_iter = strcpya_k(write_iter, "\tNA" EOLN_STR);
14569 if (unlikely(fwrite_ck(writebuf_flush, psamfile, &write_iter))) {
14570 goto OxHapslegendToPgen_ret_WRITE_FAIL;
14571 }
14572 }
14573 if (unlikely(fclose_flush_null(writebuf_flush, write_iter, &psamfile))) {
14574 goto OxHapslegendToPgen_ret_WRITE_FAIL;
14575 }
14576 BigstackReset(bigstack_mark2);
14577 }
14578
14579 const uint32_t variant_ct_limit = MINV(kPglMaxVariantCt, bigstack_left() / 8);
14580 const uint32_t keep_pgi = !(import_flags & kfImportKeepAutoconv);
14581 snprintf(outname_end, kMaxOutfnameExtBlen, ".pgen");
14582 if (keep_pgi) {
14583 *pgi_generated_ptr = 1;
14584 }
14585 uintptr_t spgw_alloc_cacheline_ct;
14586 uint32_t max_vrec_len;
14587 reterr = SpgwInitPhase1(outname, nullptr, nullptr, variant_ct_limit, sample_ct, 0, keep_pgi? kPgenWriteSeparateIndex : kPgenWriteAndCopy, kfPgenGlobalHardcallPhasePresent, (oxford_import_flags & (kfOxfordImportRefFirst | kfOxfordImportRefLast))? 1 : 2, &spgw, &spgw_alloc_cacheline_ct, &max_vrec_len);
14588 if (unlikely(reterr)) {
14589 if (reterr == kPglRetOpenFail) {
14590 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
14591 }
14592 goto OxHapslegendToPgen_ret_1;
14593 }
14594 unsigned char* spgw_alloc;
14595 if (unlikely(bigstack_alloc_uc(spgw_alloc_cacheline_ct * kCacheline, &spgw_alloc))) {
14596 goto OxHapslegendToPgen_ret_NOMEM;
14597 }
14598 SpgwInitPhase2(max_vrec_len, &spgw, spgw_alloc);
14599 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
14600 const uint32_t sample_ctl2_m1 = sample_ctl2 - 1;
14601 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
14602 const uint32_t prohibit_extra_chr = (misc_flags / kfMiscProhibitExtraChr) & 1;
14603 const uint32_t prov_ref_allele_second = !(oxford_import_flags & kfOxfordImportRefFirst);
14604 const uint32_t phaseinfo_match_4char = prov_ref_allele_second? 0x20312030 : 0x20302031;
14605 const uint32_t phaseinfo_match = 1 + prov_ref_allele_second;
14606 uint32_t variant_ct = 0;
14607 uintptr_t variant_skip_ct = 0;
14608 const uint32_t sex_info_avail = sfile_sample_ct || is_update_or_impute_sex;
14609 uint32_t par_warn_code = UINT32_MAX;
14610 if (!(import_flags & kfImportLaxChrX)) {
14611 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
14612 if ((!IsI32Neg(x_code)) && ((!sex_info_avail) || (IsHumanChrset(cip) && (!is_splitpar)))) {
14613 par_warn_code = x_code;
14614 }
14615 }
14616 uintptr_t* genovec;
14617 Halfword* phaseinfo_hwarr;
14618 if (unlikely(bigstack_alloc_w(sample_ctl2, &genovec) ||
14619 bigstack_alloc_hw(2 * sample_ctl, &phaseinfo_hwarr))) {
14620 goto OxHapslegendToPgen_ret_NOMEM;
14621 }
14622 goto OxHapslegendToPgen_first_line;
14623 while (1) {
14624 ++line_idx_haps;
14625 reterr = TextGetUnsafe(&haps_txs, &haps_line_iter);
14626 if (reterr) {
14627 if (unlikely(reterr != kPglRetEof)) {
14628 goto OxHapslegendToPgen_ret_TSTREAM_FAIL_HAPS;
14629 }
14630 if (legend_line_start) {
14631 if (unlikely(TextGet(&legend_txs) != nullptr)) {
14632 snprintf(g_logbuf, kLogbufSize, "Error: %s has fewer nonheader lines than %s.\n", hapsname, legendname);
14633 goto OxHapslegendToPgen_ret_INCONSISTENT_INPUT_WW;
14634 }
14635 }
14636 reterr = kPglRetSuccess;
14637 break;
14638 }
14639 OxHapslegendToPgen_first_line:
14640 if (legend_line_start) {
14641 ++line_idx_legend;
14642 legend_line_start = TextGet(&legend_txs);
14643 if (unlikely(legend_line_start == nullptr)) {
14644 snprintf(g_logbuf, kLogbufSize, "Error: %s has fewer nonheader lines than %s.\n", legendname, hapsname);
14645 goto OxHapslegendToPgen_ret_INCONSISTENT_INPUT_WW;
14646 }
14647 }
14648 char* linebuf_iter = haps_line_iter;
14649 char* variant_id_start;
14650 char* variant_id_end;
14651 char* bp_start;
14652 char* bp_end;
14653 char* allele0_start;
14654 char* allele0_end;
14655 char* allele1_start;
14656 char* allele1_end;
14657 if (!legend_line_start) {
14658 char* chr_code_end = CurTokenEnd(haps_line_iter);
14659 variant_id_start = FirstNonTspace(chr_code_end);
14660 variant_id_end = FirstSpaceOrEoln(variant_id_start);
14661 bp_start = FirstNonTspace(variant_id_end);
14662 bp_end = FirstSpaceOrEoln(bp_start);
14663 allele0_start = FirstNonTspace(bp_end);
14664 allele0_end = FirstSpaceOrEoln(allele0_start);
14665 allele1_start = FirstNonTspace(allele0_end);
14666 allele1_end = FirstSpaceOrEoln(allele1_start);
14667 linebuf_iter = FirstNonTspace(allele1_end);
14668 if (unlikely(IsEolnKns(*linebuf_iter))) {
14669 goto OxHapslegendToPgen_ret_MISSING_TOKENS_HAPS;
14670 }
14671 reterr = GetOrAddChrCodeDestructive("--haps file", line_idx_haps, prohibit_extra_chr, haps_line_iter, chr_code_end, cip, &cur_chr_code);
14672 if (unlikely(reterr)) {
14673 goto OxHapslegendToPgen_ret_1;
14674 }
14675 if (!IsSet(cip->chr_mask, cur_chr_code)) {
14676 ++variant_skip_ct;
14677 haps_line_iter = AdvPastDelim(linebuf_iter, '\n');
14678 continue;
14679 }
14680 pvar_cswritep = chrtoa(cip, cur_chr_code, pvar_cswritep);
14681 is_haploid = IsSet(cip->haploid_mask, cur_chr_code);
14682 } else {
14683 variant_id_start = legend_line_start;
14684 variant_id_end = FirstSpaceOrEoln(variant_id_start);
14685 bp_start = FirstNonTspace(variant_id_end);
14686 bp_end = FirstSpaceOrEoln(bp_start);
14687 allele0_start = FirstNonTspace(bp_end);
14688 allele0_end = FirstSpaceOrEoln(allele0_start);
14689 allele1_start = FirstNonTspace(allele0_end);
14690 if (unlikely(IsEolnKns(*allele1_start))) {
14691 goto OxHapslegendToPgen_ret_MISSING_TOKENS_LEGEND;
14692 }
14693 allele1_end = FirstSpaceOrEoln(allele1_start);
14694
14695 pvar_cswritep = memcpya(pvar_cswritep, single_chr_str, single_chr_slen);
14696 }
14697 *pvar_cswritep++ = '\t';
14698 const uint32_t id_slen = variant_id_end - variant_id_start;
14699 if (unlikely(id_slen > kMaxIdSlen)) {
14700 putc_unlocked('\n', stdout);
14701 logerrputs("Error: Variant names are limited to " MAX_ID_SLEN_STR " characters.\n");
14702 goto OxHapslegendToPgen_ret_MALFORMED_INPUT;
14703 }
14704 uint32_t cur_bp;
14705 if (unlikely(ScanUintDefcap(bp_start, &cur_bp))) {
14706 putc_unlocked('\n', stdout);
14707 if (legend_line_start) {
14708 logprintfww("Error: Invalid bp coordinate on line %" PRIuPTR " of %s.\n", line_idx_legend, legendname);
14709 } else {
14710 logprintfww("Error: Invalid bp coordinate on line %" PRIuPTR " of %s.\n", line_idx_haps, hapsname);
14711 }
14712 goto OxHapslegendToPgen_ret_MALFORMED_INPUT;
14713 }
14714 if (par_warn_code == cur_chr_code) {
14715 if (unlikely((!sex_info_avail) || (cur_bp <= kPAR1IntersectionLast) || (cur_bp >= kPAR2IntersectionFirst))) {
14716 putc_unlocked('\n', stdout);
14717 if (!sex_info_avail) {
14718 logerrputs("Error: chrX is present in the input, but no sex information was provided; rerun\nthis import with --sample or --update-sex. --split-par may also be\nappropriate.\n");
14719 } else {
14720 logerrputs("Error: Human chrX pseudoautosomal variant(s) appear to be present in the input,\nbut --split-par was not specified.\n");
14721 }
14722 goto OxHapslegendToPgen_ret_INCONSISTENT_INPUT;
14723 }
14724 }
14725 pvar_cswritep = u32toa_x(cur_bp, '\t', pvar_cswritep);
14726 pvar_cswritep = memcpyax(pvar_cswritep, variant_id_start, id_slen, '\t');
14727 if (!prov_ref_allele_second) {
14728 pvar_cswritep = memcpyax(pvar_cswritep, allele0_start, allele0_end - allele0_start, '\t');
14729 pvar_cswritep = memcpya(pvar_cswritep, allele1_start, allele1_end - allele1_start);
14730 } else {
14731 pvar_cswritep = memcpyax(pvar_cswritep, allele1_start, allele1_end - allele1_start, '\t');
14732 pvar_cswritep = memcpya(pvar_cswritep, allele0_start, allele0_end - allele0_start);
14733 }
14734 AppendBinaryEoln(&pvar_cswritep);
14735 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
14736 goto OxHapslegendToPgen_ret_WRITE_FAIL;
14737 }
14738 uintptr_t genovec_word_or = 0;
14739 uint32_t inner_loop_last = kBitsPerWordD2 - 1;
14740 // optimize common case: autosomal diploid, always exactly one space
14741 // this loop is time-critical; all my attemps to merge in the haploid
14742 // case have caused >10% slowdowns
14743 if ((!is_haploid) && IsEoln(linebuf_iter[sample_ct * 4 - 1])) {
14744 haps_line_iter = AdvPastDelim(&(linebuf_iter[sample_ct * 4 - 1]), '\n');
14745 linebuf_iter[sample_ct * 4 - 1] = ' ';
14746 #ifdef USE_SSE2
14747 const VecU16 all0 = vecu16_set1(0x2030);
14748 const VecU16 all1 = vecu16_set1(0x2031);
14749 const uint32_t fullword_ct = sample_ct / kBitsPerWordD2;
14750 for (uint32_t widx = 0; widx != fullword_ct; ++widx) {
14751 uintptr_t geno_first = 0;
14752 for (uint32_t uii = 0; uii != 2; ++uii) {
14753 VecU16 cur_chars = vecu16_loadu(linebuf_iter);
14754 linebuf_iter += kBytesPerVec;
14755 // todo: better ARM implementation
14756 uintptr_t zero_mm = vecu16_movemask(cur_chars == all0);
14757 uintptr_t one_mm = vecu16_movemask(cur_chars == all1);
14758 cur_chars = vecu16_loadu(linebuf_iter);
14759 linebuf_iter += kBytesPerVec;
14760 zero_mm |= S_CAST(uintptr_t, vecu16_movemask(cur_chars == all0)) << kBytesPerVec;
14761 one_mm |= S_CAST(uintptr_t, vecu16_movemask(cur_chars == all1)) << kBytesPerVec;
14762 # ifndef USE_AVX2
14763 cur_chars = vecu16_loadu(linebuf_iter);
14764 linebuf_iter += kBytesPerVec;
14765 zero_mm |= S_CAST(uintptr_t, vecu16_movemask(cur_chars == all0)) << 32;
14766 one_mm |= S_CAST(uintptr_t, vecu16_movemask(cur_chars == all1)) << 32;
14767 cur_chars = vecu16_loadu(linebuf_iter);
14768 linebuf_iter += kBytesPerVec;
14769 zero_mm |= S_CAST(uintptr_t, vecu16_movemask(cur_chars == all0)) << 48;
14770 one_mm |= S_CAST(uintptr_t, vecu16_movemask(cur_chars == all1)) << 48;
14771 # endif
14772 if (unlikely(~(zero_mm | one_mm))) {
14773 // todo: other error messages
14774 snprintf(g_logbuf, kLogbufSize, "Error: Invalid token on line %" PRIuPTR " of %s.\n", line_idx_haps, hapsname);
14775 goto OxHapslegendToPgen_ret_MALFORMED_INPUT_WW;
14776 }
14777 geno_first |= S_CAST(uintptr_t, PackWordToHalfwordMask5555(one_mm)) << (uii * 32);
14778 }
14779 const uintptr_t geno_second = (geno_first >> 1) & kMask5555;
14780 geno_first &= kMask5555;
14781 const uintptr_t geno_sum = geno_first + geno_second;
14782 genovec[widx] = geno_sum;
14783 genovec_word_or |= geno_sum;
14784 uintptr_t phaseinfo_hw = geno_second & (~geno_first);
14785 if (!prov_ref_allele_second) {
14786 phaseinfo_hw = geno_first & (~geno_second);
14787 }
14788 phaseinfo_hw = PackWordToHalfword(phaseinfo_hw);
14789 phaseinfo_hwarr[widx] = phaseinfo_hw;
14790 }
14791 const uint32_t remainder = sample_ct % kBitsPerWordD2;
14792 if (remainder) {
14793 const unsigned char* linebuf_iter_uc = R_CAST(const unsigned char*, linebuf_iter);
14794 uintptr_t genovec_word = 0;
14795 Halfword phaseinfo_hw = 0;
14796 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != remainder; ++sample_idx_lowbits) {
14797 uint32_t cur_hap_4char;
14798 CopyFromUnalignedIncrU32(&cur_hap_4char, &linebuf_iter_uc);
14799 if (unlikely((cur_hap_4char & 0xfffefffeU) != 0x20302030)) {
14800 // todo: other error messages
14801 snprintf(g_logbuf, kLogbufSize, "Error: Invalid token on line %" PRIuPTR " of %s.\n", line_idx_haps, hapsname);
14802 goto OxHapslegendToPgen_ret_MALFORMED_INPUT_WW;
14803 }
14804 // bugfix (28 Apr 2019): this needs to be uintptr_t for the next
14805 // left-shift to work
14806 const uintptr_t new_geno = (cur_hap_4char + (cur_hap_4char >> 16)) & 3;
14807 genovec_word |= new_geno << (2 * sample_idx_lowbits);
14808 if (cur_hap_4char == phaseinfo_match_4char) {
14809 phaseinfo_hw |= 1U << sample_idx_lowbits;
14810 }
14811 }
14812 genovec[fullword_ct] = genovec_word;
14813 genovec_word_or |= genovec_word;
14814 phaseinfo_hwarr[fullword_ct] = phaseinfo_hw;
14815 }
14816 #else // !USE_SSE2
14817 const unsigned char* linebuf_iter_uc = R_CAST(const unsigned char*, linebuf_iter);
14818 for (uint32_t widx = 0; ; ++widx) {
14819 if (widx >= sample_ctl2_m1) {
14820 if (widx > sample_ctl2_m1) {
14821 break;
14822 }
14823 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
14824 }
14825 uintptr_t genovec_word = 0;
14826 uint32_t phaseinfo_hw = 0;
14827 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
14828 // assumes little-endian
14829 uint32_t cur_hap_4char;
14830 CopyFromUnalignedIncrU32(&cur_hap_4char, &linebuf_iter_uc);
14831 if (unlikely((cur_hap_4char & 0xfffefffeU) != 0x20302030)) {
14832 if ((cur_hap_4char & 0xfffffffeU) == 0x202d2030) {
14833 // "0 - ", "1 - "
14834 goto OxHapslegendToPgen_ret_HAPLOID_TOKEN;
14835 }
14836 // any character < 32?
14837 if ((((cur_hap_4char & 0xe0e0e0e0U) * 7) & 0x80808080U) != 0x80808080U) {
14838 goto OxHapslegendToPgen_ret_MISSING_TOKENS_HAPS;
14839 }
14840 snprintf(g_logbuf, kLogbufSize, "Error: Invalid token on line %" PRIuPTR " of %s.\n", line_idx_haps, hapsname);
14841 goto OxHapslegendToPgen_ret_MALFORMED_INPUT_WW;
14842 }
14843 const uintptr_t new_geno = (cur_hap_4char + (cur_hap_4char >> 16)) & 3;
14844 genovec_word |= new_geno << (2 * sample_idx_lowbits);
14845 if (cur_hap_4char == phaseinfo_match_4char) {
14846 phaseinfo_hw |= 1U << sample_idx_lowbits;
14847 }
14848 }
14849 genovec[widx] = genovec_word;
14850 genovec_word_or |= genovec_word;
14851 phaseinfo_hwarr[widx] = phaseinfo_hw;
14852 }
14853 #endif // !USE_SSE2
14854 } else {
14855 for (uint32_t widx = 0; ; ++widx) {
14856 if (widx >= sample_ctl2_m1) {
14857 if (widx > sample_ctl2_m1) {
14858 break;
14859 }
14860 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
14861 }
14862 uintptr_t genovec_word = 0;
14863 uint32_t phaseinfo_hw = 0;
14864 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
14865 const uint32_t first_hap_char_code = ctou32(*linebuf_iter);
14866 const uint32_t first_hap_int = first_hap_char_code - 48;
14867 char* post_first_hap = &(linebuf_iter[1]);
14868 if (unlikely((first_hap_int >= 2) || (*post_first_hap != ' '))) {
14869 if ((first_hap_char_code <= 32) || (ctou32(*post_first_hap) < 32)) {
14870 goto OxHapslegendToPgen_ret_MISSING_TOKENS_HAPS;
14871 }
14872 snprintf(g_logbuf, kLogbufSize, "Error: Invalid token on line %" PRIuPTR " of %s.\n", line_idx_haps, hapsname);
14873 goto OxHapslegendToPgen_ret_MALFORMED_INPUT_WW;
14874 }
14875 char* second_hap = post_first_hap;
14876 uint32_t second_hap_char_code;
14877 do {
14878 second_hap_char_code = ctou32(*(++second_hap));
14879 } while (second_hap_char_code == 32);
14880 char* post_second_hap = &(second_hap[1]);
14881 const uint32_t post_second_hap_char_code = ctou32(*post_second_hap);
14882 uint32_t second_hap_int = second_hap_char_code - 48;
14883 if ((second_hap_int >= 2) || (post_second_hap_char_code > 32)) {
14884 if (likely(is_haploid && (second_hap_char_code == 45))) {
14885 // could require --sample, and require this sample to be male
14886 // in this case?
14887 second_hap_int = first_hap_int;
14888 } else {
14889 if (second_hap_char_code <= 32) {
14890 goto OxHapslegendToPgen_ret_MISSING_TOKENS_HAPS;
14891 }
14892 if ((second_hap_char_code == 45) && (post_second_hap_char_code <= 32)) {
14893 goto OxHapslegendToPgen_ret_HAPLOID_TOKEN;
14894 }
14895 snprintf(g_logbuf, kLogbufSize, "Error: Invalid token on line %" PRIuPTR " of %s.\n", line_idx_haps, hapsname);
14896 goto OxHapslegendToPgen_ret_MALFORMED_INPUT_WW;
14897 }
14898 }
14899 genovec_word |= S_CAST(uintptr_t, first_hap_int + second_hap_int) << (2 * sample_idx_lowbits);
14900 if (first_hap_int + 2 * second_hap_int == phaseinfo_match) {
14901 phaseinfo_hw |= 1U << sample_idx_lowbits;
14902 }
14903 linebuf_iter = FirstNonChar(post_second_hap, ' ');
14904 }
14905 genovec[widx] = genovec_word;
14906 genovec_word_or |= genovec_word;
14907 phaseinfo_hwarr[widx] = phaseinfo_hw;
14908 }
14909 haps_line_iter = AdvPastDelim(linebuf_iter, '\n');
14910 }
14911 if (prov_ref_allele_second) {
14912 GenovecInvertUnsafe(sample_ct, genovec);
14913 ZeroTrailingNyps(sample_ct, genovec);
14914 }
14915 if (genovec_word_or & kMask5555) {
14916 uintptr_t* __attribute__((may_alias)) phaseinfo_warr = R_CAST(uintptr_t*, phaseinfo_hwarr);
14917 if (unlikely(SpgwAppendBiallelicGenovecHphase(genovec, nullptr, phaseinfo_warr, &spgw))) {
14918 goto OxHapslegendToPgen_ret_WRITE_FAIL;
14919 }
14920 } else {
14921 if (unlikely(SpgwAppendBiallelicGenovec(genovec, &spgw))) {
14922 goto OxHapslegendToPgen_ret_WRITE_FAIL;
14923 }
14924 }
14925 if (!(++variant_ct % 1000)) {
14926 printf("\r--haps%s: %uk variants converted.", legendname[0]? " + --legend" : "", variant_ct / 1000);
14927 fflush(stdout);
14928 }
14929 }
14930 if (unlikely(CswriteCloseNull(&pvar_css, pvar_cswritep))) {
14931 goto OxHapslegendToPgen_ret_WRITE_FAIL;
14932 }
14933 reterr = SpgwFinish(&spgw);
14934 if (unlikely(reterr)) {
14935 PgenWriteFinishErrPrint(reterr, outname, outname_end);
14936 goto OxHapslegendToPgen_ret_1;
14937 }
14938 if (unlikely(!variant_ct)) {
14939 snprintf(g_logbuf, kLogbufSize, "Error: All %" PRIuPTR " variant%s in %s skipped due to chromosome filter.\n", variant_skip_ct, (variant_skip_ct == 1)? "" : "s", hapsname);
14940 goto OxHapslegendToPgen_ret_INCONSISTENT_INPUT_WW;
14941 }
14942 putc_unlocked('\r', stdout);
14943 char* write_iter = strcpya_k(g_logbuf, "--haps");
14944 if (legend_line_start) {
14945 write_iter = strcpya_k(write_iter, " + --legend");
14946 }
14947 write_iter = strcpya_k(write_iter, ": ");
14948 const uint32_t outname_base_slen = outname_end - outname;
14949 write_iter = memcpya(write_iter, outname, outname_base_slen);
14950 write_iter = strcpya_k(write_iter, ".pgen + ");
14951 if (!sfile_sample_ct) {
14952 write_iter = memcpya(write_iter, outname, outname_base_slen);
14953 write_iter = strcpya_k(write_iter, ".psam + ");
14954 }
14955 write_iter = memcpya(write_iter, outname, outname_base_slen);
14956 write_iter = strcpya_k(write_iter, ".pvar");
14957 if (output_zst) {
14958 write_iter = strcpya_k(write_iter, ".zst");
14959 }
14960 snprintf(write_iter, kLogbufSize - 3 * kPglFnamesize - 64, " written.\n");
14961 WordWrapB(0);
14962 logputsb();
14963 }
14964 while (0) {
14965 OxHapslegendToPgen_ret_TSTREAM_FAIL_HAPS:
14966 putc_unlocked('\n', stdout);
14967 TextStreamErrPrint(hapsname, &haps_txs);
14968 break;
14969 OxHapslegendToPgen_ret_TSTREAM_FAIL_LEGEND:
14970 TextStreamErrPrint(legendname, &legend_txs);
14971 break;
14972 OxHapslegendToPgen_ret_NOMEM:
14973 reterr = kPglRetNomem;
14974 break;
14975 OxHapslegendToPgen_ret_OPEN_FAIL:
14976 reterr = kPglRetOpenFail;
14977 break;
14978 OxHapslegendToPgen_ret_WRITE_FAIL:
14979 reterr = kPglRetWriteFail;
14980 break;
14981 OxHapslegendToPgen_ret_MISSING_TOKENS_HAPS:
14982 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx_haps, hapsname);
14983 OxHapslegendToPgen_ret_MALFORMED_INPUT_WW:
14984 putc_unlocked('\n', stdout);
14985 WordWrapB(0);
14986 logerrputsb();
14987 OxHapslegendToPgen_ret_MALFORMED_INPUT:
14988 reterr = kPglRetMalformedInput;
14989 break;
14990 OxHapslegendToPgen_ret_MISSING_TOKENS_LEGEND:
14991 putc_unlocked('\n', stdout);
14992 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx_legend, legendname);
14993 WordWrapB(0);
14994 logerrputsb();
14995 reterr = kPglRetMalformedInput;
14996 break;
14997 OxHapslegendToPgen_ret_HAPLOID_TOKEN:
14998 putc_unlocked('\n', stdout);
14999 snprintf(g_logbuf, kLogbufSize, "Error: Haploid-only token on line %" PRIuPTR " of %s.\n", line_idx_haps, hapsname);
15000 WordWrapB(0);
15001 logerrputsb();
15002 reterr = legendname[0]? kPglRetInconsistentInput : kPglRetMalformedInput;
15003 break;
15004 OxHapslegendToPgen_ret_INCONSISTENT_INPUT_WW:
15005 putc_unlocked('\n', stdout);
15006 WordWrapB(0);
15007 logerrputsb();
15008 OxHapslegendToPgen_ret_INCONSISTENT_INPUT:
15009 reterr = kPglRetInconsistentInput;
15010 break;
15011 }
15012 OxHapslegendToPgen_ret_1:
15013 CleanupSpgw(&spgw, &reterr);
15014 CleanupTextStream2(legendname, &legend_txs, &reterr);
15015 CleanupTextStream2(hapsname, &haps_txs, &reterr);
15016 CswriteCloseCond(&pvar_css, pvar_cswritep);
15017 fclose_cond(psamfile);
15018 BigstackReset(bigstack_mark);
15019 return reterr;
15020 }
15021
15022
15023 // probable todo: use the VCF/BGEN-import parallelization strategy to speed
15024 // this up.
15025 static_assert(sizeof(Dosage) == 2, "Plink1DosageToPgen() needs to be updated.");
15026 PglErr Plink1DosageToPgen(const char* dosagename, const char* famname, const char* mapname, const char* import_single_chr_str, const Plink1DosageInfo* pdip, const char* missing_catname, MiscFlags misc_flags, ImportFlags import_flags, uint32_t psam_01, FamCol fam_cols, int32_t missing_pheno, uint32_t hard_call_thresh, uint32_t dosage_erase_thresh, double import_dosage_certainty, uint32_t max_thread_ct, char* outname, char* outname_end, ChrInfo* cip) {
15027 // Tried making this single-pass, doesn't appear to be an improvement.
15028 unsigned char* bigstack_mark = g_bigstack_base;
15029 unsigned char* bigstack_end_mark = g_bigstack_end;
15030
15031 // these are not allocated on bigstack, and must be explicitly freed
15032 PhenoCol* pheno_cols = nullptr;
15033 char* pheno_names = nullptr;
15034 uint32_t pheno_ct = 0;
15035
15036 FILE* psamfile = nullptr;
15037 uintptr_t line_idx = 0;
15038 Plink1DosageFlags flags = pdip->flags;
15039 PglErr reterr = kPglRetSuccess;
15040 char* pvar_cswritep = nullptr;
15041 CompressStreamState pvar_css;
15042 PreinitCstream(&pvar_css);
15043 textFILE dosage_txf;
15044 TextStream dosage_txs;
15045 STPgenWriter spgw;
15046 PreinitTextFile(&dosage_txf);
15047 PreinitTextStream(&dosage_txs);
15048 PreinitSpgw(&spgw);
15049 {
15050 // 1. Read .fam file. (May as well support most .psam files too, since
15051 // it's the same driver function. However, unless 'noheader' modifier
15052 // is present, SID field cannot be used for disambiguation.)
15053 uint32_t raw_sample_ct = 0;
15054 uintptr_t* sample_include = nullptr;
15055 PedigreeIdInfo pii;
15056 InitPedigreeIdInfo(misc_flags, &pii);
15057 uintptr_t* sex_nm = nullptr;
15058 uintptr_t* sex_male = nullptr;
15059 uintptr_t* founder_info = nullptr;
15060 uintptr_t max_pheno_name_blen = 0;
15061 reterr = LoadPsam(famname, nullptr, missing_catname, fam_cols, 0x7fffffff, missing_pheno, (misc_flags / kfMiscAffection01) & 1, (misc_flags / kfMiscNoCategorical) & 1, (misc_flags / kfMiscNeg9PhenoReallyMissing) & 1, max_thread_ct, &pii, &sample_include, &founder_info, &sex_nm, &sex_male, &pheno_cols, &pheno_names, &raw_sample_ct, &pheno_ct, &max_pheno_name_blen);
15062 if (unlikely(reterr)) {
15063 goto Plink1DosageToPgen_ret_1;
15064 }
15065
15066 // 2. Read dosage-file header line if it exists, then write new .psam.
15067 const uint32_t first_data_col_idx = pdip->skips[0] + pdip->skips[1] + pdip->skips[2] + 3;
15068 uint32_t sample_ct = 0;
15069 uint32_t* dosage_sample_idx_to_fam_uidx;
15070 if (unlikely(bigstack_end_alloc_u32(raw_sample_ct, &dosage_sample_idx_to_fam_uidx))) {
15071 goto Plink1DosageToPgen_ret_NOMEM;
15072 }
15073 if (flags & kfPlink1DosageNoheader) {
15074 sample_ct = raw_sample_ct;
15075 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
15076 dosage_sample_idx_to_fam_uidx[sample_idx] = sample_idx;
15077 }
15078 } else {
15079 ZeroWArr(BitCtToWordCt(raw_sample_ct), sample_include);
15080 const uint32_t tmp_htable_size = GetHtableFastSize(raw_sample_ct);
15081 uint32_t* htable_tmp;
15082 char* idbuf;
15083 if (unlikely(bigstack_end_alloc_u32(tmp_htable_size, &htable_tmp) ||
15084 bigstack_end_alloc_c(pii.sii.max_sample_id_blen, &idbuf))) {
15085 goto Plink1DosageToPgen_ret_NOMEM;
15086 }
15087 const uint32_t duplicate_idx = PopulateStrboxHtable(pii.sii.sample_ids, raw_sample_ct, pii.sii.max_sample_id_blen, tmp_htable_size, htable_tmp);
15088 if (unlikely(duplicate_idx)) {
15089 char* duplicate_sample_id = &(pii.sii.sample_ids[duplicate_idx * pii.sii.max_sample_id_blen]);
15090 char* duplicate_fid_end = AdvToDelim(duplicate_sample_id, '\t');
15091 *duplicate_fid_end = ' ';
15092 snprintf(g_logbuf, kLogbufSize, "Error: Duplicate sample ID \"%s\" in .fam file.\n", duplicate_sample_id);
15093 goto Plink1DosageToPgen_ret_MALFORMED_INPUT_WW;
15094 }
15095
15096 uintptr_t dst_capacity = bigstack_left();
15097 #ifdef __LP64__
15098 if (dst_capacity > S_CAST(uintptr_t, kMaxLongLine) + S_CAST(uintptr_t, kDecompressChunkSize)) {
15099 dst_capacity = S_CAST(uintptr_t, kMaxLongLine) + S_CAST(uintptr_t, kDecompressChunkSize);
15100 } else if (unlikely(dst_capacity < kDecompressMinCapacity)) {
15101 goto Plink1DosageToPgen_ret_NOMEM;
15102 }
15103 #else
15104 if (unlikely(dst_capacity < kDecompressMinCapacity)) {
15105 goto Plink1DosageToPgen_ret_NOMEM;
15106 }
15107 #endif
15108 // not formally allocated
15109 char* dst = R_CAST(char*, g_bigstack_base);
15110 reterr = TextFileOpenEx(dosagename, kMaxLongLine, dst_capacity, dst, &dosage_txf);
15111 if (unlikely(reterr)) {
15112 goto Plink1DosageToPgen_ret_TFILE_FAIL2;
15113 }
15114 line_idx = 1;
15115 char* line_start = TextFileGet(&dosage_txf);
15116 if (unlikely(!line_start)) {
15117 reterr = TextFileRawErrcode(&dosage_txf);
15118 goto Plink1DosageToPgen_ret_TFILE_FAIL2;
15119 }
15120 char* loadbuf_iter = NextTokenMult(line_start, first_data_col_idx);
15121 if (unlikely(!loadbuf_iter)) {
15122 goto Plink1DosageToPgen_ret_MISSING_TOKENS;
15123 }
15124 const char id_delim = pdip->id_delim;
15125 do {
15126 char* fid_end = CurTokenEnd(loadbuf_iter);
15127 char* iid_start;
15128 char* iid_end;
15129 uint32_t iid_slen;
15130 if (id_delim) {
15131 iid_end = fid_end;
15132 fid_end = S_CAST(char*, memchr(loadbuf_iter, ctou32(id_delim), iid_end - loadbuf_iter));
15133 if (unlikely(!fid_end)) {
15134 snprintf(g_logbuf, kLogbufSize, "Error: Sample ID in --import-dosage file does not contain '%c' delimiter.\n", id_delim);
15135 goto Plink1DosageToPgen_ret_INCONSISTENT_INPUT_2;
15136 }
15137 iid_start = &(fid_end[1]);
15138 iid_slen = iid_end - iid_start;
15139 if (unlikely(memchr(iid_start, ctou32(id_delim), iid_slen))) {
15140 snprintf(g_logbuf, kLogbufSize, "Error: Sample ID in --import-dosage file has multiple instances of '%c'.\n", id_delim);
15141 goto Plink1DosageToPgen_ret_INCONSISTENT_INPUT_2;
15142 }
15143 } else {
15144 iid_start = FirstNonTspace(fid_end);
15145 if (unlikely(IsEolnKns(*iid_start))) {
15146 goto Plink1DosageToPgen_ret_MISSING_TOKENS;
15147 }
15148 iid_end = CurTokenEnd(iid_start);
15149 iid_slen = iid_end - iid_start;
15150 }
15151 const uint32_t fid_slen = fid_end - loadbuf_iter;
15152 const uint32_t cur_id_slen = fid_slen + iid_slen + 1;
15153 if (unlikely(cur_id_slen >= pii.sii.max_sample_id_blen)) {
15154 logerrputs("Error: .fam file does not contain all sample IDs in dosage file.\n");
15155 goto Plink1DosageToPgen_ret_INCONSISTENT_INPUT;
15156 }
15157 char* idbuf_iid = memcpyax(idbuf, loadbuf_iter, fid_slen, '\t');
15158 memcpyx(idbuf_iid, iid_start, iid_slen, '\0');
15159 uint32_t sample_uidx = StrboxHtableFind(idbuf, pii.sii.sample_ids, htable_tmp, pii.sii.max_sample_id_blen, cur_id_slen, tmp_htable_size);
15160 if (unlikely(sample_uidx == UINT32_MAX)) {
15161 logerrputs("Error: .fam file does not contain all sample IDs in dosage file.\n");
15162 goto Plink1DosageToPgen_ret_INCONSISTENT_INPUT;
15163 }
15164 if (unlikely(IsSet(sample_include, sample_uidx))) {
15165 idbuf_iid[-1] = ' ';
15166 snprintf(g_logbuf, kLogbufSize, "Error: Duplicate sample ID \"%s\" in dosage file.\n", idbuf);
15167 goto Plink1DosageToPgen_ret_MALFORMED_INPUT_WW;
15168 }
15169 SetBit(sample_uidx, sample_include);
15170 dosage_sample_idx_to_fam_uidx[sample_ct++] = sample_uidx;
15171 loadbuf_iter = FirstNonTspace(iid_end);
15172 } while (!IsEolnKns(*loadbuf_iter));
15173 // Not worth the trouble of move-constructing dosage_txs from dosage_txf,
15174 // since we may need to load the .map in between, and we'll need to
15175 // rewind again anyway.
15176 if (unlikely(CleanupTextFile2(dosagename, &dosage_txf, &reterr))) {
15177 goto Plink1DosageToPgen_ret_1;
15178 }
15179 line_idx = 0;
15180 }
15181
15182 snprintf(outname_end, kMaxOutfnameExtBlen, ".psam");
15183 if (unlikely(fopen_checked(outname, FOPEN_WB, &psamfile))) {
15184 goto Plink1DosageToPgen_ret_OPEN_FAIL;
15185 }
15186 char* writebuf = g_textbuf;
15187 char* writebuf_flush = &(writebuf[kMaxMediumLine]);
15188 char* write_iter = writebuf;
15189 *write_iter++ = '#';
15190 const uint32_t write_fid = DataFidColIsRequired(sample_include, &pii.sii, sample_ct, 1);
15191 if (write_fid) {
15192 write_iter = strcpya_k(write_iter, "FID\t");
15193 }
15194 write_iter = strcpya_k(write_iter, "IID");
15195 const uint32_t write_sid = DataSidColIsRequired(sample_include, pii.sii.sids, sample_ct, pii.sii.max_sid_blen, 1);
15196 if (write_sid) {
15197 write_iter = strcpya_k(write_iter, "\tSID");
15198 }
15199 const uint32_t write_parents = DataParentalColsAreRequired(sample_include, &pii.sii, &pii.parental_id_info, sample_ct, 1);
15200 if (write_parents) {
15201 write_iter = strcpya_k(write_iter, "\tPAT\tMAT");
15202 }
15203 write_iter = strcpya_k(write_iter, "\tSEX");
15204 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
15205 *write_iter++ = '\t';
15206 write_iter = strcpya(write_iter, &(pheno_names[pheno_idx * max_pheno_name_blen]));
15207 if (unlikely(fwrite_ck(writebuf_flush, psamfile, &write_iter))) {
15208 goto Plink1DosageToPgen_ret_WRITE_FAIL;
15209 }
15210 }
15211 AppendBinaryEoln(&write_iter);
15212 const char ctrl_char = '1' - psam_01;
15213 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
15214 const uint32_t sample_uidx = dosage_sample_idx_to_fam_uidx[sample_idx];
15215 const char* cur_sample_id = &(pii.sii.sample_ids[sample_uidx * pii.sii.max_sample_id_blen]);
15216 if (!write_fid) {
15217 cur_sample_id = AdvPastDelim(cur_sample_id, '\t');
15218 }
15219 write_iter = strcpya(write_iter, cur_sample_id);
15220 if (write_sid) {
15221 *write_iter++ = '\t';
15222 write_iter = strcpya(write_iter, &(pii.sii.sids[sample_uidx * pii.sii.max_sid_blen]));
15223 }
15224 if (write_parents) {
15225 *write_iter++ = '\t';
15226 write_iter = strcpyax(write_iter, &(pii.parental_id_info.paternal_ids[pii.parental_id_info.max_paternal_id_blen * sample_uidx]), '\t');
15227 write_iter = strcpya(write_iter, &(pii.parental_id_info.maternal_ids[pii.parental_id_info.max_maternal_id_blen * sample_uidx]));
15228 }
15229 *write_iter++ = '\t';
15230 if (IsSet(sex_nm, sample_uidx)) {
15231 *write_iter++ = '2' - IsSet(sex_male, sample_uidx);
15232 } else {
15233 write_iter = strcpya_k(write_iter, "NA");
15234 }
15235 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
15236 if (unlikely(fwrite_ck(writebuf_flush, psamfile, &write_iter))) {
15237 goto Plink1DosageToPgen_ret_WRITE_FAIL;
15238 }
15239 *write_iter++ = '\t';
15240 write_iter = AppendPhenoStrEx(&(pheno_cols[pheno_idx]), "NA", 2, sample_uidx, ctrl_char, write_iter);
15241 }
15242 AppendBinaryEoln(&write_iter);
15243 if (unlikely(fwrite_ck(writebuf_flush, psamfile, &write_iter))) {
15244 goto Plink1DosageToPgen_ret_WRITE_FAIL;
15245 }
15246 }
15247 if (unlikely(fclose_flush_null(writebuf_flush, write_iter, &psamfile))) {
15248 goto Plink1DosageToPgen_ret_WRITE_FAIL;
15249 }
15250 // Don't need sample info any more.
15251 BigstackEndReset(bigstack_end_mark);
15252
15253 // 3. Read .map file if it exists.
15254 uint32_t max_variant_id_slen = 1;
15255 ChrIdx* variant_chr_codes = nullptr;
15256 uint32_t* variant_bps = nullptr;
15257 char** variant_ids = nullptr;
15258 double* variant_cms = nullptr;
15259 uint32_t* variant_id_htable = nullptr;
15260 uintptr_t* variant_already_seen = nullptr;
15261 uint32_t variant_id_htable_size = 0;
15262 uint32_t map_variant_ct = 0;
15263 FinalizeChrset(misc_flags, cip);
15264 if (mapname) {
15265 reterr = LoadMap(mapname, misc_flags, cip, &max_variant_id_slen, &variant_chr_codes, &variant_bps, &variant_ids, &variant_cms, &map_variant_ct);
15266 if (unlikely(reterr)) {
15267 goto Plink1DosageToPgen_ret_1;
15268 }
15269 const uint32_t map_variant_ctl = BitCtToWordCt(map_variant_ct);
15270 if (unlikely(bigstack_alloc_w(map_variant_ctl, &variant_already_seen))) {
15271 goto Plink1DosageToPgen_ret_NOMEM;
15272 }
15273 SetAllBits(map_variant_ct, variant_already_seen);
15274 unsigned char* bigstack_end_mark2 = g_bigstack_end;
15275
15276 // allow hash table to only use half of available memory
15277 g_bigstack_end = &(g_bigstack_base[RoundDownPow2(bigstack_left() / 2, kEndAllocAlign)]);
15278
15279 reterr = AllocAndPopulateIdHtableMt(variant_already_seen, TO_CONSTCPCONSTP(variant_ids), map_variant_ct, bigstack_left() / 2, max_thread_ct, &variant_id_htable, nullptr, &variant_id_htable_size, nullptr);
15280 if (unlikely(reterr)) {
15281 goto Plink1DosageToPgen_ret_1;
15282 }
15283 g_bigstack_end = bigstack_end_mark2;
15284 ZeroWArr(map_variant_ctl, variant_already_seen);
15285 }
15286
15287 // 4. Dosage file pass 1: count variants, check whether any decimal dosages
15288 // need to be saved, write .pvar.
15289 //
15290 // Lots of overlap with OxGenToPgen().
15291
15292 const uint32_t output_zst = (import_flags / kfImportKeepAutoconvVzs) & 1;
15293 // This is overly conservative in the .pvar.zst output case, but it
15294 // shouldn't matter.
15295 uintptr_t ulii = bigstack_left() >> (1 + output_zst);
15296 // Main write buffer needs to be a bit larger than the corresponding read
15297 // buffer; also need a small chromosome buffer.
15298 if (unlikely(ulii < RoundUpPow2((kMaxMediumLine + kCacheline) / 2, kCacheline))) {
15299 goto Plink1DosageToPgen_ret_NOMEM;
15300 }
15301 ulii -= RoundUpPow2((kMaxMediumLine + kCacheline) / 2, kCacheline);
15302 uint32_t max_line_blen;
15303 if (unlikely(StandardizeMaxLineBlen(ulii, &max_line_blen))) {
15304 goto Plink1DosageToPgen_ret_NOMEM;
15305 }
15306 reterr = InitTextStream(dosagename, max_line_blen, ClipU32(max_thread_ct - 1, 1, 3), &dosage_txs);
15307 if (unlikely(reterr)) {
15308 goto Plink1DosageToPgen_ret_TSTREAM_REWIND1_FAIL;
15309 }
15310 snprintf(outname_end, kMaxOutfnameExtBlen, ".pvar");
15311 if (output_zst) {
15312 snprintf(&(outname_end[5]), kMaxOutfnameExtBlen - 5, ".zst");
15313 }
15314 unsigned char* bigstack_mark2 = g_bigstack_base;
15315 const uintptr_t overflow_buf_size = kCompressStreamBlock + kDecompressChunkSize + max_line_blen;
15316 reterr = InitCstreamAlloc(outname, 0, output_zst, 1, overflow_buf_size, &pvar_css, &pvar_cswritep);
15317 if (unlikely(reterr)) {
15318 goto Plink1DosageToPgen_ret_1;
15319 }
15320 const uint32_t prohibit_extra_chr = (misc_flags / kfMiscProhibitExtraChr) & 1;
15321 const char* single_chr_str = nullptr;
15322 uint32_t single_chr_slen = 0;
15323 const uint32_t chr_col_idx = pdip->chr_col_idx;
15324 const uint32_t check_chr_col = (chr_col_idx != UINT32_MAX);
15325 if (!check_chr_col) {
15326 if (import_single_chr_str) {
15327 uint32_t chr_code_raw = GetChrCodeRaw(import_single_chr_str);
15328 if (chr_code_raw == UINT32_MAX) {
15329 // command-line parser guarantees that prohibit_extra_chr is false
15330 // here
15331 single_chr_str = import_single_chr_str;
15332 single_chr_slen = strlen(import_single_chr_str);
15333 } else {
15334 uint32_t chr_code = chr_code_raw;
15335 if (chr_code > cip->max_code) {
15336 if (unlikely(chr_code < kMaxContigs)) {
15337 logerrputs("Error: --import-dosage single-chr= code is not in the chromosome set.\n");
15338 goto Plink1DosageToPgen_ret_INVALID_CMDLINE;
15339 }
15340 chr_code = cip->xymt_codes[chr_code - kMaxContigs];
15341 if (unlikely(IsI32Neg(chr_code))) {
15342 logerrputs("Error: --import-dosage single-chr= code is not in the chromosome set.\n");
15343 goto Plink1DosageToPgen_ret_INVALID_CMDLINE;
15344 }
15345 }
15346 if (unlikely(!IsSet(cip->chr_mask, chr_code))) {
15347 logerrputs("Error: --import-dosage single-chr= code is excluded by chromosome filter.\n");
15348 goto Plink1DosageToPgen_ret_INVALID_CMDLINE;
15349 }
15350 // check this allocation?...
15351 char* chr_buf = S_CAST(char*, bigstack_alloc_raw(kCacheline));
15352 char* chr_name_end = chrtoa(cip, chr_code, chr_buf);
15353 single_chr_str = chr_buf;
15354 single_chr_slen = chr_name_end - chr_buf;
15355 }
15356 } else {
15357 // default to "chr0"
15358 if (unlikely(!IsSet(cip->chr_mask, 0))) {
15359 logerrputs("Error: No --import-dosage chromosome information specified, and chr0 excluded.\n");
15360 goto Plink1DosageToPgen_ret_INVALID_CMDLINE;
15361 }
15362 char* chr_buf = S_CAST(char*, bigstack_alloc_raw(kCacheline));
15363 char* chr_name_end = chrtoa(cip, 0, chr_buf);
15364 single_chr_str = chr_buf;
15365 single_chr_slen = chr_name_end - chr_buf;
15366 }
15367 }
15368 pvar_cswritep = strcpya_k(pvar_cswritep, "#CHROM\tPOS\tID\tREF\tALT");
15369 if (variant_cms) {
15370 pvar_cswritep = strcpya_k(pvar_cswritep, "\tCM");
15371 }
15372 AppendBinaryEoln(&pvar_cswritep);
15373 // types:
15374 // 0 = #CHROM
15375 // 1 = POS
15376 // 2 = ID
15377 // 3 = REF
15378 // 4 = ALT
15379 // 5 = first data column
15380 // (command-line parser verifies that CHROM/POS don't collide with
15381 // anything else)
15382 uint64_t parse_table[6];
15383 // high bits = col index, low bits = col type
15384 const uint32_t id_col_idx = pdip->skips[0];
15385 const uint32_t prov_ref_allele_second = !(flags & kfPlink1DosageRefFirst);
15386 uint32_t ref_col_idx = id_col_idx + pdip->skips[1] + 1;
15387 const uint32_t alt_col_idx = ref_col_idx + (!prov_ref_allele_second);
15388 ref_col_idx += prov_ref_allele_second;
15389 parse_table[0] = (S_CAST(uint64_t, id_col_idx) << 32) + 2;
15390 parse_table[1] = (S_CAST(uint64_t, ref_col_idx) << 32) + 3;
15391 parse_table[2] = (S_CAST(uint64_t, alt_col_idx) << 32) + 4;
15392 uint32_t relevant_initial_col_ct = 3;
15393 if (check_chr_col) {
15394 parse_table[relevant_initial_col_ct++] = S_CAST(uint64_t, chr_col_idx) << 32;
15395 }
15396 const uint32_t check_pos_col = (pdip->pos_col_idx != UINT32_MAX);
15397 if (check_pos_col) {
15398 parse_table[relevant_initial_col_ct++] = (S_CAST(uint64_t, pdip->pos_col_idx) << 32) + 1;
15399 }
15400 #if ((__GNUC__ == 12) || (__GNUC__ == 13))
15401 // https://github.com/cms-sw/cmssw/issues/44582
15402 # pragma GCC diagnostic push
15403 # pragma GCC diagnostic ignored "-Warray-bounds"
15404 #endif
15405 STD_SORT(relevant_initial_col_ct, u64cmp, parse_table);
15406 #if ((__GNUC__ == 12) || (__GNUC__ == 13))
15407 # pragma GCC diagnostic pop
15408 #endif
15409 uint32_t col_skips[6];
15410 uint32_t col_types[6];
15411 for (uint32_t uii = 0; uii != relevant_initial_col_ct; ++uii) {
15412 const uint64_t parse_table_entry = parse_table[uii];
15413 col_skips[uii] = parse_table_entry >> 32;
15414 col_types[uii] = S_CAST(uint32_t, parse_table_entry);
15415 }
15416 col_skips[relevant_initial_col_ct] = first_data_col_idx;
15417 col_types[relevant_initial_col_ct++] = 5;
15418 for (uint32_t uii = relevant_initial_col_ct - 1; uii; --uii) {
15419 col_skips[uii] -= col_skips[uii - 1];
15420 }
15421
15422 double dosage_multiplier = kDosageMid;
15423 double dosage_ceil = 32767.5 / 16384.0;
15424 if (flags & kfPlink1DosageFormatSingle01) {
15425 dosage_multiplier = kDosageMax;
15426 dosage_ceil = 32767.5 / 32768.0;
15427 }
15428 uint32_t format_triple = (flags / kfPlink1DosageFormatTriple) & 1;
15429 uint32_t format_infer = !(flags & (kfPlink1DosageFormatSingle | kfPlink1DosageFormatDouble | kfPlink1DosageFormatTriple));
15430 // dosage_erase_halfdist corresponds to very high confidence (keep only
15431 // hardcall), while force_missing_halfdist corresponds to very low
15432 // confidence.
15433 const uint32_t dosage_erase_halfdist = kDosage4th - dosage_erase_thresh;
15434 const uint32_t force_missing_halfdist_p1 = (import_dosage_certainty == 0.0)? 0 : (1 + S_CAST(uint32_t, (import_dosage_certainty - 0.5) * kDosageMid));
15435 uint32_t dosage_exists = 0;
15436 uint32_t variant_ct = 0;
15437 uintptr_t variant_skip_ct = 0;
15438 uint32_t variant_uidx = 0;
15439 char* line_iter = TextLineEnd(&dosage_txs);
15440 if (!(flags & kfPlink1DosageNoheader)) {
15441 // Skip header line.
15442 line_idx = 1;
15443 reterr = TextGetUnsafe(&dosage_txs, &line_iter);
15444 if (unlikely(reterr)) {
15445 goto Plink1DosageToPgen_ret_TSTREAM_REWIND1_FAIL;
15446 }
15447 line_iter = AdvPastDelim(line_iter, '\n');
15448 }
15449 ++line_idx;
15450 for (; TextGetUnsafe2(&dosage_txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) {
15451 char* token_ptrs[6];
15452 uint32_t token_slens[6];
15453 line_iter = TokenLex0(line_iter, col_types, col_skips, relevant_initial_col_ct, token_ptrs, token_slens);
15454 if (unlikely(!line_iter)) {
15455 goto Plink1DosageToPgen_ret_MISSING_TOKENS;
15456 }
15457 // ID
15458 const char* variant_id = token_ptrs[2];
15459 const uint32_t variant_id_slen = token_slens[2];
15460 if (map_variant_ct) {
15461 variant_uidx = VariantIdDupflagHtableFind(variant_id, TO_CONSTCPCONSTP(variant_ids), variant_id_htable, variant_id_slen, variant_id_htable_size, max_variant_id_slen);
15462 if (variant_uidx >> 31) {
15463 if (likely(variant_uidx == UINT32_MAX)) {
15464 ++variant_skip_ct;
15465 continue;
15466 }
15467 snprintf(g_logbuf, kLogbufSize, "Error: Variant ID '%s' appears multiple times in .map file.\n", variant_ids[variant_uidx & 0x7fffffff]);
15468 goto Plink1DosageToPgen_ret_MALFORMED_INPUT_WW;
15469 }
15470 if (unlikely(IsSet(variant_already_seen, variant_uidx))) {
15471 snprintf(g_logbuf, kLogbufSize, "Error: Variant ID '%s' appears multiple times in --import-dosage file.\n", variant_ids[variant_uidx]);
15472 goto Plink1DosageToPgen_ret_MALFORMED_INPUT_WW;
15473 }
15474 // already performed chromosome filtering
15475 pvar_cswritep = chrtoa(cip, variant_chr_codes[variant_uidx], pvar_cswritep);
15476 *pvar_cswritep++ = '\t';
15477 pvar_cswritep = u32toa_x(variant_bps[variant_uidx], '\t', pvar_cswritep);
15478 pvar_cswritep = memcpya(pvar_cswritep, variant_id, variant_id_slen);
15479 } else {
15480 if (unlikely(variant_id_slen > kMaxIdSlen)) {
15481 putc_unlocked('\n', stdout);
15482 logerrputs("Error: Variant names are limited to " MAX_ID_SLEN_STR " characters.\n");
15483 goto Plink1DosageToPgen_ret_MALFORMED_INPUT;
15484 }
15485 // #CHROM
15486 if (check_chr_col) {
15487 char* chr_code_str = token_ptrs[0];
15488 char* chr_code_end = &(chr_code_str[token_slens[0]]);
15489 uint32_t cur_chr_code;
15490 reterr = GetOrAddChrCodeDestructive("--import-dosage file", line_idx, prohibit_extra_chr, chr_code_str, chr_code_end, cip, &cur_chr_code);
15491 if (unlikely(reterr)) {
15492 goto Plink1DosageToPgen_ret_1;
15493 }
15494 if (!IsSet(cip->chr_mask, cur_chr_code)) {
15495 ++variant_skip_ct;
15496 continue;
15497 }
15498 pvar_cswritep = chrtoa(cip, cur_chr_code, pvar_cswritep);
15499 } else {
15500 pvar_cswritep = memcpya(pvar_cswritep, single_chr_str, single_chr_slen);
15501 }
15502 *pvar_cswritep++ = '\t';
15503 // POS
15504 if (check_pos_col) {
15505 const char* pos_str = token_ptrs[1];
15506 // no need to support negative values here
15507 uint32_t cur_bp;
15508 if (unlikely(ScanUintDefcap(pos_str, &cur_bp))) {
15509 snprintf(g_logbuf, kLogbufSize, "Error: Invalid bp coordinate on line %" PRIuPTR " of %s.\n", line_idx, dosagename);
15510 goto Plink1DosageToPgen_ret_MALFORMED_INPUT_WW;
15511 }
15512 pvar_cswritep = u32toa(cur_bp, pvar_cswritep);
15513 } else {
15514 *pvar_cswritep++ = '0';
15515 }
15516 *pvar_cswritep++ = '\t';
15517 pvar_cswritep = memcpya(pvar_cswritep, variant_id, variant_id_slen);
15518 }
15519 ++variant_ct;
15520 *pvar_cswritep++ = '\t';
15521 // REF, ALT
15522 pvar_cswritep = memcpyax(pvar_cswritep, token_ptrs[3], token_slens[3], '\t');
15523 pvar_cswritep = memcpya(pvar_cswritep, token_ptrs[4], token_slens[4]);
15524 if (variant_cms) {
15525 *pvar_cswritep++ = '\t';
15526 pvar_cswritep = dtoa_g_p8(variant_cms[variant_uidx], pvar_cswritep);
15527 }
15528 AppendBinaryEoln(&pvar_cswritep);
15529 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
15530 goto Plink1DosageToPgen_ret_WRITE_FAIL;
15531 }
15532 if (!dosage_exists) {
15533 char* linebuf_iter = token_ptrs[5];
15534 if (format_infer) {
15535 const uint32_t remaining_col_ct = CountTokens(linebuf_iter);
15536 if (remaining_col_ct == sample_ct) {
15537 flags |= kfPlink1DosageFormatSingle;
15538 } else if (remaining_col_ct == sample_ct * 3) {
15539 format_triple = 1;
15540 } else if (unlikely(remaining_col_ct != sample_ct * 2)) {
15541 snprintf(g_logbuf, kLogbufSize, "Error: Unexpected format=infer column count in --import-dosage file (%u; should be %u, %u, or %u).\n", remaining_col_ct, sample_ct, sample_ct * 2, sample_ct * 3);
15542 goto Plink1DosageToPgen_ret_INCONSISTENT_INPUT_WW;
15543 }
15544 format_infer = 0;
15545 }
15546 if (flags & kfPlink1DosageFormatSingle) {
15547 // todo: modify these loops to cleanly update line_iter
15548 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
15549 if (unlikely(!linebuf_iter)) {
15550 goto Plink1DosageToPgen_ret_MISSING_TOKENS;
15551 }
15552 double a1_dosage;
15553 char* str_end = ScanadvDouble(linebuf_iter, &a1_dosage);
15554 if ((!linebuf_iter) || (a1_dosage < (0.5 / 32768.0)) || (a1_dosage >= dosage_ceil)) {
15555 linebuf_iter = NextToken(linebuf_iter);
15556 continue;
15557 }
15558 if (unlikely(!IsSpaceOrEoln(*str_end))) {
15559 str_end = CurTokenEnd(str_end);
15560 *str_end = '\0';
15561 snprintf(g_logbuf, kLogbufSize, "Error: Invalid numeric token '%s' on line %" PRIuPTR " of --import-dosage file.\n", linebuf_iter, line_idx);
15562 goto Plink1DosageToPgen_ret_MALFORMED_INPUT_WW;
15563 }
15564 a1_dosage *= dosage_multiplier;
15565 const uint32_t dosage_int = S_CAST(int32_t, a1_dosage + 0.5);
15566 const uint32_t halfdist = BiallelicDosageHalfdist(dosage_int);
15567 if ((halfdist < dosage_erase_halfdist) && (halfdist >= force_missing_halfdist_p1)) {
15568 dosage_exists = 1;
15569 break;
15570 }
15571 linebuf_iter = FirstNonTspace(str_end);
15572 }
15573 } else {
15574 // for compatibility with plink 1.x, do not actually parse third
15575 // value of each triplet if format=3
15576 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
15577 if (unlikely(!linebuf_iter)) {
15578 goto Plink1DosageToPgen_ret_MISSING_TOKENS;
15579 }
15580 double prob_2a1;
15581 char* str_end = ScanadvDouble(linebuf_iter, &prob_2a1);
15582 if (!str_end) {
15583 linebuf_iter = NextTokenMult(linebuf_iter, 2 + format_triple);
15584 continue;
15585 }
15586 if (unlikely(!IsSpaceOrEoln(*str_end))) {
15587 str_end = CurTokenEnd(str_end);
15588 *str_end = '\0';
15589 snprintf(g_logbuf, kLogbufSize, "Error: Invalid numeric token '%s' on line %" PRIuPTR " of --import-dosage file.\n", linebuf_iter, line_idx);
15590 goto Plink1DosageToPgen_ret_MALFORMED_INPUT_WW;
15591 }
15592 linebuf_iter = FirstNonTspace(str_end);
15593 if (unlikely(IsEolnKns(*linebuf_iter))) {
15594 goto Plink1DosageToPgen_ret_MISSING_TOKENS;
15595 }
15596 double prob_1a1;
15597 str_end = ScanadvDouble(linebuf_iter, &prob_1a1);
15598 if (!str_end) {
15599 linebuf_iter = NextTokenMult(linebuf_iter, 1 + format_triple);
15600 continue;
15601 }
15602 if (unlikely(!IsSpaceOrEoln(*str_end))) {
15603 str_end = CurTokenEnd(str_end);
15604 *str_end = '\0';
15605 snprintf(g_logbuf, kLogbufSize, "Error: Invalid numeric token '%s' on line %" PRIuPTR " of --import-dosage file.\n", linebuf_iter, line_idx);
15606 goto Plink1DosageToPgen_ret_MALFORMED_INPUT_WW;
15607 }
15608 linebuf_iter = NextTokenMult(str_end, 1 + format_triple);
15609 double prob_one_or_two_a1 = prob_2a1 + prob_1a1;
15610 if ((prob_2a1 < 0.0) || (prob_1a1 < 0.0) || (prob_one_or_two_a1 > 1.01 * (1 + kSmallEpsilon))) {
15611 continue;
15612 }
15613 if (prob_one_or_two_a1 > 1.0) {
15614 const double rescale = 1.0 / prob_one_or_two_a1;
15615 prob_2a1 *= rescale;
15616 prob_1a1 *= rescale;
15617 prob_one_or_two_a1 = 1.0;
15618 }
15619 const uint32_t dosage_int = S_CAST(int32_t, prob_2a1 * 32768 + prob_1a1 * 16384 + 0.5);
15620 const uint32_t halfdist = BiallelicDosageHalfdist(dosage_int);
15621 if ((halfdist < dosage_erase_halfdist) && ((prob_2a1 >= import_dosage_certainty) || (prob_1a1 >= import_dosage_certainty) || (prob_one_or_two_a1 <= 1.0 - import_dosage_certainty))) {
15622 dosage_exists = 1;
15623 break;
15624 }
15625 }
15626 }
15627 }
15628 if (!(variant_ct % 1000)) {
15629 printf("\r--import-dosage: %uk variants scanned.", variant_ct / 1000);
15630 fflush(stdout);
15631 }
15632 }
15633 if (TextStreamErrcode2(&dosage_txs, &reterr)) {
15634 goto Plink1DosageToPgen_ret_TSTREAM_REWIND1_FAIL;
15635 }
15636 putc_unlocked('\r', stdout);
15637 if (unlikely(CswriteCloseNull(&pvar_css, pvar_cswritep))) {
15638 goto Plink1DosageToPgen_ret_WRITE_FAIL;
15639 }
15640 if (unlikely(!variant_ct)) {
15641 if (!variant_skip_ct) {
15642 logerrputs("Error: Empty --import-dosage file.\n");
15643 goto Plink1DosageToPgen_ret_DEGENERATE_DATA;
15644 }
15645 logerrprintfww("Error: All %" PRIuPTR " variant%s in --import-dosage file skipped.\n", variant_skip_ct, (variant_skip_ct == 1)? "" : "s");
15646 goto Plink1DosageToPgen_ret_INCONSISTENT_INPUT;
15647 }
15648 logprintf("--import-dosage: %u variant%s scanned%s.\n", variant_ct, (variant_ct == 1)? "" : "s", dosage_exists? "" : " (all hardcalls)");
15649
15650 // 5. Dosage file pass 2: write .pgen.
15651 BigstackReset(bigstack_mark2);
15652 reterr = TextRewind(&dosage_txs);
15653 if (unlikely(reterr)) {
15654 goto Plink1DosageToPgen_ret_TSTREAM_REWIND1_FAIL;
15655 }
15656 line_iter = TextLineEnd(&dosage_txs);
15657 const uintptr_t line_ct = line_idx - 1;
15658 line_idx = 0;
15659 if (!(flags & kfPlink1DosageNoheader)) {
15660 // skip header line again
15661 ++line_idx;
15662 reterr = TextGetUnsafe(&dosage_txs, &line_iter);
15663 if (unlikely(reterr)) {
15664 goto Plink1DosageToPgen_ret_TSTREAM_REWIND2_FAIL;
15665 }
15666 line_iter = AdvPastDelim(line_iter, '\n');
15667 }
15668 snprintf(outname_end, kMaxOutfnameExtBlen, ".pgen");
15669 uintptr_t spgw_alloc_cacheline_ct;
15670 uint32_t max_vrec_len;
15671 reterr = SpgwInitPhase1(outname, nullptr, nullptr, variant_ct, sample_ct, 0, kPgenWriteBackwardSeek, dosage_exists? kfPgenGlobalDosagePresent: kfPgenGlobal0, (flags & (kfPlink1DosageRefFirst | kfPlink1DosageRefLast))? 1 : 2, &spgw, &spgw_alloc_cacheline_ct, &max_vrec_len);
15672 if (unlikely(reterr)) {
15673 if (reterr == kPglRetOpenFail) {
15674 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
15675 }
15676 goto Plink1DosageToPgen_ret_1;
15677 }
15678 unsigned char* spgw_alloc;
15679 if (unlikely(bigstack_alloc_uc(spgw_alloc_cacheline_ct * kCacheline, &spgw_alloc))) {
15680 goto Plink1DosageToPgen_ret_NOMEM;
15681 }
15682 SpgwInitPhase2(max_vrec_len, &spgw, spgw_alloc);
15683
15684 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
15685 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
15686 uintptr_t* genovec;
15687 Halfword* dosage_present_hwarr;
15688 if (unlikely(bigstack_alloc_w(sample_ctl2, &genovec) ||
15689 bigstack_alloc_hw(2 * sample_ctl, &dosage_present_hwarr))) {
15690 goto Plink1DosageToPgen_ret_NOMEM;
15691 }
15692 Dosage* dosage_main = nullptr;
15693 if (dosage_exists) {
15694 if (unlikely(bigstack_alloc_dosage(sample_ct, &dosage_main))) {
15695 goto Plink1DosageToPgen_ret_NOMEM;
15696 }
15697 }
15698 if (hard_call_thresh == UINT32_MAX) {
15699 hard_call_thresh = kDosageMid / 10;
15700 }
15701 dosage_ceil = 2.02 * (1 + kSmallEpsilon);
15702 if (flags & kfPlink1DosageFormatSingle01) {
15703 dosage_ceil = 1.01 * (1 + kSmallEpsilon);
15704 }
15705 const uint32_t hard_call_halfdist = kDosage4th - hard_call_thresh;
15706 const uint32_t sample_ctl2_m1 = sample_ctl2 - 1;
15707 uint32_t vidx = 0;
15708 for (; line_idx < line_ct; line_iter = AdvPastDelim(line_iter, '\n')) {
15709 ++line_idx;
15710 reterr = TextGetUnsafe(&dosage_txs, &line_iter);
15711 if (unlikely(reterr)) {
15712 goto Plink1DosageToPgen_ret_TSTREAM_REWIND2_FAIL;
15713 }
15714 if (variant_skip_ct) {
15715 if (map_variant_ct) {
15716 char* variant_id = NextTokenMult0(line_iter, id_col_idx);
15717 const uint32_t variant_id_slen = strlen_se(variant_id);
15718 if (VariantIdDupflagHtableFind(variant_id, TO_CONSTCPCONSTP(variant_ids), variant_id_htable, variant_id_slen, variant_id_htable_size, max_variant_id_slen) == UINT32_MAX) {
15719 continue;
15720 }
15721 line_iter = NextTokenMult(variant_id, first_data_col_idx - id_col_idx);
15722 } else {
15723 char* chr_code_str = NextTokenMult0(line_iter, chr_col_idx);
15724 char* chr_code_end = CurTokenEnd(chr_code_str);
15725 line_iter = NextTokenMult(chr_code_end, first_data_col_idx - chr_col_idx);
15726 *chr_code_end = '\0';
15727 const uint32_t chr_code = GetChrCode(chr_code_str, cip, chr_code_end - chr_code_str);
15728 if (!IsSet(cip->chr_mask, chr_code)) {
15729 continue;
15730 }
15731 }
15732 } else {
15733 line_iter = NextTokenMult(line_iter, first_data_col_idx);
15734 }
15735 if (!line_iter) {
15736 goto Plink1DosageToPgen_ret_MISSING_TOKENS;
15737 }
15738 uint32_t inner_loop_last = kBitsPerWordD2 - 1;
15739 Dosage* dosage_main_iter = dosage_main;
15740 char* linebuf_iter = line_iter;
15741 for (uint32_t widx = 0; ; ++widx) {
15742 if (widx >= sample_ctl2_m1) {
15743 if (widx > sample_ctl2_m1) {
15744 break;
15745 }
15746 inner_loop_last = (sample_ct - 1) % kBitsPerWordD2;
15747 }
15748 uintptr_t genovec_word = 0;
15749 uint32_t dosage_present_hw = 0;
15750 if (flags & kfPlink1DosageFormatSingle) {
15751 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
15752 if (unlikely(IsEolnKns(*linebuf_iter))) {
15753 goto Plink1DosageToPgen_ret_MISSING_TOKENS;
15754 }
15755 double a1_dosage;
15756 char* str_end = ScanadvDouble(linebuf_iter, &a1_dosage);
15757 if ((!str_end) || (a1_dosage < 0.0) || (a1_dosage > dosage_ceil)) {
15758 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
15759 linebuf_iter = FirstNonTspace(CurTokenEnd(linebuf_iter));
15760 continue;
15761 }
15762 if (unlikely(!IsSpaceOrEoln(*str_end))) {
15763 str_end = CurTokenEnd(str_end);
15764 *str_end = '\0';
15765 snprintf(g_logbuf, kLogbufSize, "Error: Invalid numeric token '%s' on line %" PRIuPTR " of --import-dosage file.\n", linebuf_iter, line_idx);
15766 goto Plink1DosageToPgen_ret_MALFORMED_INPUT_WW;
15767 }
15768 linebuf_iter = FirstNonTspace(str_end);
15769 uint32_t dosage_int = S_CAST(int32_t, a1_dosage * dosage_multiplier + 0.5);
15770 if (dosage_int > kDosageMax) {
15771 dosage_int = kDosageMax;
15772 }
15773 const uint32_t cur_halfdist = BiallelicDosageHalfdist(dosage_int);
15774 if (cur_halfdist < hard_call_halfdist) {
15775 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
15776 if (cur_halfdist < force_missing_halfdist_p1) {
15777 continue;
15778 }
15779 } else {
15780 genovec_word |= ((dosage_int + (kDosage4th * k1LU)) / kDosageMid) << (2 * sample_idx_lowbits);
15781 if (cur_halfdist >= dosage_erase_halfdist) {
15782 continue;
15783 }
15784 }
15785 dosage_present_hw |= 1U << sample_idx_lowbits;
15786 *dosage_main_iter++ = dosage_int;
15787 }
15788 } else {
15789 for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits <= inner_loop_last; ++sample_idx_lowbits) {
15790 if (unlikely(!linebuf_iter)) {
15791 goto Plink1DosageToPgen_ret_MISSING_TOKENS;
15792 }
15793 double prob_2a1;
15794 char* str_end = ScanadvDouble(linebuf_iter, &prob_2a1);
15795 if (!str_end) {
15796 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
15797 linebuf_iter = NextTokenMult(linebuf_iter, 2 + format_triple);
15798 continue;
15799 }
15800 if (unlikely(!IsSpaceOrEoln(*str_end))) {
15801 str_end = CurTokenEnd(str_end);
15802 *str_end = '\0';
15803 snprintf(g_logbuf, kLogbufSize, "Error: Invalid numeric token '%s' on line %" PRIuPTR " of --import-dosage file.\n", linebuf_iter, line_idx);
15804 goto Plink1DosageToPgen_ret_MALFORMED_INPUT_WW;
15805 }
15806 linebuf_iter = FirstNonTspace(str_end);
15807 if (unlikely(IsEolnKns(*linebuf_iter))) {
15808 goto Plink1DosageToPgen_ret_MISSING_TOKENS;
15809 }
15810 double prob_1a1;
15811 str_end = ScanadvDouble(linebuf_iter, &prob_1a1);
15812 if (!str_end) {
15813 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
15814 linebuf_iter = NextTokenMult(linebuf_iter, 1 + format_triple);
15815 continue;
15816 }
15817 if (unlikely(!IsSpaceOrEoln(*str_end))) {
15818 str_end = CurTokenEnd(str_end);
15819 *str_end = '\0';
15820 snprintf(g_logbuf, kLogbufSize, "Error: Invalid numeric token '%s' on line %" PRIuPTR " of --import-dosage file.\n", linebuf_iter, line_idx);
15821 goto Plink1DosageToPgen_ret_MALFORMED_INPUT_WW;
15822 }
15823 linebuf_iter = NextTokenMult(str_end, 1 + format_triple);
15824 double prob_one_or_two_a1 = prob_2a1 + prob_1a1;
15825 if ((prob_2a1 < 0.0) || (prob_1a1 < 0.0) || (prob_one_or_two_a1 > 1.01 * (1 + kSmallEpsilon))) {
15826 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
15827 continue;
15828 }
15829 if (prob_one_or_two_a1 > 1.0) {
15830 const double rescale = 1.0 / prob_one_or_two_a1;
15831 prob_2a1 *= rescale;
15832 prob_1a1 *= rescale;
15833 prob_one_or_two_a1 = 1.0;
15834 }
15835 if ((prob_2a1 < import_dosage_certainty) && (prob_1a1 < import_dosage_certainty) && (prob_one_or_two_a1 > 1.0 - import_dosage_certainty)) {
15836 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
15837 }
15838 const uint32_t dosage_int = S_CAST(int32_t, prob_2a1 * 32768 + prob_1a1 * 16384 + 0.5);
15839 const uint32_t cur_halfdist = BiallelicDosageHalfdist(dosage_int);
15840 if (cur_halfdist < hard_call_halfdist) {
15841 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
15842 } else {
15843 genovec_word |= ((dosage_int + (kDosage4th * k1LU)) / kDosageMid) << (2 * sample_idx_lowbits);
15844 if (cur_halfdist >= dosage_erase_halfdist) {
15845 continue;
15846 }
15847 }
15848 dosage_present_hw |= 1U << sample_idx_lowbits;
15849 *dosage_main_iter++ = dosage_int;
15850 }
15851 }
15852 genovec[widx] = genovec_word;
15853 dosage_present_hwarr[widx] = dosage_present_hw;
15854 }
15855 if (!prov_ref_allele_second) {
15856 GenovecInvertUnsafe(sample_ct, genovec);
15857 ZeroTrailingNyps(sample_ct, genovec);
15858 }
15859 if (dosage_main_iter != dosage_main) {
15860 const uint32_t dosage_ct = dosage_main_iter - dosage_main;
15861 if (!prov_ref_allele_second) {
15862 BiallelicDosage16Invert(dosage_ct, dosage_main);
15863 }
15864 uintptr_t* __attribute__((may_alias)) dosage_present_warr = R_CAST(uintptr_t*, dosage_present_hwarr);
15865 reterr = SpgwAppendBiallelicGenovecDosage16(genovec, dosage_present_warr, dosage_main, dosage_ct, &spgw);
15866 if (unlikely(reterr)) {
15867 goto Plink1DosageToPgen_ret_1;
15868 }
15869 } else {
15870 if (unlikely(SpgwAppendBiallelicGenovec(genovec, &spgw))) {
15871 goto Plink1DosageToPgen_ret_WRITE_FAIL;
15872 }
15873 }
15874 ++vidx;
15875 if (!(vidx % 1000)) {
15876 printf("\r--import-dosage: %uk variants converted.", vidx / 1000);
15877 fflush(stdout);
15878 }
15879 }
15880 reterr = SpgwFinish(&spgw);
15881 if (unlikely(reterr)) {
15882 goto Plink1DosageToPgen_ret_1;
15883 }
15884 putc_unlocked('\r', stdout);
15885 write_iter = strcpya_k(g_logbuf, "--import-dosage: ");
15886 const uint32_t outname_base_slen = outname_end - outname;
15887 write_iter = memcpya(write_iter, outname, outname_base_slen + 5);
15888 write_iter = strcpya_k(write_iter, " + ");
15889 write_iter = memcpya(write_iter, outname, outname_base_slen);
15890 write_iter = strcpya_k(write_iter, ".pvar");
15891 if (output_zst) {
15892 write_iter = strcpya_k(write_iter, ".zst");
15893 }
15894 write_iter = strcpya_k(write_iter, " + ");
15895 write_iter = memcpya(write_iter, outname, outname_base_slen);
15896 strcpy_k(write_iter, ".psam written.\n");
15897 WordWrapB(0);
15898 logputsb();
15899 }
15900 while (0) {
15901 Plink1DosageToPgen_ret_NOMEM:
15902 reterr = kPglRetNomem;
15903 break;
15904 Plink1DosageToPgen_ret_TFILE_FAIL2:
15905 if (TextFileEof(&dosage_txf)) {
15906 logerrprintfww("Error: %s is empty.\n", dosagename);
15907 reterr = kPglRetInconsistentInput;
15908 } else {
15909 TextFileErrPrint(dosagename, &dosage_txf);
15910 }
15911 break;
15912 Plink1DosageToPgen_ret_TSTREAM_REWIND1_FAIL:
15913 if (!(flags & kfPlink1DosageNoheader)) {
15914 Plink1DosageToPgen_ret_TSTREAM_REWIND2_FAIL:
15915 if ((reterr == kPglRetOpenFail) || (reterr == kPglRetEof)) {
15916 reterr = kPglRetRewindFail;
15917 }
15918 }
15919 TextStreamErrPrintRewind(dosagename, &dosage_txs, &reterr);
15920 break;
15921 Plink1DosageToPgen_ret_OPEN_FAIL:
15922 reterr = kPglRetOpenFail;
15923 break;
15924 Plink1DosageToPgen_ret_WRITE_FAIL:
15925 reterr = kPglRetWriteFail;
15926 break;
15927 Plink1DosageToPgen_ret_INVALID_CMDLINE:
15928 reterr = kPglRetInvalidCmdline;
15929 break;
15930 Plink1DosageToPgen_ret_MISSING_TOKENS:
15931 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, dosagename);
15932 Plink1DosageToPgen_ret_MALFORMED_INPUT_WW:
15933 WordWrapB(0);
15934 putc_unlocked('\n', stdout);
15935 logerrputsb();
15936 Plink1DosageToPgen_ret_MALFORMED_INPUT:
15937 reterr = kPglRetMalformedInput;
15938 break;
15939 Plink1DosageToPgen_ret_INCONSISTENT_INPUT_WW:
15940 WordWrapB(0);
15941 Plink1DosageToPgen_ret_INCONSISTENT_INPUT_2:
15942 logerrputsb();
15943 Plink1DosageToPgen_ret_INCONSISTENT_INPUT:
15944 reterr = kPglRetInconsistentInput;
15945 break;
15946 Plink1DosageToPgen_ret_DEGENERATE_DATA:
15947 reterr = kPglRetDegenerateData;
15948 break;
15949 }
15950 Plink1DosageToPgen_ret_1:
15951 CleanupSpgw(&spgw, &reterr);
15952 fclose_cond(psamfile);
15953 CswriteCloseCond(&pvar_css, pvar_cswritep);
15954 CleanupTextFile2(dosagename, &dosage_txf, &reterr);
15955 CleanupTextStream2(dosagename, &dosage_txs, &reterr);
15956 free_cond(pheno_names);
15957 CleanupPhenoCols(pheno_ct, pheno_cols);
15958 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
15959 return reterr;
15960 }
15961
15962
15963 typedef struct GenerateDummyCtxStruct {
15964 uint32_t sample_ct;
15965 // binary search over cdf is faster than (int)(log(drand)/log(q)) for
15966 // truncated geometric distribution
15967 STD_ARRAY_DECL(uint64_t, kBitsPerWordD2, phase_geomdist);
15968 STD_ARRAY_DECL(uint64_t, kBitsPerWordD2, dosage_geomdist);
15969 uint32_t phase_invert;
15970 uint32_t dosage_geomdist_max;
15971 uint32_t hard_call_halfdist;
15972 uint32_t dosage_erase_halfdist;
15973
15974 uint32_t geno3_thresh_ct;
15975 // Usually (<nonmissing geno freq> * 2^32).
15976 // If <nonmissing geno freq> is in (0, 1e-7), it's rounded up to 1e-7 so that
15977 // discretization doesn't really interfere with Hardy-Weinberg equilibrium.
15978 uint64_t* geno3_thresh_arr;
15979
15980 sfmt_t** sfmtp_arr;
15981
15982 uint32_t cur_block_write_ct;
15983
15984 uintptr_t* write_genovecs[2];
15985 uintptr_t* write_phasepresents[2];
15986 uintptr_t* write_phaseinfos[2];
15987 uint32_t* write_dosage_cts[2];
15988 uintptr_t* write_dosage_presents[2];
15989 Dosage* write_dosage_mains[2];
15990 uint32_t* write_dphase_cts[2];
15991 uintptr_t* write_dphase_presents[2];
15992 SDosage* write_dphase_deltas[2];
15993 } GenerateDummyCtx;
15994
15995 static_assert(sizeof(Dosage) == 2, "GenerateDummyThread() needs to be updated.");
15996 THREAD_FUNC_DECL GenerateDummyThread(void* raw_arg) {
15997 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
15998 const uintptr_t tidx = arg->tidx;
15999 GenerateDummyCtx* ctx = S_CAST(GenerateDummyCtx*, arg->sharedp->context);
16000
16001 const uint32_t sample_ct = ctx->sample_ct;
16002 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
16003 STD_ARRAY_KREF(uint64_t, kBitsPerWordD2) phase_geomdist = ctx->phase_geomdist;
16004 STD_ARRAY_KREF(uint64_t, kBitsPerWordD2) dosage_geomdist = ctx->dosage_geomdist;
16005 const uint32_t geno3_thresh_ct = ctx->geno3_thresh_ct;
16006 const uint64_t* geno3_thresh_arr = ctx->geno3_thresh_arr;
16007 const uint32_t phase_invert = ctx->phase_invert;
16008 const uint32_t phase_is_variable = (phase_geomdist[kBitsPerWordD2 - 1] != 0);
16009 const uint32_t phase_exists = phase_invert || phase_is_variable;
16010 const uint32_t dosage_geomdist_max = ctx->dosage_geomdist_max;
16011 const uint32_t dosage_exists = (dosage_geomdist_max != kBitsPerWord);
16012 const uint32_t hard_call_halfdist = ctx->hard_call_halfdist;
16013 const uint32_t dosage_erase_halfdist = ctx->dosage_erase_halfdist;
16014 const uintptr_t sample_ctaw2 = NypCtToAlignedWordCt(sample_ct);
16015 const uint32_t sample_ctl2_m1 = (sample_ct - 1) / kBitsPerWordD2;
16016 const uintptr_t sample_ctaw = BitCtToAlignedWordCt(sample_ct);
16017 sfmt_t* sfmtp = ctx->sfmtp_arr[tidx];
16018 uint64_t u64rand = sfmt_genrand_uint64(sfmtp);
16019 uint32_t rand16_left = 4;
16020 uint32_t ld_denom = 0;
16021 uint32_t ld_invert = 0;
16022 double afreq = sfmt_to_res53(sfmt_genrand_uint64(sfmtp));
16023 uint64_t geno3_thresh = 1LLU << 32;
16024 double geno3_thresh_d = 4294967296.0;
16025 if (geno3_thresh_ct) {
16026 uint32_t uii = 0;
16027 if (geno3_thresh_ct > 1) {
16028 // assumes rand16_left != 0
16029 uii = ((u64rand & 65535) * geno3_thresh_ct) >> 16;
16030 --rand16_left;
16031 }
16032 geno3_thresh = geno3_thresh_arr[uii];
16033 geno3_thresh_d = u63tod(geno3_thresh);
16034 }
16035 uint32_t parity = 0;
16036 do {
16037 const uintptr_t cur_block_write_ct = ctx->cur_block_write_ct;
16038 uint32_t vidx = (tidx * cur_block_write_ct) / calc_thread_ct;
16039 const uint32_t vidx_end = ((tidx + 1) * cur_block_write_ct) / calc_thread_ct;
16040 uintptr_t* write_genovec_iter = &(ctx->write_genovecs[parity][vidx * sample_ctaw2]);
16041 Halfword* write_phasepresent_iter = DowncastWToHW(&(ctx->write_phasepresents[parity][vidx * sample_ctaw]));
16042 Halfword* write_phaseinfo_iter = DowncastWToHW(&(ctx->write_phaseinfos[parity][vidx * sample_ctaw]));
16043 uint32_t* write_dosage_ct_iter = &(ctx->write_dosage_cts[parity][vidx]);
16044 Halfword* write_dosage_present_iter = DowncastWToHW(&(ctx->write_dosage_presents[parity][vidx * sample_ctaw]));
16045 Dosage* write_dosage_main_iter = &(ctx->write_dosage_mains[parity][vidx * sample_ct]);
16046 uint32_t* write_dphase_ct_iter = &(ctx->write_dphase_cts[parity][vidx]);
16047 Halfword* write_dphase_present_iter = DowncastWToHW(&(ctx->write_dphase_presents[parity][vidx * sample_ctaw]));
16048 SDosage* write_dphase_delta_iter = &(ctx->write_dphase_deltas[parity][vidx * sample_ct]);
16049 uintptr_t* prev_genovec = nullptr;
16050 for (; vidx != vidx_end; ++vidx) {
16051 Dosage* cur_dosage_main_iter = write_dosage_main_iter;
16052 SDosage* cur_dphase_delta_iter = write_dphase_delta_iter;
16053 uint64_t geno1_thresh;
16054 uint64_t geno2_thresh;
16055 {
16056 const uint64_t cur_rand64 = sfmt_genrand_uint64(sfmtp);
16057 // ~50% chance of high LD
16058 if (cur_rand64 & 1) {
16059 prev_genovec = nullptr;
16060 // Only update allele and missing frequencies if not simulating LD.
16061
16062 // Could make this follow e.g. a beta(0.2, 0.2) distribution, but
16063 // that's unimportant for software testing, so I won't bother
16064 // unless/until that inverse-CDF is already implemented in this
16065 // codebase for some reason.
16066 afreq = sfmt_to_res53(cur_rand64);
16067 if (geno3_thresh_ct > 1) {
16068 if (!rand16_left) {
16069 u64rand = sfmt_genrand_uint64(sfmtp);
16070 rand16_left = 4;
16071 }
16072 const uint32_t uii = ((u64rand & 65535) * geno3_thresh_ct) >> 16;
16073 u64rand >>= 16;
16074 --rand16_left;
16075 geno3_thresh = geno3_thresh_arr[uii];
16076 geno3_thresh_d = u63tod(geno3_thresh);
16077 }
16078 } else {
16079 // When generating a genovec_word in high LD with the previous one,
16080 // we use the following process to select positions to generate a
16081 // new genotype:
16082 // 1. Draw a uint16.
16083 // 2. Multiply by ld_denom, and right-shift 16 (Lemire's fast
16084 // alternative to the modulo reduction).
16085 // 3. If this is >= loop_len, stop selecting. Otherwise, generate a
16086 // new genotype for this value of sample_idx_lowbits.
16087 // Our chance of continuing the loop is r=(loop_len/ld_denom) on each
16088 // iteration, so the expected number of iterations is
16089 // r/(1-r) = loop_len / (ld_denom - loop_len).
16090 // Given a target genotype-reselection rate of R, we want this last
16091 // expectation to be near R*loop_len. (Technically a bit larger,
16092 // since we're sampling with replacement, but we only need this
16093 // calculation to hit the right ballpark.) Solving this equation:
16094 // R * loop_len = loop_len / (ld_denom - loop_len)
16095 // R = 1 / (ld_denom - loop_len)
16096 // ld_denom - loop_len = 1 / R
16097 // ld_denom = loop_len + (1 / R)
16098 // Since the chance of regenerating the same genotype as before is
16099 // sometimes smaller than 1/2 but never by that much, choosing R =
16100 // (2 / kPglMaxDifflistLenDivisor) should test a mix of
16101 // LD-compression and not-quite-LD-compression cases, while smaller
16102 // values of R test the former more heavily.
16103 const uint32_t rand_shift = (cur_rand64 >> 1) & 3;
16104 ld_denom = kBitsPerWordD2 + ((kPglMaxDifflistLenDivisor / 2) << rand_shift);
16105 // 1/16 chance of LD-invert.
16106 ld_invert = ((cur_rand64 & 120) == 120);
16107 }
16108 const double inv_afreq = 1.0 - afreq;
16109 // respect Hardy-Weinberg equilibrium
16110 geno1_thresh = S_CAST(int64_t, geno3_thresh_d * afreq * afreq);
16111 geno2_thresh = S_CAST(int64_t, geno3_thresh_d * (1.0 - inv_afreq * inv_afreq));
16112 }
16113 uint32_t loop_len = kBitsPerWordD2;
16114 uint32_t loop_len_d2 = kBitsPerWordD4;
16115 for (uint32_t widx = 0; ; ++widx) {
16116 if (widx >= sample_ctl2_m1) {
16117 if (widx > sample_ctl2_m1) {
16118 break;
16119 }
16120 loop_len = ModNz(sample_ct, kBitsPerWordD2);
16121 loop_len_d2 = loop_len / 2;
16122 if (prev_genovec) {
16123 ld_denom = ld_denom + loop_len - kBitsPerWordD2;
16124 }
16125 }
16126 uintptr_t genovec_word;
16127 if (!prev_genovec) {
16128 genovec_word = 0;
16129 for (uint32_t rand_idx = 0; rand_idx != loop_len_d2; ++rand_idx) {
16130
16131 // sfmt_genrand_uint64 calls can't be mixed with
16132 // sfmt_genrand_uint32 calls, so use it here even in 32-bit build
16133 const uint64_t cur_rand = sfmt_genrand_uint64(sfmtp);
16134 const uintptr_t rand_lowbits = cur_rand & UINT32_MAX;
16135 uintptr_t cur_geno;
16136 if (rand_lowbits >= geno2_thresh) {
16137 cur_geno = 2 + (rand_lowbits >= geno3_thresh);
16138 } else {
16139 cur_geno = (rand_lowbits >= geno1_thresh);
16140 }
16141 genovec_word = genovec_word << 2;
16142 genovec_word |= cur_geno;
16143 const uintptr_t rand_highbits = cur_rand >> 32;
16144 if (rand_highbits >= geno2_thresh) {
16145 cur_geno = 2 + (rand_highbits >= geno3_thresh);
16146 } else {
16147 cur_geno = (rand_highbits >= geno1_thresh);
16148 }
16149 genovec_word = genovec_word << 2;
16150 genovec_word |= cur_geno;
16151 }
16152 if (loop_len % 2) {
16153 const uintptr_t rand_lowbits = sfmt_genrand_uint64(sfmtp) & UINT32_MAX;
16154 uintptr_t cur_geno;
16155 if (rand_lowbits >= geno2_thresh) {
16156 cur_geno = 2 + (rand_lowbits >= geno3_thresh);
16157 } else {
16158 cur_geno = (rand_lowbits >= geno1_thresh);
16159 }
16160 genovec_word = genovec_word << 2;
16161 genovec_word |= cur_geno;
16162 }
16163 } else {
16164 genovec_word = prev_genovec[widx];
16165 if (ld_invert) {
16166 genovec_word = InvertGenoWordUnsafe(genovec_word);
16167 genovec_word = bzhi_max(genovec_word, loop_len * 2);
16168 }
16169 while (1) {
16170 if (!rand16_left) {
16171 u64rand = sfmt_genrand_uint64(sfmtp);
16172 rand16_left = 4;
16173 }
16174 const uint32_t sample_idx_lowbits = ((u64rand & 65535) * ld_denom) >> 16;
16175 u64rand >>= 16;
16176 --rand16_left;
16177 if (sample_idx_lowbits >= loop_len) {
16178 break;
16179 }
16180 if (rand16_left < 2) {
16181 u64rand = sfmt_genrand_uint64(sfmtp);
16182 rand16_left = 4;
16183 }
16184 const uintptr_t rand_lowbits = u64rand & UINT32_MAX;
16185 u64rand >>= 32;
16186 rand16_left -= 2;
16187 uintptr_t cur_geno;
16188 if (rand_lowbits >= geno2_thresh) {
16189 cur_geno = 2 + (rand_lowbits >= geno3_thresh);
16190 } else {
16191 cur_geno = (rand_lowbits >= geno1_thresh);
16192 }
16193 const uint32_t bit_shift_ct = sample_idx_lowbits * 2;
16194 genovec_word &= ~((3 * k1LU) << bit_shift_ct);
16195 genovec_word |= cur_geno << bit_shift_ct;
16196 }
16197 }
16198 // set phasepresent bits may correspond to missing or homozygous calls;
16199 // that's resolved later.
16200 uint32_t phasepresent_possible_hw = 0;
16201 uint32_t phaseinfo_hw = 0;
16202 if (phase_exists) {
16203 if (phase_is_variable) {
16204 uint32_t sample_idx_lowbits = 0;
16205 while (1) {
16206 sample_idx_lowbits += UpperBoundNonemptyU64(&phase_geomdist[0], kBitsPerWordD2, sfmt_genrand_uint64(sfmtp));
16207 if (sample_idx_lowbits >= loop_len) {
16208 break;
16209 }
16210 phasepresent_possible_hw |= 1U << sample_idx_lowbits;
16211 ++sample_idx_lowbits;
16212 }
16213 }
16214 if (phase_invert) {
16215 phasepresent_possible_hw = S_CAST(Halfword, ~phasepresent_possible_hw);
16216 }
16217 const uint32_t kInt16PerHalfword = (kBitsPerWord / 2) / 16;
16218 if (rand16_left < kInt16PerHalfword) {
16219 u64rand = sfmt_genrand_uint64(sfmtp);
16220 rand16_left = 4;
16221 }
16222 phaseinfo_hw = S_CAST(Halfword, u64rand);
16223 u64rand >>= kBitsPerWord / 2;
16224 rand16_left -= kInt16PerHalfword;
16225 }
16226 uint32_t dosage_present_hw = 0;
16227 uint32_t dphase_present_hw = 0;
16228 if (dosage_exists) {
16229 // deliberate overflow
16230 uint32_t sample_idx_lowbits = UINT32_MAX;
16231 while (1) {
16232 ++sample_idx_lowbits;
16233 if (dosage_geomdist_max) {
16234 sample_idx_lowbits += UpperBoundNonemptyU64(&dosage_geomdist[0], dosage_geomdist_max, sfmt_genrand_uint64(sfmtp));
16235 }
16236 if (sample_idx_lowbits >= loop_len) {
16237 break;
16238 }
16239 if (((genovec_word >> (2 * sample_idx_lowbits)) & 3) == 3) {
16240 continue;
16241 }
16242 if (!rand16_left) {
16243 u64rand = sfmt_genrand_uint64(sfmtp);
16244 rand16_left = 4;
16245 }
16246 // possible todo: make this respect simulated allele frequency
16247 //
16248 // repeated squaring provides a quick and dirty way to do this,
16249 // e.g. square a uniform 0..1-scaled value 4 times to get an
16250 // expectation of 1/17.
16251 const uint32_t dosage_int = ((u64rand & 65535) + 1) / 2;
16252 u64rand >>= 16;
16253 --rand16_left;
16254 const uint32_t halfdist = BiallelicDosageHalfdist(dosage_int);
16255 if (halfdist < dosage_erase_halfdist) {
16256 *cur_dosage_main_iter++ = dosage_int;
16257 const uint32_t shifted_bit = 1U << sample_idx_lowbits;
16258 dosage_present_hw |= shifted_bit;
16259 if (phasepresent_possible_hw & shifted_bit) {
16260 dphase_present_hw |= shifted_bit;
16261 int32_t cur_dphase_delta = DosageHomdist(dosage_int);
16262 // To test both the maximum-difference and the
16263 // nonmaximal-difference cases, we subtract 1 from this number
16264 // if it's even.
16265 //
16266 // Note that, as of this writing, pgenlib_write
16267 // AppendDphase16() does *not* omit a dphase_delta entry when
16268 // the implicit value inferred from hardcall-phase and dosage
16269 // would be correct. It is the caller's responsibility to
16270 // exploit this case. (MakePgenThread doesn't do this, maybe
16271 // it should. Exporting to VCF/BCF and re-importing does do
16272 // the trick.)
16273 cur_dphase_delta -= 1 - (cur_dphase_delta & 1);
16274 if (!(phaseinfo_hw & shifted_bit)) {
16275 cur_dphase_delta = -cur_dphase_delta;
16276 }
16277 *cur_dphase_delta_iter++ = cur_dphase_delta;
16278 }
16279 if (halfdist < hard_call_halfdist) {
16280 genovec_word |= (3 * k1LU) << (2 * sample_idx_lowbits);
16281 continue;
16282 }
16283 }
16284 genovec_word &= ~((3 * k1LU) << (2 * sample_idx_lowbits));
16285 genovec_word |= ((dosage_int + (kDosage4th * k1LU)) / kDosageMid) << (2 * sample_idx_lowbits);
16286 }
16287 }
16288 write_genovec_iter[widx] = genovec_word;
16289 const uint32_t cur_hets = Pack01ToHalfword(genovec_word);
16290 const uint32_t phasepresent_hw = phasepresent_possible_hw & cur_hets;
16291 write_phasepresent_iter[widx] = phasepresent_hw;
16292 write_phaseinfo_iter[widx] = phaseinfo_hw & phasepresent_hw;
16293 write_dosage_present_iter[widx] = dosage_present_hw;
16294 write_dphase_present_iter[widx] = dphase_present_hw;
16295 }
16296 ZeroTrailingNyps(sample_ct, write_genovec_iter);
16297 uintptr_t* __attribute__((may_alias)) write_phasepresent_warr = R_CAST(uintptr_t*, write_phasepresent_iter);
16298 uintptr_t* __attribute__((may_alias)) write_phaseinfo_warr = R_CAST(uintptr_t*, write_phaseinfo_iter);
16299 uintptr_t* __attribute__((may_alias)) write_dosage_present_warr = R_CAST(uintptr_t*, write_dosage_present_iter);
16300 ZeroTrailingBits(sample_ct, write_phasepresent_warr);
16301 ZeroTrailingBits(sample_ct, write_phaseinfo_warr);
16302 ZeroTrailingBits(sample_ct, write_dosage_present_warr);
16303 const uint32_t dosage_ct = cur_dosage_main_iter - write_dosage_main_iter;
16304 *write_dosage_ct_iter++ = dosage_ct;
16305 const uint32_t dphase_ct = cur_dphase_delta_iter - write_dphase_delta_iter;
16306 *write_dphase_ct_iter++ = dphase_ct;
16307 prev_genovec = write_genovec_iter;
16308 write_genovec_iter = &(write_genovec_iter[sample_ctaw2]);
16309 write_phasepresent_iter = &(write_phasepresent_iter[2 * sample_ctaw]);
16310 write_phaseinfo_iter = &(write_phaseinfo_iter[2 * sample_ctaw]);
16311 write_dosage_present_iter = &(write_dosage_present_iter[2 * sample_ctaw]);
16312 write_dosage_main_iter = &(write_dosage_main_iter[sample_ct]);
16313 write_dphase_present_iter = &(write_dphase_present_iter[2 * sample_ctaw]);
16314 write_dphase_delta_iter = &(write_dphase_delta_iter[sample_ct]);
16315 }
16316 parity = 1 - parity;
16317 } while (!THREAD_BLOCK_FINISH(arg));
16318 THREAD_RETURN;
16319 }
16320
16321 static_assert(sizeof(Dosage) == 2, "GenerateDummy() needs to be updated.");
16322 PglErr GenerateDummy(const GenDummyInfo* gendummy_info_ptr, MiscFlags misc_flags, ImportFlags import_flags, uint32_t psam_01, uint32_t hard_call_thresh, uint32_t dosage_erase_thresh, uint32_t max_thread_ct, sfmt_t* sfmtp, char* outname, char* outname_end, ChrInfo* cip) {
16323 unsigned char* bigstack_mark = g_bigstack_base;
16324 FILE* psamfile = nullptr;
16325 char* pvar_cswritep = nullptr;
16326 CompressStreamState pvar_css;
16327 PreinitCstream(&pvar_css);
16328 ThreadGroup tg;
16329 PreinitThreads(&tg);
16330 STPgenWriter spgw;
16331 PglErr reterr = kPglRetSuccess;
16332 PreinitSpgw(&spgw);
16333 {
16334 FinalizeChrset(misc_flags, cip);
16335 if (unlikely(!IsSet(cip->chr_mask, 1))) {
16336 logerrputs("Error: --dummy cannot be used when chromosome 1 is excluded.\n");
16337 goto GenerateDummy_ret_INVALID_CMDLINE;
16338 }
16339 if (unlikely(IsSet(cip->haploid_mask, 1))) {
16340 logerrputs("Error: --dummy cannot be used to generate haploid data.\n");
16341 goto GenerateDummy_ret_INVALID_CMDLINE;
16342 }
16343 char chr1_name_buf[5];
16344 char* chr1_name_end = chrtoa(cip, 1, chr1_name_buf);
16345 *chr1_name_end = '\t';
16346 const uint32_t chr1_name_blen = 1 + S_CAST(uintptr_t, chr1_name_end - chr1_name_buf);
16347 const uint32_t sample_ct = gendummy_info_ptr->sample_ct;
16348 const uint32_t variant_ct = gendummy_info_ptr->variant_ct;
16349 // missing pheno string is always "NA"
16350 const GenDummyFlags flags = gendummy_info_ptr->flags;
16351 uint16_t alleles[13];
16352 uint32_t four_alleles = 0;
16353 if (flags & kfGenDummyAcgt) {
16354 memcpy_k(alleles, "\tA\tC\tA\tG\tA\tT\tC\tG\tC\tT\tG\tT\tA", 26);
16355 four_alleles = 1;
16356 } else if (flags & kfGenDummy1234) {
16357 memcpy_k(alleles, "\t1\t2\t1\t3\t1\t4\t2\t3\t2\t4\t3\t4\t1", 26);
16358 four_alleles = 1;
16359 } else if (flags & kfGenDummy12) {
16360 memcpy_k(alleles, "\t1\t2\t1", 6);
16361 } else {
16362 memcpy_k(alleles, "\tA\tB\tA", 6);
16363 }
16364
16365 snprintf(outname_end, kMaxOutfnameExtBlen, ".pvar");
16366 const uint32_t output_zst = (import_flags / kfImportKeepAutoconvVzs) & 1;
16367 if (output_zst) {
16368 snprintf(&(outname_end[5]), kMaxOutfnameExtBlen - 5, ".zst");
16369 }
16370 const uintptr_t overflow_buf_size = 2 * kCompressStreamBlock;
16371 reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, overflow_buf_size, &pvar_css, &pvar_cswritep);
16372 if (unlikely(reterr)) {
16373 goto GenerateDummy_ret_1;
16374 }
16375 pvar_cswritep = strcpya_k(pvar_cswritep, "#CHROM\tPOS\tID\tREF\tALT");
16376 AppendBinaryEoln(&pvar_cswritep);
16377 if (four_alleles) {
16378 uint32_t urand = 0;
16379 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
16380 if (!(variant_idx % 8)) {
16381 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
16382 goto GenerateDummy_ret_WRITE_FAIL;
16383 }
16384 do {
16385 urand = sfmt_genrand_uint32(sfmtp);
16386 } while (urand < 425132032U); // 2^32 - 12^8
16387 }
16388 const uint32_t quotient = urand / 12;
16389 const uint32_t remainder = urand - (quotient * 12U);
16390 urand = quotient;
16391 pvar_cswritep = memcpya(pvar_cswritep, chr1_name_buf, chr1_name_blen);
16392 pvar_cswritep = u32toa(variant_idx, pvar_cswritep);
16393 pvar_cswritep = strcpya_k(pvar_cswritep, "\tsnp");
16394 pvar_cswritep = u32toa(variant_idx, pvar_cswritep);
16395 pvar_cswritep = memcpya(pvar_cswritep, &(alleles[remainder]), 4);
16396 AppendBinaryEoln(&pvar_cswritep);
16397 }
16398 } else {
16399 uint32_t urand = 0;
16400 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
16401 if (!(variant_idx % 32)) {
16402 if (unlikely(Cswrite(&pvar_css, &pvar_cswritep))) {
16403 goto GenerateDummy_ret_WRITE_FAIL;
16404 }
16405 urand = sfmt_genrand_uint32(sfmtp);
16406 }
16407 const uint32_t remainder = urand & 1;
16408 urand >>= 1;
16409 pvar_cswritep = memcpya(pvar_cswritep, chr1_name_buf, chr1_name_blen);
16410 pvar_cswritep = u32toa(variant_idx, pvar_cswritep);
16411 pvar_cswritep = strcpya_k(pvar_cswritep, "\tsnp");
16412 pvar_cswritep = u32toa(variant_idx, pvar_cswritep);
16413 pvar_cswritep = memcpya(pvar_cswritep, &(alleles[remainder]), 4);
16414 AppendBinaryEoln(&pvar_cswritep);
16415 }
16416 }
16417 if (unlikely(CswriteCloseNull(&pvar_css, pvar_cswritep))) {
16418 goto GenerateDummy_ret_WRITE_FAIL;
16419 }
16420 BigstackReset(bigstack_mark);
16421
16422 snprintf(outname_end, kMaxOutfnameExtBlen, ".psam");
16423 if (unlikely(fopen_checked(outname, FOPEN_WB, &psamfile))) {
16424 goto GenerateDummy_ret_OPEN_FAIL;
16425 }
16426 const uint32_t pheno_ct = gendummy_info_ptr->pheno_ct;
16427 char* writebuf;
16428 if (unlikely(bigstack_alloc_c(kMaxMediumLine + 48 + pheno_ct * MAXV(kMaxMissingPhenostrBlen, 16), &writebuf))) {
16429 goto GenerateDummy_ret_NOMEM;
16430 }
16431 char* writebuf_flush = &(writebuf[kMaxMediumLine]);
16432 // Alpha 2 change: no more FID column
16433 char* write_iter = strcpya_k(writebuf, "#IID\tSEX");
16434 for (uint32_t pheno_idx_p1 = 1; pheno_idx_p1 <= pheno_ct; ++pheno_idx_p1) {
16435 write_iter = strcpya_k(write_iter, "\tPHENO");
16436 write_iter = u32toa(pheno_idx_p1, write_iter);
16437 }
16438 AppendBinaryEoln(&write_iter);
16439 const uint32_t pheno_m_check = (gendummy_info_ptr->pheno_mfreq >= kRecip2m32 * 0.5);
16440 const uint32_t pheno_m32 = S_CAST(uint32_t, gendummy_info_ptr->pheno_mfreq * 4294967296.0 - 0.5);
16441 if ((flags & kfGenDummyScalarPheno) && pheno_ct) {
16442 uint32_t saved_rnormal = 0;
16443 double saved_rnormal_val = 0.0;
16444 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
16445 if (unlikely(fwrite_ck(writebuf_flush, psamfile, &write_iter))) {
16446 goto GenerateDummy_ret_WRITE_FAIL;
16447 }
16448 write_iter = strcpya_k(write_iter, "per");
16449 write_iter = u32toa(sample_idx, write_iter);
16450 // could add option to add some males/unknown gender
16451 write_iter = strcpya_k(write_iter, "\t2");
16452 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
16453 *write_iter++ = '\t';
16454 if (pheno_m_check && (sfmt_genrand_uint32(sfmtp) <= pheno_m32)) {
16455 write_iter = strcpya_k(write_iter, "NA");
16456 } else {
16457 double dxx;
16458 if (saved_rnormal) {
16459 dxx = saved_rnormal_val;
16460 } else {
16461 dxx = RandNormal(sfmtp, &saved_rnormal_val);
16462 }
16463 saved_rnormal_val = 1 - saved_rnormal_val;
16464 write_iter = dtoa_g(dxx, write_iter);
16465 }
16466 }
16467 AppendBinaryEoln(&write_iter);
16468 }
16469 } else {
16470 uint32_t urand = sfmt_genrand_uint32(sfmtp);
16471 uint32_t urand_bits_left = 32;
16472 const char ctrl_char = '1' - psam_01;
16473 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
16474 if (unlikely(fwrite_ck(writebuf_flush, psamfile, &write_iter))) {
16475 goto GenerateDummy_ret_WRITE_FAIL;
16476 }
16477 // bugfix (9 Mar 2018): forgot to remove FID column here
16478 write_iter = strcpya_k(write_iter, "per");
16479 write_iter = u32toa(sample_idx, write_iter);
16480 write_iter = strcpya_k(write_iter, "\t2");
16481 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
16482 *write_iter++ = '\t';
16483 if (pheno_m_check && (sfmt_genrand_uint32(sfmtp) <= pheno_m32)) {
16484 write_iter = strcpya_k(write_iter, "NA");
16485 } else {
16486 if (!urand_bits_left) {
16487 urand = sfmt_genrand_uint32(sfmtp);
16488 urand_bits_left = 32;
16489 }
16490 *write_iter++ = (urand & 1) + ctrl_char;
16491 urand >>= 1;
16492 --urand_bits_left;
16493 }
16494 }
16495 AppendBinaryEoln(&write_iter);
16496 }
16497 }
16498 if (unlikely(fclose_flush_null(writebuf_flush, write_iter, &psamfile))) {
16499 goto GenerateDummy_ret_WRITE_FAIL;
16500 }
16501
16502 BigstackReset(writebuf);
16503 snprintf(outname_end, kMaxOutfnameExtBlen, ".pgen");
16504 GenerateDummyCtx ctx;
16505 {
16506 const uint32_t geno_mfreq_ct = gendummy_info_ptr->geno_mfreq_ct;
16507 ctx.geno3_thresh_ct = geno_mfreq_ct;
16508 ctx.geno3_thresh_arr = nullptr;
16509 if (geno_mfreq_ct) {
16510 if (unlikely(geno_mfreq_ct > 65536)) {
16511 logerrputs("Error: --dummy is limited to 65536 missing-dosage frequencies.\n");
16512 goto GenerateDummy_ret_INVALID_CMDLINE;
16513 }
16514 uint32_t warning_9999999 = 0;
16515 if (unlikely(bigstack_alloc_u64(geno_mfreq_ct, &ctx.geno3_thresh_arr))) {
16516 goto GenerateDummy_ret_NOMEM;
16517 }
16518 const double* geno_mfreqs = gendummy_info_ptr->geno_mfreqs;
16519 for (uint32_t uii = 0; uii != geno_mfreq_ct; ++uii) {
16520 double nm_freq = 1.0 - geno_mfreqs[uii];
16521 if ((nm_freq < 1e-7) && (nm_freq > 0.0)) {
16522 warning_9999999 = 1;
16523 nm_freq = 1e-7;
16524 }
16525 ctx.geno3_thresh_arr[uii] = S_CAST(int64_t, nm_freq * 4294967296.0);
16526 }
16527 if (warning_9999999) {
16528 logerrputs("Warning: reducing missing dosage freq(s) in (0.9999999, 1) to 0.9999999.\n");
16529 }
16530 }
16531 }
16532 const double phase_freq = gendummy_info_ptr->phase_freq;
16533 ctx.phase_invert = 0;
16534 const uint32_t is_phased = (phase_freq >= kRecip2m53);
16535 if (!is_phased) {
16536 ctx.phase_geomdist[kBitsPerWordD2 - 1] = 0;
16537 } else {
16538 double remaining_prob = 1.0;
16539 ctx.phase_invert = (phase_freq > 0.5);
16540 if (ctx.phase_invert) {
16541 for (uint32_t uii = 0; uii != kBitsPerWordD2; ++uii) {
16542 remaining_prob *= phase_freq;
16543 ctx.phase_geomdist[uii] = -S_CAST(uint64_t, remaining_prob * k2m64);
16544 }
16545 } else {
16546 const double phase_nfreq = 1.0 - phase_freq;
16547 for (uint32_t uii = 0; uii != kBitsPerWordD2; ++uii) {
16548 remaining_prob *= phase_nfreq;
16549 ctx.phase_geomdist[uii] = -S_CAST(uint64_t, remaining_prob * k2m64);
16550 }
16551 }
16552 }
16553 const double dosage_nfreq = 1.0 - gendummy_info_ptr->dosage_freq;
16554 if (dosage_nfreq >= 1.0) {
16555 ctx.dosage_geomdist_max = kBitsPerWord; // used as a flag
16556 } else {
16557 double remaining_prob = 1.0;
16558 for (uint32_t uii = 0; uii != kBitsPerWordD2; ++uii) {
16559 remaining_prob *= dosage_nfreq;
16560 ctx.dosage_geomdist[uii] = -S_CAST(uint64_t, remaining_prob * k2m64);
16561 }
16562 uint32_t dosage_geomdist_max = kBitsPerWordD2;
16563 for (; dosage_geomdist_max; --dosage_geomdist_max) {
16564 if (ctx.dosage_geomdist[dosage_geomdist_max - 1] != 0) {
16565 break;
16566 }
16567 }
16568 ctx.dosage_geomdist_max = dosage_geomdist_max;
16569 }
16570 PgenGlobalFlags gflags = kfPgenGlobal0;
16571 if (is_phased) {
16572 gflags |= kfPgenGlobalHardcallPhasePresent;
16573 }
16574 if (dosage_nfreq < 1.0) {
16575 gflags |= kfPgenGlobalDosagePresent;
16576 }
16577 uintptr_t spgw_alloc_cacheline_ct;
16578 uint32_t max_vrec_len;
16579 reterr = SpgwInitPhase1(outname, nullptr, nullptr, variant_ct, sample_ct, 0, kPgenWriteBackwardSeek, gflags, 1, &spgw, &spgw_alloc_cacheline_ct, &max_vrec_len);
16580 if (unlikely(reterr)) {
16581 if (reterr == kPglRetOpenFail) {
16582 logerrprintfww(kErrprintfFopen, outname, strerror(errno));
16583 }
16584 goto GenerateDummy_ret_1;
16585 }
16586 unsigned char* spgw_alloc;
16587 if (unlikely(bigstack_alloc_uc(spgw_alloc_cacheline_ct * kCacheline, &spgw_alloc))) {
16588 goto GenerateDummy_ret_NOMEM;
16589 }
16590 SpgwInitPhase2(max_vrec_len, &spgw, spgw_alloc);
16591
16592 // thread-count-independent:
16593 // (everything after "2 *" rounded up to cacheline)
16594 // ctx.write_genovecs: 2 * sample_ctaw2 * sizeof(intptr_t) *
16595 // main_block_size
16596 // ctx.write_dosage_cts: 2 * sizeof(int32_t) * main_block_size
16597 // ctx.write_dosage_presents: 2 * sample_ctaw * sizeof(intptr_t) *
16598 // main_block_size
16599 // ctx.write_dosage_mains: 2 * sample_ct * sizeof(Dosage)
16600 uint32_t calc_thread_ct = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
16601 // saturates around 4 compute threads, both with and without dosage
16602 // (todo: test this on something other than a MacBook Pro, could just be a
16603 // hyperthreading artifact)
16604 if (calc_thread_ct > 4) {
16605 calc_thread_ct = 4;
16606 }
16607 if (unlikely(InitAllocSfmtpArr(calc_thread_ct, 0, sfmtp, &ctx.sfmtp_arr))) {
16608 goto GenerateDummy_ret_NOMEM;
16609 }
16610 const uint32_t sample_ctaw2 = NypCtToAlignedWordCt(sample_ct);
16611 const uint32_t sample_ctaw = BitCtToAlignedWordCt(sample_ct);
16612 // we're making 18 allocations; be pessimistic re: rounding
16613 uintptr_t cachelines_avail_m18 = bigstack_left() / kCacheline;
16614 if (unlikely(cachelines_avail_m18 < 18)) {
16615 goto GenerateDummy_ret_NOMEM;
16616 }
16617 cachelines_avail_m18 -= 18;
16618 const uintptr_t bytes_req_per_in_block_variant = 2 * (sample_ctaw2 * sizeof(intptr_t) + 2 * sizeof(int32_t) + sample_ctaw * 4 * sizeof(intptr_t) + sample_ct * 2 * sizeof(Dosage));
16619 uintptr_t main_block_size = (cachelines_avail_m18 * kCacheline) / bytes_req_per_in_block_variant;
16620 if (main_block_size > 65536) {
16621 main_block_size = 65536;
16622 } else if (unlikely(main_block_size < 8)) {
16623 // this threshold is arbitrary
16624 goto GenerateDummy_ret_NOMEM;
16625 }
16626 if (calc_thread_ct > main_block_size / 8) {
16627 calc_thread_ct = main_block_size / 8;
16628 }
16629 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
16630 goto GenerateDummy_ret_NOMEM;
16631 }
16632 ctx.sample_ct = sample_ct;
16633 if (unlikely(bigstack_alloc_w(sample_ctaw2 * main_block_size, &(ctx.write_genovecs[0])) ||
16634 bigstack_alloc_w(sample_ctaw2 * main_block_size, &(ctx.write_genovecs[1])) ||
16635 bigstack_alloc_w(sample_ctaw * main_block_size, &(ctx.write_phasepresents[0])) ||
16636 bigstack_alloc_w(sample_ctaw * main_block_size, &(ctx.write_phasepresents[1])) ||
16637 bigstack_alloc_w(sample_ctaw * main_block_size, &(ctx.write_phaseinfos[0])) ||
16638 bigstack_alloc_w(sample_ctaw * main_block_size, &(ctx.write_phaseinfos[1])) ||
16639 bigstack_alloc_u32(main_block_size, &(ctx.write_dosage_cts[0])) ||
16640 bigstack_alloc_u32(main_block_size, &(ctx.write_dosage_cts[1])) ||
16641 bigstack_alloc_w(sample_ctaw * main_block_size, &(ctx.write_dosage_presents[0])) ||
16642 bigstack_alloc_w(sample_ctaw * main_block_size, &(ctx.write_dosage_presents[1])) ||
16643 bigstack_alloc_dosage(sample_ct * main_block_size, &(ctx.write_dosage_mains[0])) ||
16644 bigstack_alloc_dosage(sample_ct * main_block_size, &(ctx.write_dosage_mains[1])) ||
16645 bigstack_alloc_u32(main_block_size, &(ctx.write_dphase_cts[0])) ||
16646 bigstack_alloc_u32(main_block_size, &(ctx.write_dphase_cts[1])) ||
16647 bigstack_alloc_w(sample_ctaw * main_block_size, &(ctx.write_dphase_presents[0])) ||
16648 bigstack_alloc_w(sample_ctaw * main_block_size, &(ctx.write_dphase_presents[1])) ||
16649 bigstack_alloc_dphase(sample_ct * main_block_size, &(ctx.write_dphase_deltas[0])) ||
16650 bigstack_alloc_dphase(sample_ct * main_block_size, &(ctx.write_dphase_deltas[1])))) {
16651 // this should be impossible
16652 assert(0);
16653 goto GenerateDummy_ret_NOMEM;
16654 }
16655 // bugfix (3 Nov 2017): forgot to handle hard_call_thresh default value
16656 if (hard_call_thresh == UINT32_MAX) {
16657 hard_call_thresh = kDosageMid / 10;
16658 }
16659 ctx.hard_call_halfdist = kDosage4th - hard_call_thresh;
16660 ctx.dosage_erase_halfdist = kDosage4th - dosage_erase_thresh;
16661 SetThreadFuncAndData(GenerateDummyThread, &ctx, &tg);
16662
16663 // Main workflow:
16664 // 1. Set n=0
16665 //
16666 // 2. Spawn threads generating batch n genotype data
16667 // 3. If n>0, write results for block (n-1)
16668 // 4. Increment n by 1
16669 // 5. Join threads
16670 // 6. Goto step 2 unless eof
16671 //
16672 // 7. Write results for last block
16673 uint32_t prev_block_write_ct = 0;
16674 uint32_t parity = 0;
16675 for (uint32_t vidx_start = 0; ; ) {
16676 uint32_t cur_block_write_ct = 0;
16677 if (!IsLastBlock(&tg)) {
16678 cur_block_write_ct = MINV(variant_ct - vidx_start, main_block_size);
16679 }
16680 if (vidx_start) {
16681 JoinThreads(&tg);
16682 // GenerateDummyThread() never errors out
16683 }
16684 if (!IsLastBlock(&tg)) {
16685 ctx.cur_block_write_ct = cur_block_write_ct;
16686 if (vidx_start + cur_block_write_ct == variant_ct) {
16687 DeclareLastThreadBlock(&tg);
16688 }
16689 if (unlikely(SpawnThreads(&tg))) {
16690 goto GenerateDummy_ret_THREAD_CREATE_FAIL;
16691 }
16692 }
16693 parity = 1 - parity;
16694 if (vidx_start) {
16695 // write *previous* block results
16696 uintptr_t* write_genovec_iter = ctx.write_genovecs[parity];
16697 uintptr_t* write_phasepresent_iter = ctx.write_phasepresents[parity];
16698 uintptr_t* write_phaseinfo_iter = ctx.write_phaseinfos[parity];
16699 uint32_t* write_dosage_ct_iter = ctx.write_dosage_cts[parity];
16700 uintptr_t* write_dosage_present_iter = ctx.write_dosage_presents[parity];
16701 Dosage* write_dosage_main_iter = ctx.write_dosage_mains[parity];
16702 uint32_t* write_dphase_ct_iter = ctx.write_dphase_cts[parity];
16703 uintptr_t* write_dphase_present_iter = ctx.write_dphase_presents[parity];
16704 SDosage* write_dphase_delta_iter = ctx.write_dphase_deltas[parity];
16705 for (uint32_t vidx = vidx_start - prev_block_write_ct; vidx != vidx_start; ++vidx) {
16706 const uint32_t cur_dosage_ct = *write_dosage_ct_iter++;
16707 const uint32_t cur_dphase_ct = *write_dphase_ct_iter++;
16708 if (!cur_dosage_ct) {
16709 if (!is_phased) {
16710 if (unlikely(SpgwAppendBiallelicGenovec(write_genovec_iter, &spgw))) {
16711 goto GenerateDummy_ret_WRITE_FAIL;
16712 }
16713 } else {
16714 if (unlikely(SpgwAppendBiallelicGenovecHphase(write_genovec_iter, write_phasepresent_iter, write_phaseinfo_iter, &spgw))) {
16715 goto GenerateDummy_ret_WRITE_FAIL;
16716 }
16717 }
16718 } else {
16719 if (!is_phased) {
16720 reterr = SpgwAppendBiallelicGenovecDosage16(write_genovec_iter, write_dosage_present_iter, write_dosage_main_iter, cur_dosage_ct, &spgw);
16721 if (unlikely(reterr)) {
16722 goto GenerateDummy_ret_1;
16723 }
16724 } else {
16725 reterr = SpgwAppendBiallelicGenovecDphase16(write_genovec_iter, write_phasepresent_iter, write_phaseinfo_iter, write_dosage_present_iter, write_dphase_present_iter, write_dosage_main_iter, write_dphase_delta_iter, cur_dosage_ct, cur_dphase_ct, &spgw);
16726 if (unlikely(reterr)) {
16727 goto GenerateDummy_ret_1;
16728 }
16729 }
16730 }
16731 write_genovec_iter = &(write_genovec_iter[sample_ctaw2]);
16732 write_phasepresent_iter = &(write_phasepresent_iter[sample_ctaw]);
16733 write_phaseinfo_iter = &(write_phaseinfo_iter[sample_ctaw]);
16734 write_dosage_present_iter = &(write_dosage_present_iter[sample_ctaw]);
16735 write_dosage_main_iter = &(write_dosage_main_iter[sample_ct]);
16736 write_dphase_present_iter = &(write_dphase_present_iter[sample_ctaw]);
16737 write_dphase_delta_iter = &(write_dphase_delta_iter[sample_ct]);
16738 }
16739 }
16740 if (vidx_start == variant_ct) {
16741 break;
16742 }
16743 if (vidx_start) {
16744 printf("\r--dummy: %uk variants written.", vidx_start / 1000);
16745 fflush(stdout);
16746 }
16747 vidx_start += cur_block_write_ct;
16748 prev_block_write_ct = cur_block_write_ct;
16749 }
16750 reterr = SpgwFinish(&spgw);
16751 if (unlikely(reterr)) {
16752 goto GenerateDummy_ret_1;
16753 }
16754
16755 putc_unlocked('\r', stdout);
16756 *outname_end = '\0';
16757 logprintfww("Dummy data (%u sample%s, %u SNP%s) written to %s.pgen + %s.pvar%s + %s.psam .\n", sample_ct, (sample_ct == 1)? "" : "s", variant_ct, (variant_ct == 1)? "" : "s", outname, outname, output_zst? ".zst" : "", outname);
16758 }
16759 while (0) {
16760 GenerateDummy_ret_NOMEM:
16761 reterr = kPglRetNomem;
16762 break;
16763 GenerateDummy_ret_OPEN_FAIL:
16764 reterr = kPglRetOpenFail;
16765 break;
16766 GenerateDummy_ret_WRITE_FAIL:
16767 reterr = kPglRetWriteFail;
16768 break;
16769 GenerateDummy_ret_INVALID_CMDLINE:
16770 reterr = kPglRetInvalidCmdline;
16771 break;
16772 GenerateDummy_ret_THREAD_CREATE_FAIL:
16773 reterr = kPglRetThreadCreateFail;
16774 break;
16775 }
16776 GenerateDummy_ret_1:
16777 CleanupSpgw(&spgw, &reterr);
16778 CleanupThreads(&tg);
16779 fclose_cond(psamfile);
16780 CswriteCloseCond(&pvar_css, pvar_cswritep);
16781 BigstackReset(bigstack_mark);
16782 return reterr;
16783 }
16784
16785 #ifdef __cplusplus
16786 } // namespace plink2
16787 #endif