Debian Codegraph @

plink2_pvar.cc

raw
1 // This library is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
2 // Christopher Chang.
3 //
4 // This library is free software: you can redistribute it and/or modify it
5 // under the terms of the GNU Lesser General Public License as published by the
6 // Free Software Foundation; either version 3 of the License, or (at your
7 // option) any later version.
8 //
9 // This library is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
12 // for more details.
13 //
14 // You should have received a copy of the GNU Lesser General Public License
15 // along with this library. If not, see <http://www.gnu.org/licenses/>.
16
17 #include "plink2_pvar.h"
18
19 #ifdef __cplusplus
20 namespace plink2 {
21 #endif
22
23 // this used to employ a backward-growing linked list, with variable-size
24 // elements, but demultiplexing was relatively expensive. now we allocate
25 // size-64k pos[], allele_idxs[], ids[], cms[], etc. blocks, and just memcpy
26 // those chunks at the end. (cms[] is lazy-initialized.)
27 //
28 // probable todo: try making this more parallel. could e.g. repeatedly peek at
29 // end of ReadLineStream buffer, count # of '\n's, and divvy them up between
30 // worker threads.
31 CONSTI32(kLoadPvarBlockSize, 65536);
32 static_assert(!(kLoadPvarBlockSize & (kLoadPvarBlockSize - 1)), "kLoadPvarBlockSize must be a power of 2.");
33 static_assert(kLoadPvarBlockSize >= (kMaxMediumLine / 8), "kLoadPvarBlockSize cannot be smaller than kMaxMediumLine / 8.");
34
35
36 static_assert(!kChrOffsetX, "ReadChrsetHeaderLine() assumes kChrOffsetX == 0.");
37 static_assert(kChrOffsetY == 1, "ReadChrsetHeaderLine() assumes kChrOffsetY == 1.");
38 static_assert(kChrOffsetPAR1 == 4, "ReadChrsetHeaderLine() assumes kChrOffsetPAR1 == 4.");
39 PglErr ReadChrsetHeaderLine(const char* chrset_iter, const char* file_descrip, MiscFlags misc_flags, uintptr_t line_idx, ChrInfo* cip) {
40 // chrset_iter is expected to point to first character after
41 // "##chrSet=<".
42 PglErr reterr = kPglRetSuccess;
43 {
44 uint32_t prev_autosome_ct = 0;
45 uint32_t prev_haploid = 0;
46 STD_ARRAY_DECL(uint32_t, kChrOffsetCt, prev_xymt_codes);
47 if ((cip->chrset_source == kChrsetSourceCmdline) && (misc_flags & kfMiscChrOverrideCmdline)) {
48 goto ReadChrsetHeaderLine_ret_1;
49 }
50 if (((cip->chrset_source == kChrsetSourceCmdline) && (!(misc_flags & kfMiscChrOverrideFile))) || (cip->chrset_source == kChrsetSourceAnotherFile)) {
51 // save off info we need for consistency check
52 prev_autosome_ct = cip->autosome_ct;
53 prev_haploid = cip->haploid_mask[0] & 1;
54 STD_ARRAY_COPY(cip->xymt_codes, kChrOffsetCt, prev_xymt_codes);
55 }
56 // bugfix (23 Jan 2021): forgot to zero this out in file-only case
57 ZeroWArr(kChrMaskWords, cip->haploid_mask);
58 for (uint32_t uii = 0; uii != kChrOffsetCt; ++uii) {
59 cip->xymt_codes[uii] = UINT32_MAXM1;
60 }
61 if (StrStartsWithUnsafe(chrset_iter, "ID=")) {
62 // Need this field to conform to VCFv4.3 specification.
63 // Just ignore the ID value.
64 chrset_iter = strchrnul_n(&(chrset_iter[strlen("ID=")]), ',');
65 if (*chrset_iter != ',') {
66 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s does not have expected ##chrSet format.\n", line_idx, file_descrip);
67 goto ReadChrsetHeaderLine_ret_MALFORMED_INPUT_WW;
68 }
69 ++chrset_iter;
70 }
71 if (StrStartsWithUnsafe(chrset_iter, "haploidAutosomeCt=")) {
72 uint32_t explicit_haploid_ct;
73 if (unlikely(ScanPosintCapped(&(chrset_iter[strlen("haploidAutosomeCt=")]), kMaxChrTextnum, &explicit_haploid_ct))) {
74 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s has an unsupported ##chrSet haploid count (max %u).\n", line_idx, file_descrip, kMaxChrTextnum);
75 goto ReadChrsetHeaderLine_ret_MALFORMED_INPUT_WW;
76 }
77 // could verify that X, Y, etc. are not present?
78 if (prev_autosome_ct) {
79 if (unlikely(!prev_haploid)) {
80 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s specifies a haploid genome, while a diploid genome was specified %s.\n", line_idx, file_descrip, (cip->chrset_source == kChrsetSourceCmdline)? "on the command line" : "in another .pvar");
81 goto ReadChrsetHeaderLine_ret_INCONSISTENT_INPUT_WW;
82 }
83 if (unlikely(explicit_haploid_ct != prev_autosome_ct)) {
84 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s specifies %u autosome%s, while %s specified %u.\n", line_idx, file_descrip, explicit_haploid_ct, (explicit_haploid_ct == 1)? "" : "s", (cip->chrset_source == kChrsetSourceCmdline)? "the command line" : "another .pvar", prev_autosome_ct);
85 goto ReadChrsetHeaderLine_ret_INCONSISTENT_INPUT_WW;
86 }
87 }
88 cip->autosome_ct = explicit_haploid_ct;
89 SetAllBits(explicit_haploid_ct + 1, cip->haploid_mask);
90 } else {
91 if (unlikely(!StrStartsWithUnsafe(chrset_iter, "autosomePairCt="))) {
92 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s does not have expected ##chrSet format.\n", line_idx, file_descrip);
93 goto ReadChrsetHeaderLine_ret_MALFORMED_INPUT_WW;
94 }
95 chrset_iter = &(chrset_iter[strlen("autosomePairCt=")]);
96 uint32_t explicit_autosome_ct;
97 if (unlikely(ScanmovPosintCapped(kMaxChrTextnum, &chrset_iter, &explicit_autosome_ct))) {
98 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s has an unsupported ##chrSet autosome count (max %u).\n", line_idx, file_descrip, kMaxChrTextnum);
99 goto ReadChrsetHeaderLine_ret_MALFORMED_INPUT_WW;
100 }
101 cip->autosome_ct = explicit_autosome_ct;
102 if (*chrset_iter != '>') {
103 if (unlikely(*chrset_iter != ',')) {
104 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s does not have expected ##chrSet format.\n", line_idx, file_descrip);
105 goto ReadChrsetHeaderLine_ret_MALFORMED_INPUT_WW;
106 }
107 // this can theoretically be confused by e.g. a Description="..." field
108 // containing commas not followed by spaces
109 do {
110 ++chrset_iter;
111 // uppercase
112 uint32_t first_char_ui = ctou32(*chrset_iter) & 0xdf;
113
114 uint32_t second_char_ui = ctou32(chrset_iter[1]);
115 // 44 is ',', 62 is '>'
116 if ((second_char_ui == 44) || (second_char_ui == 62)) {
117 if (first_char_ui == 77) {
118 // M
119 cip->xymt_codes[kChrOffsetMT] = explicit_autosome_ct + 1 + kChrOffsetMT;
120 SetBit(explicit_autosome_ct + 1 + kChrOffsetMT, cip->haploid_mask);
121 } else {
122 first_char_ui -= 88; // X = 0, Y = 1, everything else larger
123 if (first_char_ui < 2) {
124 cip->xymt_codes[first_char_ui] = explicit_autosome_ct + 1 + first_char_ui;
125 SetBit(explicit_autosome_ct + 1 + first_char_ui, cip->haploid_mask);
126 }
127 }
128 } else {
129 second_char_ui &= 0xdf;
130 const uint32_t third_char_ui = ctou32(chrset_iter[2]);
131 if ((third_char_ui == 44) || (third_char_ui == 62)) {
132 if ((first_char_ui == 88) && (second_char_ui == 89)) {
133 // XY
134 cip->xymt_codes[kChrOffsetXY] = explicit_autosome_ct + 1 + kChrOffsetXY;
135 } else if ((first_char_ui == 77) && (second_char_ui == 84)) {
136 // MT
137 cip->xymt_codes[kChrOffsetMT] = explicit_autosome_ct + 1 + kChrOffsetMT;
138 SetBit(explicit_autosome_ct + 1 + kChrOffsetMT, cip->haploid_mask);
139 }
140 } else if ((first_char_ui == 80) && (second_char_ui == 65) && ((third_char_ui & 0xdf) == 82)) {
141 // PAR1, PAR2
142 const uint32_t par_idx_m1 = ctou32(chrset_iter[3]) - '1';
143 if ((par_idx_m1 < 2) && ((chrset_iter[4] == ',') || (chrset_iter[4] == '>'))) {
144 cip->xymt_codes[kChrOffsetPAR1] = explicit_autosome_ct + 1 + kChrOffsetPAR1 + par_idx_m1;
145 }
146 }
147 }
148 } while (!strchrnul_n_mov(',', &chrset_iter));
149 }
150 if (prev_autosome_ct) {
151 if (unlikely(prev_haploid)) {
152 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s specifies a diploid genome, while a haploid genome was specified %s.\n", line_idx, file_descrip, (cip->chrset_source == kChrsetSourceCmdline)? "on the command line" : "in another .pvar");
153 goto ReadChrsetHeaderLine_ret_INCONSISTENT_INPUT_WW;
154 }
155 if (unlikely(explicit_autosome_ct != prev_autosome_ct)) {
156 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s specifies %u autosome%s, while %s specified %u.\n", line_idx, file_descrip, explicit_autosome_ct, (explicit_autosome_ct == 1)? "" : "s", (cip->chrset_source == kChrsetSourceCmdline)? "the command line" : "another .pvar", prev_autosome_ct);
157 goto ReadChrsetHeaderLine_ret_INCONSISTENT_INPUT_WW;
158 }
159 for (uint32_t xymt_idx = 0; xymt_idx != kChrOffsetPAR1; ++xymt_idx) {
160 // it's okay if the command line doesn't explicitly exclude e.g. chrX
161 // while for whatever reason it is excluded from ##chrSet; but the
162 // reverse can create problems
163 if (unlikely(IsI32Neg(prev_xymt_codes[xymt_idx]) && (!IsI32Neg(cip->xymt_codes[xymt_idx])))) {
164 snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s specifies a chromosome set including %s, while %s excludes it.\n", line_idx, file_descrip, g_xymt_log_names[xymt_idx], (cip->chrset_source == kChrsetSourceCmdline)? "the command line" : "another .pvar");
165 goto ReadChrsetHeaderLine_ret_INCONSISTENT_INPUT_WW;
166 }
167 }
168 }
169 }
170 cip->chrset_source = kChrsetSourceFile;
171 }
172 while (0) {
173 ReadChrsetHeaderLine_ret_MALFORMED_INPUT_WW:
174 WordWrapB(0);
175 logerrputsb();
176 reterr = kPglRetMalformedInput;
177 break;
178 ReadChrsetHeaderLine_ret_INCONSISTENT_INPUT_WW:
179 WordWrapB(0);
180 logerrputsb();
181 reterr = kPglRetInconsistentInput;
182 break;
183 }
184 ReadChrsetHeaderLine_ret_1:
185 return reterr;
186 }
187
188 static_assert(kfVaridTemplateAlleleRefOr1 == 1, "VaridTemplateInit() or VaridTemplateAlleleFlags needs to be updated.");
189 static_assert(kfVaridTemplateAlleleAltOr2 == 2, "VaridTemplateInit() or VaridTemplateAlleleFlags needs to be updated.");
190 void VaridTemplateInit(const char* varid_template_str, const char* missing_id_match, char* chr_output_name_buf, uint32_t new_id_max_allele_slen, uint32_t overflow_substitute_blen, VaridTemplate* vtp) {
191 // template string was previously validated
192 // varid_template is only input, everything else is output values
193 const char* varid_template_str_iter = varid_template_str;
194 uint32_t template_insert_ct = 0;
195 uint32_t template_base_len = 0;
196 VaridTemplateAlleleFlags allele_flags = kfVaridTemplateAllele0;
197 vtp->chr_output_name_buf = chr_output_name_buf;
198 vtp->segs[0] = varid_template_str_iter;
199 vtp->chr_slen = 0;
200 for (unsigned char ucc = *varid_template_str_iter; ucc; ucc = *(++varid_template_str_iter)) {
201 if (ucc > '@') {
202 continue;
203 }
204 // VaridTemplateIsValid() ensures ucc is in {'$', '1', '2', 'A', 'R', 'a',
205 // 'r'}.
206 uint32_t seg_len;
207 uint32_t insert_type;
208 if (ucc == '@') {
209 seg_len = varid_template_str_iter - vtp->segs[template_insert_ct];
210 insert_type = 0;
211 } else if (ucc == '#') {
212 seg_len = varid_template_str_iter - vtp->segs[template_insert_ct];
213 insert_type = 1;
214 } else if (ucc != '$') {
215 continue;
216 } else {
217 seg_len = varid_template_str_iter - vtp->segs[template_insert_ct];
218 const uint32_t char_code = ctou32(*(++varid_template_str_iter));
219 uint32_t flagbit; // 1 if '1' or 'R'/'r', 2 if '2' or 'A'/'a'
220 if (char_code <= '2') {
221 allele_flags |= kfVaridTemplateAlleleAsciiOrder;
222 flagbit = char_code - 48;
223 } else {
224 flagbit = 1 + ((char_code & 0xdf) == 'A');
225 }
226 allele_flags |= S_CAST(VaridTemplateAlleleFlags, flagbit);
227 insert_type = flagbit + 1;
228 }
229 vtp->seg_lens[template_insert_ct] = seg_len;
230 template_base_len += seg_len;
231 vtp->insert_types[template_insert_ct++] = insert_type;
232 vtp->segs[template_insert_ct] = &(varid_template_str_iter[1]);
233 }
234 const uint32_t seg_len = varid_template_str_iter - vtp->segs[template_insert_ct];
235 vtp->seg_lens[template_insert_ct] = seg_len;
236 vtp->insert_ct = template_insert_ct;
237 vtp->base_len = template_base_len + seg_len;
238 vtp->allele_flags = allele_flags;
239 vtp->new_id_max_allele_slen = new_id_max_allele_slen;
240 vtp->overflow_substitute_blen = overflow_substitute_blen;
241 vtp->missing_id_match = missing_id_match;
242 }
243
244 static_assert((!(kMaxIdSlen % kCacheline)), "VaridInitAll() must be updated.");
245 BoolErr VaridInitAll(unsigned char* arena_end, const char* varid_template_str, const char* varid_multi_template_str, const char* varid_multi_nonsnp_template_str, MiscFlags misc_flags, uint32_t new_variant_id_max_allele_slen, unsigned char** arena_basep, const char** missing_varid_matchp, char** chr_output_name_bufp, VaridTemplate** varid_templatepp, VaridTemplate** varid_multi_templatepp, VaridTemplate** varid_multi_nonsnp_templatepp, uint32_t* missing_varid_blenp, uint32_t* missing_varid_match_slenp) {
246 unsigned char* arena_base = *arena_basep;
247 if (unlikely(S_CAST(uintptr_t, arena_end - arena_base) < (chr_output_name_bufp != nullptr) * kMaxIdSlen + 3 * RoundUpPow2(sizeof(VaridTemplate), kCacheline))) {
248 return 1;
249 }
250 char* chr_output_name_buf = nullptr;
251 if (chr_output_name_bufp) {
252 chr_output_name_buf = R_CAST(char*, arena_base);
253 *chr_output_name_bufp = chr_output_name_buf;
254 arena_base = &(arena_base[kMaxIdSlen]);
255 }
256 if (!(*missing_varid_matchp)) {
257 *missing_varid_matchp = &(g_one_char_strs[92]); // '.'
258 }
259 uint32_t missing_varid_blen = strlen(*missing_varid_matchp);
260 if (misc_flags & kfMiscSetMissingVarIds) {
261 *missing_varid_match_slenp = missing_varid_blen;
262 }
263 ++missing_varid_blen;
264 if (missing_varid_blenp) {
265 *missing_varid_blenp = missing_varid_blen;
266 }
267 *varid_templatepp = R_CAST(VaridTemplate*, arena_base);
268 arena_base = &(arena_base[RoundUpPow2(sizeof(VaridTemplate), kCacheline)]);
269 const uint32_t new_variant_id_overflow_missing = (misc_flags / kfMiscNewVarIdOverflowMissing) & 1;
270 const uint32_t overflow_substitute_blen = new_variant_id_overflow_missing? missing_varid_blen : 0;
271 VaridTemplateInit(varid_template_str, *missing_varid_matchp, chr_output_name_buf, new_variant_id_max_allele_slen, overflow_substitute_blen, *varid_templatepp);
272 if (varid_multi_template_str) {
273 *varid_multi_templatepp = R_CAST(VaridTemplate*, arena_base);
274 arena_base = &(arena_base[RoundUpPow2(sizeof(VaridTemplate), kCacheline)]);
275 VaridTemplateInit(varid_multi_template_str, *missing_varid_matchp, chr_output_name_buf, new_variant_id_max_allele_slen, overflow_substitute_blen, *varid_multi_templatepp);
276 }
277 if (varid_multi_nonsnp_template_str) {
278 *varid_multi_nonsnp_templatepp = R_CAST(VaridTemplate*, arena_base);
279 arena_base = &(arena_base[RoundUpPow2(sizeof(VaridTemplate), kCacheline)]);
280 VaridTemplateInit(varid_multi_nonsnp_template_str, *missing_varid_matchp, chr_output_name_buf, new_variant_id_max_allele_slen, overflow_substitute_blen, *varid_multi_nonsnp_templatepp);
281 }
282 *arena_basep = arena_base;
283 return 0;
284 }
285
286 // alt1_end currently allowed to be nullptr in biallelic case
287 BoolErr VaridTemplateApply(unsigned char* tmp_alloc_base, const VaridTemplate* vtp, const char* ref_start, const char* alt1_start, uint32_t cur_bp, uint32_t ref_token_slen, uint32_t extra_alt_ct, uint32_t alt_token_slen, unsigned char** tmp_alloc_endp, uintptr_t* new_id_allele_len_overflowp, uint32_t* id_slen_ptr) {
288 // (insert_ptrs[x], insert_slens[x]) is the (start, slen) of the
289 // insert-segment of type x:
290 // 0: chromosome
291 // 1: 1-based position
292 // 2: $r or $1
293 // 3: $a or $2
294 // Types 0 and 1 are always present, but 2 and/or 3 can be missing.
295 uint32_t insert_slens[4];
296 const VaridTemplateAlleleFlags allele_flags = vtp->allele_flags;
297 const uint32_t new_id_max_allele_slen = vtp->new_id_max_allele_slen;
298 uint32_t id_slen = UintSlen(cur_bp);
299 insert_slens[0] = vtp->chr_slen;
300 insert_slens[1] = id_slen;
301 id_slen += vtp->base_len;
302 const uint32_t ref_or_1_exists = (allele_flags & kfVaridTemplateAlleleRefOr1)? 1 : 0;
303 uint32_t ref_slen = 0;
304 uint32_t cur_overflow = 0;
305 const char* tmp_allele_ptrs[2]; // [0] = RefOr1, [1] = AltOr2
306 tmp_allele_ptrs[0] = nullptr;
307 tmp_allele_ptrs[1] = nullptr; // maybe-uninitialized warning
308 if (ref_or_1_exists) {
309 ref_slen = ref_token_slen;
310 if (ref_slen > new_id_max_allele_slen) {
311 ref_slen = new_id_max_allele_slen;
312 cur_overflow = 1;
313 }
314 insert_slens[2] = ref_slen;
315 id_slen += ref_slen;
316 tmp_allele_ptrs[0] = ref_start;
317 }
318 if (allele_flags & (kfVaridTemplateAlleleAltOr2 | kfVaridTemplateAlleleAsciiOrder)) {
319 uint32_t alt1_slen;
320 if (!extra_alt_ct) {
321 alt1_slen = alt_token_slen;
322 } else {
323 alt1_slen = AdvToDelim(alt1_start, ',') - alt1_start;
324 }
325 if (alt1_slen > new_id_max_allele_slen) {
326 alt1_slen = new_id_max_allele_slen;
327 ++cur_overflow;
328 }
329 id_slen += alt1_slen;
330 if (!(allele_flags & kfVaridTemplateAlleleAsciiOrder)) {
331 VaridTemplateApply_keep_allele_ascii_order:
332 insert_slens[3] = alt1_slen;
333 tmp_allele_ptrs[1] = alt1_start;
334 } else {
335 uint32_t smaller_slen = alt1_slen;
336 const int32_t ref_slen_geq = (ref_slen >= alt1_slen);
337 if (!ref_slen_geq) {
338 smaller_slen = ref_slen;
339 }
340 int32_t memcmp_result = Memcmp(ref_start, alt1_start, smaller_slen);
341 if (!memcmp_result) {
342 memcmp_result = ref_slen_geq;
343 }
344 if (memcmp_result <= 0) {
345 goto VaridTemplateApply_keep_allele_ascii_order;
346 }
347 insert_slens[3] = ref_slen;
348 tmp_allele_ptrs[1] = tmp_allele_ptrs[0];
349 insert_slens[2] = alt1_slen;
350 tmp_allele_ptrs[0] = alt1_start;
351 }
352 }
353 const uint32_t overflow_substitute_blen = vtp->overflow_substitute_blen;
354 if (overflow_substitute_blen && cur_overflow) {
355 // er, do we really want to make a separate allocation here? see if we can
356 // remove this. (that would impose more constraints on downstream
357 // variant-ID-changing functions, though.)
358 if (PtrWSubCk(tmp_alloc_base, overflow_substitute_blen, tmp_alloc_endp)) {
359 return 1;
360 }
361 memcpy(*tmp_alloc_endp, vtp->missing_id_match, overflow_substitute_blen);
362 id_slen = 0;
363 cur_overflow = 1;
364 } else {
365 if (PtrWSubCk(tmp_alloc_base, id_slen + 1, tmp_alloc_endp)) {
366 return 1;
367 }
368 char* id_iter = R_CAST(char*, *tmp_alloc_endp);
369 const uint32_t insert_ct = vtp->insert_ct;
370 char* insert_ptrs[4];
371
372 // maybe-uninitialized warnings
373 insert_ptrs[0] = nullptr;
374 insert_ptrs[1] = nullptr;
375
376 insert_ptrs[2] = nullptr;
377 insert_ptrs[3] = nullptr;
378 // insert_ct currently guaranteed to be >= 2 since @ and # required
379 // insert_ct > 2 possibilities:
380 // $r without $a: insert_ct=3, use tmp_allele_ptrs[0] and insert_slens[2]
381 // $a without $r: insert_ct=3, use tmp_allele_ptrs[1] and insert_slens[3]
382 // (fixed bug on 24 Nov 2024)
383 // $r+$a or $1+$2: insert_ct=4, use (tmp_allele_ptrs[0], insert_slens[2])
384 // followed by (tmp_allele_ptrs[1], insert_slens[3])
385 for (uint32_t insert_idx = 0; insert_idx != insert_ct; ++insert_idx) {
386 id_iter = memcpya(id_iter, vtp->segs[insert_idx], vtp->seg_lens[insert_idx]);
387 const uint32_t cur_insert_type = vtp->insert_types[insert_idx];
388 insert_ptrs[cur_insert_type] = id_iter;
389 id_iter = &(id_iter[insert_slens[cur_insert_type]]);
390 }
391 memcpyx(id_iter, vtp->segs[insert_ct], vtp->seg_lens[insert_ct], '\0');
392
393 memcpy(insert_ptrs[0], vtp->chr_output_name_buf, insert_slens[0]);
394 u32toa(cur_bp, insert_ptrs[1]);
395 if (insert_ct > 2) {
396 for (uint32_t insert_type_idx = 2; insert_type_idx != 4; ++insert_type_idx) {
397 char* cur_dst = insert_ptrs[insert_type_idx];
398 if (cur_dst == nullptr) {
399 // bugfix (24 Nov 2024)
400 continue;
401 }
402 memcpy(cur_dst, tmp_allele_ptrs[insert_type_idx - 2], insert_slens[insert_type_idx]);
403 }
404 }
405 }
406 *id_slen_ptr = id_slen;
407 *new_id_allele_len_overflowp += cur_overflow;
408 return 0;
409 }
410
411 // Exported variant of VaridTemplateApply() which appends to a buffer.
412 // Probable todo: pull out the common parts of the functions.
413 char* VaridTemplateWrite(const VaridTemplate* vtp, const char* ref_start, const char* alt1_start, uint32_t cur_bp, uint32_t ref_token_slen, uint32_t extra_alt_ct, uint32_t alt_token_slen, uint32_t* max_overflow_slenp, char* dst) {
414 uint32_t insert_slens[4];
415 const uint32_t allele_flags = vtp->allele_flags;
416 const uint32_t new_id_max_allele_slen = vtp->new_id_max_allele_slen;
417 uint32_t id_slen = UintSlen(cur_bp);
418 insert_slens[0] = vtp->chr_slen;
419 insert_slens[1] = id_slen;
420 id_slen += vtp->base_len;
421 const uint32_t ref_or_1_exists = (allele_flags & kfVaridTemplateAlleleRefOr1)? 1 : 0;
422 uint32_t ref_slen = 0;
423 uint32_t cur_max_overflow_slen = 0;
424 const char* tmp_allele_ptrs[2];
425 tmp_allele_ptrs[0] = nullptr;
426 tmp_allele_ptrs[1] = nullptr;
427 if (ref_or_1_exists) {
428 ref_slen = ref_token_slen;
429 if (ref_slen > new_id_max_allele_slen) {
430 cur_max_overflow_slen = ref_slen;
431 ref_slen = new_id_max_allele_slen;
432 }
433 insert_slens[2] = ref_slen;
434 id_slen += ref_slen;
435 tmp_allele_ptrs[0] = ref_start;
436 }
437 if (allele_flags & (kfVaridTemplateAlleleAltOr2 | kfVaridTemplateAlleleAsciiOrder)) {
438 uint32_t alt1_slen;
439 if (!extra_alt_ct) {
440 alt1_slen = alt_token_slen;
441 } else {
442 alt1_slen = AdvToDelim(alt1_start, ',') - alt1_start;
443 }
444 if (alt1_slen > new_id_max_allele_slen) {
445 if (alt1_slen > cur_max_overflow_slen) {
446 cur_max_overflow_slen = alt1_slen;
447 }
448 alt1_slen = new_id_max_allele_slen;
449 }
450 id_slen += alt1_slen;
451 if (!(allele_flags & kfVaridTemplateAlleleAsciiOrder)) {
452 VaridTemplateWrite_keep_allele_ascii_order:
453 insert_slens[3] = alt1_slen;
454 tmp_allele_ptrs[1] = alt1_start;
455 } else {
456 uint32_t smaller_slen = alt1_slen;
457 const int32_t ref_slen_geq = (ref_slen >= alt1_slen);
458 if (!ref_slen_geq) {
459 smaller_slen = ref_slen;
460 }
461 int32_t memcmp_result = Memcmp(ref_start, alt1_start, smaller_slen);
462 if (!memcmp_result) {
463 memcmp_result = ref_slen_geq;
464 }
465 if (memcmp_result <= 0) {
466 goto VaridTemplateWrite_keep_allele_ascii_order;
467 }
468 insert_slens[3] = ref_slen;
469 tmp_allele_ptrs[1] = tmp_allele_ptrs[0];
470 insert_slens[2] = alt1_slen;
471 tmp_allele_ptrs[0] = alt1_start;
472 }
473 }
474 if (cur_max_overflow_slen) {
475 if (cur_max_overflow_slen > *max_overflow_slenp) {
476 *max_overflow_slenp = cur_max_overflow_slen;
477 }
478 const uint32_t overflow_substitute_blen = vtp->overflow_substitute_blen;
479 if (overflow_substitute_blen) {
480 return memcpya(dst, vtp->missing_id_match, overflow_substitute_blen);
481 }
482 }
483 char* id_iter = dst;
484 const uint32_t insert_ct = vtp->insert_ct;
485 char* insert_ptrs[4];
486
487 // maybe-uninitialized warnings
488 insert_ptrs[0] = nullptr;
489 insert_ptrs[1] = nullptr;
490
491 insert_ptrs[2] = nullptr;
492 insert_ptrs[3] = nullptr;
493
494 for (uint32_t insert_idx = 0; insert_idx != insert_ct; ++insert_idx) {
495 id_iter = memcpya(id_iter, vtp->segs[insert_idx], vtp->seg_lens[insert_idx]);
496 const uint32_t cur_insert_type = vtp->insert_types[insert_idx];
497 insert_ptrs[cur_insert_type] = id_iter;
498 id_iter = &(id_iter[insert_slens[cur_insert_type]]);
499 }
500 char* id_end = memcpya(id_iter, vtp->segs[insert_ct], vtp->seg_lens[insert_ct]);
501
502 memcpy(insert_ptrs[0], vtp->chr_output_name_buf, insert_slens[0]);
503 u32toa(cur_bp, insert_ptrs[1]);
504 if (insert_ct > 2) {
505 for (uint32_t insert_type_idx = 2; insert_type_idx != 4; ++insert_type_idx) {
506 char* cur_dst = insert_ptrs[insert_type_idx];
507 if (cur_dst == nullptr) {
508 continue;
509 }
510 memcpy(cur_dst, tmp_allele_ptrs[insert_type_idx - 2], insert_slens[insert_type_idx]);
511 }
512 }
513 return id_end;
514 }
515
516 uint32_t VaridWorstCaseSlen(const VaridTemplate* vtp, uint32_t max_chr_slen, uint32_t max_allele_slen) {
517 const VaridTemplateAlleleFlags allele_flags = vtp->allele_flags;
518 uint32_t allele_ct = (allele_flags & kfVaridTemplateAlleleRefOr1)? 1 : 0;
519 allele_ct += (allele_flags & kfVaridTemplateAlleleAltOr2)? 1 : 0;
520 // +10 for base-pair coordinate
521 return (max_allele_slen * allele_ct + vtp->base_len + max_chr_slen + 10);
522 }
523
524 void BackfillChrIdxs(const ChrInfo* cip, uint32_t chrs_encountered_m1, uint32_t offset, uint32_t end_vidx, ChrIdx* chr_idxs) {
525 for (uint32_t chr_fo_idx = chrs_encountered_m1; ; --chr_fo_idx) {
526 uint32_t start_vidx = cip->chr_fo_vidx_start[chr_fo_idx];
527 if (start_vidx < offset) {
528 start_vidx = offset;
529 }
530 ChrIdx* chr_idxs_write_base = &(chr_idxs[start_vidx - offset]);
531 const uint32_t vidx_ct = end_vidx - start_vidx;
532 const ChrIdx cur_chr_idx = cip->chr_file_order[chr_fo_idx];
533 for (uint32_t uii = 0; uii != vidx_ct; ++uii) {
534 chr_idxs_write_base[uii] = cur_chr_idx;
535 }
536 if (start_vidx == offset) {
537 return;
538 }
539 end_vidx = start_vidx;
540 }
541 }
542
543 uint32_t PrInInfo(uint32_t info_slen, char* info_token) {
544 if (memequal_sk(info_token, "PR") && ((info_slen == 2) || (info_token[2] == ';'))) {
545 return 1;
546 }
547 if (memequal_sk(&(info_token[S_CAST(int32_t, info_slen) - 3]), ";PR")) {
548 return 1;
549 }
550 info_token[info_slen] = '\0';
551 char* first_info_end = strchr(info_token, ';');
552 return first_info_end && (strstr(info_token, ";PR;") != nullptr);
553 }
554
555 char* InfoPrStart(uint32_t info_slen, char* info_token) {
556 if (memequal_sk(info_token, "PR") && ((info_slen == 2) || (info_token[2] == ';'))) {
557 return info_token;
558 }
559 if (memequal_sk(&(info_token[S_CAST(int32_t, info_slen) - 3]), ";PR")) {
560 return &(info_token[info_slen - 2]);
561 }
562 // bugfix (29 Aug 2023): need this function to be nondestructive
563 const char token_end_char = info_token[info_slen];
564 info_token[info_slen] = '\0';
565 char* first_info_end = strchr(info_token, ';');
566 if (!first_info_end) {
567 info_token[info_slen] = token_end_char;
568 return nullptr;
569 }
570 char* pr_prestart = strstr(first_info_end, ";PR;");
571 info_token[info_slen] = token_end_char;
572 // bugfix (27 Sep 2019): had this backward
573 return pr_prestart? (&(pr_prestart[1])) : nullptr;
574 }
575
576 typedef struct InfoExistStruct {
577 NONCOPYABLE(InfoExistStruct);
578 char* prekeys;
579 uint32_t key_ct;
580 uint32_t key_slens[];
581 } InfoExist;
582
583 PglErr InfoExistInit(const unsigned char* arena_end, const char* require_info_flattened, const char* flagname_p, unsigned char** arena_base_ptr, InfoExist** existpp) {
584 const char* read_iter = require_info_flattened;
585 uintptr_t prekeys_blen = 0;
586 do {
587 const char* key_end_or_invalid = strchrnul2(read_iter, ';', '=');
588 if (unlikely(*key_end_or_invalid)) {
589 if (*key_end_or_invalid == ';') {
590 logerrprintfww("Error: Invalid --%s key '%s' (semicolon prohibited).\n", flagname_p, read_iter);
591 } else {
592 logerrprintfww("Error: Invalid --%s key '%s' ('=' prohibited).\n", flagname_p, read_iter);
593 }
594 return kPglRetInvalidCmdline;
595 }
596 ++prekeys_blen;
597 read_iter = &(key_end_or_invalid[1]);
598 } while (*read_iter);
599 prekeys_blen += read_iter - require_info_flattened;
600 const uint32_t key_ct = prekeys_blen - S_CAST(uintptr_t, read_iter - require_info_flattened);
601 const uintptr_t bytes_used = offsetof(InfoExist, key_slens) + key_ct * sizeof(int32_t) + prekeys_blen;
602 const uintptr_t cur_alloc = RoundUpPow2(bytes_used, kCacheline);
603 if (unlikely(S_CAST(uintptr_t, arena_end - (*arena_base_ptr)) < cur_alloc)) {
604 return kPglRetNomem;
605 }
606 *existpp = R_CAST(InfoExist*, *arena_base_ptr);
607 (*existpp)->prekeys = R_CAST(char*, &((*arena_base_ptr)[bytes_used - prekeys_blen]));
608 (*arena_base_ptr) += cur_alloc;
609 (*existpp)->key_ct = key_ct;
610 read_iter = require_info_flattened;
611 char* write_iter = (*existpp)->prekeys;
612 for (uint32_t kidx = 0; kidx != key_ct; ++kidx) {
613 *write_iter++ = ';';
614 const uintptr_t slen = strlen(read_iter);
615 (*existpp)->key_slens[kidx] = slen;
616 const uintptr_t blen = slen + 1;
617 write_iter = memcpya(write_iter, read_iter, blen);
618 read_iter = &(read_iter[blen]);
619 }
620 return kPglRetSuccess;
621 }
622
623 // Returns 1 iff all keys are found.
624 uint32_t InfoExistCheck(const char* info_token, const InfoExist* existp) {
625 const uint32_t key_ct = existp->key_ct;
626 const char* prekeys_iter = existp->prekeys;
627 const uint32_t* key_slens = existp->key_slens;
628 for (uint32_t kidx = 0; kidx != key_ct; ++kidx) {
629 const uint32_t key_slen = key_slens[kidx];
630 const char* possible_hit;
631 // similar logic to hardcoded PR, except key can also be followed by '=',
632 // and if it is there can't be a lone '.' after the equals
633 if (memequal(info_token, &(prekeys_iter[1]), key_slen)) {
634 possible_hit = &(info_token[key_slen]);
635 } else {
636 possible_hit = strstr(info_token, prekeys_iter);
637 if (!possible_hit) {
638 return 0;
639 }
640 possible_hit = &(possible_hit[key_slen + 1]);
641 }
642 while (1) {
643 const char cc = *possible_hit;
644 if ((!cc) || (cc == ';')) {
645 break;
646 }
647 if (cc == '=') {
648 if ((possible_hit[1] != '.') || (possible_hit[2] && (possible_hit[2] != ';'))) {
649 break;
650 }
651 return 0;
652 }
653 possible_hit = strstr(possible_hit, prekeys_iter);
654 if (!possible_hit) {
655 return 0;
656 }
657 possible_hit = &(possible_hit[key_slen + 1]);
658 }
659 prekeys_iter = &(prekeys_iter[key_slen + 2]);
660 }
661 return 1;
662 }
663
664 // Returns 1 iff all keys are absent.
665 uint32_t InfoNonexistCheck(const char* info_token, const InfoExist* nonexistp) {
666 const uint32_t key_ct = nonexistp->key_ct;
667 const char* prekeys_iter = nonexistp->prekeys;
668 const uint32_t* key_slens = nonexistp->key_slens;
669 uint32_t key_slen = 0;
670 for (uint32_t kidx = 0; kidx != key_ct; ++kidx, prekeys_iter = &(prekeys_iter[key_slen + 2])) {
671 key_slen = key_slens[kidx];
672 const char* possible_hit;
673 if (memequal(info_token, &(prekeys_iter[1]), key_slen)) {
674 possible_hit = &(info_token[key_slen]);
675 } else {
676 possible_hit = strstr(info_token, prekeys_iter);
677 if (!possible_hit) {
678 continue;
679 }
680 possible_hit = &(possible_hit[key_slen + 1]);
681 }
682 while (1) {
683 const char cc = *possible_hit;
684 if ((!cc) || (cc == ';')) {
685 return 0;
686 }
687 if (cc == '=') {
688 if ((possible_hit[1] != '.') || (possible_hit[2] && (possible_hit[2] != ';'))) {
689 return 0;
690 }
691 break;
692 }
693 possible_hit = strstr(possible_hit, prekeys_iter);
694 if (!possible_hit) {
695 break;
696 }
697 possible_hit = &(possible_hit[key_slen + 1]);
698 }
699 }
700 return 1;
701 }
702
703 typedef struct InfoFilterStruct {
704 NONCOPYABLE(InfoFilterStruct);
705 char* prekey;
706 const char* val_str;
707 uint32_t key_slen;
708 uint32_t val_slen;
709 CmpBinaryOp binary_op;
710 double val;
711 } InfoFilter;
712
713 PglErr InfoFilterInit(const unsigned char* arena_end, const CmpExpr* filter_exprp, const char* flagname_p, unsigned char** arena_base_ptr, InfoFilter* filterp) {
714 const char* pheno_name = filter_exprp->pheno_name;
715 const char* pheno_name_end_or_invalid = strchrnul3(pheno_name, ';', '=', ',');
716 if (unlikely(*pheno_name_end_or_invalid)) {
717 if (*pheno_name_end_or_invalid == ';') {
718 logerrprintfww("Error: Invalid --%s key '%s' (semicolon prohibited).\n", flagname_p, pheno_name);
719 } else if (*pheno_name_end_or_invalid == '=') {
720 logerrprintfww("Error: Invalid --%s key '%s' ('=' prohibited).\n", flagname_p, pheno_name);
721 } else {
722 logerrprintfww("Error: Invalid --%s key '%s' (comma prohibited).\n", flagname_p, pheno_name);
723 }
724 return kPglRetInvalidCmdline;
725 }
726 uint32_t key_slen = pheno_name_end_or_invalid - pheno_name;
727 const uintptr_t cur_alloc = RoundUpPow2(3 + key_slen, kCacheline);
728 if (unlikely(S_CAST(uintptr_t, arena_end - (*arena_base_ptr)) < cur_alloc)) {
729 return kPglRetNomem;
730 }
731 filterp->prekey = R_CAST(char*, *arena_base_ptr);
732 (*arena_base_ptr) += cur_alloc;
733 filterp->prekey[0] = ';';
734 char* key_iter = memcpya(&(filterp->prekey[1]), pheno_name, key_slen);
735 strcpy_k(key_iter, "=");
736 ++key_slen;
737 filterp->key_slen = key_slen;
738 filterp->val_str = nullptr;
739 filterp->val_slen = 0;
740 const CmpBinaryOp binary_op = filter_exprp->binary_op;
741 filterp->binary_op = binary_op;
742 // shouldn't need to initialize val
743
744 const char* val_str = &(pheno_name[key_slen]);
745 // bugfix (14 Dec 2017): INFO string constants are not guaranteed to start in
746 // a letter. Only interpret the value as a number if ScanadvDouble()
747 // consumes the entire value string.
748 const char* val_num_end = ScanadvDouble(val_str, &filterp->val);
749 if (val_num_end && (!val_num_end[0])) {
750 return kPglRetSuccess;
751 }
752 if (unlikely((binary_op != kCmpOperatorNoteq) && (binary_op != kCmpOperatorEq))) {
753 logerrprintfww("Error: Invalid --%s value '%s' (finite number expected).\n", flagname_p, val_str);
754 return kPglRetInvalidCmdline;
755 }
756 const char* val_str_end_or_invalid = strchrnul2(val_str, ';', '=');
757 if (*val_str_end_or_invalid) {
758 if (unlikely(*val_str_end_or_invalid == '=')) {
759 logerrprintfww("Error: Invalid --%s value '%s' ('=' prohibited).\n", flagname_p, val_str);
760 return kPglRetInvalidCmdline;
761 } else if (unlikely(val_str_end_or_invalid[1])) {
762 logerrprintfww("Error: Invalid --%s value '%s' (semicolon prohibited, unless by itself to specify empty-string).\n", flagname_p, val_str);
763 return kPglRetInvalidCmdline;
764 }
765 // Empty-string special case.
766 filterp->val_str = &(val_str[1]);
767 return kPglRetSuccess;
768 }
769 filterp->val_str = val_str;
770 filterp->val_slen = val_str_end_or_invalid - val_str;
771 return kPglRetSuccess;
772 }
773
774 uint32_t InfoConditionSatisfied(const char* info_token, const InfoFilter* filterp) {
775 const char* prekey = filterp->prekey;
776 const uint32_t key_slen = filterp->key_slen;
777 const CmpBinaryOp binary_op = filterp->binary_op;
778 const char* possible_hit;
779 // search for "[key]=" at start or ";[key]=" later; key_slen includes the
780 // trailing =
781 if (memequal(info_token, &(prekey[1]), key_slen)) {
782 possible_hit = &(info_token[key_slen]);
783 } else {
784 possible_hit = strstr(info_token, prekey);
785 if (!possible_hit) {
786 return (binary_op == kCmpOperatorNoteq);
787 }
788 possible_hit = &(possible_hit[key_slen + 1]);
789 }
790 if (filterp->val_str) {
791 const uint32_t val_slen = filterp->val_slen;
792 const uint32_t mismatch = ((!memequal(possible_hit, filterp->val_str, val_slen)) || (possible_hit[val_slen] && (possible_hit[val_slen] != ';')));
793 return mismatch ^ (binary_op != kCmpOperatorNoteq);
794 }
795 // bugfix (3 Jan 2020): semicolon (or \0) terminator expected, can't use
796 // ScantokDouble
797 double dxx;
798 const char* scan_end = ScanadvDouble(possible_hit, &dxx);
799 if ((!scan_end) || ((*scan_end != ';') && (*scan_end))) {
800 return (binary_op == kCmpOperatorNoteq);
801 }
802 const double val = filterp->val;
803 switch (binary_op) {
804 case kCmpOperatorNoteq:
805 return (dxx != val);
806 case kCmpOperatorLe:
807 return (dxx < val);
808 case kCmpOperatorLeq:
809 return (dxx <= val);
810 case kCmpOperatorGe:
811 return (dxx > val);
812 case kCmpOperatorGeq:
813 return (dxx >= val);
814 case kCmpOperatorEq:
815 return (dxx == val);
816 }
817 // should be unreachable, but some gcc versions complain
818 return 0;
819 }
820
821 PglErr SplitPar(const uint32_t* variant_bps, UnsortedVar vpos_sortstatus, uint32_t splitpar_bound1, uint32_t splitpar_bound2, uintptr_t* variant_include, uintptr_t* loaded_chr_mask, ChrInfo* cip, uint32_t* chrs_encountered_m1_ptr, uint32_t* exclude_ct_ptr) {
822 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
823 if (IsI32Neg(x_code) || (!IsSet(loaded_chr_mask, x_code))) {
824 logerrputs("Warning: --split-par had no effect (no X chromosome in dataset).\n");
825 return kPglRetSuccess;
826 }
827 const uint32_t par1_code = cip->xymt_codes[kChrOffsetPAR1];
828 const uint32_t par2_code = cip->xymt_codes[kChrOffsetPAR2];
829 if (unlikely(IsI32Neg(par2_code))) {
830 // may want to remove this restriction later
831 logerrputs("Error: --split-par cannot currently be used with a custom chromosome set.\n");
832 return kPglRetInvalidCmdline;
833 }
834 if (unlikely(IsSet(loaded_chr_mask, par1_code) || IsSet(loaded_chr_mask, par2_code))) {
835 logerrputs("Error: --split-par cannot be used on a dataset which already contains a PAR1 or\nPAR2 region.\n");
836 return kPglRetInvalidCmdline;
837 }
838 if (unlikely(vpos_sortstatus & kfUnsortedVarBp)) {
839 logerrputs("Error: --split-par cannot be used with an unsorted .bim/.pvar file.\n");
840 return kPglRetInvalidCmdline;
841 }
842 const uint32_t orig_xchr_fo_idx = cip->chr_idx_to_foidx[x_code];
843 const uint32_t orig_x_start = cip->chr_fo_vidx_start[orig_xchr_fo_idx];
844 const uint32_t orig_x_end = cip->chr_fo_vidx_start[orig_xchr_fo_idx + 1];
845 const uint32_t par1_end = LowerBoundConstrainedNonemptyU32(variant_bps, orig_x_start, orig_x_end, splitpar_bound1 + 1);
846 const uint32_t par2_start = LowerBoundConstrainedNonemptyU32(variant_bps, par1_end, orig_x_end, splitpar_bound2);
847 uint32_t tot_codes_changed = (par1_end - orig_x_start) + (orig_x_end - par2_start);
848 if (!tot_codes_changed) {
849 logerrputs("Warning: --split-par had no effect (no X variants were in the PARs).\n");
850 return kPglRetSuccess;
851 }
852 // one of the PARs, and/or the main chrX body, may be empty; that's not a big
853 // deal
854 *chrs_encountered_m1_ptr += 2;
855 const uint32_t chrs_encountered_m1 = *chrs_encountered_m1_ptr;
856 cip->chr_fo_vidx_start[chrs_encountered_m1 + 1] = cip->chr_fo_vidx_start[chrs_encountered_m1 - 1];
857 for (uint32_t chr_fo_idx = chrs_encountered_m1 - 2; chr_fo_idx != orig_xchr_fo_idx; --chr_fo_idx) {
858 cip->chr_fo_vidx_start[chr_fo_idx + 2] = cip->chr_fo_vidx_start[chr_fo_idx];
859 const uint32_t cur_chr_idx = cip->chr_file_order[chr_fo_idx];
860 cip->chr_file_order[chr_fo_idx + 2] = cur_chr_idx;
861 cip->chr_idx_to_foidx[cur_chr_idx] = chr_fo_idx + 2;
862 }
863 cip->chr_fo_vidx_start[orig_xchr_fo_idx + 1] = par1_end;
864 cip->chr_fo_vidx_start[orig_xchr_fo_idx + 2] = par2_start;
865 cip->chr_file_order[orig_xchr_fo_idx] = par1_code;
866 cip->chr_file_order[orig_xchr_fo_idx + 1] = x_code;
867 cip->chr_file_order[orig_xchr_fo_idx + 2] = par2_code;
868 cip->chr_idx_to_foidx[par1_code] = orig_xchr_fo_idx;
869 cip->chr_idx_to_foidx[x_code] = orig_xchr_fo_idx + 1;
870 cip->chr_idx_to_foidx[par2_code] = orig_xchr_fo_idx + 2;
871 uintptr_t* chr_mask = cip->chr_mask;
872 if (par1_end > orig_x_start) {
873 if (!IsSet(chr_mask, par1_code)) {
874 *exclude_ct_ptr += PopcountBitRange(variant_include, orig_x_start, par1_end);
875 ClearBitsNz(orig_x_start, par1_end, variant_include);
876 } else {
877 SetBit(par1_code, loaded_chr_mask);
878 }
879 }
880 if (par1_end == par2_start) {
881 ClearBit(x_code, chr_mask);
882 } else if (!IsSet(chr_mask, x_code)) {
883 ClearBit(x_code, chr_mask);
884 *exclude_ct_ptr += PopcountBitRange(variant_include, par1_end, par2_start);
885 ClearBitsNz(par1_end, par2_start, variant_include);
886 }
887 if (par2_start < orig_x_end) {
888 if (!IsSet(chr_mask, par2_code)) {
889 *exclude_ct_ptr += PopcountBitRange(variant_include, par2_start, orig_x_end);
890 ClearBitsNz(par2_start, orig_x_end, variant_include);
891 } else {
892 SetBit(par2_code, loaded_chr_mask);
893 }
894 }
895 logprintf("--split-par: %u chromosome code%s changed.\n", tot_codes_changed, (tot_codes_changed == 1)? "" : "s");
896 return kPglRetSuccess;
897 }
898
899 PglErr LoadPvar(const char* pvarname, const char* var_filter_exceptions_flattened, const char* varid_template_str, const char* varid_multi_template_str, const char* varid_multi_nonsnp_template_str, const char* missing_varid_match, const char* require_info_flattened, const char* require_no_info_flattened, const CmpExpr* extract_if_info_exprp, const CmpExpr* exclude_if_info_exprp, MiscFlags misc_flags, PvarPsamFlags pvar_psam_flags, uint32_t xheader_needed, uint32_t qualfilter_needed, float var_min_qual, uint32_t splitpar_bound1, uint32_t splitpar_bound2, uint32_t new_variant_id_max_allele_slen, uint32_t snps_only, uint32_t split_chr_ok, uint32_t filter_min_allele_ct, uint32_t filter_max_allele_ct, char input_missing_geno_char, uint32_t max_thread_ct, ChrInfo* cip, uint32_t* max_variant_id_slen_ptr, uint32_t* info_reload_slen_ptr, UnsortedVar* vpos_sortstatus_ptr, char** xheader_ptr, uintptr_t** variant_include_ptr, uint32_t** variant_bps_ptr, char*** variant_ids_ptr, uintptr_t** allele_idx_offsets_ptr, const char*** allele_storage_ptr, uintptr_t** qual_present_ptr, float** quals_ptr, uintptr_t** filter_present_ptr, uintptr_t** filter_npass_ptr, char*** filter_storage_ptr, uintptr_t** nonref_flags_ptr, double** variant_cms_ptr, ChrIdx** chr_idxs_ptr, uint32_t* raw_variant_ct_ptr, uint32_t* variant_ct_ptr, uint32_t* max_allele_ct_ptr, uint32_t* max_allele_slen_ptr, uintptr_t* xheader_blen_ptr, InfoFlags* info_flags_ptr, uint32_t* max_filter_slen_ptr) {
900 // chr_info, max_variant_id_slen, and info_reload_slen are in/out; just
901 // outparameters after them. (Due to its large size in some VCFs, INFO is
902 // not kept in memory for now. This has a speed penalty, of course; maybe
903 // it's worthwhile to conditionally load it later.)
904
905 // allele_idx_offsets currently assumed to be initialized to nullptr
906
907 // should handle raw_variant_ct == 0 properly
908
909 // possible todo: optionally skip allele code loading
910 // probable todo: conditionally compute the value previously known as
911 // INFO/END. (does this allow the CNV module to be unified with the rest
912 // of the program?) but this will probably wait until I need to analyze
913 // some sort of CNV data, and that day keeps getting postponed... for now,
914 // the BCF exporter performs its own parsing of INFO/END to have a decent
915 // shot at filling each variant's rlen field correctly.
916 // possible todo: require FILTER to only contain values declared in header,
917 // and modify its storage accordingly? (pointless for now, but worthwhile
918 // to keep an eye on what typical VCF files look like.)
919
920 // Workspace is used as follows:
921 // |--header, allele_storage->----|--other return arrays---|--linebuf--|-
922 // 1/4
923 //
924 // -temp-->----|----<- filter failures, variant IDs, long alleles--|
925 // end
926 // I.e. on successful return, both bigstack_base and bigstack_end will move.
927 // This is designed to be called near the start of a program, at a time when
928 // no large temporary buffer is needed.
929 unsigned char* bigstack_mark = g_bigstack_base;
930 unsigned char* bigstack_end_mark = g_bigstack_end;
931 uintptr_t line_idx = 0;
932 uint32_t max_extra_alt_ct = 0;
933 uint32_t max_allele_slen = 1;
934 PglErr reterr = kPglRetSuccess;
935 TextStream pvar_txs;
936 PreinitTextStream(&pvar_txs);
937 {
938 const uintptr_t quarter_left = RoundDownPow2(bigstack_left() / 4, kCacheline);
939 uint32_t max_line_blen;
940 if (unlikely(StandardizeMaxLineBlenEx(quarter_left, kLoadPvarBlockSize * 2 * sizeof(intptr_t), &max_line_blen))) {
941 goto LoadPvar_ret_NOMEM;
942 }
943 // bugfix (29 Jun 2018): don't cap allele_storage space at 2 GB, otherwise
944 // we're limited to 134M variants
945 unsigned char* rlstream_start = &(bigstack_mark[quarter_left]);
946 g_bigstack_base = rlstream_start;
947 uint32_t decompress_thread_ct = max_thread_ct - 1;
948 // 3 still seems best on a heavily multicore Linux test machine
949 if (decompress_thread_ct > 3) {
950 decompress_thread_ct = 3;
951 } else if (!decompress_thread_ct) {
952 decompress_thread_ct = 1;
953 }
954 reterr = InitTextStream(pvarname, max_line_blen, decompress_thread_ct, &pvar_txs);
955 if (unlikely(reterr)) {
956 goto LoadPvar_ret_TSTREAM_FAIL;
957 }
958 unsigned char* tmp_alloc_base = g_bigstack_base;
959 g_bigstack_base = bigstack_mark;
960
961 char* xheader_end = ((pvar_psam_flags & (kfPvarColXheader | kfPvarColVcfheader)) || xheader_needed)? R_CAST(char*, bigstack_mark) : nullptr;
962 uint32_t chrset_present = 0;
963 uint32_t info_pr_exists = 0;
964 uint32_t info_pr_nonflag_exists = 0;
965 uint32_t info_nonpr_present = 0;
966 char* line_iter = TextLineEnd(&pvar_txs);
967 char* line_start;
968 while (1) {
969 ++line_idx;
970 if (!TextGetUnsafe2(&pvar_txs, &line_iter)) {
971 if (unlikely(TextStreamErrcode2(&pvar_txs, &reterr))) {
972 goto LoadPvar_ret_TSTREAM_FAIL;
973 }
974 line_start = K_CAST(char*, &(g_one_char_strs[0]));
975 --line_iter;
976 break;
977 }
978 line_start = line_iter;
979 if ((*line_start != '#') || tokequal_k(line_start, "#CHROM")) {
980 break;
981 }
982 if (StrStartsWithUnsafe(line_start, "##INFO=<")) {
983 line_iter = &(line_iter[strlen("##INFO=<")]);
984 char* idval;
985 uint32_t id_slen;
986 if (unlikely(HkvlineId(&line_iter, &idval, &id_slen))) {
987 goto LoadPvar_ret_MALFORMED_HEADER_LINE;
988 }
989 if (strequal_k(idval, "PR", id_slen)) {
990 if (unlikely(info_pr_exists || info_pr_nonflag_exists)) {
991 snprintf(g_logbuf, kLogbufSize, "Error: Duplicate INFO/PR header line in %s.\n", pvarname);
992 goto LoadPvar_ret_MALFORMED_INPUT_WW;
993 }
994 // Could also enforce numstr == "0".
995 char* typestr;
996 uint32_t type_slen;
997 if (unlikely(HkvlineFind(line_iter, "Type", &typestr, &type_slen))) {
998 goto LoadPvar_ret_MALFORMED_HEADER_LINE;
999 }
1000 info_pr_nonflag_exists = !strequal_k(typestr, "Flag", type_slen);
1001 info_pr_exists = 1 - info_pr_nonflag_exists;
1002 if (info_pr_nonflag_exists) {
1003 logerrprintfww("Warning: Header line %" PRIuPTR " of %s has an unexpected definition of INFO/PR. This interferes with a few merge and liftover operations.\n", line_idx, pvarname);
1004 }
1005 } else if (!info_nonpr_present) {
1006 info_nonpr_present = 1;
1007 }
1008 }
1009 if (StrStartsWithUnsafe(line_start, "##chrSet=<")) {
1010 if (unlikely(chrset_present)) {
1011 snprintf(g_logbuf, kLogbufSize, "Error: Multiple ##chrSet header lines in %s.\n", pvarname);
1012 goto LoadPvar_ret_MALFORMED_INPUT_WW;
1013 }
1014 chrset_present = 1;
1015 const uint32_t cmdline_chrset = (cip->chrset_source == kChrsetSourceCmdline) && (!(misc_flags & kfMiscChrOverrideFile));
1016 reterr = ReadChrsetHeaderLine(&(line_start[strlen("##chrSet=<")]), pvarname, misc_flags, line_idx, cip);
1017 if (unlikely(reterr)) {
1018 goto LoadPvar_ret_1;
1019 }
1020 if (!cmdline_chrset) {
1021 const uint32_t autosome_ct = cip->autosome_ct;
1022 if (cip->haploid_mask[0] & 1) {
1023 logprintf("chrSet header line: %u autosome%s (haploid).\n", autosome_ct, (autosome_ct == 1)? "" : "s");
1024 } else {
1025 logprintf("chrSet header line: %u autosome pair%s.\n", autosome_ct, (autosome_ct == 1)? "" : "s");
1026 }
1027 }
1028 } else if (xheader_end) {
1029 // if the "pvar file" was actually a VCF, suppress the same lines we'd
1030 // suppress when importing with --vcf.
1031 if ((!StrStartsWithUnsafe(line_start, "##fileformat=")) &&
1032 (!StrStartsWithUnsafe(line_start, "##fileDate=")) &&
1033 (!StrStartsWithUnsafe(line_start, "##source=")) &&
1034 (!StrStartsWithUnsafe(line_start, "##FORMAT="))) {
1035 char* line_lf = AdvToDelim(line_start, '\n');
1036 uint32_t line_slen = line_lf - line_start;
1037 if (line_start[line_slen - 1] == '\r') {
1038 --line_slen;
1039 }
1040 if (unlikely(S_CAST(uintptr_t, R_CAST(char*, rlstream_start) - xheader_end) < line_slen + 2)) {
1041 goto LoadPvar_ret_NOMEM;
1042 }
1043 xheader_end = memcpya(xheader_end, line_start, line_slen);
1044 AppendBinaryEoln(&xheader_end);
1045 line_iter = line_lf;
1046 }
1047 }
1048 line_iter = AdvPastDelim(line_iter, '\n');
1049 }
1050 if (xheader_end) {
1051 *xheader_ptr = R_CAST(char*, bigstack_mark);
1052 *xheader_blen_ptr = xheader_end - (*xheader_ptr);
1053 BigstackBaseSet(xheader_end);
1054 }
1055 FinalizeChrset(misc_flags, cip);
1056 const char** allele_storage = R_CAST(const char**, g_bigstack_base);
1057 const char** allele_storage_iter = allele_storage;
1058
1059 uint32_t col_skips[8];
1060 uint32_t col_types[8];
1061 uint32_t relevant_postchr_col_ct = 5;
1062 uint32_t no_multiallelic_allowed = 0;
1063 uint32_t alt_col_idx = 4;
1064 uint32_t load_qual_col = 0;
1065 uint32_t load_filter_col = 0;
1066 uint32_t info_col_present = 0;
1067 uint32_t cm_col_present = 0;
1068 if (line_start[0] == '#') {
1069 *info_flags_ptr = S_CAST(InfoFlags, (info_pr_exists * kfInfoPrFlagPresent) | (info_pr_nonflag_exists * kfInfoPrNonflagPresent) | (info_nonpr_present * kfInfoNonprPresent));
1070 // parse header
1071 // [-1] = #CHROM (must be first column)
1072 // [0] = POS
1073 // [1] = ID
1074 // [2] = REF
1075 // [3] = ALT
1076 // [4] = QUAL
1077 // [5] = FILTER
1078 // [6] = INFO
1079 // [7] = CM (usually absent)
1080
1081 // code is similar to plink 1.9 annotate() and gene_report(), but they
1082 // don't have a forced first column
1083 // might want to write plink2_common library functions for this...
1084 const char* token_end = &(line_start[6]);
1085 uint32_t found_header_bitset = 0;
1086 relevant_postchr_col_ct = 0;
1087 const char* linebuf_iter;
1088 for (uint32_t col_idx = 1; ; ++col_idx) {
1089 linebuf_iter = FirstNonTspace(token_end);
1090 if (IsEolnKns(*linebuf_iter)) {
1091 break;
1092 }
1093 token_end = CurTokenEnd(linebuf_iter);
1094 const uint32_t token_slen = token_end - linebuf_iter;
1095 uint32_t cur_col_type;
1096 if (token_slen <= 3) {
1097 if (token_slen == 3) {
1098 if (memequal_sk(linebuf_iter, "POS")) {
1099 cur_col_type = 0;
1100 } else if (memequal_sk(linebuf_iter, "REF")) {
1101 cur_col_type = 2;
1102 } else if (memequal_sk(linebuf_iter, "ALT")) {
1103 cur_col_type = 3;
1104 alt_col_idx = col_idx;
1105 } else {
1106 continue;
1107 }
1108 } else if (token_slen == 2) {
1109 if (memequal_sk(linebuf_iter, "ID")) {
1110 cur_col_type = 1;
1111 } else if (memequal_sk(linebuf_iter, "CM")) {
1112 cur_col_type = 7;
1113 cm_col_present = 1;
1114 } else {
1115 continue;
1116 }
1117 } else {
1118 continue;
1119 }
1120 } else if (strequal_k(linebuf_iter, "QUAL", token_slen)) {
1121 load_qual_col = 2 * ((pvar_psam_flags & (kfPvarColMaybequal | kfPvarColQual)) || qualfilter_needed) + (var_min_qual != -1);
1122 if (!load_qual_col) {
1123 continue;
1124 }
1125 cur_col_type = 4;
1126 } else if (strequal_k(linebuf_iter, "INFO", token_slen)) {
1127 cur_col_type = 6;
1128 info_col_present = 1;
1129 } else if (token_slen == 6) {
1130 if (memequal_sk(linebuf_iter, "FILTER")) {
1131 load_filter_col = 2 * ((pvar_psam_flags & (kfPvarColMaybefilter | kfPvarColFilter)) || qualfilter_needed) + ((misc_flags / kfMiscExcludePvarFilterFail) & 1);
1132 if (!load_filter_col) {
1133 continue;
1134 }
1135 cur_col_type = 5;
1136 } else if (memequal_sk(linebuf_iter, "FORMAT")) {
1137 break;
1138 } else {
1139 continue;
1140 }
1141 } else {
1142 continue;
1143 }
1144 const uint32_t cur_col_type_shifted = 1 << cur_col_type;
1145 if (unlikely(found_header_bitset & cur_col_type_shifted)) {
1146 // known token, so no overflow danger
1147 char* write_iter = strcpya_k(g_logbuf, "Error: Duplicate column header '");
1148 write_iter = memcpya(write_iter, linebuf_iter, token_slen);
1149 write_iter = strcpya_k(write_iter, "' on line ");
1150 write_iter = wtoa(line_idx, write_iter);
1151 write_iter = strcpya_k(write_iter, " of ");
1152 write_iter = strcpya(write_iter, pvarname);
1153 memcpy_k(write_iter, ".\n\0", 4);
1154 goto LoadPvar_ret_MALFORMED_INPUT_WW;
1155 }
1156 found_header_bitset |= cur_col_type_shifted;
1157 col_skips[relevant_postchr_col_ct] = col_idx;
1158 col_types[relevant_postchr_col_ct++] = cur_col_type;
1159 }
1160 if (unlikely((found_header_bitset & 0x0f) != 0x0f)) {
1161 snprintf(g_logbuf, kLogbufSize, "Error: Missing column header(s) on line %" PRIuPTR " of %s. (POS, ID, REF, and ALT are required.)\n", line_idx, pvarname);
1162 goto LoadPvar_ret_MALFORMED_INPUT_WW;
1163 }
1164 if ((var_min_qual != -1) && (!(found_header_bitset & 0x10))) {
1165 logerrputs("Error: --var-min-qual used on a variant file with no QUAL column.\n");
1166 goto LoadPvar_ret_INCONSISTENT_INPUT;
1167 }
1168 for (uint32_t rpc_col_idx = relevant_postchr_col_ct - 1; rpc_col_idx; --rpc_col_idx) {
1169 col_skips[rpc_col_idx] -= col_skips[rpc_col_idx - 1];
1170 }
1171 // skip this line in main loop
1172 line_iter = K_CAST(char*, AdvToDelim(linebuf_iter, '\n'));
1173 line_start = line_iter;
1174 } else if (line_start[0] != '\n') {
1175 no_multiallelic_allowed = 1;
1176 if (var_min_qual != -1) {
1177 logerrputs("Error: --var-min-qual used on a variant file with no QUAL column.\n");
1178 goto LoadPvar_ret_INCONSISTENT_INPUT;
1179 }
1180 *info_flags_ptr = kfInfoPrNonrefDefault;
1181 col_skips[0] = 1;
1182 col_skips[1] = 1;
1183 col_skips[2] = 1;
1184 col_skips[3] = 1;
1185 col_types[0] = 1;
1186 // CM column is formally optional in headerless .pvar files (and it was
1187 // "secretly" optional for the standard plink 1.9 standard .bim loader).
1188 // If the line has exactly 5 columns, assume CM is omitted.
1189
1190 // Note that this doesn't break in the line_start = &(g_one_char_strs[0])
1191 // case.
1192 const char* linebuf_iter = NextTokenMult(line_start, 4);
1193 if (unlikely(!linebuf_iter)) {
1194 goto LoadPvar_ret_MISSING_TOKENS;
1195 }
1196 linebuf_iter = NextToken(linebuf_iter);
1197 if (!linebuf_iter) {
1198 // #CHROM ID POS ALT REF
1199 relevant_postchr_col_ct = 4;
1200 col_types[1] = 0;
1201 col_types[2] = 3;
1202 col_types[3] = 2;
1203 alt_col_idx = 3;
1204 } else {
1205 // #CHROM ID CM POS ALT REF
1206 col_skips[4] = 1;
1207 col_types[1] = 7;
1208 col_types[2] = 0;
1209 col_types[3] = 3;
1210 col_types[4] = 2;
1211 // alt_col_idx = 4;
1212 cm_col_present = 1;
1213 }
1214 }
1215 uint32_t info_reload_slen = *info_reload_slen_ptr;
1216
1217 // done with header. line_start now points to either the beginning of the
1218 // first real line, or an eoln character.
1219 uint32_t max_variant_id_slen = *max_variant_id_slen_ptr;
1220 uint32_t chrs_encountered_m1 = UINT32_MAX; // intentional overflow
1221 uint32_t prev_chr_code = UINT32_MAX; // force initial mismatch
1222 uint32_t raw_variant_ct = 0;
1223 uintptr_t* chr_mask = cip->chr_mask;
1224 const char* missing_allele_str = &(g_one_char_strs[92]);
1225 double last_cm = -DBL_MAX;
1226 int32_t last_bp = 0;
1227
1228 // this way, we only need to check allele_storage_iter against this (i)
1229 // when processing a multiallelic variant or (ii) at the end of a block
1230 const char** allele_storage_limit = R_CAST(const char**, &(rlstream_start[-S_CAST(intptr_t, kLoadPvarBlockSize * 2 * sizeof(intptr_t))]));
1231
1232 uintptr_t* loaded_chr_mask = R_CAST(uintptr_t*, tmp_alloc_base);
1233 unsigned char* tmp_alloc_end = bigstack_end_mark;
1234 // guaranteed to succeed since max_line_blen > 128k, etc.
1235 /*
1236 if ((uintptr_t)(tmp_alloc_end - tmp_alloc_base) < RoundUpPow2(kChrMaskWords * sizeof(intptr_t), kCacheline)) {
1237 goto LoadPvar_ret_NOMEM;
1238 }
1239 */
1240 tmp_alloc_base = &(tmp_alloc_base[RoundUpPow2(kChrMaskWords * sizeof(intptr_t), kCacheline)]);
1241 // bugfix (2 Jun 2017): forgot to zero-initialize loaded_chr_mask
1242 ZeroWArr(kChrMaskWords, loaded_chr_mask);
1243
1244 InfoExist* info_existp = nullptr;
1245 if (require_info_flattened) {
1246 reterr = InfoExistInit(tmp_alloc_end, require_info_flattened, "require-info", &tmp_alloc_base, &info_existp);
1247 if (unlikely(reterr)) {
1248 goto LoadPvar_ret_1;
1249 }
1250 }
1251 InfoExist* info_nonexistp = nullptr;
1252 if (require_no_info_flattened) {
1253 reterr = InfoExistInit(tmp_alloc_end, require_no_info_flattened, "require-no-info", &tmp_alloc_base, &info_nonexistp);
1254 if (unlikely(reterr)) {
1255 goto LoadPvar_ret_1;
1256 }
1257 }
1258 InfoFilter info_keep;
1259 info_keep.prekey = nullptr;
1260 if (extract_if_info_exprp->pheno_name) {
1261 // todo: also print warning (or optionally error out?) if header line is
1262 // missing or doesn't match type expectation
1263 // (same for --require-info)
1264 reterr = InfoFilterInit(tmp_alloc_end, extract_if_info_exprp, "extract-if-info", &tmp_alloc_base, &info_keep);
1265 if (unlikely(reterr)) {
1266 goto LoadPvar_ret_1;
1267 }
1268 }
1269 InfoFilter info_remove;
1270 info_remove.prekey = nullptr;
1271 if (exclude_if_info_exprp->pheno_name) {
1272 reterr = InfoFilterInit(tmp_alloc_end, exclude_if_info_exprp, "exclude-if-info", &tmp_alloc_base, &info_remove);
1273 if (unlikely(reterr)) {
1274 goto LoadPvar_ret_1;
1275 }
1276 }
1277 if (!info_col_present) {
1278 if (unlikely(require_info_flattened)) {
1279 logerrputs("Error: --require-info used on a variant file with no INFO column.\n");
1280 goto LoadPvar_ret_INCONSISTENT_INPUT;
1281 }
1282 if (unlikely(info_keep.prekey)) {
1283 logerrputs("Error: --extract-if-info used on a variant file with no INFO column.\n");
1284 goto LoadPvar_ret_INCONSISTENT_INPUT;
1285 }
1286 info_pr_exists = 0;
1287 info_reload_slen = 0;
1288 } else if ((!info_pr_exists) && (!info_reload_slen) && (!info_existp) && (!info_nonexistp) && (!info_keep.prekey) && (!info_remove.prekey)) {
1289 info_col_present = 0;
1290 }
1291
1292 uint32_t fexcept_ct = 0;
1293 uintptr_t max_fexcept_blen = 2;
1294 char* sorted_fexcepts = nullptr;
1295 if (var_filter_exceptions_flattened) {
1296 if (unlikely(MultistrToStrboxDedupArenaAlloc(tmp_alloc_end, var_filter_exceptions_flattened, &tmp_alloc_base, &sorted_fexcepts, &fexcept_ct, &max_fexcept_blen))) {
1297 goto LoadPvar_ret_NOMEM;
1298 }
1299 }
1300 char* chr_output_name_buf = nullptr;
1301 VaridTemplate* varid_templatep = nullptr;
1302 VaridTemplate* varid_multi_templatep = nullptr;
1303 VaridTemplate* varid_multi_nonsnp_templatep = nullptr;
1304 uint32_t missing_varid_blen = 0;
1305 uint32_t missing_varid_match_slen = 0;
1306 if (varid_template_str) {
1307 if (unlikely(VaridInitAll(tmp_alloc_end, varid_template_str, varid_multi_template_str, varid_multi_nonsnp_template_str, misc_flags, new_variant_id_max_allele_slen, &tmp_alloc_base, &missing_varid_match, &chr_output_name_buf, &varid_templatep, &varid_multi_templatep, &varid_multi_nonsnp_templatep, &missing_varid_blen, &missing_varid_match_slen))) {
1308 goto LoadPvar_ret_NOMEM;
1309 }
1310 }
1311
1312 // prevent later return-array allocations from overlapping with temporary
1313 // storage
1314 g_bigstack_end = tmp_alloc_base;
1315
1316 // prevent variant_id_htable_find from breaking
1317 if (R_CAST(const char*, tmp_alloc_end) > (&(g_one_char_strs[512 - kMaxIdSlen]))) {
1318 tmp_alloc_end = R_CAST(unsigned char*, K_CAST(char*, &(g_one_char_strs[512 - kMaxIdSlen])));
1319 }
1320 const uint32_t prohibit_extra_chrs = (misc_flags / kfMiscProhibitExtraChr) & 1;
1321 const uint32_t merge_par = ((misc_flags & (kfMiscMergePar | kfMiscMergeX)) != 0);
1322 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
1323 uint32_t parx_code = cip->xymt_codes[kChrOffsetPAR1];
1324 uint32_t par2_code = cip->xymt_codes[kChrOffsetPAR2];
1325 if (misc_flags & kfMiscMergeX) {
1326 parx_code = cip->xymt_codes[kChrOffsetXY];
1327 par2_code = UINT32_MAXM1;
1328 }
1329 uint32_t merge_par_ct = 0;
1330
1331 // Corner case: with --split-par + --not-chr x, we should keep the
1332 // pseudoautosomal regions. To facilitate this, we temporarily don't mask
1333 // out chrX; SplitPar() handles this properly later.
1334 const uint32_t splitpar_and_exclude_x = splitpar_bound2 && (!IsI32Neg(x_code)) && (!IsSet(cip->chr_mask, x_code));
1335 if (splitpar_and_exclude_x) {
1336 SetBit(x_code, cip->chr_mask);
1337 }
1338
1339 uint8_t acgtm_bool_table[256] = {
1340 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1341 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1342 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
1343 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1344 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1345 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1346 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1347 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1348 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1349 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1350 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1351 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1352 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1353 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1354 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1355 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1356 if (snps_only > 1) {
1357 acgtm_bool_table[ctou32(input_missing_geno_char)] = 1;
1358 }
1359
1360 uint32_t* cur_bps = nullptr;
1361 uintptr_t* cur_allele_idxs = nullptr;
1362 char** cur_ids = nullptr;
1363 uintptr_t* cur_include = nullptr;
1364 uintptr_t* cur_qual_present = nullptr;
1365 float* cur_quals = nullptr;
1366 uintptr_t* cur_filter_present = nullptr;
1367 uintptr_t* cur_filter_npass = nullptr;
1368 char** cur_filter_storage = nullptr;
1369 uintptr_t* cur_nonref_flags = nullptr;
1370
1371 // only need this for --set-{missing,all}-var-ids error message
1372 uint32_t max_chr_slen = 0;
1373
1374 uint32_t max_filter_slen = 0;
1375 uint32_t exclude_ct = 0;
1376
1377 // only allocated when necessary
1378 // if we want to scale this approach to more fields, we'll need to add a
1379 // few pointers to the start of each block. right now, we force cur_cms[]
1380 // to be allocated before cur_chr_idxs[] when both are present, but this
1381 // is error-prone.
1382 uint32_t at_least_one_npass_filter = 0;
1383 uint32_t at_least_one_nzero_cm = 0;
1384 uintptr_t new_variant_id_allele_len_overflow = 0;
1385 double* cur_cms = nullptr;
1386 uint32_t cms_start_block = UINT32_MAX;
1387
1388 ChrIdx* cur_chr_idxs = nullptr;
1389 uint32_t chr_idxs_start_block = UINT32_MAX;
1390 uint32_t is_split_chr = 0;
1391 UnsortedVar vpos_sortstatus = kfUnsortedVar0;
1392
1393 if (IsEolnKns(*line_start)) {
1394 ++line_iter;
1395 ++line_idx;
1396 } else {
1397 line_iter = line_start;
1398 }
1399 for (; TextGetUnsafe2(&pvar_txs, &line_iter); ++line_iter, ++line_idx) {
1400 if (unlikely(line_iter[0] == '#')) {
1401 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s starts with a '#'. (This is only permitted before the first nonheader line, and if a #CHROM header line is present it must denote the end of the header block.)\n", line_idx, pvarname);
1402 goto LoadPvar_ret_MALFORMED_INPUT_WW;
1403 }
1404 #ifdef __LP64__
1405 if (unlikely(raw_variant_ct == kPglMaxVariantCt)) {
1406 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");
1407 goto LoadPvar_ret_MALFORMED_INPUT;
1408 }
1409 #endif
1410 const uint32_t variant_idx_lowbits = raw_variant_ct % kLoadPvarBlockSize;
1411 if (!variant_idx_lowbits) {
1412 if (unlikely((S_CAST(uintptr_t, tmp_alloc_end - tmp_alloc_base) <=
1413 kLoadPvarBlockSize *
1414 (sizeof(int32_t) +
1415 2 * sizeof(intptr_t) +
1416 at_least_one_nzero_cm * sizeof(double)) +
1417 is_split_chr * sizeof(ChrIdx) +
1418 (1 + info_pr_exists) * (kLoadPvarBlockSize / CHAR_BIT) +
1419 (load_qual_col? ((kLoadPvarBlockSize / CHAR_BIT) + kLoadPvarBlockSize * sizeof(float)) : 0) +
1420 (load_filter_col? (2 * (kLoadPvarBlockSize / CHAR_BIT) + kLoadPvarBlockSize * sizeof(intptr_t)) : 0)) ||
1421 (allele_storage_iter >= allele_storage_limit))) {
1422 goto LoadPvar_ret_NOMEM;
1423 }
1424 cur_bps = R_CAST(uint32_t*, tmp_alloc_base);
1425 cur_allele_idxs = R_CAST(uintptr_t*, &(tmp_alloc_base[kLoadPvarBlockSize * sizeof(int32_t)]));
1426 cur_ids = R_CAST(char**, &(tmp_alloc_base[kLoadPvarBlockSize * (sizeof(int32_t) + sizeof(intptr_t))]));
1427 cur_include = R_CAST(uintptr_t*, &(tmp_alloc_base[kLoadPvarBlockSize * (sizeof(int32_t) + 2 * sizeof(intptr_t))]));
1428 SetAllWArr(kLoadPvarBlockSize / kBitsPerWord, cur_include);
1429 tmp_alloc_base = &(tmp_alloc_base[kLoadPvarBlockSize * (sizeof(int32_t) + 2 * sizeof(intptr_t)) + (kLoadPvarBlockSize / CHAR_BIT)]);
1430 if (load_qual_col > 1) {
1431 cur_qual_present = R_CAST(uintptr_t*, tmp_alloc_base);
1432 ZeroWArr(kLoadPvarBlockSize / kBitsPerWord, cur_qual_present);
1433 cur_quals = R_CAST(float*, &(tmp_alloc_base[kLoadPvarBlockSize / CHAR_BIT]));
1434 tmp_alloc_base = &(tmp_alloc_base[kLoadPvarBlockSize * sizeof(float) + (kLoadPvarBlockSize / CHAR_BIT)]);
1435 }
1436 if (load_filter_col > 1) {
1437 cur_filter_present = R_CAST(uintptr_t*, tmp_alloc_base);
1438 cur_filter_npass = R_CAST(uintptr_t*, &(tmp_alloc_base[kLoadPvarBlockSize / CHAR_BIT]));
1439 cur_filter_storage = R_CAST(char**, &(tmp_alloc_base[2 * (kLoadPvarBlockSize / CHAR_BIT)]));
1440 ZeroWArr(kLoadPvarBlockSize / kBitsPerWord, cur_filter_present);
1441 ZeroWArr(kLoadPvarBlockSize / kBitsPerWord, cur_filter_npass);
1442 tmp_alloc_base = &(tmp_alloc_base[2 * (kLoadPvarBlockSize / CHAR_BIT) + kLoadPvarBlockSize * sizeof(intptr_t)]);
1443 }
1444 if (info_pr_exists) {
1445 cur_nonref_flags = R_CAST(uintptr_t*, tmp_alloc_base);
1446 ZeroWArr(kLoadPvarBlockSize / kBitsPerWord, cur_nonref_flags);
1447 tmp_alloc_base = &(tmp_alloc_base[kLoadPvarBlockSize / CHAR_BIT]);
1448 }
1449 if (at_least_one_nzero_cm) {
1450 cur_cms = R_CAST(double*, tmp_alloc_base);
1451 ZeroDArr(kLoadPvarBlockSize, cur_cms);
1452 tmp_alloc_base = R_CAST(unsigned char*, &(cur_cms[kLoadPvarBlockSize]));
1453 }
1454 if (is_split_chr) {
1455 cur_chr_idxs = R_CAST(ChrIdx*, tmp_alloc_base);
1456 tmp_alloc_base = R_CAST(unsigned char*, &(cur_chr_idxs[kLoadPvarBlockSize]));
1457 }
1458 }
1459 char* linebuf_iter = CurTokenEnd(line_iter);
1460 // #CHROM
1461 if (unlikely(*linebuf_iter == '\n')) {
1462 goto LoadPvar_ret_MISSING_TOKENS;
1463 }
1464 uint32_t cur_chr_code;
1465 reterr = GetOrAddChrCodeDestructive(".pvar file", line_idx, prohibit_extra_chrs, line_iter, linebuf_iter, cip, &cur_chr_code);
1466 if (unlikely(reterr)) {
1467 goto LoadPvar_ret_1;
1468 }
1469 if (merge_par) {
1470 if (cur_chr_code == par2_code) {
1471 // don't permit PAR1 variants after PAR2
1472 parx_code = par2_code;
1473 }
1474 if (cur_chr_code == parx_code) {
1475 ++merge_par_ct;
1476 cur_chr_code = x_code;
1477 }
1478 }
1479 if (cur_chr_code != prev_chr_code) {
1480 prev_chr_code = cur_chr_code;
1481 if (!is_split_chr) {
1482 if (IsSet(loaded_chr_mask, cur_chr_code)) {
1483 if (unlikely(!split_chr_ok)) {
1484 snprintf(g_logbuf, kLogbufSize, "Error: %s has a split chromosome. Use --make-pgen + --sort-vars (without other simultaneous commands) to remedy this.\n", pvarname);
1485 goto LoadPvar_ret_MALFORMED_INPUT_WW;
1486 }
1487 if (unlikely(S_CAST(uintptr_t, tmp_alloc_end - tmp_alloc_base) < kLoadPvarBlockSize * sizeof(ChrIdx))) {
1488 goto LoadPvar_ret_NOMEM;
1489 }
1490 cur_chr_idxs = R_CAST(ChrIdx*, tmp_alloc_base);
1491 tmp_alloc_base = R_CAST(unsigned char*, &(cur_chr_idxs[kLoadPvarBlockSize]));
1492 // may want to track the first problem variant index
1493 // cip->chr_fo_vidx_start[chrs_encountered_m1] = raw_variant_ct;
1494 BackfillChrIdxs(cip, chrs_encountered_m1, RoundDownPow2(raw_variant_ct, kLoadPvarBlockSize), raw_variant_ct, cur_chr_idxs);
1495 chr_idxs_start_block = raw_variant_ct / kLoadPvarBlockSize;
1496 is_split_chr = 1;
1497 vpos_sortstatus |= kfUnsortedVarBp | kfUnsortedVarCm | kfUnsortedVarSplitChr;
1498 } else {
1499 // how much of this do we need in split-chrom case?
1500 cip->chr_file_order[++chrs_encountered_m1] = cur_chr_code;
1501 cip->chr_fo_vidx_start[chrs_encountered_m1] = raw_variant_ct;
1502 cip->chr_idx_to_foidx[cur_chr_code] = chrs_encountered_m1;
1503 last_cm = -DBL_MAX;
1504 }
1505 }
1506 // always need to set this, if we want to avoid chromosome-length
1507 // overestimation in --sort-vars + early-variant-filter +
1508 // pvar-cols=+vcfheader case.
1509 last_bp = 0;
1510
1511 SetBit(cur_chr_code, loaded_chr_mask);
1512 if (chr_output_name_buf) {
1513 char* chr_name_end = chrtoa(cip, cur_chr_code, chr_output_name_buf);
1514 const uint32_t chr_slen = chr_name_end - chr_output_name_buf;
1515 if (chr_slen > max_chr_slen) {
1516 max_chr_slen = chr_slen;
1517 }
1518 const int32_t chr_slen_delta = chr_slen - varid_templatep->chr_slen;
1519 varid_templatep->chr_slen = chr_slen;
1520 varid_templatep->base_len += chr_slen_delta;
1521 if (varid_multi_templatep) {
1522 varid_multi_templatep->chr_slen = chr_slen;
1523 varid_multi_templatep->base_len += chr_slen_delta;
1524 }
1525 if (varid_multi_nonsnp_templatep) {
1526 varid_multi_nonsnp_templatep->chr_slen = chr_slen;
1527 varid_multi_nonsnp_templatep->base_len += chr_slen_delta;
1528 }
1529 }
1530 }
1531 *linebuf_iter = '\t';
1532
1533 // could make this store (and cur_allele_idxs[] allocation) conditional
1534 // on a multiallelic variant being sighted, but unlike the CM column
1535 // this should become common
1536 cur_allele_idxs[variant_idx_lowbits] = allele_storage_iter - allele_storage;
1537
1538 char* token_ptrs[8];
1539 uint32_t token_slens[8];
1540 uint32_t extra_alt_ct;
1541 if (IsSet(chr_mask, cur_chr_code) || info_pr_exists) {
1542 linebuf_iter = TokenLex(linebuf_iter, col_types, col_skips, relevant_postchr_col_ct, token_ptrs, token_slens);
1543 if (unlikely(!linebuf_iter)) {
1544 goto LoadPvar_ret_MISSING_TOKENS;
1545 }
1546
1547 extra_alt_ct = CountByte(token_ptrs[3], ',', token_slens[3]);
1548 if (extra_alt_ct > max_extra_alt_ct) {
1549 if (extra_alt_ct >= kPglMaxAltAlleleCt) {
1550 logerrprintfww("Error: Too many ALT alleles on line %" PRIuPTR " of %s. (This " PROG_NAME_STR " build is limited to " PGL_MAX_ALT_ALLELE_CT_STR ".)\n", line_idx, pvarname);
1551 reterr = kPglRetNotYetSupported;
1552 goto LoadPvar_ret_1;
1553 }
1554 max_extra_alt_ct = extra_alt_ct;
1555 }
1556
1557 // It is possible for the info_token[info_slen] assignment below to
1558 // clobber the line terminator, so we advance line_iter to eoln here
1559 // and never reference it again before the next line.
1560 line_iter = AdvToDelim(linebuf_iter, '\n');
1561 if (info_col_present) {
1562 const uint32_t info_slen = token_slens[6];
1563 if (info_slen > info_reload_slen) {
1564 info_reload_slen = info_slen;
1565 }
1566 char* info_token = token_ptrs[6];
1567 info_token[info_slen] = '\0';
1568 if (info_pr_exists) {
1569 // always load all nonref_flags entries so (i) --ref-from-fa +
1570 // --make-just-pvar works and (ii) they can be compared against
1571 // the .pgen.
1572 if ((memequal_sk(info_token, "PR") && ((info_slen == 2) || (info_token[2] == ';'))) || memequal_sk(&(info_token[S_CAST(int32_t, info_slen) - 3]), ";PR")) {
1573 SetBit(variant_idx_lowbits, cur_nonref_flags);
1574 } else {
1575 const char* first_info_end = strchr(info_token, ';');
1576 if (first_info_end && strstr(first_info_end, ";PR;")) {
1577 SetBit(variant_idx_lowbits, cur_nonref_flags);
1578 }
1579 }
1580 if (!IsSet(chr_mask, cur_chr_code)) {
1581 goto LoadPvar_skip_variant;
1582 }
1583 }
1584 if (info_existp) {
1585 if (!InfoExistCheck(info_token, info_existp)) {
1586 goto LoadPvar_skip_variant;
1587 }
1588 }
1589 if (info_nonexistp) {
1590 if (!InfoNonexistCheck(info_token, info_nonexistp)) {
1591 goto LoadPvar_skip_variant;
1592 }
1593 }
1594 if (info_keep.prekey) {
1595 if (!InfoConditionSatisfied(info_token, &info_keep)) {
1596 goto LoadPvar_skip_variant;
1597 }
1598 }
1599 if (info_remove.prekey) {
1600 if (InfoConditionSatisfied(info_token, &info_remove)) {
1601 goto LoadPvar_skip_variant;
1602 }
1603 }
1604 }
1605 // POS
1606 int32_t cur_bp;
1607 if (unlikely(ScanIntAbsDefcap(token_ptrs[0], &cur_bp))) {
1608 snprintf(g_logbuf, kLogbufSize, "Error: Invalid bp coordinate on line %" PRIuPTR " of %s.\n", line_idx, pvarname);
1609 goto LoadPvar_ret_MALFORMED_INPUT_WW;
1610 }
1611
1612 if (cur_bp < 0) {
1613 goto LoadPvar_skip_variant;
1614 }
1615
1616 // QUAL
1617 if (load_qual_col) {
1618 const char* qual_token = token_ptrs[4];
1619 if ((qual_token[0] != '.') || (qual_token[1] > ' ')) {
1620 float cur_qual;
1621 if (unlikely(ScanFloatAllowInf(qual_token, &cur_qual))) {
1622 snprintf(g_logbuf, kLogbufSize, "Error: Invalid QUAL value on line %" PRIuPTR " of %s.\n", line_idx, pvarname);
1623 goto LoadPvar_ret_MALFORMED_INPUT_WW;
1624 }
1625 if ((load_qual_col & 1) && (cur_qual < var_min_qual)) {
1626 goto LoadPvar_skip_variant;
1627 }
1628 if (load_qual_col > 1) {
1629 SetBit(variant_idx_lowbits, cur_qual_present);
1630 // possible todo: optimize all-quals-same case
1631 // possible todo: conditionally allocate, like cur_cms
1632 cur_quals[variant_idx_lowbits] = cur_qual;
1633 }
1634 } else if (load_qual_col & 1) {
1635 goto LoadPvar_skip_variant;
1636 }
1637 }
1638
1639 // avoid repeating the ALT string split in --set-...-var-ids case
1640 linebuf_iter = token_ptrs[3];
1641 uint32_t remaining_alt_char_ct = token_slens[3];
1642 // handle --snps-only here instead of later, since it reduces the
1643 // amount of data we need to load
1644 if (snps_only) {
1645 if ((token_slens[2] != 1) || (remaining_alt_char_ct != 2 * extra_alt_ct + 1)) {
1646 goto LoadPvar_skip_variant;
1647 }
1648 if (snps_only > 1) {
1649 // just-acgt
1650 if (!acgtm_bool_table[ctou32(token_ptrs[2][0])]) {
1651 goto LoadPvar_skip_variant;
1652 }
1653 for (uint32_t uii = 0; uii <= extra_alt_ct; ++uii) {
1654 if (!acgtm_bool_table[ctou32(linebuf_iter[2 * uii])]) {
1655 goto LoadPvar_skip_variant;
1656 }
1657 }
1658 }
1659 }
1660
1661 // also handle --min-alleles/--max-alleles here
1662 if (filter_min_allele_ct || (filter_max_allele_ct <= kPglMaxAltAlleleCt)) {
1663 uint32_t allele_ct = extra_alt_ct + 2;
1664 if (!extra_alt_ct) {
1665 // allele_ct == 1 or 2 for filtering purposes, depending on
1666 // whether ALT allele matches a missing code. (Don't see a reason
1667 // to subtract 1 for missing REF.)
1668 if ((remaining_alt_char_ct == 1) && ((linebuf_iter[0] == '.') || (linebuf_iter[0] == input_missing_geno_char))) {
1669 allele_ct = 1;
1670 }
1671 }
1672 if ((allele_ct < filter_min_allele_ct) || (allele_ct > filter_max_allele_ct)) {
1673 goto LoadPvar_skip_variant;
1674 }
1675 }
1676
1677 // FILTER
1678 if (load_filter_col) {
1679 const char* filter_token = token_ptrs[5];
1680 const uint32_t filter_slen = token_slens[5];
1681 if ((filter_slen > 1) || (filter_token[0] != '.')) {
1682 if (!strequal_k(filter_token, "PASS", filter_slen)) {
1683 if (load_filter_col & 1) {
1684 if (!fexcept_ct) {
1685 goto LoadPvar_skip_variant;
1686 }
1687 const char* filter_token_end = &(filter_token[filter_slen]);
1688 for (const char* filter_token_iter = filter_token; ; ) {
1689 const char* cur_filter_name_end = AdvToDelimOrEnd(filter_token_iter, filter_token_end, ';');
1690 uint32_t cur_slen = cur_filter_name_end - filter_token_iter;
1691 // possible todo: error out on "PASS", since that
1692 // shouldn't coexist with other filters
1693 // possible todo: maintain a dictionary of FILTER
1694 // strings, analogous to what BCF2 does on disk
1695 if (bsearch_strbox(filter_token_iter, sorted_fexcepts, cur_slen, max_fexcept_blen, fexcept_ct) == -1) {
1696 goto LoadPvar_skip_variant;
1697 }
1698 if (cur_filter_name_end == filter_token_end) {
1699 break;
1700 }
1701 filter_token_iter = &(cur_filter_name_end[1]);
1702 }
1703 }
1704 if (load_filter_col > 1) {
1705 SetBit(variant_idx_lowbits, cur_filter_npass);
1706 at_least_one_npass_filter = 1;
1707 // possible todo: detect repeated filter values, store more
1708 // compactly
1709 if (filter_slen > max_filter_slen) {
1710 max_filter_slen = filter_slen;
1711 }
1712 if (StoreStringAtEnd(tmp_alloc_base, filter_token, filter_slen, &tmp_alloc_end, &(cur_filter_storage[variant_idx_lowbits]))) {
1713 goto LoadPvar_ret_NOMEM;
1714 }
1715 }
1716 }
1717 if (load_filter_col > 1) {
1718 SetBit(variant_idx_lowbits, cur_filter_present);
1719 }
1720 }
1721 }
1722
1723 if (cur_chr_idxs) {
1724 cur_chr_idxs[variant_idx_lowbits] = cur_chr_code;
1725 }
1726 if (cur_bp < last_bp) {
1727 vpos_sortstatus |= kfUnsortedVarBp;
1728 }
1729 cur_bps[variant_idx_lowbits] = cur_bp;
1730 last_bp = cur_bp;
1731 const uint32_t ref_slen = token_slens[2];
1732 uint32_t id_slen;
1733 if ((!varid_templatep) || (missing_varid_match_slen && ((token_slens[1] != missing_varid_match_slen) || (!memequal(token_ptrs[1], missing_varid_match, missing_varid_match_slen))))) {
1734 id_slen = token_slens[1];
1735 if (PtrWSubCk(tmp_alloc_base, id_slen + 1, &tmp_alloc_end)) {
1736 goto LoadPvar_ret_NOMEM;
1737 }
1738 memcpyx(tmp_alloc_end, token_ptrs[1], id_slen, '\0');
1739 } else {
1740 VaridTemplate* cur_varid_templatep = varid_templatep;
1741 if (extra_alt_ct && (varid_multi_templatep || varid_multi_nonsnp_templatep)) {
1742 if (varid_multi_templatep) {
1743 cur_varid_templatep = varid_multi_templatep;
1744 }
1745 if (varid_multi_nonsnp_templatep) {
1746 if ((ref_slen > 1) || (remaining_alt_char_ct != 2 * extra_alt_ct + 1)) {
1747 cur_varid_templatep = varid_multi_nonsnp_templatep;
1748 }
1749 }
1750 }
1751 if (unlikely(VaridTemplateApply(tmp_alloc_base, cur_varid_templatep, token_ptrs[2], linebuf_iter, cur_bp, token_slens[2], extra_alt_ct, remaining_alt_char_ct, &tmp_alloc_end, &new_variant_id_allele_len_overflow, &id_slen))) {
1752 goto LoadPvar_ret_NOMEM;
1753 }
1754 }
1755 if (id_slen > max_variant_id_slen) {
1756 max_variant_id_slen = id_slen;
1757 }
1758 cur_ids[variant_idx_lowbits] = R_CAST(char*, tmp_alloc_end);
1759
1760 // REF
1761 const char* ref_allele = token_ptrs[2];
1762 char ref_allele_first_char = ref_allele[0];
1763 uint32_t missing_allele_ct = 0;
1764 if (ref_slen == 1) {
1765 if (ref_allele_first_char == input_missing_geno_char) {
1766 ref_allele_first_char = '.';
1767 }
1768 missing_allele_ct += (ref_allele_first_char == '.');
1769 *allele_storage_iter = &(g_one_char_strs[2 * ctou32(ref_allele_first_char)]);
1770 } else {
1771 // sanity check: prohibit comma
1772 // (could also do it in ref_slen == 1 case, but that's much less
1773 // likely to happen by accident)
1774 if (unlikely(memchr(ref_allele, ',', ref_slen) != nullptr)) {
1775 snprintf(g_logbuf, kLogbufSize, "Error: Invalid REF allele on line %" PRIuPTR " of %s.\n", line_idx, pvarname);
1776 goto LoadPvar_ret_MALFORMED_INPUT_WW;
1777 }
1778 if (StoreStringAtEndK(tmp_alloc_base, ref_allele, ref_slen, &tmp_alloc_end, allele_storage_iter)) {
1779 goto LoadPvar_ret_NOMEM;
1780 }
1781 if (ref_slen > max_allele_slen) {
1782 max_allele_slen = ref_slen;
1783 }
1784 }
1785 ++allele_storage_iter;
1786
1787 // ALT
1788 if (extra_alt_ct) {
1789 if (PtrCheck(allele_storage_limit, allele_storage_iter, extra_alt_ct * sizeof(intptr_t))) {
1790 goto LoadPvar_ret_NOMEM;
1791 }
1792 char* alt_token_end = &(linebuf_iter[remaining_alt_char_ct]);
1793 for (uint32_t alt_idx = 0; alt_idx != extra_alt_ct; ++alt_idx) {
1794 char* cur_alt_end = AdvToDelim(linebuf_iter, ',');
1795 const uint32_t cur_allele_slen = cur_alt_end - linebuf_iter;
1796 if (cur_allele_slen == 1) {
1797 const char geno_char = linebuf_iter[0];
1798 if (unlikely((geno_char == '.') || (geno_char == input_missing_geno_char))) {
1799 goto LoadPvar_ret_MULTIALLELIC_MISSING_ALLELE_CODE;
1800 }
1801 *allele_storage_iter = &(g_one_char_strs[2 * ctou32(geno_char)]);
1802 } else {
1803 if (unlikely(!cur_allele_slen)) {
1804 goto LoadPvar_ret_EMPTY_ALLELE_CODE;
1805 }
1806 if (StoreStringAtEndK(tmp_alloc_base, linebuf_iter, cur_allele_slen, &tmp_alloc_end, allele_storage_iter)) {
1807 goto LoadPvar_ret_NOMEM;
1808 }
1809 if (cur_allele_slen > max_allele_slen) {
1810 max_allele_slen = cur_allele_slen;
1811 }
1812 }
1813 ++allele_storage_iter;
1814 linebuf_iter = &(cur_alt_end[1]);
1815 }
1816 remaining_alt_char_ct = alt_token_end - linebuf_iter;
1817 if (unlikely(!remaining_alt_char_ct)) {
1818 goto LoadPvar_ret_EMPTY_ALLELE_CODE;
1819 }
1820 }
1821 if (remaining_alt_char_ct == 1) {
1822 char geno_char = linebuf_iter[0];
1823 if (geno_char == input_missing_geno_char) {
1824 geno_char = '.';
1825 }
1826 if (geno_char == '.') {
1827 ++missing_allele_ct;
1828 }
1829 *allele_storage_iter = &(g_one_char_strs[2 * ctou32(geno_char)]);
1830 } else {
1831 if (StoreStringAtEndK(tmp_alloc_base, linebuf_iter, remaining_alt_char_ct, &tmp_alloc_end, allele_storage_iter)) {
1832 goto LoadPvar_ret_NOMEM;
1833 }
1834 if (remaining_alt_char_ct > max_allele_slen) {
1835 max_allele_slen = remaining_alt_char_ct;
1836 }
1837 }
1838 if (unlikely(missing_allele_ct && extra_alt_ct)) {
1839 goto LoadPvar_ret_MULTIALLELIC_MISSING_ALLELE_CODE;
1840 }
1841 ++allele_storage_iter;
1842
1843 // CM
1844 if (cm_col_present) {
1845 const char* cm_token = token_ptrs[7];
1846 if ((cm_token[0] != '0') || (cm_token[1] > ' ')) {
1847 double cur_cm;
1848 if (unlikely(!ScantokDouble(cm_token, &cur_cm))) {
1849 snprintf(g_logbuf, kLogbufSize, "Error: Invalid centimorgan position on line %" PRIuPTR " of %s.\n", line_idx, pvarname);
1850 goto LoadPvar_ret_MALFORMED_INPUT_WW;
1851 }
1852 if (cur_cm < last_cm) {
1853 vpos_sortstatus |= kfUnsortedVarCm;
1854 } else {
1855 last_cm = cur_cm;
1856 }
1857 if (cur_cm != 0.0) {
1858 if (!at_least_one_nzero_cm) {
1859 if (unlikely(S_CAST(uintptr_t, tmp_alloc_end - tmp_alloc_base) < kLoadPvarBlockSize * sizeof(double))) {
1860 goto LoadPvar_ret_NOMEM;
1861 }
1862 if (cur_chr_idxs) {
1863 // reposition cur_chr_idxs[] after cur_cms[]
1864 cur_cms = R_CAST(double*, cur_chr_idxs);
1865 cur_chr_idxs = R_CAST(ChrIdx*, &(cur_cms[kLoadPvarBlockSize]));
1866 memcpy(cur_chr_idxs, cur_cms, kLoadPvarBlockSize * sizeof(ChrIdx));
1867 tmp_alloc_base = R_CAST(unsigned char*, &(cur_chr_idxs[kLoadPvarBlockSize]));
1868 } else {
1869 cur_cms = R_CAST(double*, tmp_alloc_base);
1870 tmp_alloc_base = R_CAST(unsigned char*, &(cur_cms[kLoadPvarBlockSize]));
1871 }
1872 ZeroDArr(kLoadPvarBlockSize, cur_cms);
1873 cms_start_block = raw_variant_ct / kLoadPvarBlockSize;
1874 at_least_one_nzero_cm = 1;
1875 }
1876 cur_cms[variant_idx_lowbits] = cur_cm;
1877 }
1878 }
1879 }
1880 } else {
1881 {
1882 // linebuf_iter guaranteed to be at '\t' after chromosome code
1883 char* alt_col_start = NextTokenMult(linebuf_iter, alt_col_idx);
1884 if (unlikely(!alt_col_start)) {
1885 goto LoadPvar_ret_MISSING_TOKENS;
1886 }
1887 char* alt_col_end = CurTokenEnd(alt_col_start);
1888 extra_alt_ct = CountByte(alt_col_start, ',', alt_col_end - alt_col_start);
1889 line_iter = AdvToDelim(alt_col_end, '\n');
1890 }
1891 LoadPvar_skip_variant:
1892 ++exclude_ct;
1893 ClearBit(variant_idx_lowbits, cur_include);
1894 cur_bps[variant_idx_lowbits] = last_bp;
1895 // need to advance allele_storage_iter for later allele_idx_offsets
1896 // lookups to work properly
1897 *allele_storage_iter++ = missing_allele_str;
1898 *allele_storage_iter++ = missing_allele_str;
1899 if (extra_alt_ct) {
1900 if (PtrCheck(allele_storage_limit, allele_storage_iter, extra_alt_ct * sizeof(intptr_t))) {
1901 goto LoadPvar_ret_NOMEM;
1902 }
1903 for (uint32_t uii = 0; uii != extra_alt_ct; ++uii) {
1904 *allele_storage_iter++ = missing_allele_str;
1905 }
1906 }
1907 }
1908 ++raw_variant_ct;
1909 }
1910 if (unlikely(TextStreamErrcode2(&pvar_txs, &reterr))) {
1911 goto LoadPvar_ret_TSTREAM_FAIL;
1912 }
1913 reterr = kPglRetSuccess;
1914 if (unlikely(max_variant_id_slen > kMaxIdSlen)) {
1915 logerrputs("Error: Variant names are limited to " MAX_ID_SLEN_STR " characters.\n");
1916 goto LoadPvar_ret_MALFORMED_INPUT;
1917 }
1918 if (new_variant_id_allele_len_overflow) {
1919 const uint32_t new_variant_id_overflow_missing = (misc_flags / kfMiscNewVarIdOverflowMissing) & 1;
1920 if (new_variant_id_overflow_missing) {
1921 logerrprintfww("Warning: %" PRIuPTR " variant ID%s %s due to allele code length.\n", new_variant_id_allele_len_overflow, (new_variant_id_allele_len_overflow == 1)? "" : "s", missing_varid_match_slen? "unchanged by --set-missing-var-ids" : "erased by --set-all-var-ids");
1922 if (max_variant_id_slen < missing_varid_blen - 1) {
1923 max_variant_id_slen = missing_varid_blen - 1;
1924 }
1925 } else if (likely(misc_flags & kfMiscNewVarIdOverflowTruncate)) {
1926 // this is less likely in practice than the error branch, but let's
1927 // keep our usage of likely()/unlikely() as easy to interpret as
1928 // possible.
1929 logerrprintf("Warning: %" PRIuPTR " allele code%s truncated by --set-%s-var-ids.\n", new_variant_id_allele_len_overflow, (new_variant_id_allele_len_overflow == 1)? "" : "s", missing_varid_match_slen? "missing" : "all");
1930 } else {
1931 uint32_t worst_case_id_slen = VaridWorstCaseSlen(varid_templatep, max_chr_slen, max_allele_slen);
1932 if ((worst_case_id_slen <= kMaxIdSlen) && varid_multi_templatep) {
1933 const uint32_t tmp_slen = VaridWorstCaseSlen(varid_multi_templatep, max_chr_slen, max_allele_slen);
1934 if (tmp_slen > worst_case_id_slen) {
1935 worst_case_id_slen = tmp_slen;
1936 }
1937 }
1938 if ((worst_case_id_slen <= kMaxIdSlen) && varid_multi_nonsnp_templatep) {
1939 const uint32_t tmp_slen = VaridWorstCaseSlen(varid_multi_nonsnp_templatep, max_chr_slen, max_allele_slen);
1940 if (tmp_slen > worst_case_id_slen) {
1941 worst_case_id_slen = tmp_slen;
1942 }
1943 }
1944 logerrprintf("Error: %" PRIuPTR " allele code%s too long for --set-%s-var-ids.\n", new_variant_id_allele_len_overflow, (new_variant_id_allele_len_overflow == 1)? "" : "s", missing_varid_match_slen? "missing" : "all");
1945 if (worst_case_id_slen <= kMaxIdSlen) {
1946 logerrprintfww("The longest observed allele code in this dataset has length %u. If you're fine with the corresponding ID length, rerun with \"--new-id-max-allele-len %u\" added to your command line.\n", max_allele_slen, max_allele_slen);
1947 logerrputs("Otherwise, use \"--new-id-max-allele-len <limit> missing\" to set the IDs of all\nvariants with an allele code longer than the given length-limit to '.' (and\nthen process those variants with another script, if necessary).\n");
1948 } else {
1949 logerrprintfww("The longest observed allele code in this dataset has length %u. We recommend deciding on a length-limit, and then adding \"--new-id-max-allele-len <limit> missing\" to your command line to cause variants with longer allele codes to be assigned '.' IDs. (You can then process just those variants with another script, if necessary.)\n", max_allele_slen);
1950 }
1951 goto LoadPvar_ret_INCONSISTENT_INPUT;
1952 }
1953 }
1954 *max_variant_id_slen_ptr = max_variant_id_slen;
1955 *max_allele_ct_ptr = max_extra_alt_ct + 2;
1956 *max_allele_slen_ptr = max_allele_slen;
1957 *max_filter_slen_ptr = max_filter_slen;
1958 *raw_variant_ct_ptr = raw_variant_ct;
1959 uintptr_t allele_idx_end = allele_storage_iter - allele_storage;
1960 BigstackFinalizeCp(allele_storage, allele_idx_end);
1961 // We may clobber this object soon, so close it now (verifying
1962 // rewindability first, if necessary).
1963 if (unlikely(CleanupTextStream2(pvarname, &pvar_txs, &reterr))) {
1964 goto LoadPvar_ret_1;
1965 }
1966 uintptr_t* allele_idx_offsets = nullptr;
1967 const uint32_t full_block_ct = raw_variant_ct / kLoadPvarBlockSize;
1968 const uintptr_t raw_variant_ct_lowbits = raw_variant_ct % kLoadPvarBlockSize;
1969 // todo: determine whether we want variant_include to be guaranteed to be
1970 // terminated by a zero bit
1971 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
1972 if (unlikely(bigstack_alloc_w(raw_variant_ctl, variant_include_ptr) ||
1973 bigstack_alloc_u32(raw_variant_ct, variant_bps_ptr) ||
1974 bigstack_alloc_cp(raw_variant_ct, variant_ids_ptr))) {
1975 goto LoadPvar_ret_NOMEM;
1976 }
1977 uintptr_t* qual_present = nullptr;
1978 float* quals = nullptr;
1979 if (load_qual_col > 1) {
1980 if (unlikely(bigstack_alloc_w(raw_variant_ctl, qual_present_ptr) ||
1981 bigstack_alloc_f(raw_variant_ct, quals_ptr))) {
1982 goto LoadPvar_ret_NOMEM;
1983 }
1984 qual_present = *qual_present_ptr;
1985 quals = *quals_ptr;
1986 }
1987 uintptr_t* filter_present = nullptr;
1988 uintptr_t* filter_npass = nullptr;
1989 char** filter_storage = nullptr;
1990 if (load_filter_col > 1) {
1991 if (unlikely(bigstack_alloc_w(raw_variant_ctl, filter_present_ptr) ||
1992 bigstack_alloc_w(raw_variant_ctl, filter_npass_ptr))) {
1993 goto LoadPvar_ret_NOMEM;
1994 }
1995 filter_present = *filter_present_ptr;
1996 filter_npass = *filter_npass_ptr;
1997 if (at_least_one_npass_filter) {
1998 // possible todo: store this in a sparse manner
1999 if (unlikely(bigstack_alloc_cp(raw_variant_ct, filter_storage_ptr))) {
2000 goto LoadPvar_ret_NOMEM;
2001 }
2002 filter_storage = *filter_storage_ptr;
2003 }
2004 }
2005 uintptr_t* nonref_flags = nullptr;
2006 if (info_pr_exists) {
2007 if (unlikely(bigstack_alloc_w(raw_variant_ctl, nonref_flags_ptr))) {
2008 goto LoadPvar_ret_NOMEM;
2009 }
2010 nonref_flags = *nonref_flags_ptr;
2011 }
2012 // load_qual_col > 1:
2013 // kLoadPvarBlockSize / CHAR_BIT for qual_present
2014 // kLoadPvarBlockSize * sizeof(float) for quals
2015 // load_filter_col > 1:
2016 // 2 * (kLoadPvarBlockSize / CHAR_BIT) for filter_present, filter_npass
2017 // kLoadPvarBlockSize * sizeof(intptr_t) for filter_storage
2018 // at_least_one_nzero_cm:
2019 // kLoadPvarBlockSize * sizeof(double)
2020 // is_split_chr:
2021 // kLoadPvarBlockSize * sizeof(ChrIdx)
2022 unsigned char* read_iter = g_bigstack_end;
2023 uint32_t* variant_bps = *variant_bps_ptr;
2024 char** variant_ids = *variant_ids_ptr;
2025 uintptr_t* variant_include = *variant_include_ptr;
2026 for (uint32_t block_idx = 0; block_idx != full_block_ct; ++block_idx) {
2027 memcpy(&(variant_bps[block_idx * kLoadPvarBlockSize]), read_iter, kLoadPvarBlockSize * sizeof(int32_t));
2028 // skip over allele_idx_offsets
2029 read_iter = &(read_iter[kLoadPvarBlockSize * (sizeof(int32_t) + sizeof(intptr_t))]);
2030 memcpy(&(variant_ids[block_idx * kLoadPvarBlockSize]), read_iter, kLoadPvarBlockSize * sizeof(intptr_t));
2031 read_iter = &(read_iter[kLoadPvarBlockSize * sizeof(intptr_t)]);
2032 memcpy(&(variant_include[block_idx * (kLoadPvarBlockSize / kBitsPerWord)]), read_iter, kLoadPvarBlockSize / CHAR_BIT);
2033 read_iter = &(read_iter[kLoadPvarBlockSize / CHAR_BIT]);
2034 if (qual_present) {
2035 memcpy(&(qual_present[block_idx * (kLoadPvarBlockSize / kBitsPerWord)]), read_iter, kLoadPvarBlockSize / CHAR_BIT);
2036 read_iter = &(read_iter[kLoadPvarBlockSize / CHAR_BIT]);
2037 memcpy(&(quals[block_idx * kLoadPvarBlockSize]), read_iter, kLoadPvarBlockSize * sizeof(float));
2038 read_iter = &(read_iter[kLoadPvarBlockSize * sizeof(float)]);
2039 }
2040 if (filter_present) {
2041 memcpy(&(filter_present[block_idx * (kLoadPvarBlockSize / kBitsPerWord)]), read_iter, kLoadPvarBlockSize / CHAR_BIT);
2042 read_iter = &(read_iter[kLoadPvarBlockSize / CHAR_BIT]);
2043 memcpy(&(filter_npass[block_idx * (kLoadPvarBlockSize / kBitsPerWord)]), read_iter, kLoadPvarBlockSize / CHAR_BIT);
2044 read_iter = &(read_iter[kLoadPvarBlockSize / CHAR_BIT]);
2045 if (filter_storage) {
2046 memcpy(&(filter_storage[block_idx * kLoadPvarBlockSize]), read_iter, kLoadPvarBlockSize * sizeof(intptr_t));
2047 }
2048 read_iter = &(read_iter[kLoadPvarBlockSize * sizeof(intptr_t)]);
2049 }
2050 if (info_pr_exists) {
2051 memcpy(&(nonref_flags[block_idx * (kLoadPvarBlockSize / kBitsPerWord)]), read_iter, kLoadPvarBlockSize / CHAR_BIT);
2052 read_iter = &(read_iter[kLoadPvarBlockSize / CHAR_BIT]);
2053 }
2054 // skip over cms
2055 if (block_idx >= cms_start_block) {
2056 read_iter = &(read_iter[kLoadPvarBlockSize * sizeof(double)]);
2057 }
2058 // skip over chr_idxs
2059 if (block_idx >= chr_idxs_start_block) {
2060 read_iter = &(read_iter[kLoadPvarBlockSize * sizeof(ChrIdx)]);
2061 }
2062 }
2063 memcpy(&(variant_bps[full_block_ct * kLoadPvarBlockSize]), read_iter, raw_variant_ct_lowbits * sizeof(int32_t));
2064 read_iter = &(read_iter[kLoadPvarBlockSize * (sizeof(int32_t) + sizeof(intptr_t))]);
2065 memcpy(&(variant_ids[full_block_ct * kLoadPvarBlockSize]), read_iter, raw_variant_ct_lowbits * sizeof(intptr_t));
2066 read_iter = &(read_iter[kLoadPvarBlockSize * sizeof(intptr_t)]);
2067 const uint32_t last_bitblock_size = DivUp(raw_variant_ct_lowbits, CHAR_BIT);
2068 memcpy(&(variant_include[full_block_ct * (kLoadPvarBlockSize / kBitsPerWord)]), read_iter, last_bitblock_size);
2069 ZeroTrailingBits(raw_variant_ct, variant_include);
2070 read_iter = &(read_iter[kLoadPvarBlockSize / CHAR_BIT]);
2071 if (qual_present) {
2072 memcpy(&(qual_present[full_block_ct * (kLoadPvarBlockSize / kBitsPerWord)]), read_iter, last_bitblock_size);
2073 ZeroTrailingBits(raw_variant_ct, qual_present);
2074 read_iter = &(read_iter[kLoadPvarBlockSize / CHAR_BIT]);
2075 memcpy(&(quals[full_block_ct * kLoadPvarBlockSize]), read_iter, raw_variant_ct_lowbits * sizeof(float));
2076 read_iter = &(read_iter[kLoadPvarBlockSize * sizeof(float)]);
2077 }
2078 if (filter_present) {
2079 memcpy(&(filter_present[full_block_ct * (kLoadPvarBlockSize / kBitsPerWord)]), read_iter, last_bitblock_size);
2080 ZeroTrailingBits(raw_variant_ct, filter_present);
2081 read_iter = &(read_iter[kLoadPvarBlockSize / CHAR_BIT]);
2082 memcpy(&(filter_npass[full_block_ct * (kLoadPvarBlockSize / kBitsPerWord)]), read_iter, last_bitblock_size);
2083 ZeroTrailingBits(raw_variant_ct, filter_npass);
2084 read_iter = &(read_iter[kLoadPvarBlockSize / CHAR_BIT]);
2085 if (filter_storage) {
2086 memcpy(&(filter_storage[full_block_ct * kLoadPvarBlockSize]), read_iter, raw_variant_ct_lowbits * sizeof(intptr_t));
2087 }
2088 // bugfix (3 Feb 2021): temporary filter_storage space was allocated
2089 // regardless of whether any non-PASS values were ultimately found
2090 read_iter = &(read_iter[kLoadPvarBlockSize * sizeof(intptr_t)]);
2091 }
2092 if (info_pr_exists) {
2093 memcpy(&(nonref_flags[full_block_ct * (kLoadPvarBlockSize / kBitsPerWord)]), read_iter, last_bitblock_size);
2094 ZeroTrailingBits(raw_variant_ct, nonref_flags);
2095 // read_iter = &(read_iter[kLoadPvarBlockSize / CHAR_BIT]);
2096 }
2097 const uintptr_t read_iter_stride_base = kLoadPvarBlockSize * (sizeof(int32_t) + 2 * sizeof(intptr_t)) + (kLoadPvarBlockSize / CHAR_BIT) + (load_qual_col > 1) * ((kLoadPvarBlockSize / CHAR_BIT) + kLoadPvarBlockSize * sizeof(float)) + (load_filter_col > 1) * (2 * (kLoadPvarBlockSize / CHAR_BIT) + kLoadPvarBlockSize * sizeof(intptr_t)) + info_pr_exists * (kLoadPvarBlockSize / CHAR_BIT);
2098 if (allele_idx_end > 2 * S_CAST(uintptr_t, raw_variant_ct)) {
2099 if (no_multiallelic_allowed) {
2100 snprintf(g_logbuf, kLogbufSize, "Error: %s contains multiallelic variant(s), despite having no #CHROM header line. Add that header line to make it obvious that this isn't a valid .bim.\n", pvarname);
2101 goto LoadPvar_ret_MALFORMED_INPUT_WW;
2102 }
2103 if (unlikely(bigstack_alloc_w(raw_variant_ct + 1, allele_idx_offsets_ptr))) {
2104 goto LoadPvar_ret_NOMEM;
2105 }
2106 allele_idx_offsets = *allele_idx_offsets_ptr;
2107 uintptr_t* allele_idx_read_iter = R_CAST(uintptr_t*, &(g_bigstack_end[kLoadPvarBlockSize * sizeof(int32_t)]));
2108 for (uint32_t block_idx = 0; block_idx != full_block_ct; ++block_idx) {
2109 memcpy(&(allele_idx_offsets[block_idx * kLoadPvarBlockSize]), allele_idx_read_iter, kLoadPvarBlockSize * sizeof(intptr_t));
2110 allele_idx_read_iter = R_CAST(uintptr_t*, R_CAST(uintptr_t, allele_idx_read_iter) + read_iter_stride_base + (block_idx >= cms_start_block) * kLoadPvarBlockSize * sizeof(double) + (block_idx >= chr_idxs_start_block) * kLoadPvarBlockSize * sizeof(ChrIdx));
2111 }
2112 memcpy(&(allele_idx_offsets[full_block_ct * kLoadPvarBlockSize]), allele_idx_read_iter, raw_variant_ct_lowbits * sizeof(intptr_t));
2113 allele_idx_offsets[raw_variant_ct] = allele_idx_end;
2114 }
2115 if (at_least_one_nzero_cm) {
2116 if (unlikely(bigstack_alloc_d(raw_variant_ct, variant_cms_ptr))) {
2117 goto LoadPvar_ret_NOMEM;
2118 }
2119 double* variant_cms = *variant_cms_ptr;
2120 ZeroDArr(cms_start_block * kLoadPvarBlockSize, variant_cms);
2121 double* cms_read_iter = R_CAST(double*, &(g_bigstack_end[read_iter_stride_base * (cms_start_block + 1)]));
2122 if (cms_start_block > chr_idxs_start_block) {
2123 cms_read_iter = R_CAST(double*, R_CAST(uintptr_t, cms_read_iter) + kLoadPvarBlockSize * sizeof(ChrIdx) * (cms_start_block - chr_idxs_start_block));
2124 }
2125 for (uint32_t block_idx = cms_start_block; block_idx != full_block_ct; ++block_idx) {
2126 memcpy(&(variant_cms[block_idx * kLoadPvarBlockSize]), cms_read_iter, kLoadPvarBlockSize * sizeof(double));
2127 cms_read_iter = R_CAST(double*, R_CAST(uintptr_t, cms_read_iter) + read_iter_stride_base + kLoadPvarBlockSize * sizeof(double) + (block_idx >= chr_idxs_start_block) * kLoadPvarBlockSize * sizeof(ChrIdx));
2128 }
2129 memcpy(&(variant_cms[full_block_ct * kLoadPvarBlockSize]), cms_read_iter, raw_variant_ct_lowbits * sizeof(double));
2130 } else {
2131 *variant_cms_ptr = nullptr;
2132 }
2133 if (!is_split_chr) {
2134 cip->chr_fo_vidx_start[chrs_encountered_m1 + 1] = raw_variant_ct;
2135 if (splitpar_bound2) {
2136 if (splitpar_and_exclude_x) {
2137 ClearBit(x_code, chr_mask);
2138 }
2139 reterr = SplitPar(variant_bps, *vpos_sortstatus_ptr, splitpar_bound1, splitpar_bound2, variant_include, loaded_chr_mask, cip, &chrs_encountered_m1, &exclude_ct);
2140 if (unlikely(reterr)) {
2141 goto LoadPvar_ret_1;
2142 }
2143 }
2144 cip->chr_ct = chrs_encountered_m1 + 1;
2145 } else {
2146 ChrIdx* chr_idxs;
2147 if (unlikely(BIGSTACK_ALLOC_X(ChrIdx, raw_variant_ct, &chr_idxs))) {
2148 goto LoadPvar_ret_NOMEM;
2149 }
2150 *chr_idxs_ptr = chr_idxs;
2151 if (chr_idxs_start_block) {
2152 const uint32_t end_vidx = chr_idxs_start_block * kLoadPvarBlockSize;
2153 uint32_t chr_fo_idx = chrs_encountered_m1;
2154 while (cip->chr_fo_vidx_start[chr_fo_idx] >= end_vidx) {
2155 --chr_fo_idx;
2156 }
2157 BackfillChrIdxs(cip, chr_fo_idx, 0, end_vidx, chr_idxs);
2158 }
2159 ChrIdx* chr_idxs_read_iter = R_CAST(ChrIdx*, &(g_bigstack_end[read_iter_stride_base * (chr_idxs_start_block + 1)]));
2160 if (chr_idxs_start_block >= cms_start_block) {
2161 chr_idxs_read_iter = R_CAST(ChrIdx*, R_CAST(uintptr_t, chr_idxs_read_iter) + kLoadPvarBlockSize * sizeof(double) * (chr_idxs_start_block + 1 - cms_start_block));
2162 }
2163 for (uint32_t block_idx = chr_idxs_start_block; block_idx != full_block_ct; ) {
2164 memcpy(&(chr_idxs[block_idx * kLoadPvarBlockSize]), chr_idxs_read_iter, kLoadPvarBlockSize * sizeof(ChrIdx));
2165 ++block_idx;
2166 chr_idxs_read_iter = R_CAST(ChrIdx*, R_CAST(uintptr_t, chr_idxs_read_iter) + read_iter_stride_base + kLoadPvarBlockSize * sizeof(ChrIdx) + (block_idx >= cms_start_block) * kLoadPvarBlockSize * sizeof(double));
2167 }
2168 memcpy(&(chr_idxs[full_block_ct * kLoadPvarBlockSize]), chr_idxs_read_iter, raw_variant_ct_lowbits * sizeof(ChrIdx));
2169 cip->chr_ct = PopcountWords(loaded_chr_mask, DivUp(cip->max_code + cip->name_ct + 1, kBitsPerWord));
2170 }
2171 if (merge_par) {
2172 const uint32_t is_plink2_par = (misc_flags / kfMiscMergePar) & 1;
2173 if (merge_par_ct) {
2174 logprintf("--merge-%s: %u chromosome code%s changed.\n", is_plink2_par? "par" : "x", merge_par_ct, (merge_par_ct == 1)? "" : "s");
2175 } else if (is_plink2_par) {
2176 logerrputs("Warning: --merge-par had no effect (no PAR1/PAR2 chromosome codes present).\n");
2177 } else {
2178 logerrputs("Warning: --merge-x had no effect (no XY chromosome codes present).\n");
2179 }
2180 }
2181 const uint32_t name_ct = cip->name_ct;
2182 if (name_ct) {
2183 logprintf("Note: %u nonstandard chromosome code%s present.\n", name_ct, (name_ct == 1)? "" : "s");
2184 }
2185 const uint32_t last_chr_code = cip->max_code + name_ct;
2186 const uint32_t chr_word_ct = BitCtToWordCt(last_chr_code + 1);
2187 BitvecAnd(loaded_chr_mask, chr_word_ct, chr_mask);
2188 BigstackEndSet(tmp_alloc_end);
2189 *variant_ct_ptr = raw_variant_ct - exclude_ct;
2190 *vpos_sortstatus_ptr = vpos_sortstatus;
2191 *allele_storage_ptr = allele_storage;
2192 // if only INFO/PR flag present, no need to reload
2193 if (!(info_nonpr_present || info_pr_nonflag_exists)) {
2194 info_reload_slen = 0;
2195 }
2196 if (info_reload_slen) {
2197 // treat open-fail as rewind-fail here
2198 if (unlikely(ForceNonFifo(pvarname))) {
2199 logerrprintfww(kErrprintfRewind, pvarname);
2200 reterr = kPglRetRewindFail;
2201 goto LoadPvar_ret_1;
2202 }
2203 }
2204 *info_reload_slen_ptr = info_reload_slen;
2205 }
2206
2207 while (0) {
2208 LoadPvar_ret_NOMEM:
2209 reterr = kPglRetNomem;
2210 break;
2211 LoadPvar_ret_TSTREAM_FAIL:
2212 TextStreamErrPrint(pvarname, &pvar_txs);
2213 break;
2214 LoadPvar_ret_EMPTY_ALLELE_CODE:
2215 snprintf(g_logbuf, kLogbufSize, "Error: Empty allele code on line %" PRIuPTR " of %s.\n", line_idx, pvarname);
2216 LoadPvar_ret_MALFORMED_INPUT_WW:
2217 WordWrapB(0);
2218 logerrputsb();
2219 LoadPvar_ret_MALFORMED_INPUT:
2220 reterr = kPglRetMalformedInput;
2221 break;
2222 LoadPvar_ret_MALFORMED_HEADER_LINE:
2223 logerrprintf("Error: Header line %" PRIuPTR " of %s is malformed.\n", line_idx);
2224 reterr = kPglRetMalformedInput;
2225 break;
2226 LoadPvar_ret_MULTIALLELIC_MISSING_ALLELE_CODE:
2227 // Note that we must permit one or even both alleles to be missing in the
2228 // biallelic case, for .ped data to be usable.
2229 snprintf(g_logbuf, kLogbufSize, "Error: Missing allele code in multiallelic variant on line %" PRIuPTR " of %s.\n", line_idx, pvarname);
2230 WordWrapB(0);
2231 logerrputsb();
2232 LoadPvar_ret_INCONSISTENT_INPUT:
2233 reterr = kPglRetInconsistentInput;
2234 break;
2235 LoadPvar_ret_MISSING_TOKENS:
2236 logerrprintfww("Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, pvarname);
2237 reterr = kPglRetMalformedInput;
2238 break;
2239 // old NONMISSING_ALT_MATCHES_REF sanity-check replaced with conditional
2240 // CheckAlleleUniqueness() call.
2241 }
2242 LoadPvar_ret_1:
2243 CleanupTextStream2(pvarname, &pvar_txs, &reterr);
2244 if (reterr) {
2245 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
2246 }
2247 return reterr;
2248 }
2249
2250 // Useful when we need to read from multiple .pgens (possibly with multiallelic
2251 // variants) at once, and the usual LoadPvar() memory footprint is larger than
2252 // we want.
2253 // allele_idx_offsets is allocated at the bottom of bigstack. It's assumed to
2254 // be initialized to nullptr.
2255 // max_allele_ct is assumed to be initialized to 2.
2256 // raw_variant_ctp, max_allele_slenp, and/or max_observed_line_blenp can be
2257 // nullptr if the caller is uninterested in them. If they're all null, this
2258 // can exit immediately on .bim files.
2259 PglErr LoadAlleleIdxOffsetsFromPvar(const char* pvarname, const char* file_descrip, uint32_t max_thread_ct, uint32_t* raw_variant_ctp, uint32_t* max_allele_slenp, uint32_t* max_observed_line_blenp, uintptr_t** allele_idx_offsets_ptr, uint32_t* max_allele_ctp) {
2260 unsigned char* bigstack_mark = g_bigstack_base;
2261 unsigned char* bigstack_end_mark = g_bigstack_end;
2262 uintptr_t line_idx = 0;
2263 PglErr reterr = kPglRetSuccess;
2264 TextStream txs;
2265 PreinitTextStream(&txs);
2266 {
2267 uint32_t max_line_blen;
2268 if (unlikely(StandardizeMaxLineBlen(bigstack_left() / 4, &max_line_blen))) {
2269 goto LoadAlleleIdxOffsetsFromPvar_ret_NOMEM;
2270 }
2271 reterr = InitTextStreamEx(pvarname, 1, kMaxLongLine, max_line_blen, ClipU32(max_thread_ct - 1, 1, 4), &txs);
2272 if (unlikely(reterr)) {
2273 goto LoadAlleleIdxOffsetsFromPvar_ret_TSTREAM_FAIL;
2274 }
2275 uint32_t max_observed_line_blen = 0;
2276 const char* line_start;
2277 // Skip header.
2278 do {
2279 line_start = TextGet(&txs);
2280 if (unlikely(!line_start)) {
2281 if (!TextStreamErrcode2(&txs, &reterr)) {
2282 snprintf(g_logbuf, kLogbufSize, "Error: %s is empty.\n", file_descrip);
2283 goto LoadAlleleIdxOffsetsFromPvar_ret_MALFORMED_INPUT_WW;
2284 }
2285 goto LoadAlleleIdxOffsetsFromPvar_ret_TSTREAM_FAIL;
2286 }
2287 ++line_idx;
2288 const char* line_end = TextLineEnd(&txs);
2289 const uint32_t cur_line_blen = line_end - line_start;
2290 if (cur_line_blen > max_observed_line_blen) {
2291 max_observed_line_blen = cur_line_blen;
2292 }
2293 } while ((*line_start == '#') && (!tokequal_k(line_start, "#CHROM")));
2294 // multiallelics prohibited in .bim files (and .bim lookalikes to reduce
2295 // confusion)
2296 const uint32_t no_multiallelic_allowed = (*line_start != '#');
2297 uint32_t col_skips[2];
2298 uint32_t col_types[2];
2299 if (!no_multiallelic_allowed) {
2300 // [0] = REF
2301 // [1] = ALT
2302 const char* token_end = &(line_start[6]);
2303 uint32_t found_header_bitset = 0;
2304 uint32_t relevant_col_uidx = 0;
2305 for (uint32_t col_idx = 1; ; ++col_idx) {
2306 const char* token_start = FirstNonTspace(token_end);
2307 if (IsEolnKns(*token_start)) {
2308 break;
2309 }
2310 token_end = CurTokenEnd(token_start);
2311 const uint32_t token_slen = token_end - token_start;
2312 uint32_t cur_col_type;
2313 if (strequal_k(token_start, "REF", token_slen)) {
2314 cur_col_type = 0;
2315 } else if (strequal_k(token_start, "ALT", token_slen)) {
2316 cur_col_type = 1;
2317 } else {
2318 continue;
2319 }
2320 const uint32_t cur_col_type_shifted = 1 << cur_col_type;
2321 if (unlikely(found_header_bitset & cur_col_type_shifted)) {
2322 char* write_iter = strcpya_k(g_logbuf, "Error: Duplicate column header '");
2323 write_iter = memcpya(write_iter, token_start, token_slen);
2324 write_iter = strcpya_k(write_iter, "' on line ");
2325 write_iter = wtoa(line_idx, write_iter);
2326 write_iter = strcpya_k(write_iter, " of ");
2327 write_iter = strcpya(write_iter, file_descrip);
2328 memcpy_k(write_iter, ".\n\0", 4);
2329 goto LoadAlleleIdxOffsetsFromPvar_ret_MALFORMED_INPUT_WW;
2330 }
2331 found_header_bitset |= cur_col_type_shifted;
2332 col_skips[relevant_col_uidx] = col_idx;
2333 col_types[relevant_col_uidx++] = cur_col_type;
2334 }
2335 if (unlikely(found_header_bitset != 3)) {
2336 snprintf(g_logbuf, kLogbufSize, "Error: Missing column header(s) on line %" PRIuPTR " of %s. (POS, ID, REF, and ALT are required.)\n", line_idx, file_descrip);
2337 goto LoadAlleleIdxOffsetsFromPvar_ret_MALFORMED_INPUT_WW;
2338 }
2339 col_skips[1] -= col_skips[0];
2340 line_start = TextGet(&txs);
2341 if (unlikely(!line_start)) {
2342 if (!TextStreamErrcode2(&txs, &reterr)) {
2343 snprintf(g_logbuf, kLogbufSize, "Error: %s is empty.\n", file_descrip);
2344 goto LoadAlleleIdxOffsetsFromPvar_ret_MALFORMED_INPUT_WW;
2345 }
2346 goto LoadAlleleIdxOffsetsFromPvar_ret_TSTREAM_FAIL;
2347 }
2348 ++line_idx;
2349 const char* line_end = TextLineEnd(&txs);
2350 const uint32_t cur_line_blen = line_end - line_start;
2351 if (cur_line_blen > max_observed_line_blen) {
2352 max_observed_line_blen = cur_line_blen;
2353 }
2354 } else {
2355 const char* fifth_column_start = NextTokenMult(line_start, 4);
2356 if (unlikely(!fifth_column_start)) {
2357 snprintf(g_logbuf, kLogbufSize, "Error: Fewer columns than expected in %s.\n", file_descrip);
2358 goto LoadAlleleIdxOffsetsFromPvar_ret_MALFORMED_INPUT_WW;
2359 }
2360 if ((!raw_variant_ctp) && (!max_allele_slenp) && (!max_observed_line_blenp)) {
2361 goto LoadAlleleIdxOffsetsFromPvar_ret_1;
2362 }
2363 col_skips[1] = 1;
2364 col_types[0] = 1;
2365 col_types[1] = 0;
2366 const char* sixth_column_start = NextToken(fifth_column_start);
2367 if (sixth_column_start) {
2368 // #CHROM ID CM POS ALT REF
2369 col_skips[0] = 4;
2370 } else {
2371 // #CHROM ID POS ALT REF
2372 col_skips[0] = 3;
2373 }
2374 }
2375 uintptr_t* allele_idx_offsets = R_CAST(uintptr_t*, g_bigstack_base);
2376 uintptr_t* allele_idx_offsets_limit = R_CAST(uintptr_t*, g_bigstack_end);
2377 if (allele_idx_offsets_limit == allele_idx_offsets) {
2378 goto LoadAlleleIdxOffsetsFromPvar_ret_NOMEM;
2379 }
2380 #ifdef __LP64__
2381 if (allele_idx_offsets_limit > &(allele_idx_offsets[kPglMaxVariantCt + 1])) {
2382 allele_idx_offsets_limit = &(allele_idx_offsets[kPglMaxVariantCt + 1]);
2383 }
2384 #endif
2385 uintptr_t* allele_idx_offsets_iter = allele_idx_offsets;
2386 uintptr_t allele_idx = 0;
2387 *allele_idx_offsets_iter++ = allele_idx;
2388 uint32_t max_allele_ct = 2;
2389 uint32_t max_allele_slen = 1;
2390 while (1) {
2391 if (allele_idx_offsets_iter == allele_idx_offsets_limit) {
2392 #ifdef __LP64__
2393 if (allele_idx_offsets_limit == &(allele_idx_offsets[kPglMaxVariantCt + 1])) {
2394 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");
2395 goto LoadAlleleIdxOffsetsFromPvar_ret_MALFORMED_INPUT;
2396 }
2397 #endif
2398 goto LoadAlleleIdxOffsetsFromPvar_ret_NOMEM;
2399 }
2400 const char* token_ptrs[2];
2401 uint32_t token_slens[2];
2402 const char* last_token_end = TokenLexK(line_start, col_types, col_skips, 2, token_ptrs, token_slens);
2403 if (unlikely(!last_token_end)) {
2404 goto LoadAlleleIdxOffsetsFromPvar_ret_MISSING_TOKENS;
2405 }
2406 if (token_slens[0] > max_allele_slen) {
2407 max_allele_slen = token_slens[0];
2408 }
2409 const uint32_t alt_col_slen = token_slens[1];
2410 const char* alt_iter = token_ptrs[1];
2411 const char* alt_end = &(alt_iter[alt_col_slen]);
2412 uint32_t extra_alt_ct = 0;
2413 if (alt_col_slen > 1) {
2414 extra_alt_ct = CountByte(alt_iter, ',', alt_col_slen);
2415 for (uint32_t alt_idx = 0; alt_idx != extra_alt_ct; ++alt_idx) {
2416 const char* cur_alt_end = AdvToDelim(alt_iter, ',');
2417 const uint32_t cur_allele_slen = cur_alt_end - alt_iter;
2418 if (cur_allele_slen > max_allele_slen) {
2419 max_allele_slen = cur_allele_slen;
2420 }
2421 alt_iter = &(cur_alt_end[1]);
2422 }
2423 const uint32_t cur_allele_slen = alt_end - alt_iter;
2424 if (cur_allele_slen > max_allele_slen) {
2425 max_allele_slen = cur_allele_slen;
2426 }
2427 }
2428 const uint32_t cur_allele_ct = 2 + extra_alt_ct;
2429 if (cur_allele_ct > max_allele_ct) {
2430 max_allele_ct = cur_allele_ct;
2431 }
2432 allele_idx += cur_allele_ct;
2433 *allele_idx_offsets_iter++ = allele_idx;
2434 const char* line_end = AdvPastDelim(alt_end, '\n');
2435 const uint32_t cur_line_blen = line_end - line_start;
2436 if (cur_line_blen > max_observed_line_blen) {
2437 max_observed_line_blen = cur_line_blen;
2438 }
2439 line_start = line_end;
2440 if (!TextGetUnsafe2K(&txs, &line_start)) {
2441 break;
2442 }
2443 ++line_idx;
2444 if (unlikely(*line_start == '#')) {
2445 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s starts with a '#'. (This is only permitted before the first nonheader line, and if a #CHROM header line is present it must denote the end of the header block.)\n", line_idx, file_descrip);
2446 goto LoadAlleleIdxOffsetsFromPvar_ret_MALFORMED_INPUT_WW;
2447 }
2448 }
2449 if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
2450 goto LoadAlleleIdxOffsetsFromPvar_ret_TSTREAM_FAIL;
2451 }
2452 const uintptr_t raw_variant_ct_p1 = allele_idx_offsets_iter - allele_idx_offsets;
2453 const uintptr_t raw_variant_ct = raw_variant_ct_p1 - 1;
2454 if (allele_idx > 2 * raw_variant_ct) {
2455 BigstackFinalizeW(allele_idx_offsets, raw_variant_ct_p1);
2456 *allele_idx_offsets_ptr = allele_idx_offsets;
2457 }
2458 *max_allele_ctp = max_allele_ct;
2459 if (max_allele_slenp) {
2460 *max_allele_slenp = max_allele_slen;
2461 }
2462 if (raw_variant_ctp) {
2463 *raw_variant_ctp = raw_variant_ct;
2464 }
2465 if (max_observed_line_blenp) {
2466 *max_observed_line_blenp = max_observed_line_blen;
2467 }
2468 }
2469 while (0) {
2470 LoadAlleleIdxOffsetsFromPvar_ret_NOMEM:
2471 reterr = kPglRetNomem;
2472 break;
2473 LoadAlleleIdxOffsetsFromPvar_ret_TSTREAM_FAIL:
2474 TextStreamErrPrint(file_descrip, &txs);
2475 break;
2476 LoadAlleleIdxOffsetsFromPvar_ret_MISSING_TOKENS:
2477 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, file_descrip);
2478 LoadAlleleIdxOffsetsFromPvar_ret_MALFORMED_INPUT_WW:
2479 WordWrapB(0);
2480 logerrputsb();
2481 #ifdef __LP64__
2482 LoadAlleleIdxOffsetsFromPvar_ret_MALFORMED_INPUT:
2483 #endif
2484 reterr = kPglRetMalformedInput;
2485 break;
2486 }
2487 LoadAlleleIdxOffsetsFromPvar_ret_1:
2488 CleanupTextStream2(file_descrip, &txs, &reterr);
2489 BigstackEndReset(bigstack_end_mark);
2490 if (reterr) {
2491 BigstackReset(bigstack_mark);
2492 }
2493 return reterr;
2494 }
2495
2496 #ifdef __cplusplus
2497 } // namespace plink2
2498 #endif